问:
could not install frama-c-Phosphorus using opam
I had successfully installed frama-c-Silicon using opam by the instructions, but when I want to upgrade to Phosphorus, opam does not work.

I used the command:

opam pin add frama-c Downloads/frama-c-Phosphorus20170501.tar.gz

it said that:

```<code>[NOTE] Package frama-c is already path-pinned to
       /home/talos/Downloads/frama-c-Phosphorus-20170501.tar.gz.
       This will erase any previous custom definition.
Proceed ? [Y/n] y

[frama-c] /home/talos/Downloads/frama-c-Phosphorus-20170501.tar.gz synchronized

frama-c needs to be installed.
The following actions will be performed:
  ∗  install frama-c-base 20161101*           [required by frama-c]
       Why3 can be used by the WP plug-in for running additional automatic solvers
       Coq can be used with the WP plug-in for proving interactively proof obligations
  ∗  install frama-c      20161101*
       Alt-Ergo Graphical Interface can be used by the WP plug-in
===== ∗  2 =====
Do you want to continue ? [Y/n] y

=-=- Gathering sources =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
[frama-c.20161101] /home/talos/Downloads/frama-c-Phosphorus-20170501.tar.gz already up-to-date
[frama-c-base.20161101] /home/talos/Downloads/frama-c-Phosphorus-20170501.tar.gz already up-to-date

=-=- Processing actions -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#=== ERROR while installing frama-c-base.20161101 =============================#
These patches didn't apply at /home/talos/.opam/system/build/frama-c-base.20161101:
  - 4.05-support.patch

=-=- Error report -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
The following actions were aborted
  ∗  install frama-c 20161101
The following actions failed
  ∗  install frama-c-base 20161101
No changes have been performed
[NOTE] Pinning command successful, but your installed packages may be out of
       sync.
</code>```

答:
I think your problem is related more to the usage of OPAM itself (opam pin in particular) than Frama-C.

This line in particular indicates that you have pinned a Frama-C package in your OPAM installation:

```<code>[NOTE] Package frama-c is already path-pinned to
       /home/talos/Downloads/frama-c-Phosphorus-20170501.tar.gz.
       This will erase any previous custom definition.
</code>```

This was only necessary before the Phosphorus package was available in OPAM. You should revert to a default configuration by removing it and then installing it via the "standard" (non-pinned) way:

```<code>opam pin remove frama-c
# just in case, you may want to unpin the frama-c-base package, if it is pinned
opam pin remove frama-c-base
# then install the package normally; you may need to update OPAM to make
# sure the package is available in your repository
opam update
opam install frama-c
</code>```

Note that, if you still have a message displayed such as:

```<code>The following actions will be performed:
  ∗  install frama-c-base 20161101*           [required by frama-c]
</code>```

That might indicate an issue with OPAM's constraints.

The version number of the Phosphorus release is 20170501. Anything other than that means you won't get Phosphorus, but an older version. It is not worth continuing: the issue must be fixed beforehand.

Body:
I had successfully installed frama-c-Silicon using opam by the instructions, but when I want to upgrade to Phosphorus, opam does not work.

I used the command:

opam pin add frama-c Downloads/frama-c-Phosphorus20170501.tar.gz

it said that:

[NOTE] Package frama-c is already path-pinned to
       /home/talos/Downloads/frama-c-Phosphorus-20170501.tar.gz.
       This will erase any previous custom definition.
Proceed ? [Y/n] y

[frama-c] /home/talos/Downloads/frama-c-Phosphorus-20170501.tar.gz synchronized

frama-c needs to be installed.
The following actions will be performed:
  ∗  install frama-c-base 20161101*           [required by frama-c]
       Why3 can be used by the WP plug-in for running additional automatic solvers
       Coq can be used with the WP plug-in for proving interactively proof obligations
  ∗  install frama-c      20161101*
       Alt-Ergo Graphical Interface can be used by the WP plug-in
===== ∗  2 =====
Do you want to continue ? [Y/n] y

=-=- Gathering sources =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
[frama-c.20161101] /home/talos/Downloads/frama-c-Phosphorus-20170501.tar.gz already up-to-date
[frama-c-base.20161101] /home/talos/Downloads/frama-c-Phosphorus-20170501.tar.gz already up-to-date

=-=- Processing actions -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#=== ERROR while installing frama-c-base.20161101 =============================#
These patches didn't apply at /home/talos/.opam/system/build/frama-c-base.20161101:
  - 4.05-support.patch

=-=- Error report -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
The following actions were aborted
  ∗  install frama-c 20161101
The following actions failed
  ∗  install frama-c-base 20161101
No changes have been performed
[NOTE] Pinning command successful, but your installed packages may be out of
       sync.

Body:
I think your problem is related more to the usage of OPAM itself (opam pin in particular) than Frama-C.

This line in particular indicates that you have pinned a Frama-C package in your OPAM installation:

[NOTE] Package frama-c is already path-pinned to
       /home/talos/Downloads/frama-c-Phosphorus-20170501.tar.gz.
       This will erase any previous custom definition.

This was only necessary before the Phosphorus package was available in OPAM. You should revert to a default configuration by removing it and then installing it via the "standard" (non-pinned) way:

opam pin remove frama-c
# just in case, you may want to unpin the frama-c-base package, if it is pinned
opam pin remove frama-c-base
# then install the package normally; you may need to update OPAM to make
# sure the package is available in your repository
opam update
opam install frama-c

Note that, if you still have a message displayed such as:

The following actions will be performed:
  ∗  install frama-c-base 20161101*           [required by frama-c]

That might indicate an issue with OPAM's constraints.

The version number of the Phosphorus release is 20170501. Anything other than that means you won't get Phosphorus, but an older version. It is not worth continuing: the issue must be fixed beforehand.


来源: stackexchange

问:
Why is System.out.println so slow?
Is this something common to all programming languages? Doing multiple print followed by a println seems faster  but moving everything to a string and just printing that seems fastest. Why?

EDIT: For example, Java can find all the prime numbers up to 1 million in less than a second - but printing then all out each on their own println can take minutes! Up to a 10 billion can hours to print!

EX:

```<code>package sieveoferatosthenes;
public class Main {
    public static void main(String[] args) {
        int upTo = 10000000;
        boolean primes[] = new boolean[upTo];
        for( int b = 0; b < upTo; b++ ){
            primes[b] = true;
        }
        primes[0] = false;
        primes[1] = false;

        int testing = 1;

        while( testing <= Math.sqrt(upTo)){
            testing ++;
            int testingWith = testing;
            if( primes[testing] ){
                while( testingWith < upTo ){
                    testingWith = testingWith + testing;
                    if ( testingWith >= upTo){
                    }
                    else{
                        primes[testingWith] = false;
                    }

                }
            }
        }
        for( int b = 2; b < upTo; b++){
            if( primes[b] ){
                System.out.println( b );
            }
        }
    }
}
</code>```

答:
The problem you have is that displaying to the screen is very espensive, especially if you have a graphical windows/X-windows environment (rather than a pure text terminal)  Just to render one digit in a font is far more expensive than the calculations you are doing.  When you send data to the screen faster than it can display it, it buffered the data and quickly blocks.  Even writing to a file is significant compare to the calculations, but its 10x - 100x faster than displaying on the screen.

BTW: math.sqrt() is very expensive, and using a loop is much slower than using modulus i.e. % to determine if a number is a multiple.  BitSet can be 8x more space efficient than boolean[], and faster for operations on multiple bits e.g. counting or searching bits.

If I dump the output to a file, it is quick, but writing to the console is slow, and if I write to the console the data which was written to a file it takes about the same amount of time.

```<code>Took 289 ms to examine 10,000,000 numbers.
Took 149 ms to toString primes up to 10,000,000.
Took 306 ms to write to a file primes up to 10,000,000.
Took 61,082 ms to write to a System.out primes up to 10,000,000.

time cat primes.txt

real    1m24.916s
user    0m3.619s
sys     0m12.058s
</code>```

The code

```<code>int upTo = 10*1000*1000;
long start = System.nanoTime();
BitSet nonprimes = new BitSet(upTo);
for (int t = 2; t * t < upTo; t++) {
    if (nonprimes.get(t)) continue;
    for (int i = 2 * t; i <= upTo; i += t)
        nonprimes.set(i);
}
PrintWriter report = new PrintWriter("report.txt");
long time = System.nanoTime() - start;
report.printf("Took %,d ms to examine %,d numbers.%n", time / 1000 / 1000, upTo);

long start2 = System.nanoTime();
for (int i = 2; i < upTo; i++) {
    if (!nonprimes.get(i))
        Integer.toString(i);
}
long time2 = System.nanoTime() - start2;
report.printf("Took %,d ms to toString primes up to %,d.%n", time2 / 1000 / 1000, upTo);

long start3 = System.nanoTime();
PrintWriter pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream("primes.txt"), 64*1024));
for (int i = 2; i < upTo; i++) {
    if (!nonprimes.get(i))
        pw.println(i);
}
pw.close();
long time3 = System.nanoTime() - start3;
report.printf("Took %,d ms to write to a file primes up to %,d.%n", time3 / 1000 / 1000, upTo);

long start4 = System.nanoTime();
for (int i = 2; i < upTo; i++) {
    if (!nonprimes.get(i))
        System.out.println(i);
}
long time4 = System.nanoTime() - start4;
report.printf("Took %,d ms to write to a System.out primes up to %,d.%n", time4 / 1000 / 1000, upTo);
report.close();
</code>```

ContentLicense: CC BY-SA 2.5

Title: Why is System.out.println so slow?

Body:
Is this something common to all programming languages? Doing multiple print followed by a println seems faster  but moving everything to a string and just printing that seems fastest. Why?

EDIT: For example, Java can find all the prime numbers up to 1 million in less than a second - but printing then all out each on their own println can take minutes! Up to a 10 billion can hours to print!

EX:

package sieveoferatosthenes;
public class Main {
    public static void main(String[] args) {
        int upTo = 10000000;
        boolean primes[] = new boolean[upTo];
        for( int b = 0; b < upTo; b++ ){
            primes[b] = true;
        }
        primes[0] = false;
        primes[1] = false;

        int testing = 1;

        while( testing <= Math.sqrt(upTo)){
            testing ++;
            int testingWith = testing;
            if( primes[testing] ){
                while( testingWith < upTo ){
                    testingWith = testingWith + testing;
                    if ( testingWith >= upTo){
                    }
                    else{
                        primes[testingWith] = false;
                    }

                }
            }
        }
        for( int b = 2; b < upTo; b++){
            if( primes[b] ){
                System.out.println( b );
            }
        }
    }
}

Body:
The problem you have is that displaying to the screen is very espensive, especially if you have a graphical windows/X-windows environment (rather than a pure text terminal)  Just to render one digit in a font is far more expensive than the calculations you are doing.  When you send data to the screen faster than it can display it, it buffered the data and quickly blocks.  Even writing to a file is significant compare to the calculations, but its 10x - 100x faster than displaying on the screen.

BTW: math.sqrt() is very expensive, and using a loop is much slower than using modulus i.e. % to determine if a number is a multiple.  BitSet can be 8x more space efficient than boolean[], and faster for operations on multiple bits e.g. counting or searching bits.

If I dump the output to a file, it is quick, but writing to the console is slow, and if I write to the console the data which was written to a file it takes about the same amount of time.

Took 289 ms to examine 10,000,000 numbers.
Took 149 ms to toString primes up to 10,000,000.
Took 306 ms to write to a file primes up to 10,000,000.
Took 61,082 ms to write to a System.out primes up to 10,000,000.

time cat primes.txt

real    1m24.916s
user    0m3.619s
sys     0m12.058s

The code

int upTo = 10*1000*1000;
long start = System.nanoTime();
BitSet nonprimes = new BitSet(upTo);
for (int t = 2; t * t < upTo; t++) {
    if (nonprimes.get(t)) continue;
    for (int i = 2 * t; i <= upTo; i += t)
        nonprimes.set(i);
}
PrintWriter report = new PrintWriter("report.txt");
long time = System.nanoTime() - start;
report.printf("Took %,d ms to examine %,d numbers.%n", time / 1000 / 1000, upTo);

long start2 = System.nanoTime();
for (int i = 2; i < upTo; i++) {
    if (!nonprimes.get(i))
        Integer.toString(i);
}
long time2 = System.nanoTime() - start2;
report.printf("Took %,d ms to toString primes up to %,d.%n", time2 / 1000 / 1000, upTo);

long start3 = System.nanoTime();
PrintWriter pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream("primes.txt"), 64*1024));
for (int i = 2; i < upTo; i++) {
    if (!nonprimes.get(i))
        pw.println(i);
}
pw.close();
long time3 = System.nanoTime() - start3;
report.printf("Took %,d ms to write to a file primes up to %,d.%n", time3 / 1000 / 1000, upTo);

long start4 = System.nanoTime();
for (int i = 2; i < upTo; i++) {
    if (!nonprimes.get(i))
        System.out.println(i);
}
long time4 = System.nanoTime() - start4;
report.printf("Took %,d ms to write to a System.out primes up to %,d.%n", time4 / 1000 / 1000, upTo);
report.close();

ContentLicense: CC BY-SA 4.0


问:
How to implement swipeview QtQuick 2.5
I have QT 5.5 and it won't support SwipeView. I tried doing with listView but I am not getting what I expected. I want a similar functionality code in QT 5.5 like the code given below which is written in QT 5.6. Please help</p>

```<code>import QtQuick 2.6
import QtQuick.Controls 2.0
import QtQuick.Window 2.0
Window {
    visible: true
    width: 200
    height: 400
    title: qsTr("Hello World")

    id: page

    SwipeView {
        id: swipeView
        anchors.fill: parent
        currentIndex: 0
        Page {
                    Label {
                        text: qsTr("First page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Second page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Third page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Fourth page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Fifth page")
                        anchors.centerIn: parent
                    }
                }
    }

    Rectangle
    {
        id:minus
        width:parent.width/2
        height:100
        anchors.left:parent.left
        anchors.bottom:parent.bottom
        color:"red"
        MouseArea
        {
            anchors.fill:parent
            onClicked:{
                if(swipeView.currentIndex>0)
                    swipeView.currentIndex--
            }
        }
    }
    Rectangle
    {
        id:plus
        width:parent.width/2
        height:100
        anchors.right:parent.right
        anchors.bottom:parent.bottom
        color:"green"
        MouseArea
        {
            anchors.fill:parent
            onClicked:{
                if(swipeView.currentIndex<4)
                    swipeView.currentIndex++
            }
        }
    }

}
</code>```

答:
Qt Quick Controls 2 was introduced in Qt 5.7:

Qt Quick Controls 2 provides a set of controls that can be used to build complete interfaces in Qt Quick. The module was introduced in Qt 5.7.

Qt Labs Controls was introduced in Qt 5.6, so the code that you referenced would have to use the Qt.labs.controls 1.0 import in order to run with Qt 5.6.

You need to use a newer Qt version (5.6 or newer).

ContentLicense: CC BY-SA 3.0

Title: How to implement swipeview QtQuick 2.5

Body:
I have QT 5.5 and it won't support SwipeView. I tried doing with listView but I am not getting what I expected. I want a similar functionality code in QT 5.5 like the code given below which is written in QT 5.6. Please help

import QtQuick 2.6
import QtQuick.Controls 2.0
import QtQuick.Window 2.0
Window {
    visible: true
    width: 200
    height: 400
    title: qsTr("Hello World")

    id: page

    SwipeView {
        id: swipeView
        anchors.fill: parent
        currentIndex: 0
        Page {
                    Label {
                        text: qsTr("First page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Second page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Third page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Fourth page")
                        anchors.centerIn: parent
                    }
                }
        Page {
                    Label {
                        text: qsTr("Fifth page")
                        anchors.centerIn: parent
                    }
                }
    }

    Rectangle
    {
        id:minus
        width:parent.width/2
        height:100
        anchors.left:parent.left
        anchors.bottom:parent.bottom
        color:"red"
        MouseArea
        {
            anchors.fill:parent
            onClicked:{
                if(swipeView.currentIndex>0)
                    swipeView.currentIndex--
            }
        }
    }
    Rectangle
    {
        id:plus
        width:parent.width/2
        height:100
        anchors.right:parent.right
        anchors.bottom:parent.bottom
        color:"green"
        MouseArea
        {
            anchors.fill:parent
            onClicked:{
                if(swipeView.currentIndex<4)
                    swipeView.currentIndex++
            }
        }
    }

}


问:
Tomcat manager remote deploy script
I'm writing a shell script to auto deploy/undeploy using the tomcat manager.

Following the instructions on http://tomcat.apache.org/tomcat-6.0-doc/manager-howto.html#Deploy_A_New_Application_Remotely, I use curl for my deployment

```<code>curl --anyauth -u username:pwd -d path=/something -d war=file:target/someWar.war https://someurl.com/manager/deploy
</code>```

And I get the response saying HTTP method POST is not supported by this URL.

So I change my curl to be a get using -G

```<code>curl --anyauth -u username:pwd -G -d path=/something -d war=file:target/someWar.war https://someurl.com/manager/deploy
</code>```

I get a response of FAIL - Failed to deploy application at context path /something and it seems to be looking for the file locally on the server instead of my machine. There are pluings which do remote deploy without having to scp the file over so I'm wondering what I'm missing.

I'm currently out of ideas (I don't see any other option on the tomcat manager configuration page).

答:
The easiest way to deploy an app is to write an Ant script. The only other thing (apart from Ant) you will need is catalina-ant.jar to be present in the classpath.

Have a look at this chapter of the manual:
http://tomcat.apache.org/tomcat-6.0-doc/manager-howto.html#Executing_Manager_Commands_With_Ant

The script does a similar thing: uses HTTP to deploy your .war to the manager app. You might even want to capture the packets to see the exact headers if you still want to use curl. I would not recommend curl though as I think Ant solution is more portable and error-prone (e.g what if they will change low level deployment API?).

Title: Tomcat manager remote deploy script

Body:
I'm writing a shell script to auto deploy/undeploy using the tomcat manager.

Following the instructions on http://tomcat.apache.org/tomcat-6.0-doc/manager-howto.html#Deploy_A_New_Application_Remotely, I use curl for my deployment

curl --anyauth -u username:pwd -d path=/something -d war=file:target/someWar.war https://someurl.com/manager/deploy

And I get the response saying HTTP method POST is not supported by this URL.

So I change my curl to be a get using -G

curl --anyauth -u username:pwd -G -d path=/something -d war=file:target/someWar.war https://someurl.com/manager/deploy

I get a response of FAIL - Failed to deploy application at context path /something and it seems to be looking for the file locally on the server instead of my machine. There are pluings which do remote deploy without having to scp the file over so I'm wondering what I'm missing.

I'm currently out of ideas (I don't see any other option on the tomcat manager configuration page).


问:
SonarJava-71 Exclude issues on generated code when annotated with javax.annotation.Generated
I see this https://jira.sonarsource.com/browse/SONARJAVA-71 improvement which the current status is closed. I was asked to raise my question here.

I would like to know how to implement the fix because i tried to use latest SonarJava 4.10.0.10260, however it still reports issues on class/methods with @generated annotation. Please advise how to implement this fix. Which version of SonarJava release this fix is included. Thanks!

答:
SONARAVA-71 has been implemented in version 4.9 of the SonarJava Analyzer, so your version of SonarJava should ignore such annotated elements if configured correctly.

Now, in order to have classes ans methods annotated with (and only with) @javax.annotation.Generated being ignored by the analyzer, be sure to provide the bytecode for your analysis.


问:
GET request not getting data in codepen but working on browser tab
This is my Codepen for a simple weather app I did long ago. However, it is not working now. When I paste the api into browser tab, I'm getting data, but in the Codepen it is not working.

```<code>var api = "http://api.openweathermap.org/data/2.5/weather?
q=Lam%20Tin,HK&appid=23a5271ef6a94716ac17ec27e9f4bcd8";
$.getJSON(api, function(data) {
  console.log(data);
});
</code>```

答:
Error

```<code>The page at 'https://codepen.io/iamanoopc/pen/JEjYKR?editors=0011' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://api.openweathermap.org/data/2.5/weather?q=Lam%20Tin,HK&appid=23a5271ef6a94716ac17ec27e9f4bcd8'. This request has been blocked; the content must be served over HTTPS.
</code>```

Explanation

error as been showed very clearly .HTTPS, but requested an insecure XMLHttpRequest .Is secure domain server https .your http call is insecure .For the security reason .They will blocked your request This request has been blocked; the content must be served over HTTPS

Alternate

Try with insecure http domain server snippet like jsbin

Demo with Jsbin

Body:
This is my Codepen for a simple weather app I did long ago. However, it is not working now. When I paste the api into browser tab, I'm getting data, but in the Codepen it is not working.

var api = "http://api.openweathermap.org/data/2.5/weather?
q=Lam%20Tin,HK&appid=23a5271ef6a94716ac17ec27e9f4bcd8";
$.getJSON(api, function(data) {
  console.log(data);
});

Body:
Error

The page at 'https://codepen.io/iamanoopc/pen/JEjYKR?editors=0011' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://api.openweathermap.org/data/2.5/weather?q=Lam%20Tin,HK&appid=23a5271ef6a94716ac17ec27e9f4bcd8'. This request has been blocked; the content must be served over HTTPS.

Explanation

error as been showed very clearly .HTTPS, but requested an insecure XMLHttpRequest .Is secure domain server https .your http call is insecure .For the security reason .They will blocked your request This request has been blocked; the content must be served over HTTPS

Alternate

Try with insecure http domain server snippet like jsbin

Demo with Jsbin


问:
TFS to GitHub and viceversa sync
I dont know whether this is possible, but would like to know if we can do this?

Our client is using GitHub, and we are using TFS.

We dont want to change any of our settings, and want to continue on the work. But would like to sync the projects from TFS to Github and from GItHub to TFS as batch process every 30 mins, or whenever the change is made.

Any help or any pointers for implementing the same would be of great help.

Thanks

答:
Unfortunately, there is no this kind official tool or services. You have to manually do the sync. Such as setting up two remotes in a local Git repository, i.e

```<code>git remote add upstream https://github.com/foo/bar.git
git remote add origin https://tfsserver/DefaultCollection/_git/bar
</code>```

And then simply do a git pull upstream master followed by a git push
  origin master assuming that master is the branch that you want to keep
  in sync.

With either version control system, you probably want to keep a branch
  in version control in your TFS repository to match what is in your
  upstream GitHub project so that you can easily see change coming in
  the one place and then handle your merges inside your local
  repository.

Source Link:
  Integrating Github code to TFS - auto check-in

Another workaround is with help of a special build in TFS, then calling git command during the build pipeline. Detail steps please refer this blog: Keep Git repository in sync between VSTS / TFS and Git You could also use the Git Tasks in marketplace.

Title: TFS to GitHub and viceversa sync

Body:
Unfortunately, there is no this kind official tool or services. You have to manually do the sync. Such as setting up two remotes in a local Git repository, i.e

git remote add upstream https://github.com/foo/bar.git
git remote add origin https://tfsserver/DefaultCollection/_git/bar

And then simply do a git pull upstream master followed by a git push
  origin master assuming that master is the branch that you want to keep
  in sync.

With either version control system, you probably want to keep a branch
  in version control in your TFS repository to match what is in your
  upstream GitHub project so that you can easily see change coming in
  the one place and then handle your merges inside your local
  repository.

Source Link:
  Integrating Github code to TFS - auto check-in

Another workaround is with help of a special build in TFS, then calling git command during the build pipeline. Detail steps please refer this blog: Keep Git repository in sync between VSTS / TFS and Git You could also use the Git Tasks in marketplace.


问:
Make Inno Setup automatically add data from custom pages to .inf file
I created a installer with custom wizard pages. All works fine so far.
Next I wanted to create a settings file using /SAVEINF (to start the installer later on in silent mode) using the following command:

```<code>Installer.exe /SAVEINF="Unattended.txt"
</code>```

After entering all user input and running the installer, I looked at the file created. The only user input I see is the installation location but missing all my input on the custom wizard pages. All I see is:

```<code>[Setup]
Lang=en
Dir=C:\temp
Group=MyProgram
NoIcons=0
Tasks=
</code>```

Why? What do I need to do to have the custom wizard page values also in the settings file?

To be more specific.

I start the installer I've created with option to create a settings file using the /SAVEINF option on the commandline. I expected all items to be added to this file including the one from my custom wizard pages, but that's not the case. I only see the installation location from the standard setup page.

Of course I can add them manually and implement in the installer code to read them from the file, but I expected it to be automated.

答:
Indeed, Inno Setup won't save any custom fields to the .inf file.

It will never save anything to the .inf file beyond the standard Lang, Dir, Group, NoIcons, SetupType, Components and Tasks items.

See SaveInf function in Inno Setup source code:

procedure SaveInf(const FileName: String);
const
  Section = 'Setup';
begin
  SetIniString(Section, 'Lang',
    PSetupLanguageEntry(Entries[seLanguage][ActiveLanguage]).Name, FileName);
  SetIniString(Section, 'Dir', WizardDirValue, FileName);
  SetIniString(Section, 'Group', WizardGroupValue, FileName);
  SetIniBool(Section, 'NoIcons', WizardNoIcons, FileName);
  if WizardSetupType <> nil then begin
    SetIniString(Section, 'SetupType', WizardSetupType.Name, FileName);
    SetIniString(Section, 'Components', StringsToCommaString(WizardComponents), FileName);
  end
  else begin
    DeleteIniEntry(Section, 'SetupType', FileName);
    DeleteIniEntry(Section, 'Components', FileName);
  end;
  SetIniString(Section, 'Tasks', StringsToCommaString(WizardTasks), FileName);
end;
```

There are more items Inno Setup will load from the .inf file. See the LoadInf function. But again, not custom fields/pages. Just options that can otherwise be specified using command-line switches, like Silent, VerySilent, NoRestart, etc.

If you want custom fields in the .inf file, you have to implement them on your own:

Inno Setup Load defaults for custom installation settings from a file (.inf) for silent installation.

Body:
I created a installer with custom wizard pages. All works fine so far.
Next I wanted to create a settings file using /SAVEINF (to start the installer later on in silent mode) using the following command:

Installer.exe /SAVEINF="Unattended.txt"

After entering all user input and running the installer, I looked at the file created. The only user input I see is the installation location but missing all my input on the custom wizard pages. All I see is:

[Setup]
Lang=en
Dir=C:\temp
Group=MyProgram
NoIcons=0
Tasks=

Why? What do I need to do to have the custom wizard page values also in the settings file?

To be more specific.

I start the installer I've created with option to create a settings file using the /SAVEINF option on the commandline. I expected all items to be added to this file including the one from my custom wizard pages, but that's not the case. I only see the installation location from the standard setup page.

Of course I can add them manually and implement in the installer code to read them from the file, but I expected it to be automated.

Body:
Indeed, Inno Setup won't save any custom fields to the .inf file.

It will never save anything to the .inf file beyond the standard Lang, Dir, Group, NoIcons, SetupType, Components and Tasks items.

See SaveInf function in Inno Setup source code:

procedure SaveInf(const FileName: String);
const
  Section = 'Setup';
begin
  SetIniString(Section, 'Lang',
    PSetupLanguageEntry(Entries[seLanguage][ActiveLanguage]).Name, FileName);
  SetIniString(Section, 'Dir', WizardDirValue, FileName);
  SetIniString(Section, 'Group', WizardGroupValue, FileName);
  SetIniBool(Section, 'NoIcons', WizardNoIcons, FileName);
  if WizardSetupType <> nil then begin
    SetIniString(Section, 'SetupType', WizardSetupType.Name, FileName);
    SetIniString(Section, 'Components', StringsToCommaString(WizardComponents), FileName);
  end
  else begin
    DeleteIniEntry(Section, 'SetupType', FileName);
    DeleteIniEntry(Section, 'Components', FileName);
  end;
  SetIniString(Section, 'Tasks', StringsToCommaString(WizardTasks), FileName);
end;

There are more items Inno Setup will load from the .inf file. See the LoadInf function. But again, not custom fields/pages. Just options that can otherwise be specified using command-line switches, like Silent, VerySilent, NoRestart, etc.

If you want custom fields in the .inf file, you have to implement them on your own:

Inno Setup Load defaults for custom installation settings from a file (.inf) for silent installation.


问:
How to Encrypt outgoing https requests
Is there a way to completely encrypt the outgoing HTTPS requests from the software to the server ? i mean there are apps like Charles and Fiddler that can capture the HTTPS traffic and see everything like the Headers,URL,...
i don not want anyone to see or capture the traffic going from my app.
i'm using Delphi 10.1 VCL App</p>

答:
If you're using HTTPS and you are properly validating certificates as a browser would, there is no way for an intermediate to view URLs or headers, or content.  All they can see is which server you're communicating with.

The way Charles gets around this is that it presents its own non-genuine certificate, which won't validate, and proxies the communication.  If your app is validating certificates it would refuse to communicate with the Charles proxy.  If you viewed the Charles proxy with a web browser it would present an SSL certificate error.

If you trust that particular Charles proxy and want to add an exception in your client or browser, you can.  But it only allows that particular one - it doesn't mean anyone else can intercept your HTTPS, or read URLs, etc, using their own Charles proxy or similar.

Title: How to Encrypt outgoing https requests


问:
getting started with Tensor Flow
I am trying to learn tensor flow. In the given example how can we define rank and shape?? I mean how to find the rank and shape??</p>

```<code>    3 # a rank 0 tensor; this is a scalar with shape []
    [1. ,2., 3.] # a rank 1 tensor; this is a vector with shape [3]
    [[1., 2., 3.], [4., 5., 6.]] # a rank 2 tensor; a matrix with shape [2, 3]
    [[[1., 2., 3.]], [[7., 8., 9.]]] # a rank 3 tensor with shape [2, 1, 3]
</code>```

答:
Rank is the number of dimensions in the tensor. Refer to:
https://en.wikipedia.org/wiki/Tensor

The total number of indices required to identify each component uniquely is equal to the dimension of the array, and is called the order, degree or rank of the tensor.

Shape describes the number of elements in each dimension of the tensor.

In the given example,

```<code>[1. ,2., 3.]
</code>```

is a set of numbers with only one dimension. This is called a vector and generally used to represent a line.

```<code>[[1., 2., 3.], [4., 5., 6.]]
</code>```

is a set of numbers with two dimensions. This is called a matrix and generally represents a set of lines geometrically. (Each line described by elements in each of the inner brackets)

This can be generalized to more than two dimensions.
More generally, all these sets of numbers are known as Tensors. TensorFlow uses these sets of numbers as a data structure.

Title: getting started with Tensor Flow

Body:
I am trying to learn tensor flow. In the given example how can we define rank and shape?? I mean how to find the rank and shape??

    3 # a rank 0 tensor; this is a scalar with shape []
    [1. ,2., 3.] # a rank 1 tensor; this is a vector with shape [3]
    [[1., 2., 3.], [4., 5., 6.]] # a rank 2 tensor; a matrix with shape [2, 3]
    [[[1., 2., 3.]], [[7., 8., 9.]]] # a rank 3 tensor with shape [2, 1, 3]

Body:
Rank is the number of dimensions in the tensor. Refer to:
https://en.wikipedia.org/wiki/Tensor

The total number of indices required to identify each component uniquely is equal to the dimension of the array, and is called the order, degree or rank of the tensor.

Shape describes the number of elements in each dimension of the tensor.

In the given example,

[1. ,2., 3.]

is a set of numbers with only one dimension. This is called a vector and generally used to represent a line.

[[1., 2., 3.], [4., 5., 6.]]

is a set of numbers with two dimensions. This is called a matrix and generally represents a set of lines geometrically. (Each line described by elements in each of the inner brackets)

This can be generalized to more than two dimensions.
More generally, all these sets of numbers are known as Tensors. TensorFlow uses these sets of numbers as a data structure.


问:
Is mouse over Form?
This code is not working for me on Delphi XE:

http://delphi.about.com/cs/adptips2000/a/bltip0800_5.htm

```<code>procedure TForm1.FormDeactivate(Sender: TObject) ;
begin
   ReleaseCapture;
end;

procedure TForm1.FormMouseMove
(Sender: TObject; Shift: TShiftState; X,Y: Integer) ;
begin
  If GetCapture = 0 then
    SetCapture(Form1.Handle) ;
    if PtInRect(Rect(Form1.Left,
                    Form1.Top,
                    Form1.Left + Form1.Width,
                    Form1.Top + Form1.Height),
                    ClientToScreen(Point(x, y))) then
     Form1.Caption := 'Mouse is over form' else
     Form1.Caption := 'Mouse is outside of form';
end;
</code>```

No errors - it just has no effect.

Please help.

EDIT 1

It turned out the problem is not with the code, even mouse FormMouseEnter and FormMouseLeave are not working because I'm passing the form to a Unit I created with a function like this:

procedure Slide(Form: TForm; Show: Boolean);

I'm calling the Show method from inside this procedure. How can I overcome this problem?

Thanks.

EDIT 2

I don't want to use the function I posted now. I want to use what the people suggested below (FormMouseEnter and FormMouseLeave) but it's not working in my case as well.

答: You could use OnMouseEnter and OnMouseLeave events to keep track of whether the mouse is over the form or not without capturing the mouse cursor.

Title: Is mouse over Form?

Body:
This code is not working for me on Delphi XE:

http://delphi.about.com/cs/adptips2000/a/bltip0800_5.htm

procedure TForm1.FormDeactivate(Sender: TObject) ;
begin
   ReleaseCapture;
end;

procedure TForm1.FormMouseMove
(Sender: TObject; Shift: TShiftState; X,Y: Integer) ;
begin
  If GetCapture = 0 then
    SetCapture(Form1.Handle) ;
    if PtInRect(Rect(Form1.Left,
                    Form1.Top,
                    Form1.Left + Form1.Width,
                    Form1.Top + Form1.Height),
                    ClientToScreen(Point(x, y))) then
     Form1.Caption := 'Mouse is over form' else
     Form1.Caption := 'Mouse is outside of form';
end;

No errors - it just has no effect.

Please help.

EDIT 1

It turned out the problem is not with the code, even mouse FormMouseEnter and FormMouseLeave are not working because I'm passing the form to a Unit I created with a function like this:

procedure Slide(Form: TForm; Show: Boolean);

I'm calling the Show method from inside this procedure. How can I overcome this problem?

Thanks.

EDIT 2

I don't want to use the function I posted now. I want to use what the people suggested below (FormMouseEnter and FormMouseLeave) but it's not working in my case as well.


问:
How to detect a mobile device using jQuery
Is there a way to detect whether or not a user is using a mobile device in jQuery? Something similar to the CSS @media attribute? I would like to run a different script if the browser is on a handheld device.

The jQuery $.browser function is not what I am looking for.

答:
Use this    </p>

```<code>if( screen.width <= 480 ) {
    // is mobile
}
</code>```

Body:
Use this

if( screen.width <= 480 ) {
    // is mobile
}


问:
Is there any way to have multiple intents code flow in the chatbot created using Amazon Lex?
I am trying to build a conversation chatbot which has branching conversations resulting in different intents being called based on the results. Something like

A

|\

| C

|/

D

So the intent A is the trigger for the bot and based on inputs taken in A it might go to C for further data or go to D. I was going through the documentation but couldn't find anything to implement this kind of interface. How can i implement this kind of chat interface in Lex.

Thanks for your time and help

答:
This is possible by using lambda.

you have to write a middle ware service using aws lambda and then your lex service will call lambda service for the results and that result can be now trigger the next bot using lambda trigger service.

Might need lot of work around but it is possible.

For more information http://docs.aws.amazon.com/lex/latest/dg/using-lambda.html


问:
how to determine the the execution time, CPU and memory utilization of a shell script(test.sh)?
I need to know the complete execution time, CPU and memory utilization of a shell script that I have written. I want to execute the commands that outputs the CPU and memory utilization from the same script. I am more interested in real time CPU utilization rather than average time CPU utilization when the script finishes its execution.Is this feasible? OS - FreeBSD and linux

Please help.

答:
What I understood from your question is you want to know how much CPU is been utilized by your script. Then just after running your script capture the process id of that script/processes and use
ps -p  -o %cpu,%mem command  to see the CPU utilization </p>


问:
How to restrict calculated value to four decimal places
I want to limit decimal place till 4 for below code, how to do that,</p>

```<code>var a = Convert.ToDecimal( 80794992640) / (1024 * 1024);
</code>```

答:
This will round it to 4 decimal places:</p>

```<code>var a = Math.Round(Convert.ToDecimal( 80794992640) / (1024 * 1024), 4);
</code>```

Body:
I want to limit decimal place till 4 for below code, how to do that,

var a = Convert.ToDecimal( 80794992640) / (1024 * 1024);

Body:
This will round it to 4 decimal places:

var a = Math.Round(Convert.ToDecimal( 80794992640) / (1024 * 1024), 4);


问:
Ruby on Rails: Why the confirmation message does not appear in "link_to('delete', ...)"?
I have the following link next to one of my products:

```<code><%= link_to("Delete", {:action => 'destroy', :id => product.id}, :class => 'action', :confirm => 'Are you sure?') %>
</code>```

but when I click it, the confirmation box does not appear.

The generated HTML is:

```<code><a data-confirm="Are you sure ?" class="action" href="/products/destroy/48">Delete</a>
</code>```

Please advise.

答:
Ensure rails.js is being loaded on the page. The easiest way to accomplish this is with:</p>

```<code>javascript_include_tag :defaults
</code>```

Body:
I have the following link next to one of my products:

<%= link_to("Delete", {:action => 'destroy', :id => product.id}, :class => 'action', :confirm => 'Are you sure?') %>

but when I click it, the confirmation box does not appear.

The generated HTML is:

Delete

Please advise.

Body:
Ensure rails.js is being loaded on the page. The easiest way to accomplish this is with:

javascript_include_tag :defaults


问:
android numberpicker for floating point numbers
The user of our app should be able to adjust a floating point number. At the moment, I filled an ArrayAdapter with all possible values and attached it to a spinner.

This solution doesn't really meet our expectations, since the spinner dropdown box is way too tall. Is there a better way? I was looking at Numberpicker - but this seems to work only with Integer values.

Any ideas?

Thanks!

答:
Another solution is to combine two numberfields into one component. See the Money Picker Example. Its advantage is that you don't have to initialize all possible double values for your spinner.

You may also need to attach special digits formatting, like "00", "0123" or other, using java.lang.String.format() function. Example is here.

Add Double Picker xml-layout:

```<code><LinearLayout
  xmlns:android = "http://schemas.android.com/apk/res/android"
  android:layout_width = "fill_parent"
  android:layout_height = "wrap_content"
  android:gravity = "center">

  <NumberPicker
    android:id = "@+id/integer_picker"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:layout_gravity = "center"/>

  <TextView
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:layout_gravity = "center"
    android:padding = "5dp"
    android:text = "@string/local_separator"
    android:textSize = "20sp"/>

  <NumberPicker
    android:id = "@+id/fraction_picker"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:layout_gravity = "center"/>

  <TextView
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:layout_gravity = "center"
    android:padding = "5dp"
    android:text = "@string/measure_unit_sign"
    android:textSize = "20sp"/>

</LinearLayout>
</code>```

Add custom Double Picker class:

```<code>import android.content.Context;
import android.view.LayoutInflater;
import android.widget.NumberPicker;

/**
 * UI component for double (floating point) values. Can be used
 * for money and other measures.
 */
public class DoublePicker
  extends NumberPicker {

  private int decimals;
  private NumberPicker integerPicker;
  private NumberPicker fractionPicker;

  public DoublePicker(
    Context context) {

    super(
      context);

      LayoutInflater
        .from(
          context)
        .inflate(
          R.layout.double_picker,
          this);

      integerPicker =
        (NumberPicker) findViewById(
          R.id.integer_picker);

      fractionPicker =
        (NumberPicker) findViewById(
          R.id.fraction_picker);
  }

  public int getDecimals() {

    return decimals;
  }

  /**
   * Sets the amount of digits after separator.
   *
   * @param decimals Anount of decimals.
   */
  public void setDecimals(final int decimals) {

    this.decimals = decimals;

    this.setFormatter(new DoublePicker.Formatter() {

      @Override
      public String format(int i) {

        return String.format(
          "%." + decimals + "f",
          i);
      }
    });
  }

  public void setValue(double value) {

    integerPicker.setValue((int) value);

    fractionPicker.setValue(
      Integer.valueOf(
        String
          .valueOf(value)
          .split(".")
          [1]));
  }
}
</code>```

Use new Double Picker component in your activity xml:

```<code><com.example.DoublePicker
  android:id ="@+id/double_picker"
  android:layout_width ="match_parent"
  android:layout_height ="wrap_content" />
</code>```

Body:
Another solution is to combine two numberfields into one component. See the Money Picker Example. Its advantage is that you don't have to initialize all possible double values for your spinner.

You may also need to attach special digits formatting, like "00", "0123" or other, using java.lang.String.format() function. Example is here.

Add Double Picker xml-layout:

<LinearLayout
  xmlns:android = "http://schemas.android.com/apk/res/android"
  android:layout_width = "fill_parent"
  android:layout_height = "wrap_content"
  android:gravity = "center">

  <NumberPicker
    android:id = "@+id/integer_picker"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:layout_gravity = "center"/>

  <TextView
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:layout_gravity = "center"
    android:padding = "5dp"
    android:text = "@string/local_separator"
    android:textSize = "20sp"/>

  <NumberPicker
    android:id = "@+id/fraction_picker"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:layout_gravity = "center"/>

  <TextView
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:layout_gravity = "center"
    android:padding = "5dp"
    android:text = "@string/measure_unit_sign"
    android:textSize = "20sp"/>

</LinearLayout>

Add custom Double Picker class:

import android.content.Context;
import android.view.LayoutInflater;
import android.widget.NumberPicker;

/**
 * UI component for double (floating point) values. Can be used
 * for money and other measures.
 */
public class DoublePicker
  extends NumberPicker {

  private int decimals;
  private NumberPicker integerPicker;
  private NumberPicker fractionPicker;

  public DoublePicker(
    Context context) {

    super(
      context);

      LayoutInflater
        .from(
          context)
        .inflate(
          R.layout.double_picker,
          this);

      integerPicker =
        (NumberPicker) findViewById(
          R.id.integer_picker);

      fractionPicker =
        (NumberPicker) findViewById(
          R.id.fraction_picker);
  }

  public int getDecimals() {

    return decimals;
  }

  /**
   * Sets the amount of digits after separator.
   *
   * @param decimals Anount of decimals.
   */
  public void setDecimals(final int decimals) {

    this.decimals = decimals;

    this.setFormatter(new DoublePicker.Formatter() {

      @Override
      public String format(int i) {

        return String.format(
          "%." + decimals + "f",
          i);
      }
    });
  }

  public void setValue(double value) {

    integerPicker.setValue((int) value);

    fractionPicker.setValue(
      Integer.valueOf(
        String
          .valueOf(value)
          .split(".")
          [1]));
  }
}

Use new Double Picker component in your activity xml:

<com.example.DoublePicker
  android:id ="@+id/double_picker"
  android:layout_width ="match_parent"
  android:layout_height ="wrap_content" />


问:
json_decode doesn't work on my string
I have JSON Object which I have encoded like so

```<code>{
"id": "",
"steps": [
             {
        "target": "purchase_order_items_itemmaster_id",
        "title": "",
        "placement": "",
        "content": "",
        "xoffset": "",
        "yoffset": ""
              }
         ]
}
$JSONData = json_encode($finalData,JSON_PRETTY_PRINT);
</code>```

I am taking this JSON data and storing it in a file like so

```<code>File::put("path","var tour = \n [ \n\t $JSONData \n ];");
</code>```

which looks something like this in the file

```<code>    var tour =
 [
     {
    "id": "",
    "steps": [
        {
            "target": "purchase_order_items_itemmaster_id",
            "title": "",
            "placement": "",
            "content": "",
            "xoffset": "",
            "yoffset": ""
        }
    ]
}
 ];
</code>```

Now I am reading it back form the second line like so

```<code> [
     {
    "id": "",
    "steps": [
        {
            "target": "purchase_order_items_itemmaster_id",
            "title": "",
            "placement": "",
            "content": "",
            "xoffset": "",
            "yoffset": ""
        }
    ]
}
 ];
</code>```

The problem is when I want to decode it back it doesn't happen,this is how I am trying to do that,

```<code>$lines = file_get_contents("path",NULL,NULL,10);

$a = json_decode($lines);
</code>```

Now according to expected output the $a should have the decoded data but it has null.

Can someone point out the mistake?

答:
try to save data in file like

```<code>$fp = fopen('path', 'w');
fwrite($fp, json_encode($JSONData)); //if $JSONData is in string
fclose($fp);
</code>```

instead of

```<code>File::put("path","var tour = \n [ \n\t $JSONData \n ];");
</code>```

//and  read like

```<code>// Read JSON file
$json = file_get_contents('path');

//Decode JSON
$json_data = json_decode($json,true);

//Print data
print_r($json_data);
</code>```

Title: json_decode doesn't work on my string

Body:
I have JSON Object which I have encoded like so

{
"id": "",
"steps": [
             {
        "target": "purchase_order_items_itemmaster_id",
        "title": "",
        "placement": "",
        "content": "",
        "xoffset": "",
        "yoffset": ""
              }
         ]
}
$JSONData = json_encode($finalData,JSON_PRETTY_PRINT);

I am taking this JSON data and storing it in a file like so

File::put("path","var tour = \n [ \n\t $JSONData \n ];");

which looks something like this in the file

    var tour =
 [
     {
    "id": "",
    "steps": [
        {
            "target": "purchase_order_items_itemmaster_id",
            "title": "",
            "placement": "",
            "content": "",
            "xoffset": "",
            "yoffset": ""
        }
    ]
}
 ];

Now I am reading it back form the second line like so

 [
     {
    "id": "",
    "steps": [
        {
            "target": "purchase_order_items_itemmaster_id",
            "title": "",
            "placement": "",
            "content": "",
            "xoffset": "",
            "yoffset": ""
        }
    ]
}
 ];

The problem is when I want to decode it back it doesn't happen,this is how I am trying to do that,

$lines = file_get_contents("path",NULL,NULL,10);

$a = json_decode($lines);

Now according to expected output the $a should have the decoded data but it has null.

Can someone point out the mistake?

Body:
try to save data in file like

$fp = fopen('path', 'w');
fwrite($fp, json_encode($JSONData)); //if $JSONData is in string
fclose($fp);

instead of

File::put("path","var tour = \n [ \n\t $JSONData \n ];");

//and  read like

// Read JSON file
$json = file_get_contents('path');

//Decode JSON
$json_data = json_decode($json,true);

//Print data
print_r($json_data);


答:
I guess you can round it if you want to fix it to 4 digits:

```<code>var a = Math.Round(Convert.ToDecimal( 80794992640) / (1024 * 1024),4 );
</code>```

but if your concern is to restrict it in the display then you can just apply the restriction in the ToString method:

```<code>a.ToString("0.####");
</code>```

the latter method will keep the precision for the calculations but cut the precision only for display

Title: How to restrict calculated value to four decimal places

Body:
I guess you can round it if you want to fix it to 4 digits:

var a = Math.Round(Convert.ToDecimal( 80794992640) / (1024 * 1024),4 );

but if your concern is to restrict it in the display then you can just apply the restriction in the ToString method:

a.ToString("0.####");

the latter method will keep the precision for the calculations but cut the precision only for display


问:
Update a table column using a mapping table?
I have three tables: a, b, c. Table b is a mapping table for table a and table c. I am trying to update table a column = table c column.

When implementing the update, I receive an error:

[S0001][4104] The multi-part identifier could not be bound

```<code>UPDATE table_a
SET table_a.Sector = table_c.Sector
FROM table_a
INNER JOIN table_b
  ON table_a.business_ID = cast(table_b.business_id as BIGINT)
INNER JOIN table_c
  ON table_b.ACARA_SML_ID = table_c.ACARA_SML_ID
WHERE a.State = 'ABC';
</code>```

答:
Use UPDATE statement directly from SELECT clause :</p>

```<code> UPDATE table_a SET table_a.Sector = C.Sector
 FROM table_c C
 WHERE EXISTS
 ( SELECT 1 FROM table_b B B.ACARA_SML_ID = C.ACARA_SML_ID AND
              table_a.business_ID = CAST(B.business_id AS BIGINT)
 ) AND A.[STATE] = 'ABC'
</code>```

Body:
I have three tables: a, b, c. Table b is a mapping table for table a and table c. I am trying to update table a column = table c column.

When implementing the update, I receive an error:

[S0001][4104] The multi-part identifier could not be bound

UPDATE table_a
SET table_a.Sector = table_c.Sector
FROM table_a
INNER JOIN table_b
  ON table_a.business_ID = cast(table_b.business_id as BIGINT)
INNER JOIN table_c
  ON table_b.ACARA_SML_ID = table_c.ACARA_SML_ID
WHERE a.State = 'ABC';

Body:
Use UPDATE statement directly from SELECT clause :

 UPDATE table_a SET table_a.Sector = C.Sector
 FROM table_c C
 WHERE EXISTS
 ( SELECT 1 FROM table_b B B.ACARA_SML_ID = C.ACARA_SML_ID AND
              table_a.business_ID = CAST(B.business_id AS BIGINT)
 ) AND A.[STATE] = 'ABC'


问:
What does this code means?
```<code>namespace myApplication    {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}
</code>```

What is partial class Form1 : Form

and what is InitializeComponents();

and why it is used Form1 : Form instead of only Form1

答:
InitializeComponents(); is a function for initializing the values of the form. Please right click on it and click on Showdefinition to see its contents. It is used to assign values to labels, textbox, Buttons etc in your form.

public partial class Form1 : Form
 By using partial it is possible to write the definition of same class in two different source file in the same namespace.It will be treated as same during compilation.You can find a class with same name Form1 in your project which is created automatically.

Form1 is the name of the Form and : is used to inherit the properties of base class . Here Form represents System.Windows.Forms.Form. We are inheriting to access the properties and methods of base class.

Title: What does this code means?

Body:
namespace myApplication    {
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}

What is partial class Form1 : Form

and what is InitializeComponents();

and why it is used Form1 : Form instead of only Form1


问:
Checking if value in XML is undefined (Javascript)
(I hope this question isn't too silly I am pretty much a novice at javascript)
I am parsing through an XML file for titles of books and I find each title by doing this.

```<code>(xml).find('title')[i].childNodes[0].nodeValue
</code>```

right now, i is just a counter and the line is in a while loop.
The problem that I am having is my condition for the while loop. I want to stop iterating when there are no more titles in the xml to look for. Right now I am getting exceptions each time the xml runs out of titles.

I suppose I want to make the condition of my while loop something along the lines of this:

```<code>(while(xml).find('title')[i].childNodes[0].nodeValue != undefined)
</code>```

or even do a for loop along the lines of

```<code>for(i = 0; i < numberoftitles.length; i++)
</code>```

but I have no idea how to actually get the numberoftitles, or the syntax for the while loop.

答:
Assuming that you have the XML structure similar to below, and each BOOK element has TITLE in it:

```<code><BOOK>
  <TITLE>ABC><TITLE/>
  ..
</BOOK>
<BOOK>
  <TITLE>PQR</TITLE>
  ..
</BOOK>
</code>```

You can use the following to get all the TITLE values:

```<code>var tmp = xmlDoc.getElementsByTagName("TITLE");

for(var i = 0; i < tmp.length; i++)
{
  console.log(tmp[i].childNodes[0].nodeValue);
}
</code>```

Body:
(I hope this question isn't too silly I am pretty much a novice at javascript)
I am parsing through an XML file for titles of books and I find each title by doing this.

(xml).find('title')[i].childNodes[0].nodeValue

right now, i is just a counter and the line is in a while loop.
The problem that I am having is my condition for the while loop. I want to stop iterating when there are no more titles in the xml to look for. Right now I am getting exceptions each time the xml runs out of titles.

I suppose I want to make the condition of my while loop something along the lines of this:

(while(xml).find('title')[i].childNodes[0].nodeValue != undefined)

or even do a for loop along the lines of

for(i = 0; i < numberoftitles.length; i++)

but I have no idea how to actually get the numberoftitles, or the syntax for the while loop.

Body:
Assuming that you have the XML structure similar to below, and each BOOK element has TITLE in it:

<BOOK>
  <TITLE>ABC><TITLE/>
  ..
</BOOK>
<BOOK>
  <TITLE>PQR</TITLE>
  ..
</BOOK>

You can use the following to get all the TITLE values:

var tmp = xmlDoc.getElementsByTagName("TITLE");

for(var i = 0; i < tmp.length; i++)
{
  console.log(tmp[i].childNodes[0].nodeValue);
}


问:
Save Figure to new Image
I've done removal lines from image and I want to save (figure) it into a new image.

Line is removed:

So here's my code.

```<code>clc;              % Clear the command window.
close all;        % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures if you have the Image Processing Toolbox.
clear;            % Erase all existing variables. Or clearvars if you want.
workspace;        % Make sure the workspace panel is showing.
format short g;
format compact;
fontSize = 20;

grayImage = imread('tab1.png');
% Save this figure handle.
hFig1 = gcf;
% Get the dimensions of the image.
% numberOfColorBands should be = 1.
[rows, columns, numberOfColorBands] = size(grayImage);
if numberOfColorBands > 1
    % It's not really gray scale like we expected - it's color.
    % Convert it to gray scale by taking only the green channel.
    grayImage = grayImage(:, :, 2); % Take green channel.
end

binaryImage = grayImage < 240;
binaryImage(: ,1: 20) = false;
imshow(grayImage, []);
hold on;
cc = bwconncomp(binaryImage);
% Measure the bounding box of all blobs.
measurements = regionprops(cc, 'BoundingBox');
fprintf('Found %d regions\n', cc.NumObjects);
numSkinnyRegions = 0;
bboxes=cat(1,measurements.BoundingBox);
for k = 1 : cc.NumObjects
    figure(hFig1); % Switch to figure 1.
    print(gcf,'Figuree','-dpng');
    thisBB = measurements(k).BoundingBox
    % Draw a box around the region in cyan.
    hRect = rectangle('Position', thisBB, 'EdgeColor', 'c', 'LineWidth', 1);
    aspectRatio(k) = thisBB(4)/thisBB(3);
    if (thisBB(4) <= 3 || thisBB(3) <= 3) && (aspectRatio(k) > 4 || aspectRatio(k) < 1/4)
        numSkinnyRegions = numSkinnyRegions + 1;
        % Save it to a cell array, just in case we want to use it after the loop is done.
        croppedImages{numSkinnyRegions} = imcrop(binaryImage, thisBB);
        % Draw skinny regions in a different color
        delete(hRect); % Get rid of old one.
        hRect = rectangle('Position', thisBB);
        hRect.FaceColor = 'w';
        hRect.EdgeColor = 'w';
        hRect.LineWidth = 2;
   end
end

figure; imshow(grayImage)
</code>```

When I save the figure into a png file, the result is the image contained a black lines, different from what i got in figure.
saved image.

So what's wrong from my code? Did I put the code print(gcf,'Figuree','-dpng'); in a wrong line?

答: Ok now i got my own answer! Just use export_fig from mathworks file exchange. Cheers!

Title: Save Figure to new Image

Body:
I've done removal lines from image and I want to save (figure) it into a new image.

Line is removed:

So here's my code.

clc;              % Clear the command window.
close all;        % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures if you have the Image Processing Toolbox.
clear;            % Erase all existing variables. Or clearvars if you want.
workspace;        % Make sure the workspace panel is showing.
format short g;
format compact;
fontSize = 20;

grayImage = imread('tab1.png');
% Save this figure handle.
hFig1 = gcf;
% Get the dimensions of the image.
% numberOfColorBands should be = 1.
[rows, columns, numberOfColorBands] = size(grayImage);
if numberOfColorBands > 1
    % It's not really gray scale like we expected - it's color.
    % Convert it to gray scale by taking only the green channel.
    grayImage = grayImage(:, :, 2); % Take green channel.
end

binaryImage = grayImage < 240;
binaryImage(: ,1: 20) = false;
imshow(grayImage, []);
hold on;
cc = bwconncomp(binaryImage);
% Measure the bounding box of all blobs.
measurements = regionprops(cc, 'BoundingBox');
fprintf('Found %d regions\n', cc.NumObjects);
numSkinnyRegions = 0;
bboxes=cat(1,measurements.BoundingBox);
for k = 1 : cc.NumObjects
    figure(hFig1); % Switch to figure 1.
    print(gcf,'Figuree','-dpng');
    thisBB = measurements(k).BoundingBox
    % Draw a box around the region in cyan.
    hRect = rectangle('Position', thisBB, 'EdgeColor', 'c', 'LineWidth', 1);
    aspectRatio(k) = thisBB(4)/thisBB(3);
    if (thisBB(4) <= 3 || thisBB(3) <= 3) && (aspectRatio(k) > 4 || aspectRatio(k) < 1/4)
        numSkinnyRegions = numSkinnyRegions + 1;
        % Save it to a cell array, just in case we want to use it after the loop is done.
        croppedImages{numSkinnyRegions} = imcrop(binaryImage, thisBB);
        % Draw skinny regions in a different color
        delete(hRect); % Get rid of old one.
        hRect = rectangle('Position', thisBB);
        hRect.FaceColor = 'w';
        hRect.EdgeColor = 'w';
        hRect.LineWidth = 2;
   end
end

figure; imshow(grayImage)

When I save the figure into a png file, the result is the image contained a black lines, different from what i got in figure.
saved image.

So what's wrong from my code? Did I put the code print(gcf,'Figuree','-dpng'); in a wrong line?


问:
Derive parameter type with Roslyn
I have created the following object to walk my constructor:

```<code>internal class ConstructorWalker : CSharpSyntaxWalker
{
    private string className = String.Empty;
    private readonly SemanticModel semanticModel;
    private readonly Action<string> callback;

    public ConstructorWalker(Document document, Action<string> callback)
    {
        this.semanticModel = document.GetSemanticModelAsync().Result;
        this.callback = callback;
    }

    public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
    {
        var typeToMatch = typeof(Dictionary<string, Func<GenericMobileRequest, Result<object>, Task>>);
        var parameters = node.ParameterList;

        foreach (var param in parameters.ChildNodes()) {
            //This does not work... .Symbol is null
            var paramType = ((IParameterSymbol)semanticModel.GetSymbolInfo(param).Symbol).Type;
            if(paramType == typeToMatch) {
               //PROFIT!!!
            }
        }
</code>```

How can I determine the type of the parameter so I can ensure it is of the type I am interested in?

答:
Getting the actual Type of a parameter can't be done so easily with Roslyn. You can get the TypeSyntax and ITypeSymbol as shown below, but unless you use reflection you can't really get a Type object (as far as I know).

```<code>string typeToMatchString = "Dictionary<string, Func<Exception, HashSet<object>, Task>>"

foreach (var parameter in node.ParameterList.Parameters)
{
    var typeSyntax = parameter.Type;
    var typeSymbol = semanticModel.GetTypeInfo(typeSyntax).Type;

    // Maybe comparing the name is enough?
    if (typeSymbol.ToDisplayString() == typeToMatchString)
        //PROFIT???
}
</code>```

You might want to check out this related question as well.

Title: Derive parameter type with Roslyn

Body:
I have created the following object to walk my constructor:

internal class ConstructorWalker : CSharpSyntaxWalker
{
    private string className = String.Empty;
    private readonly SemanticModel semanticModel;
    private readonly Action<string> callback;

    public ConstructorWalker(Document document, Action<string> callback)
    {
        this.semanticModel = document.GetSemanticModelAsync().Result;
        this.callback = callback;
    }

    public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
    {
        var typeToMatch = typeof(Dictionary<string, Func<GenericMobileRequest, Result<object>, Task>>);
        var parameters = node.ParameterList;

        foreach (var param in parameters.ChildNodes()) {
            //This does not work... .Symbol is null
            var paramType = ((IParameterSymbol)semanticModel.GetSymbolInfo(param).Symbol).Type;
            if(paramType == typeToMatch) {
               //PROFIT!!!
            }
        }

How can I determine the type of the parameter so I can ensure it is of the type I am interested in?

Body:
Getting the actual Type of a parameter can't be done so easily with Roslyn. You can get the TypeSyntax and ITypeSymbol as shown below, but unless you use reflection you can't really get a Type object (as far as I know).

string typeToMatchString = "Dictionary<string, Func<Exception, HashSet<object>, Task>>"

foreach (var parameter in node.ParameterList.Parameters)
{
    var typeSyntax = parameter.Type;
    var typeSymbol = semanticModel.GetTypeInfo(typeSyntax).Type;

    // Maybe comparing the name is enough?
    if (typeSymbol.ToDisplayString() == typeToMatchString)
        //PROFIT???
}

You might want to check out this related question as well.


问:
filtering some strings but some of them not! with grepl
I am trying to filter some strings in the data. For example I want to filter out 'AxxBy' strings but there is this string 'AxxByy' I want to keep! x and y stands for number of digits!

Here is what I tried,

```<code>data <- data.frame(pair=paste(paste('A',c(seq(1:4),10,11),sep=''),paste('B',c(2,3,4,22,33,44),sep=''),sep=''))
    pair
1   A1B2
2   A2B3
3   A3B4
4  A4B22
5 A10B33
6 A11B44
</code>```

I want to remove those pairs starting with A1 but not A10 and A11. Same as for also B2 but keep B22! etc.

```<code>x <- c(paste('A',1,sep=''), paste('B',2,sep='')) # filtering conditions

library(dplyr)
df <- data%>%
  filter(!grepl(paste(x,collapse='|'),pair))

 pair
1 A2B3
2 A3B4
</code>```

In this post Filtering observations in dplyr in combination with grepl
it is possible to add line starting with "^x|xx$" by regex functions but I haven't seen any post if the filtering conditions defined outside of the pipe.

Expected output

```<code>  pair
    1   A2B33
    2   A3B4
    3   A4B22
    4   A10B33
    6   A11B44
</code>```

The thumb of rule is that; if there is two digits after 'A' put B so AxxB and !grepl everything for defined xx numbers in the x input. if there is only 'B' and one digit which is 'By' is given !grepl 'By$' not 'Byy' inputs. Of course this includes 'AxBy$' and 'AxxBy$' that's all. I still cannot generalize @alistaire solution!

答:
The OP has requested to filter out 'AxxBy' strings but wants to keep string 'AxxByy' (where 'x' and 'y' denote digits.

Often it is easier to specify what to keep than what to remove. To keep strings which obey the pattern 'AxxByy' the regular expression

```<code>"^A\\d{2}B\\d{2}$"
</code>```

can be used where ^ denotes the begin of the string, \\d{2} a sequence of exactly two digits, and $ the end of the string. A and B stand for themselves.

With this regular expression, dplyr, and  grepl() can be used to filter the input data frame DF:

```<code>library(dplyr)
#which rows are kept?
kept <- DF %>%
+   filter(grepl("^A\\d{2}B\\d{2}$", pair))
kept
#    pair
#1 A10B33
#2 A11B44

# which rows are removed?
removed <- DF %>%
+   filter(!grepl("^A\\d{2}B\\d{2}$", pair))
removed
#      pair
#1     A1B2
#2     A2B3
#3     A3B4
#4    A4B22
#5       AB
#6        A
#7        B
#8       A1
#9      A12
#10      B1
#11     B12
#12 AA12B34
#13 A12BB34
</code>```

Note that I've added some edge cases for demonstration.

BTW: dplyr is not required if only the vector pair needs to be filtered. So, in base R the alternative expressions

```<code>pair[grepl("^A\\d{2}B\\d{2}$", pair)]
grep("^A\\d{2}B\\d{2}$", pair, value = TRUE)
</code>```

both return the strings to keep:

```<code>[1] "A10B33" "A11B44"
</code>```

while

```<code>pair[!grepl("^A\\d{2}B\\d{2}$", pair)]
</code>```

returns the removed strings:

```<code> [1] "A1B2"    "A2B3"    "A3B4"    "A4B22"   "AB"      "A"       "B"       "A1"
 [9] "A12"     "B1"      "B12"     "AA12B34" "A12BB34"
</code>```

Data

As given by the OP but with some edge cases appended:

```<code># create vector of test patterns using paste0() instead of paste(..., sep = "")
pair <- paste0("A", c(1:4, 10, 11), "B", c(2, 3, 4, 22, 33, 44))
# alternatvely use sprintf()
pair <- sprintf("A%iB%i", c(1:4, 10, 11), c(2, 3, 4, 22, 33, 44))
# add some edge cases
pair <- append(pair, c("AB", "A", "B", "A1", "A12", "B1", "B12", "AA12B34", "A12BB34"))
# create data frame
DF <- data.frame(pair)
DF
#      pair
#1     A1B2
#2     A2B3
#3     A3B4
#4    A4B22
#5   A10B33
#6   A11B44
#7       AB
#8        A
#9        B
#10      A1
#11     A12
#12      B1
#13     B12
#14 AA12B34
#15 A12BB34
</code>```

Body:
I am trying to filter some strings in the data. For example I want to filter out 'AxxBy' strings but there is this string 'AxxByy' I want to keep! x and y stands for number of digits!

Here is what I tried,

data <- data.frame(pair=paste(paste('A',c(seq(1:4),10,11),sep=''),paste('B',c(2,3,4,22,33,44),sep=''),sep=''))
    pair
1   A1B2
2   A2B3
3   A3B4
4  A4B22
5 A10B33
6 A11B44

I want to remove those pairs starting with A1 but not A10 and A11. Same as for also B2 but keep B22! etc.

x <- c(paste('A',1,sep=''), paste('B',2,sep='')) # filtering conditions

library(dplyr)
df <- data%>%
  filter(!grepl(paste(x,collapse='|'),pair))

 pair
1 A2B3
2 A3B4

In this post Filtering observations in dplyr in combination with grepl
it is possible to add line starting with "^x|xx$" by regex functions but I haven't seen any post if the filtering conditions defined outside of the pipe.

Expected output

  pair
    1   A2B33
    2   A3B4
    3   A4B22
    4   A10B33
    6   A11B44

The thumb of rule is that; if there is two digits after 'A' put B so AxxB and !grepl everything for defined xx numbers in the x input. if there is only 'B' and one digit which is 'By' is given !grepl 'By$' not 'Byy' inputs. Of course this includes 'AxBy$' and 'AxxBy$' that's all. I still cannot generalize @alistaire solution!

Body:
The OP has requested to filter out 'AxxBy' strings but wants to keep string 'AxxByy' (where 'x' and 'y' denote digits.

Often it is easier to specify what to keep than what to remove. To keep strings which obey the pattern 'AxxByy' the regular expression

"^A\\d{2}B\\d{2}$"

can be used where ^ denotes the begin of the string, \\d{2} a sequence of exactly two digits, and $ the end of the string. A and B stand for themselves.

With this regular expression, dplyr, and  grepl() can be used to filter the input data frame DF:

library(dplyr)
#which rows are kept?
kept <- DF %>%
+   filter(grepl("^A\\d{2}B\\d{2}$", pair))
kept
#    pair
#1 A10B33
#2 A11B44

# which rows are removed?
removed <- DF %>%
+   filter(!grepl("^A\\d{2}B\\d{2}$", pair))
removed
#      pair
#1     A1B2
#2     A2B3
#3     A3B4
#4    A4B22
#5       AB
#6        A
#7        B
#8       A1
#9      A12
#10      B1
#11     B12
#12 AA12B34
#13 A12BB34

Note that I've added some edge cases for demonstration.

BTW: dplyr is not required if only the vector pair needs to be filtered. So, in base R the alternative expressions

pair[grepl("^A\\d{2}B\\d{2}$", pair)]
grep("^A\\d{2}B\\d{2}$", pair, value = TRUE)

both return the strings to keep:

[1] "A10B33" "A11B44"

while

pair[!grepl("^A\\d{2}B\\d{2}$", pair)]

returns the removed strings:

 [1] "A1B2"    "A2B3"    "A3B4"    "A4B22"   "AB"      "A"       "B"       "A1"
 [9] "A12"     "B1"      "B12"     "AA12B34" "A12BB34"

Data

As given by the OP but with some edge cases appended:

# create vector of test patterns using paste0() instead of paste(..., sep = "")
pair <- paste0("A", c(1:4, 10, 11), "B", c(2, 3, 4, 22, 33, 44))
# alternatvely use sprintf()
pair <- sprintf("A%iB%i", c(1:4, 10, 11), c(2, 3, 4, 22, 33, 44))
# add some edge cases
pair <- append(pair, c("AB", "A", "B", "A1", "A12", "B1", "B12", "AA12B34", "A12BB34"))
# create data frame
DF <- data.frame(pair)
DF
#      pair
#1     A1B2
#2     A2B3
#3     A3B4
#4    A4B22
#5   A10B33
#6   A11B44
#7       AB
#8        A
#9        B
#10      A1
#11     A12
#12      B1
#13     B12
#14 AA12B34
#15 A12BB34


问:
Using orWhere in bookshelf js object
I have build a query using bookshelf js.  When I use orWhere in the query it gives an error

Object has no method 'orWhere'.

Given below is my code

```<code>var filters = {};

// Restaurnat id is must
if (restaurant_id != undefined) {
    filters.restaurant_id = restaurant_id
} else {
    res.json({
        status: 422,
        message: "No restaurant id provided",
        data: ""
    });
}

var query = dp.CusOrder.query('where', filters);

if (customer_name != undefined) {
    var first_name = '%' + customer_name + '%';

    query.where('first_name', 'LIKE', first_name)
        .orWhere('last_name', 'LIKE', first_name);
}

query.fetchAll()
    .then(function(result) {
        res.json({
            data: result
        });
    });
</code>```

答:
Check out the bookshelf-eloquent extension which exposes many of the Knex.js functions directly on the bookshelf model. It also adds whereLike() and orWhereLike(). Your code would then look something like this:</p>

```<code>...

let query = dp.CusOrder.where(filters);

if (customer_name != undefined) {
    let first_name = '%' + customer_name + '%';

    query.whereLike('first_name', first_name)
        .orWhereLike('last_name', first_name);
}

let result = await query.fetchAll();
</code>```

Title: Using orWhere in bookshelf js object

Body:
I have build a query using bookshelf js.  When I use orWhere in the query it gives an error

Object has no method 'orWhere'.

Given below is my code

var filters = {};

// Restaurnat id is must
if (restaurant_id != undefined) {
    filters.restaurant_id = restaurant_id
} else {
    res.json({
        status: 422,
        message: "No restaurant id provided",
        data: ""
    });
}

var query = dp.CusOrder.query('where', filters);

if (customer_name != undefined) {
    var first_name = '%' + customer_name + '%';

    query.where('first_name', 'LIKE', first_name)
        .orWhere('last_name', 'LIKE', first_name);
}

query.fetchAll()
    .then(function(result) {
        res.json({
            data: result
        });
    });

Body:
Check out the bookshelf-eloquent extension which exposes many of the Knex.js functions directly on the bookshelf model. It also adds whereLike() and orWhereLike(). Your code would then look something like this:

...

let query = dp.CusOrder.where(filters);

if (customer_name != undefined) {
    let first_name = '%' + customer_name + '%';

    query.whereLike('first_name', first_name)
        .orWhereLike('last_name', first_name);
}

let result = await query.fetchAll();


问:
Where to put universal-router in React and how to define a link?
These are pretty basic questions, but the docs of universal-router don't explain this, and the examples it gives don't seem to work in my React project.

I have this in my index.js:

```<code>import Router from 'universal-router';
import { HomeComponent, HelpComponent, AboutComponent } from './home.jsx';

const routes = [
    { path: '/', action: () => <HomeComponent /> },
    { path: '/home', action: () => <HomeComponent /> },
    { path: '/about', action: () => <AboutComponent /> },
    { path: '/help', action: () => <HelpComponent /> },
    { path: '*', action: () => <h1>Nope.</h1> }
];

const router = new Router(routes);

router.resolve({ path: '/' }).then(component => {
    ReactDOM.render(component, document.getElementById('router-outlet'));
});

router.resolve({ path: '/help' }).then(component => {
    ReactDOM.render(component, document.getElementById('router-outlet'));
});

router.resolve({ path: '/about' }).then(component => {
    ReactDOM.render(component, document.getElementById('router-outlet'));
});
</code>```

And this in my App component, a very simple menu:

```<code>export class App extends React.Component {
    render() {
        return(
                <div>
                    <a href="/">Root</a> |
                    <a href="/home">Home</a> |
                    <a href="/help">Help</a> |
                    <a href="/about">About</a> |
                    <a href="/uijsklfdsse">404</a>
                </div>
                );
    }
}
</code>```

As you see, this is pretty straightforward, I am just trying to figure how to get this working. It is almost exactly what's written here, yet it doesn't work. For some reason it's always the AboutComponent which gets called, and it seems like the browser is refreshing the entire page when I click a link, so it's not behaving as a SPA. I have a feeling that I am putting the route definitions to the wrong place, but where am I supposed to put it? And is this how I am supposed to define links?

I am using universal-router because React-router says upon installation that it's deprecated and replaced by this thing. Let me know if it was a bad idea.

答:
I think you should call router.resolve only once. This seems the reason why your app is always ended up with AboutComponent. Try to remove this part from your index.js:

```<code>router.resolve({ path: '/help' }).then(component => {
    ReactDOM.render(component, document.getElementById('router-outlet'));
});

router.resolve({ path: '/about' }).then(component => {
    ReactDOM.render(component, document.getElementById('router-outlet'));
});
</code>```

Also, react-router is not deprecated. I recommend you to use react-router:
https://github.com/ReactTraining/react-router

Body:
These are pretty basic questions, but the docs of universal-router don't explain this, and the examples it gives don't seem to work in my React project.

I have this in my index.js:

import Router from 'universal-router';
import { HomeComponent, HelpComponent, AboutComponent } from './home.jsx';

const routes = [
    { path: '/', action: () => <HomeComponent /> },
    { path: '/home', action: () => <HomeComponent /> },
    { path: '/about', action: () => <AboutComponent /> },
    { path: '/help', action: () => <HelpComponent /> },
    { path: '*', action: () =>
Nope.
 }
];

const router = new Router(routes);

router.resolve({ path: '/' }).then(component => {
    ReactDOM.render(component, document.getElementById('router-outlet'));
});

router.resolve({ path: '/help' }).then(component => {
    ReactDOM.render(component, document.getElementById('router-outlet'));
});

router.resolve({ path: '/about' }).then(component => {
    ReactDOM.render(component, document.getElementById('router-outlet'));
});

And this in my App component, a very simple menu:

export class App extends React.Component {
    render() {
        return(

                    Root |
                    Home |
                    Help |
                    About |
                    404

                );
    }
}

As you see, this is pretty straightforward, I am just trying to figure how to get this working. It is almost exactly what's written here, yet it doesn't work. For some reason it's always the AboutComponent which gets called, and it seems like the browser is refreshing the entire page when I click a link, so it's not behaving as a SPA. I have a feeling that I am putting the route definitions to the wrong place, but where am I supposed to put it? And is this how I am supposed to define links?

I am using universal-router because React-router says upon installation that it's deprecated and replaced by this thing. Let me know if it was a bad idea.

Body:
I think you should call router.resolve only once. This seems the reason why your app is always ended up with AboutComponent. Try to remove this part from your index.js:

router.resolve({ path: '/help' }).then(component => {
    ReactDOM.render(component, document.getElementById('router-outlet'));
});

router.resolve({ path: '/about' }).then(component => {
    ReactDOM.render(component, document.getElementById('router-outlet'));
});

Also, react-router is not deprecated. I recommend you to use react-router:
https://github.com/ReactTraining/react-router


问:
May I get ng-model's key instead of value in ng-value?
I am trying to set up a radio selector based on an array and return the key instead of the value to the server.

Here is the array:

```<code>$scope.customer_types = ['a', 'b', 'c', 'd', 'other'];
</code>```

Here is the radio selector:

```<code><label style="margin-right:15px"><input type="radio" ng-model="ctype" ng-value="customer_type" name="customer_type">{{customer_type}}</label>
</code>```

Now $scope.ctype will store the selected customer type and return a number, for example if I select other it should send out 4 to the server. I can do a reverse filter for this but it seems to me if I can use something like ng-value="customer_type[key]" it would be a lot easier...

答:
Since you want the key to be the position of the element in the array, you could use $index to fetch the selected customer type.

function MyCtrl($scope) {
  $scope.customer_types = ['a', 'b', 'c', 'd', 'other'];
  $scope.selectedType = function(index) {
    $scope.ctype = index;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app ng-controller="MyCtrl">
  <div ng-repeat="customer_type in customer_types">
    <label style="margin-right:15px">
    <input type="radio" ng-value="$index" name="customer_type" ng-model="ctype" ng-click="selectedType($index)">{{customer_type}}</label>
  </div>

  Selected Customer type : {{ctype}}
</body></code>```

Body:
I am trying to set up a radio selector based on an array and return the key instead of the value to the server.

Here is the array:

$scope.customer_types = ['a', 'b', 'c', 'd', 'other'];

Here is the radio selector:

<input type="radio" ng-model="ctype" ng-value="customer_type" name="customer_type">{{customer_type}}

Now $scope.ctype will store the selected customer type and return a number, for example if I select other it should send out 4 to the server. I can do a reverse filter for this but it seems to me if I can use something like ng-value="customer_type[key]" it would be a lot easier...

Body:
Since you want the key to be the position of the element in the array, you could use $index to fetch the selected customer type.

function MyCtrl($scope) {
  $scope.customer_types = ['a', 'b', 'c', 'd', 'other'];
  $scope.selectedType = function(index) {
    $scope.ctype = index;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app ng-controller="MyCtrl">
  <div ng-repeat="customer_type in customer_types">
    <label style="margin-right:15px">
    <input type="radio" ng-value="$index" name="customer_type" ng-model="ctype" ng-click="selectedType($index)">{{customer_type}}</label>
  </div>

  Selected Customer type : {{ctype}}
</body>


问:
Designing RESTful web services with XMPP servers
We have a website which uses HTML, angular in the front end and java in the back-end. We use RESTful webservices to perform read and write operations to the back-end, as we have IOS and Android apps too. We have messaging service in our website and apps, I am trying to make it as fast as possible. I am doing some research and came along XMPP servers for faster messaging. Can I develop RESTful web services for XMPP servers? and which language and environment is best to do it?.

Thanks,
Mani

答:
I believe XMPP-FTW is the thing you are looking for.

This module takes away all of the XML and works by hooking to events which are passed between client and server using a transport in JSON.


问:
SQL update column twice
I have a string column (Col1) in table (Tab1). I want to write a script that removes '%' or '&' characters from the string values.

The select for this is the following:

```<code>SELECT REPLACE( Tab1.Col1, '&', ''),
       REPLACE(Tab1.Col1, '%', '')
FROM Table1 Tab1
WHERE Tab1.Col1 like '%[&]%'
      OR Tab1.Col1 like '%[%]%'
</code>```

Does this seem correct? If it is how would I convert this to any update statement? I tried the following:

```<code>UPDATE Tab1
SET Tab1.Col1 =  REPLACE( Tab1.Col1, '&', ''),
    Tab1.Col1 = REPLACE (Tab1.Col1, '%', '')
FROM Table1 Tab1
WHERE Tab1.Col1 like '%[&]%'
      OR Tab1.Col1 like '%[%]%'
</code>```

This doesn't work as you cant update column twice in SET.
Is there any other way I can do this? I know I'm probably doing something silly here so apologies for my ignorance.

Thanks in advance.

答:
As you don't say what RDBMS you are using, I'm avoiding things that are obviously non-portable:</p>

```<code>UPDATE Tab1
SET Tab1.Col1 = REPLACE(REPLACE(Tab1.Col1, '&', ''), '%', '')
WHERE Tab1.Col1 <> REPLACE(REPLACE(Tab1.Col1, '&', ''), '%', '');
</code>```

Title: SQL update column twice

Body:
I have a string column (Col1) in table (Tab1). I want to write a script that removes '%' or '&' characters from the string values.

The select for this is the following:

SELECT REPLACE( Tab1.Col1, '&', ''),
       REPLACE(Tab1.Col1, '%', '')
FROM Table1 Tab1
WHERE Tab1.Col1 like '%[&]%'
      OR Tab1.Col1 like '%[%]%'

Does this seem correct? If it is how would I convert this to any update statement? I tried the following:

UPDATE Tab1
SET Tab1.Col1 =  REPLACE( Tab1.Col1, '&', ''),
    Tab1.Col1 = REPLACE (Tab1.Col1, '%', '')
FROM Table1 Tab1
WHERE Tab1.Col1 like '%[&]%'
      OR Tab1.Col1 like '%[%]%'

This doesn't work as you cant update column twice in SET.
Is there any other way I can do this? I know I'm probably doing something silly here so apologies for my ignorance.

Thanks in advance.

Body:
As you don't say what RDBMS you are using, I'm avoiding things that are obviously non-portable:

UPDATE Tab1
SET Tab1.Col1 = REPLACE(REPLACE(Tab1.Col1, '&', ''), '%', '')
WHERE Tab1.Col1 <> REPLACE(REPLACE(Tab1.Col1, '&', ''), '%', '');


问:
Launch sublime text 3 in git bash from windows path: C:\Program Files (x86)\Sublime Text 3
I need to run sublime 3 on windows 10. Sublime installation directory is: C:\Program Files (x86)\Sublime Text 3.

I tried these;

```<code>$ c:/Program\ Files\(\x86\)/Sublime\ Text\ 3/sublime_text.exe

$ c:/Program\ Files\ (x86)/Sublime\ Text\ 3/sublime_text.exe

$ c:/Program\ Files(x86)/Sublime\ Text\ 3/sublime_text.exe;
</code>```

I get syntax error, and No such file or directory on several attempts.

答:
This is what i did.

Create a file .bash_profile under C:\Users\UserName

In .bash_profile file i typed it as

alias 'subl= "/c/Program Files/Sublime Text 3/subl.exe"'

Body:
I need to run sublime 3 on windows 10. Sublime installation directory is: C:\Program Files (x86)\Sublime Text 3.

I tried these;

$ c:/Program\ Files\(\x86\)/Sublime\ Text\ 3/sublime_text.exe

$ c:/Program\ Files\ (x86)/Sublime\ Text\ 3/sublime_text.exe

$ c:/Program\ Files(x86)/Sublime\ Text\ 3/sublime_text.exe;

I get syntax error, and No such file or directory on several attempts.


问:
Use Xcode 8 with iOS 11
I want to use Xcode 8 with iOS 11.

should I upgrade my Xcode. However, my code can't be built by the new compiler, so I want to stay with Xcode 8.

How can I achieve that?

Apple revealed several new iOS 11 features at WWDC 2017.

答:
As of now this is only for Debugging on iOS device, not Simulator

Xcode 8 could not support unless you have the DeviceSupport folder for the iOS 11 version.

You can download a Xcode 9 beta (latest Xcode 9) or get an DeviceSupport folder from other user.

Simply copy it to your folder or create an symbolic link

sudo ln -s /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.0\ \(15A372\) /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/11.0

reference: Use Xcode 7 with iOS 10

Title: Use Xcode 8 with iOS 11


问:
auto-width first of three columns by content
Maybe someone is able to help me:
I got three columns. The first column should get as much width as available. The second column should get the width that the content within it needs. The third column-width is fixed.

I prepared a fiddle with some content. To visualize what i want to get just take a look at the bottom row in the fiddle.

So taking a look at the first row, the second column should move straight before the right column and the first column get as much width as possible.

the css part:

```<code>.wrap {
  width: 100%;
}

.first {
  background-color: coral;
  float: left;
  min-width: 33%;
}

.second {
  background-color: lightblue;
  float: left;
}

.third {
  background-color: lightgreen;
  float: right;
  min-width: 25%;
}
</code>```

the html part:

```<code><div class="wrap">
  <div class="first">xxxxx</div>
  <div class="second">yyyy</div>
  <div class="third">zzzzzzz</div>
</div>
<br>
<br>
<br>
<div class="wrap">
  <div class="first"> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
    <br>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  </div>
  <div class="second">yyyyyyy</div>
  <div class="third ">zzzzzz</div>
</div>
</code>```

link to fiddle

答:
Try this:

Note: In class.third you can mention fixed width instead of
  min-width as per your requirement.

Check demo here

CSS:

```<code>.wrap {
  width: 100%;
  display: flex;
}

.first {
  background-color: coral;
  flex: 1 0 0;
  word-break: break-all;
}

.second {
  background-color: lightblue;
}

.third {
  background-color: lightgreen;
  min-width: 25%;
  word-break: break-all;
}
</code>```

Body:
Maybe someone is able to help me:
I got three columns. The first column should get as much width as available. The second column should get the width that the content within it needs. The third column-width is fixed.

I prepared a fiddle with some content. To visualize what i want to get just take a look at the bottom row in the fiddle.

So taking a look at the first row, the second column should move straight before the right column and the first column get as much width as possible.

the css part:

.wrap {
  width: 100%;
}

.first {
  background-color: coral;
  float: left;
  min-width: 33%;
}

.second {
  background-color: lightblue;
  float: left;
}

.third {
  background-color: lightgreen;
  float: right;
  min-width: 25%;
}

the html part:

xxxxx

yyyy

zzzzzzz

 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

yyyyyyy

zzzzzz

link to fiddle

Body:
Try this:

Note: In class.third you can mention fixed width instead of
  min-width as per your requirement.

Check demo here

CSS:

.wrap {
  width: 100%;
  display: flex;
}

.first {
  background-color: coral;
  flex: 1 0 0;
  word-break: break-all;
}

.second {
  background-color: lightblue;
}

.third {
  background-color: lightgreen;
  min-width: 25%;
  word-break: break-all;
}