问:
Psycopg2 db connection hangs on lost network connection

Problem description

I'm using psycopg2 to connect to my PostgreSQL database on a remote host. I open a connection and wait for requests, then for each request I run queries on the connection and return data.

But when the network connection is lost after the connection is already open the next db query hangs and I have to kill the program manually.

Details:

it hangs for at least 2 hours (I couldn't wait longer)

the "network down" situation is actually VPN going down (db host is accesible only by VPN)

I can't use asynchronous connection because I need transactions

python 2.6

psycopg 2.2.1

debian linux 6 and 7, 64bit

postgresql 8.4 and 9.1

What I want/need

I need some reliable way to detect a failed connection before running a query, so my program won't hang, or a way to make cursor.execute(..) raise an exception on failed connection.

Example:

```<code>import psycopg2
import time

conn = psycopg2.connect("host='dbs' dbname='foo' user='joe' password='x'")
time.sleep(10) # I manually turn VPN off during this sleep..
cu = conn.cursor()
cu.execute('SELECT 1') # <- hangs here
print cu.fetchone()
cu.commit()
</code>```

What have I tried (and what didn't work):

setting TCP timeout "globally" - before psycopg2 import, I added:

```<code>import socket
socket.setdefaulttimeout(10)
</code>```

setting TCP timeout on psycopg.connection's socket:

```<code>..
conn = psycopg2.connect(...
s = socket.fromfd(conn.fileno(), socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
..
</code>```

enabling keepalive for psycopg.connection's socket:

```<code>...
conn = psycopg2.connect(...
s = socket.fromfd(conn.fileno(), socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
...
</code>```

答:
Took a look at the socket timeout and after reading this and this, these settings worked for me</p>

```<code>s = socket.fromfd(connection.fileno(),
                  socket.AF_INET, socket.SOCK_STREAM)
# Enable sending of keep-alive messages
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
# Time the connection needs to remain idle before start sending
# keepalive probes
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, int(ceil(time)))
# Time between individual keepalive probes
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 1)
# The maximum number of keepalive probes should send before dropping
# the connection
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 3)
</code>```

Body:
Problem description

I'm using psycopg2 to connect to my PostgreSQL database on a remote host. I open a connection and wait for requests, then for each request I run queries on the connection and return data.

But when the network connection is lost after the connection is already open the next db query hangs and I have to kill the program manually.

Details:

it hangs for at least 2 hours (I couldn't wait longer)

the "network down" situation is actually VPN going down (db host is accesible only by VPN)

I can't use asynchronous connection because I need transactions

python 2.6

psycopg 2.2.1

debian linux 6 and 7, 64bit

postgresql 8.4 and 9.1

What I want/need

I need some reliable way to detect a failed connection before running a query, so my program won't hang, or a way to make cursor.execute(..) raise an exception on failed connection.

Example:

import psycopg2
import time

conn = psycopg2.connect("host='dbs' dbname='foo' user='joe' password='x'")
time.sleep(10) # I manually turn VPN off during this sleep..
cu = conn.cursor()
cu.execute('SELECT 1') # <- hangs here
print cu.fetchone()
cu.commit()

What have I tried (and what didn't work):

setting TCP timeout "globally" - before psycopg2 import, I added:

import socket
socket.setdefaulttimeout(10)

setting TCP timeout on psycopg.connection's socket:

..
conn = psycopg2.connect(...
s = socket.fromfd(conn.fileno(), socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
..

enabling keepalive for psycopg.connection's socket:

...
conn = psycopg2.connect(...
s = socket.fromfd(conn.fileno(), socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
...

Body:
Took a look at the socket timeout and after reading this and this, these settings worked for me

s = socket.fromfd(connection.fileno(),
                  socket.AF_INET, socket.SOCK_STREAM)
# Enable sending of keep-alive messages
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
# Time the connection needs to remain idle before start sending
# keepalive probes
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, int(ceil(time)))
# Time between individual keepalive probes
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 1)
# The maximum number of keepalive probes should send before dropping
# the connection
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 3)


来源: stackexchange

问:
Java libraries for converting between character encodings
The problem I am looking to solve is converting between unicode storage types. As I understand it, one character in UTF-8 can be represented by 1 to 4 bytes of data whereas a character in UTF-16 can be represented in 1-2, two bytes blocks of data. This variable length means it's a pain to convert between the two and produce something that is sensible in the english language. </p>

<p>What I am looking for is a library that would let me specify a language or locale, and a storage mechanism (utf-8 etc.) and have it produce a more sensible result. Am I dreaming in the clouds?  </p>

答:
It is sensible for a lot of character sets.  There's still a few that can't fit into Unicode, but not many.

First remember that the bytes are not characters, to deal with characters you need to convert them, and typically the easiest way to do that is to wrap a Byte Stream in a Reader (or Writer) which was constructed with the appropriate encoding / decoding set.

For a list of directly supported encodings, here's what comes with the JVM.

The key is not to use default Readers and Writers, as they use the platform's encoding.  Instead pick one encoding.  UTF-8 is good on disk size, poor on encoding / decoding performance; while UTF-32 is horrible on disk size and excellent on encoding / decoding performance.  UTF-16 is something of a compromise.  All UTF based encodings optimize to handle ASCII characters a bit more efficiently, so UTF-8 might beat UTF-16 if you are only dealing with mostly ASCII.

Note that you cannot convert bytes into a new character set, they are "casted" to the new character set.  That means if you want to convert bytes to a new character set, you must turn them into Strings or Characters and the get the bytes of the string in the new character set.

One way to read a byte stream as an InputStream with your own specified Character Set is to use a InputStreamReader constructed with an alternate character set.  Likewise, you need to use an OutputStreamWriter constructed with an alternate character set.

All files that you don't manage directly should use the platform character set (since that's probably what they will be) and be converted to the character set of choice when being saved or inputted into the program.

ContentLicense: CC BY-SA 2.5

Body:
The problem I am looking to solve is converting between unicode storage types. As I understand it, one character in UTF-8 can be represented by 1 to 4 bytes of data whereas a character in UTF-16 can be represented in 1-2, two bytes blocks of data. This variable length means it's a pain to convert between the two and produce something that is sensible in the english language.

What I am looking for is a library that would let me specify a language or locale, and a storage mechanism (utf-8 etc.) and have it produce a more sensible result. Am I dreaming in the clouds?


问:
Facebook Login not working in IOS SDK
I am struggling with the issue of Facebook login, Yesterday Facebook login working correctly but today when I run my app it's not working don't know why, why it's not working suddenly I already configured all things related to Facebook login in Facebook develop console everything is configured
Please help me out if you have any idea, I already enable Keychain sharing also.

Code for Facebook Login

```<code>@IBAction func onClickFacebookLoginAction(_ sender: Any) {

    var message = String()
    if Reachability.isConnectedToNetwork() == true{

        let loginView:FBSDKLoginManager = FBSDKLoginManager()
        loginView.loginBehavior = FBSDKLoginBehavior.web
        loginView.logIn(withReadPermissions: ["email","public_profile","user_friends"], from: self, handler: { (result, error) in
            if(error != nil){

                print("Error while try to login with facebook-\(error?.localizedDescription)")
            }else if (result?.isCancelled)!{

                print("User cancel the facebook login")
            }else{

                if result?.grantedPermissions != nil{
                    if (result?.grantedPermissions .contains("email"))!{
                        self.ShowProgressHUD()
                        self.fetchUserInfo()
                    }else{
                        message = message.appending("Facebook email permission error")
                        self.showAlertMessage(message: message, title: "")
                    }
                }
            }
        })
    }
}

func fetchUserInfo() -> Void {

    if (FBSDKAccessToken.current() != nil) {

        let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "/me", parameters:["fields": "id, first_name, last_name, name, email, picture"])
        graphRequest.start(completionHandler: { (connection, result, error) in

            if(error != nil){

                self.showAlertMessage(message: (error?.localizedDescription)!, title: "")

            }
            else
            {
                 print("Result is:\(result)")
                self.dictionary = result as! [String : AnyObject]
                let name = self.dictionary["name"] as!String
                let email = self.dictionary["email"] as! String
                let token = FBSDKAccessToken.current().tokenString

                print("name is -\(name)")
                print("email is -\(email)")
                print("token is -\(token)")

                DispatchQueue.main.async {

                    let SelectionViewObj = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
                    self.navigationController?.pushViewController(SelectionViewObj, animated: true)
                }
            }
        })
    }
}
</code>```

答:
This is the code i am using to authenticate facebook.its working like a charm.Just check or replace with this.</p>

```<code>self.fbLoginManager = FBSDKLoginManager.init()
fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
self.fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) -> Void in
    if (error == nil) {
        let fbloginresult : FBSDKLoginManagerLoginResult = result!
        if fbloginresult.grantedPermissions != nil && fbloginresult.grantedPermissions.contains("email") {
            if((FBSDKAccessToken.current()) != nil){
                FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id, first_name, last_name, email, gender, birthday, location"]).start(completionHandler: { (connection, result, error) -> Void in
                    if error != nil {
                        print(error?.localizedDescription ?? "error in facebook login...!")
                        return
                    }
                    if let dict = result as? NSDictionary {
                        print("facebook login result --->\n\(dict)")
                        guard let id = dict["id"] else {
                            print("Ooops... id = nil")
                            return
                        }
                        //  let firstName: String = dict["first_name"] as? String ?? ""
                       // let lastName : String = dict["last_name"] as? String ?? ""
                      //  let email : String = dict["email"] as? String ?? ""

                        self.fbLoginManager.logOut()
                    }
                })
            }
        } else {
            print("facebook ---> login canceled")
        }
    } else {
        print(error?.localizedDescription ?? "facebook login has error")
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Facebook Login not working in IOS SDK

Body:
I am struggling with the issue of Facebook login, Yesterday Facebook login working correctly but today when I run my app it's not working don't know why, why it's not working suddenly I already configured all things related to Facebook login in Facebook develop console everything is configured
Please help me out if you have any idea, I already enable Keychain sharing also.

Code for Facebook Login

@IBAction func onClickFacebookLoginAction(_ sender: Any) {

    var message = String()
    if Reachability.isConnectedToNetwork() == true{

        let loginView:FBSDKLoginManager = FBSDKLoginManager()
        loginView.loginBehavior = FBSDKLoginBehavior.web
        loginView.logIn(withReadPermissions: ["email","public_profile","user_friends"], from: self, handler: { (result, error) in
            if(error != nil){

                print("Error while try to login with facebook-\(error?.localizedDescription)")
            }else if (result?.isCancelled)!{

                print("User cancel the facebook login")
            }else{

                if result?.grantedPermissions != nil{
                    if (result?.grantedPermissions .contains("email"))!{
                        self.ShowProgressHUD()
                        self.fetchUserInfo()
                    }else{
                        message = message.appending("Facebook email permission error")
                        self.showAlertMessage(message: message, title: "")
                    }
                }
            }
        })
    }
}

func fetchUserInfo() -> Void {

    if (FBSDKAccessToken.current() != nil) {

        let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "/me", parameters:["fields": "id, first_name, last_name, name, email, picture"])
        graphRequest.start(completionHandler: { (connection, result, error) in

            if(error != nil){

                self.showAlertMessage(message: (error?.localizedDescription)!, title: "")

            }
            else
            {
                 print("Result is:\(result)")
                self.dictionary = result as! [String : AnyObject]
                let name = self.dictionary["name"] as!String
                let email = self.dictionary["email"] as! String
                let token = FBSDKAccessToken.current().tokenString

                print("name is -\(name)")
                print("email is -\(email)")
                print("token is -\(token)")

                DispatchQueue.main.async {

                    let SelectionViewObj = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
                    self.navigationController?.pushViewController(SelectionViewObj, animated: true)
                }
            }
        })
    }
}

Body:
This is the code i am using to authenticate facebook.its working like a charm.Just check or replace with this.

self.fbLoginManager = FBSDKLoginManager.init()
fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
self.fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) -> Void in
    if (error == nil) {
        let fbloginresult : FBSDKLoginManagerLoginResult = result!
        if fbloginresult.grantedPermissions != nil && fbloginresult.grantedPermissions.contains("email") {
            if((FBSDKAccessToken.current()) != nil){
                FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id, first_name, last_name, email, gender, birthday, location"]).start(completionHandler: { (connection, result, error) -> Void in
                    if error != nil {
                        print(error?.localizedDescription ?? "error in facebook login...!")
                        return
                    }
                    if let dict = result as? NSDictionary {
                        print("facebook login result --->\n\(dict)")
                        guard let id = dict["id"] else {
                            print("Ooops... id = nil")
                            return
                        }
                        //  let firstName: String = dict["first_name"] as? String ?? ""
                       // let lastName : String = dict["last_name"] as? String ?? ""
                      //  let email : String = dict["email"] as? String ?? ""

                        self.fbLoginManager.logOut()
                    }
                })
            }
        } else {
            print("facebook ---> login canceled")
        }
    } else {
        print(error?.localizedDescription ?? "facebook login has error")
    }
}


问:
Missing classes in google-cloud:0.18.0-alpha
I updated google-cloud dependency from 0.4.0 to 0.18.0-alpha

```<code>    <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud</artifactId>
        <version>0.18.0-alpha</version>
    </dependency>
</code>```

After version update, following classes are gone.

```<code>com.google.cloud.AuthCredentials
com.google.cloud.Page
</code>```

Which classes should I replace them with?

答:
Use com.google.api.gax.paging.Page instead of com.google.cloud.Page

Use com.google.auth.oauth2.ServiceAccountCredentials instead of com.google.cloud.AuthCredentials.

AuthCredentials.ServiceAccountAuthCredentialsclass is removed (see https://github.com/GoogleCloudPlatform/google-cloud-java/pull/1375).

Old usage

```<code>AuthCredentials.ServiceAccountAuthCredentials serviceAccountAuthCredentials = AuthCredentials
            .ServiceAccountAuthCredentials.createForJson(new FileInputStream(CREDENTIALS_FILE));
</code>```

New usage

```<code>ServiceAccountCredentials serviceAccountAuthCredentials = ServiceAccountCredentials.fromStream(new FileInputStream(CREDENTIALS_FILE));
</code>```

https://github.com/GoogleCloudPlatform/google-cloud-java/pull/1947

Some methods are renamed

builder() methods renamed to newBuilder()

getter/setter methods renamed to Java Bean naming standard. For example, BlobId.bucket() renamed to BlobId.getBucket().

Body:
I updated google-cloud dependency from 0.4.0 to 0.18.0-alpha

    <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud</artifactId>
        <version>0.18.0-alpha</version>
    </dependency>

After version update, following classes are gone.

com.google.cloud.AuthCredentials
com.google.cloud.Page

Which classes should I replace them with?

Body:
Use com.google.api.gax.paging.Page instead of com.google.cloud.Page

Use com.google.auth.oauth2.ServiceAccountCredentials instead of com.google.cloud.AuthCredentials.

AuthCredentials.ServiceAccountAuthCredentialsclass is removed (see https://github.com/GoogleCloudPlatform/google-cloud-java/pull/1375).

Old usage

AuthCredentials.ServiceAccountAuthCredentials serviceAccountAuthCredentials = AuthCredentials
            .ServiceAccountAuthCredentials.createForJson(new FileInputStream(CREDENTIALS_FILE));

New usage

ServiceAccountCredentials serviceAccountAuthCredentials = ServiceAccountCredentials.fromStream(new FileInputStream(CREDENTIALS_FILE));

https://github.com/GoogleCloudPlatform/google-cloud-java/pull/1947

Some methods are renamed

builder() methods renamed to newBuilder()

getter/setter methods renamed to Java Bean naming standard. For example, BlobId.bucket() renamed to BlobId.getBucket().


问:
ReferenceError: success is not defined - Angularjs
I am getting "ReferenceError: success is not defined" when doing a Restful call from controller to my node.js back end as follows:

authControllers.js:

```<code>authControllers.controller('authCtrl', ['$scope', '$location', '$window', 'UserService', 'AuthenticationService',
function authCtrl($scope, $location, $window, UserService, AuthenticationService) {
  $scope.me = function() {
    UserService.me(function(res) {
      $scope.myDetails = res;
    }, function() {
      console.log('Failed to fetch details');
      $rootScope.error = 'Failed to fetch details';
    })
  };
}]);
</code>```

html:

```<code><div class="row" data-ng-controller="authCtrl" data-ng-init="me()">
    <div class="col-lg-12">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <strong>Your Details</strong>
            </div>
            <div class="panel-body">
                <p>{{myDetails.data.username}}</p>
                <p>{{myDetails.data.email}}</p>
            </div>
        </div>
    </div>
</div>
</code>```

authServices.js:

```<code>authServices.factory('UserService',['$http', function($http) {
  return {
    me:function() {
    return $http.get(options.api.base_url + '/me').success(success).error(error)
    }
  }
}]);
</code>```

A successful nodeJs call is being received and it's returning data as well, but couldn't get it in the front end. Please help !

答: There's no way to access any DB from any framework that has been developed in javascript you need to have a server if you want to perform CURD operations first go through nodejs if you want server to be written in JS then you can go through rest calls in nodejs that will help you to develop your app. </p>

Body:
I am getting "ReferenceError: success is not defined" when doing a Restful call from controller to my node.js back end as follows:

authControllers.js:

authControllers.controller('authCtrl', ['$scope', '$location', '$window', 'UserService', 'AuthenticationService',
function authCtrl($scope, $location, $window, UserService, AuthenticationService) {
  $scope.me = function() {
    UserService.me(function(res) {
      $scope.myDetails = res;
    }, function() {
      console.log('Failed to fetch details');
      $rootScope.error = 'Failed to fetch details';
    })
  };
}]);

html:

                Your Details

{{myDetails.data.username}}

{{myDetails.data.email}}

authServices.js:

authServices.factory('UserService',['$http', function($http) {
  return {
    me:function() {
    return $http.get(options.api.base_url + '/me').success(success).error(error)
    }
  }
}]);

A successful nodeJs call is being received and it's returning data as well, but couldn't get it in the front end. Please help !


问:
jQuery code not working as I want
Sorry about the title I just don't know what to set it as. If you can think of a title for this question please tell me or edit, thanks. Now to the question. I have written some jQuery code which displays different boxes depending on which link is clicked. And when you click the link again all the boxes reappear which is exactly what I want. My problem is that when I click link1 then link2 and then go back to link1 all the images reappear. I don't want this to happen. I only want the boxes for link1 to appear. All the boxes should only show at the start and when you click a link twice.

$(".links").click(function(){
  var current_link = $(this);
  var images = $(".images")

  $(images).removeClass('hide');
  $(images).removeClass('show');

  var current = $(this).data("cat");
  $(images).addClass('hide');
  $('.'+current).addClass('show');

   $(current_link).click(function(){
      $(images).toggleClass('hide');
   });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul{
  list-style-type: none;
}

ul li{
  display: inline-block;
}

ul li a{
  font-size: 20px;
  padding: 10px;
  background-color: yellow;
}

.change{
  background-color: red;
}

.print{
  height: 100px;
  width: 100px;
  background-color: blue;
  display: inline-block;
}

.portfolio{
  height: 100px;
  width: 100px;
  background-color: red;
  display: inline-block;
}

.web{
  height: 100px;
  width: 100px;
  background-color: orange;
  display: inline-block;
}

.hide{
  display: none;
}

.show{
  display: inline-block;
}</code>```

link1

link2

link3

```

答:
You can add a condition on the links by adding a class .active and check if the link has that class, and use just the class .hide for the .images, no need to use class .show

See code snippet:

$(".links").click(function() {

  var current_link = $(this);
  var images = $(".images");
  var links = $(".links");
  var current = $(this).data("cat");

  if (current_link.hasClass('active')) {

    links.removeClass('active');
    images.removeClass('hide');

  } else {

    links.removeClass('active');
    current_link.addClass('active');
    images.addClass('hide');
    $('.' + current).removeClass('hide');
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  list-style-type: none;
}

ul li,
.images {
  display: inline-block;
}

ul li a {
  font-size: 20px;
  padding: 10px;
  background-color: yellow;
}

.change {
  background-color: red;
}

.images {
  height: 100px;
  width: 100px;
}

.print {
  background-color: blue;
}

.portfolio {
  background-color: red;
}

.web {
  background-color: orange;
}

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

link1

link2

link3

```

Title: jQuery code not working as I want

Body:
Sorry about the title I just don't know what to set it as. If you can think of a title for this question please tell me or edit, thanks. Now to the question. I have written some jQuery code which displays different boxes depending on which link is clicked. And when you click the link again all the boxes reappear which is exactly what I want. My problem is that when I click link1 then link2 and then go back to link1 all the images reappear. I don't want this to happen. I only want the boxes for link1 to appear. All the boxes should only show at the start and when you click a link twice.

$(".links").click(function(){
  var current_link = $(this);
  var images = $(".images")

  $(images).removeClass('hide');
  $(images).removeClass('show');

  var current = $(this).data("cat");
  $(images).addClass('hide');
  $('.'+current).addClass('show');

   $(current_link).click(function(){
      $(images).toggleClass('hide');
   });
});

ul{
  list-style-type: none;
}

ul li{
  display: inline-block;
}

ul li a{
  font-size: 20px;
  padding: 10px;
  background-color: yellow;
}

.change{
  background-color: red;
}

.print{
  height: 100px;
  width: 100px;
  background-color: blue;
  display: inline-block;
}

.portfolio{
  height: 100px;
  width: 100px;
  background-color: red;
  display: inline-block;
}

.web{
  height: 100px;
  width: 100px;
  background-color: orange;
  display: inline-block;
}

.hide{
  display: none;
}

.show{
  display: inline-block;
}

link1

link2

link3

Body:
You can add a condition on the links by adding a class .active and check if the link has that class, and use just the class .hide for the .images, no need to use class .show

See code snippet:

$(".links").click(function() {

  var current_link = $(this);
  var images = $(".images");
  var links = $(".links");
  var current = $(this).data("cat");

  if (current_link.hasClass('active')) {

    links.removeClass('active');
    images.removeClass('hide');

  } else {

    links.removeClass('active');
    current_link.addClass('active');
    images.addClass('hide');
    $('.' + current).removeClass('hide');
  }

});

ul {
  list-style-type: none;
}

ul li,
.images {
  display: inline-block;
}

ul li a {
  font-size: 20px;
  padding: 10px;
  background-color: yellow;
}

.change {
  background-color: red;
}

.images {
  height: 100px;
  width: 100px;
}

.print {
  background-color: blue;
}

.portfolio {
  background-color: red;
}

.web {
  background-color: orange;
}

.hide {
  display: none;
}

<ul>
  <li><a id="hi" class="links" data-cat="print" href="#">link1</a></li>
  <li><a class="links" data-cat="portfolio" href="#">link2</a></li>
  <li><a class="links" data-cat="web" href="#">link3</a></li>
</ul>

<div class="print images"></div>

<div class="portfolio images"></div>

<div class="web images"></div>

<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>


问:
How to detect when a custom tableview cell goes off the screen?
In my app I have a custom tableViewCell,

I also have a View Controller with a tableView, where I display custom tableViewCells.

Is there a method (ViewController method or TableViewCell method) which fires when tableViewCell goes off the screen, I need to make some Core Data updates in it for my cell.

(I need to know the method, because I need to update Core Data value of Timer() in my tableViewCell when it goes off the screen.)

答:
there is a tableView(_:didEndDisplaying:forRowAt:) delegate method:
https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614870-tableview


问:
Inserting a confirmation before deleting item from database using php and javascript
Adding a confirmation before deleting item from database. I have a search.php page where users can search throught the items which are listed in table, near each item there is a delete icon.  The delete icon calls a php function "deleteItem($id)" located in deleteItem.php.

Without any confirmation all is working fine. I call the function using the below:-

```<code><a href="deleteItem.php?id='.$id.'">Delete Icon</a>
</code>```

To add a confirmation before delete I am using a javascript function which is located in the head of the search.php and is show below:-

```<code><script type="text/javascript">
   function confirmDelete(id){
      if(confirm("Are you sure you want to delete this item?")){
          window.location = "deleteItem.php?id="+id;
   }else{
          // abort message ... //
      }
</script>
</code>```

I am using an onclick event to call the confirmDelete function as follows:-

```<code><a href="" onclick="confirmDelete('.$id.')">Delete Icon</a>
</code>```

Following some time trying to fix the issue it seems that the php page deleteItem.php?id="+id is never executed.  How can I call the deleteItem function located in the deleteItem.php file using window.location or any other method from the javascript function?

答:
I have solved this using the below:
 Delete Link <\a>

This is one of the solutions I have tried before posting the question.  I was forgetting the return.

Body:
Adding a confirmation before deleting item from database. I have a search.php page where users can search throught the items which are listed in table, near each item there is a delete icon.  The delete icon calls a php function "deleteItem($id)" located in deleteItem.php.

Without any confirmation all is working fine. I call the function using the below:-

Delete Icon

To add a confirmation before delete I am using a javascript function which is located in the head of the search.php and is show below:-

I am using an onclick event to call the confirmDelete function as follows:-

Delete Icon

Following some time trying to fix the issue it seems that the php page deleteItem.php?id="+id is never executed.  How can I call the deleteItem function located in the deleteItem.php file using window.location or any other method from the javascript function?


问:
Angular material md-select-header issue
i have below code

```<code><md-select class="" name="partners" ng-model="obj.con" data-md-container-class="selectdemoSelectHeader"
ng-disabled="notEditable('partners')">
    <md-select-header class="demo-select-header">
        <input ng-model="mdSelectHeader.searchTerm1" type="search" placeholder="{{'SEARCH' | T}}" class="demo-header-searchbox md-text">
    </md-select-header>
    <md-option ng-repeat="z in _.find(partnerContactList, { 'id': obj.par*1 }).contacts | filter:mdSelectHeader.searchTerm1" value="{{z.name}}">{{z.name}} ({{z.phone}},{{z.email}})</md-option>
</md-select>
</code>```

I have no idea why the  unable to type anything.

Another code in the same page could work if the control is rendered dynamically.

For example, if i use ng-if or ng-repeat to render the control dynamically, the input field cannot type anything, otherwise, it could work.

Anyone has fix on it?

Thanks.

答:
I believe this is a known issue with angular material library. However, there'a also a workaround in this discussion by using $event.stopPropagation() with angular built-in keydown.

```<code><md-select class="" name="partners" ng-model="obj.con" data-md-container-class="selectdemoSelectHeader"
ng-disabled="notEditable('partners')">
    <md-select-header class="demo-select-header">
        <input ng-model="mdSelectHeader.searchTerm1" type="search" placeholder="{{'SEARCH' | T}}" class="demo-header-searchbox md-text" ng-keydown="$event.stopPropagation()">
    </md-select-header>
    <md-option ng-repeat="z in _.find(partnerContactList, { 'id': obj.par*1 }).contacts | filter:mdSelectHeader.searchTerm1" value="{{z.name}}">{{z.name}} ({{z.phone}},{{z.email}})</md-option>
</md-select>
</code>```

Here's a working sample

Title: Angular material md-select-header issue

Body:
i have below code

<md-select class="" name="partners" ng-model="obj.con" data-md-container-class="selectdemoSelectHeader"
ng-disabled="notEditable('partners')">
    <md-select-header class="demo-select-header">
        <input ng-model="mdSelectHeader.searchTerm1" type="search" placeholder="{{'SEARCH' | T}}" class="demo-header-searchbox md-text">
    </md-select-header>
    <md-option ng-repeat="z in _.find(partnerContactList, { 'id': obj.par*1 }).contacts | filter:mdSelectHeader.searchTerm1" value="{{z.name}}">{{z.name}} ({{z.phone}},{{z.email}})</md-option>
</md-select>

I have no idea why the  unable to type anything.

Another code in the same page could work if the control is rendered dynamically.

For example, if i use ng-if or ng-repeat to render the control dynamically, the input field cannot type anything, otherwise, it could work.

Anyone has fix on it?

Thanks.

Body:
I believe this is a known issue with angular material library. However, there'a also a workaround in this discussion by using $event.stopPropagation() with angular built-in keydown.

<md-select class="" name="partners" ng-model="obj.con" data-md-container-class="selectdemoSelectHeader"
ng-disabled="notEditable('partners')">
    <md-select-header class="demo-select-header">
        <input ng-model="mdSelectHeader.searchTerm1" type="search" placeholder="{{'SEARCH' | T}}" class="demo-header-searchbox md-text" ng-keydown="$event.stopPropagation()">
    </md-select-header>
    <md-option ng-repeat="z in _.find(partnerContactList, { 'id': obj.par*1 }).contacts | filter:mdSelectHeader.searchTerm1" value="{{z.name}}">{{z.name}} ({{z.phone}},{{z.email}})</md-option>
</md-select>

Here's a working sample


问:
How is data, address and Instruction differentiated in Processor/Register/memory?
In Processor, how are Data, Address and instructions are differentiated? When a program is executed, how is processor differentiate instructions when everything is in 0s and 1s and registers load both data, addresses?

答:
When u start an application the eip (program counter) is set to where the text data of your program is, the text data is your code (0..1). From here it starts to execute instructions from the address that is putted on eip. The instructions are defined on a ROM near the cpu (or cache) if by any chance the cpu tries to execute something that is not an instruction it throws an exception (interrupt on this level). How he knows if it is instruction or not imagine that foreach instruction that is fetch he checks the rom like and hashtable to see if it is a valid instruction.

This is a very simple aproach of the problem because many things happen XDD.

ContentLicense: CC BY-SA 4.0


问:
artisan migration and seeding on sqlite in memory, always empty?
I'm trying to setup migration and seeding for a Laravel 5.4 application.
Migration and seeding are working for mysql db.
However when I try to run it on a sqlite in memory db, it seems to me that the db remains empty. Migration apparently run, but seeding complains about missing tables.

I simply configured sqlite as this in database.php

```<code>    'sqlite_memory' => [
        'driver' => 'sqlite',
        'database' => ':memory:',
        'prefix' => '',
    ],
</code>```

and I set my default connections as

```<code>'default' => env('DB_CONNECTION', 'test_sqlite'),
</code>```

I had eliminated all other kinds of connections from database.php and .env, just in case.

After succesfully running php artisan migrate, I enter sqlite3 and I see only a db:

```<code>Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .database
seq  name             file
---  ---------------
 0    main
sqlite> .dbinfo
sqlite> .tables
sqlite>
</code>```

It looks to me as there is nothing inside.
If I try php artisan db:seed, I get immediately "no such table error" on any table..

I did manage however to make sqlite work with file db.
I don't know how to troubleshoot this...

答: I believe an in-memory sqlite db only lasts as long as the current connection is open. These two lines 'Connected to a transient in-memory database.' and 'Use ".open FILENAME" to reopen on a persistent database.' suggest the db is no longer stored in memory after migrating. </p>

Body:
I'm trying to setup migration and seeding for a Laravel 5.4 application.
Migration and seeding are working for mysql db.
However when I try to run it on a sqlite in memory db, it seems to me that the db remains empty. Migration apparently run, but seeding complains about missing tables.

I simply configured sqlite as this in database.php

    'sqlite_memory' => [
        'driver' => 'sqlite',
        'database' => ':memory:',
        'prefix' => '',
    ],

and I set my default connections as

'default' => env('DB_CONNECTION', 'test_sqlite'),

I had eliminated all other kinds of connections from database.php and .env, just in case.

After succesfully running php artisan migrate, I enter sqlite3 and I see only a db:

Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .database
seq  name             file
---  ---------------
 0    main
sqlite> .dbinfo
sqlite> .tables
sqlite>

It looks to me as there is nothing inside.
If I try php artisan db:seed, I get immediately "no such table error" on any table..

I did manage however to make sqlite work with file db.
I don't know how to troubleshoot this...


问:
Go - void function and direct assignment
I have a little problem in Go language.
I have this struct:

```<code>type Time struct{
    hour,min,sec int
}
</code>```

And this function that initializes it:

```<code>func init_Time(t Time) (int,int,int){
    t.hour, t.min, t.sec = time.Now().Clock()
    return t.hour, t.min, t.sec
}
</code>```

And the main is:

```<code>func main(){
   var Tm Time
   Tm.hour, Tm.min, Tm.sec = init_Time(Tm)
   fmt.Printf("Time: %d:%d:%d", Tm.hour, Tm.min, Tm.sec)
}
</code>```

I have imported time package too. It works perfectly but I have 2 questions about it:

In my code, why is the assignment to the variables (hour,min,sec) twice done both in the init_Time function:

t.hour, t.min, t.sec = time.Now().Clock()

and in the main():

```<code>Tm.hour, Tm.min, Tm.sec = init_Time(Tm)
</code>```

Is it necessary or is my mistake?

Why if I modify the init_Time function by transforming it into a void function, it returns values "Time: 0:0:0" instead of the current time?

(Example:)

```<code>func init_Time(t Time) {
      t.hour, t.min, t.sec = time.Now().Clock()
}
...
func main(){
     var Tm Time
     init_Time(Tm)
     fmt.Printf("Time: %d:%d:%d", Tm.hour, Tm.min, Tm.sec)
}
</code>```

答:
Calling any function (or method) and passing values makes a copy of the values, and inside the function (or method) you can only modify the copy. Hence if you don't assign the return values in your first example to the fields of Time, changes made in init_Time() are lost when the function returns. This also answers your 2nd question.

If you want the caller to observe the changes, you must pass a pointer to your value, and have the function modify the pointed value. In this case it is not even required to return the (modified) value:

```<code>func InitTime(t *Time) {
  t.hour, t.min, t.sec = time.Now().Clock()
}
</code>```

Using it:

```<code>t := Time{}
InitTime(&t)
fmt.Printf("Time: %d:%d:%d\n", t.hour, t.min, t.sec)
</code>```

Output (try it on the Go Playground):

```<code>Time: 23:0:0
</code>```

(Note that the current time on the Go Playground always starts at 23:00:00.)

Also it's idiomatic to create a "constructor" like function:

```<code>func NewTime() *Time {
    t := &Time{}
    t.hour, t.min, t.sec = time.Now().Clock()
    return t
}
</code>```

Using it:

```<code>t2 := NewTime()
fmt.Printf("Time: %d:%d:%d\n", t2.hour, t2.min, t2.sec)
</code>```

Output is the same.

See related questions:

Golang Operator Overloading

Copy instances of type T, when any of the methods of a named type T have a pointer receiver

Body:
I have a little problem in Go language.
I have this struct:

type Time struct{
    hour,min,sec int
}

And this function that initializes it:

func init_Time(t Time) (int,int,int){
    t.hour, t.min, t.sec = time.Now().Clock()
    return t.hour, t.min, t.sec
}

And the main is:

func main(){
   var Tm Time
   Tm.hour, Tm.min, Tm.sec = init_Time(Tm)
   fmt.Printf("Time: %d:%d:%d", Tm.hour, Tm.min, Tm.sec)
}

I have imported time package too. It works perfectly but I have 2 questions about it:

In my code, why is the assignment to the variables (hour,min,sec) twice done both in the init_Time function:

t.hour, t.min, t.sec = time.Now().Clock()

and in the main():

Tm.hour, Tm.min, Tm.sec = init_Time(Tm)

Is it necessary or is my mistake?

Why if I modify the init_Time function by transforming it into a void function, it returns values "Time: 0:0:0" instead of the current time?

(Example:)

func init_Time(t Time) {
      t.hour, t.min, t.sec = time.Now().Clock()
}
...
func main(){
     var Tm Time
     init_Time(Tm)
     fmt.Printf("Time: %d:%d:%d", Tm.hour, Tm.min, Tm.sec)
}

Body:
Calling any function (or method) and passing values makes a copy of the values, and inside the function (or method) you can only modify the copy. Hence if you don't assign the return values in your first example to the fields of Time, changes made in init_Time() are lost when the function returns. This also answers your 2nd question.

If you want the caller to observe the changes, you must pass a pointer to your value, and have the function modify the pointed value. In this case it is not even required to return the (modified) value:

func InitTime(t *Time) {
  t.hour, t.min, t.sec = time.Now().Clock()
}

Using it:

t := Time{}
InitTime(&t)
fmt.Printf("Time: %d:%d:%d\n", t.hour, t.min, t.sec)

Output (try it on the Go Playground):

Time: 23:0:0

(Note that the current time on the Go Playground always starts at 23:00:00.)

Also it's idiomatic to create a "constructor" like function:

func NewTime() *Time {
    t := &Time{}
    t.hour, t.min, t.sec = time.Now().Clock()
    return t
}

Using it:

t2 := NewTime()
fmt.Printf("Time: %d:%d:%d\n", t2.hour, t2.min, t2.sec)

Output is the same.

See related questions:

Golang Operator Overloading

Copy instances of type T, when any of the methods of a named type T have a pointer receiver


问:
Find top 10 students mark using array of object
I recently had an interview,they asked me a small question
the question is follows

There is list of Students

```<code>    List<Student> students;

    Class Student{
     String rollNo;
     Map<String, Integer> marks ;
}
</code>```

Stdunt.marks is actually cobination of subject and mark

Should write an method which should return top 10 students array according to the subject.

```<code>List<Student> getTop10(String subjectName){
}
</code>```

答:
The answer i have given is blelow

```<code>private static void PrintTop5(ArrayList<Student> list,String subject){
    Collections.sort(list, new Comparator<Student>() {

        @Override
        public int compare(Student st1, Student st2) {
            // TODO Auto-generated method stub
            return  st2.getSubjectMark(subject) - st1.getSubjectMark(subject);
        }
    });

    ArrayList<Student> studentList = new ArrayList<Student>(list.subList(0,5));
    for(Student student : studentList){
        System.out.println(student.getRollNum() + " MARK : "+student.getSubjectMark(subject));
    }
}
</code>```

Student class look like below

```<code>package com.main;

import java.util.HashMap;

public class Student {

    private String rollNo;
    private HashMap<String, Integer> marks ;

    public Student(){
        marks = new HashMap<>();
    }

    public void setRollNumber(String number){
        this.rollNo = number;
    }

    public void setSubjectAndMark(String subName,int mark){
        this.marks.put(subName, mark);
    }

    public HashMap<String, Integer> getAllMarks(){
        return marks;
    }

    public int getSubjectMark(String subject){
        return marks.get(subject);
    }

    public String getRollNum(){
        return rollNo;
    }
}
</code>```

Body:
I recently had an interview,they asked me a small question
the question is follows

There is list of Students

    List<Student> students;

    Class Student{
     String rollNo;
     Map<String, Integer> marks ;
}

Stdunt.marks is actually cobination of subject and mark

Should write an method which should return top 10 students array according to the subject.

List<Student> getTop10(String subjectName){
}

Body:
The answer i have given is blelow

private static void PrintTop5(ArrayList<Student> list,String subject){
    Collections.sort(list, new Comparator<Student>() {

        @Override
        public int compare(Student st1, Student st2) {
            // TODO Auto-generated method stub
            return  st2.getSubjectMark(subject) - st1.getSubjectMark(subject);
        }
    });

    ArrayList<Student> studentList = new ArrayList<Student>(list.subList(0,5));
    for(Student student : studentList){
        System.out.println(student.getRollNum() + " MARK : "+student.getSubjectMark(subject));
    }
}

Student class look like below

package com.main;

import java.util.HashMap;

public class Student {

    private String rollNo;
    private HashMap<String, Integer> marks ;

    public Student(){
        marks = new HashMap<>();
    }

    public void setRollNumber(String number){
        this.rollNo = number;
    }

    public void setSubjectAndMark(String subName,int mark){
        this.marks.put(subName, mark);
    }

    public HashMap<String, Integer> getAllMarks(){
        return marks;
    }

    public int getSubjectMark(String subject){
        return marks.get(subject);
    }

    public String getRollNum(){
        return rollNo;
    }
}


问:
How c# wpf Button property name binding
This is My code.

Button Name="{Binding menu_id}"

I can't binding it with the field how can I do? Thanks.

答:
Name is what it is called and how you refer to it in your program. For example,

```<code><Button x:Name="myButton"/>
</code>```

You can then refer to your button by its name like this

```<code>myButton.Content = "Hello";
</code>```

To set the button's content you need to bind to Content like this

```<code><Button Content="{Binding ButtonText}"
</code>```

And have a property like this

```<code>private string buttonText= "Hello";
public string ButtonText
{
    get { return buttonText; }
}
</code>```

If you need to update your binding at any point you also need to implement INotifyPropertyChange. You might also want to look at your binding options to decide what kind of binding you need.

Title: How c# wpf Button property name binding

Body:
Name is what it is called and how you refer to it in your program. For example,

<Button x:Name="myButton"/>

You can then refer to your button by its name like this

myButton.Content = "Hello";

To set the button's content you need to bind to Content like this

<Button Content="{Binding ButtonText}"

And have a property like this

private string buttonText= "Hello";
public string ButtonText
{
    get { return buttonText; }
}

If you need to update your binding at any point you also need to implement INotifyPropertyChange. You might also want to look at your binding options to decide what kind of binding you need.


问:
How do I get one column with one row and one column with two rows nested in HTML/CSS
I'm looking for the easiest way to get a icon on the left vertical aligned with the two lines of text on the right.

What I'm struggling with is the way I have to organize my HTML. I can functionally build this, but I think it's not efficient/clean the way I do this (too much code). So any advice on how this problem can be tackled is highly appreciated :). A screenshot from what I want to achieve is below. I'm using Font Awesome and Bootstrap 3 for development.

Screenshot of what I want to achieve

答:
just add div display to table-row

https://jsfiddle.net/q2x9sLo9/

    Address

    Mirpur New Bazar Road, Dhaka-12101

```<code><div style="background-color:#00ced1;display: table-row;">
<i class="fa fa-envelope" style="float:left; padding:18px; background-color:#00ced1; color:white; font-size:40px"></i>
<div style="float:left; background-color:#00ced1; color:white;">
<h4>
E-mail
</h4><p>
example@info.com
</p>
</div>
</div>

<div style="background-color:#00ced1;display: table-row;">
<i class="fa fa-phone" style="float:left; padding:18px; background-color:#00ced1; color:white; font-size:59px"></i>
<div style="float:left; background-color:#00ced1; color:white;">
<h4>
Phone
</h4><p>
(732) 803-01 03
</p>
</div>``
</div>
</code>```

Body:
just add div display to table-row

https://jsfiddle.net/q2x9sLo9/

    Address

    Mirpur New Bazar Road, Dhaka-12101

<div style="background-color:#00ced1;display: table-row;">
<i class="fa fa-envelope" style="float:left; padding:18px; background-color:#00ced1; color:white; font-size:40px"></i>
<div style="float:left; background-color:#00ced1; color:white;">
<h4>
E-mail
</h4><p>
example@info.com
</p>
</div>
</div>

<div style="background-color:#00ced1;display: table-row;">
<i class="fa fa-phone" style="float:left; padding:18px; background-color:#00ced1; color:white; font-size:59px"></i>
<div style="float:left; background-color:#00ced1; color:white;">
<h4>
Phone
</h4><p>
(732) 803-01 03
</p>
</div>``
</div>


问:
Can I join table one more time to existing join?
I have following query:

```<code>SELECT *
FROM A
  JOIN B ON A.id = B.a_id
  JOIN C ON B.id = C.b_id
  JOIN D ON C.id = D.c_id;
</code>```

I need to join another table to it - table E.
But I need to join it on B.id and E.a_id.
Can I write query like that:

```<code>SELECT *
FROM A
  JOIN B ON A.id = B.a_id
  JOIN C ON B.id = C.b_id
  JOIN D ON C.id = D.c_id
  JOIN E ON B.id = E.a_id;
</code>```

Is this correct way of doing this?

答:
Yes, you can. Some tips for the join querys.

Try to use primary key in the ON clause, otherwise create index in this columns and avoid to use * choose just the columns that you need. For more information improve your question.

Body:
I have following query:

SELECT *
FROM A
  JOIN B ON A.id = B.a_id
  JOIN C ON B.id = C.b_id
  JOIN D ON C.id = D.c_id;

I need to join another table to it - table E.
But I need to join it on B.id and E.a_id.
Can I write query like that:

SELECT *
FROM A
  JOIN B ON A.id = B.a_id
  JOIN C ON B.id = C.b_id
  JOIN D ON C.id = D.c_id
  JOIN E ON B.id = E.a_id;

Is this correct way of doing this?


问:
Spark - avro data not visible when queried from hive
I am creating dataframe using spark avro like

```<code>dataframe.write.format("com.databricks.spark.avro").save(outputPath)
</code>```

The output path in my case will be like hdfs path + table_name + partition

The table table_name is already created in hive using AvroSerDe where the LOCATION is set to outputPath.

However the created dataframe is not visible when I do a select * for table_name from hive. What could be issue

答: ALTER Table ADD PARTITION fixed the issue</p>

Body:
I am creating dataframe using spark avro like

dataframe.write.format("com.databricks.spark.avro").save(outputPath)

The output path in my case will be like hdfs path + table_name + partition

The table table_name is already created in hive using AvroSerDe where the LOCATION is set to outputPath.

However the created dataframe is not visible when I do a select * for table_name from hive. What could be issue


问:
How to launch Excel files in specific order via cmd?
I have 2 excel sheets which uses cmd to open them. 3 cmd is used.

One calls for sheet1 (OPENEXCEL1.bat).

```<code>"D:\APPS\Microsoft Office\Office14\excel.exe" /e "C:\Users\Desktop\Sheet1.xlsx.
</code>```

Second calls for the sheet2 (OPENEXCEL2.bat).

```<code>"D:\APPS\Microsoft Office\Office12\excel.exe" /e "C:\Users\Desktop\Sheet2.xlsx.
</code>```

And the third acts as master calling for the previous 2 cmd.

```<code>start cmd /k call "OPENEXCEL1.bat"
start cmd /k call "OPENEXCEL2.bat"
</code>```

Currently the 2 excel sheets are connected via VBA where sheet2 obtain data from sheet1. If sheet1 opens first before sheet2, the data transfer is fine. However if sheet2 opens before sheet1, an error will occur.

When I used this cmd, I noticed that the sequence of Excel sheet opens is different at times. Meaning that sometimes sheet1 opens first resulting in no problems, or sometimes sheet2 opens first resulting in problems as stated earlier.

Considering I'm new to cmd, is there a command that I can use to tell cmd that I want sheet1 to open 1st then proceed to sheet2?

答:
As @Stephan said, there are some problems with your scripts. You can use only 1 script to fix the problems.

OpenExcel.bat

```<code>@echo off

"D:\Foo\Bar.xlsx"
timeout /t 5
"D:\Foo\Baz.xlsx"
</code>```

This would open Bar.xlsx, wait 5 seconds, and open Baz.xlsx

Body:
I have 2 excel sheets which uses cmd to open them. 3 cmd is used.

One calls for sheet1 (OPENEXCEL1.bat).

"D:\APPS\Microsoft Office\Office14\excel.exe" /e "C:\Users\Desktop\Sheet1.xlsx.

Second calls for the sheet2 (OPENEXCEL2.bat).

"D:\APPS\Microsoft Office\Office12\excel.exe" /e "C:\Users\Desktop\Sheet2.xlsx.

And the third acts as master calling for the previous 2 cmd.

start cmd /k call "OPENEXCEL1.bat"
start cmd /k call "OPENEXCEL2.bat"

Currently the 2 excel sheets are connected via VBA where sheet2 obtain data from sheet1. If sheet1 opens first before sheet2, the data transfer is fine. However if sheet2 opens before sheet1, an error will occur.

When I used this cmd, I noticed that the sequence of Excel sheet opens is different at times. Meaning that sometimes sheet1 opens first resulting in no problems, or sometimes sheet2 opens first resulting in problems as stated earlier.

Considering I'm new to cmd, is there a command that I can use to tell cmd that I want sheet1 to open 1st then proceed to sheet2?

Body:
As @Stephan said, there are some problems with your scripts. You can use only 1 script to fix the problems.

OpenExcel.bat

@echo off

"D:\Foo\Bar.xlsx"
timeout /t 5
"D:\Foo\Baz.xlsx"

This would open Bar.xlsx, wait 5 seconds, and open Baz.xlsx


问:
React Native ios app crashes when run outside of xcode with failed to scene-create after 19.88s error
My react native app is crashing when launched outside of Xcode with the following exception showing up in the crash report on the device logs for thread 0.

```<code>    Incident Identifier: DB5E0F81-977F-44B0-BD8B-FAAF33F98119
CrashReporter Key:   e3b8d0751b47b37db0d7d6fcc5dde46051f8d30c
Hardware Model:      iPhone7,1
Process:             crashTest [388]
Path:                /var/mobile/Containers/Bundle/Application/CE56E818-7288-4A39-8220-16E17158C916/crashTest.app/crashTest
Identifier:          org.reactjs.native.example.crashTest
Version:             1 (1.0)
Code Type:           ARM-64 (Native)
Parent Process:      launchd [1]

Date/Time:           2017-04-25 12:42:30.30 -0400
Launch Time:         2017-04-25 12:42:10.10 -0400
OS Version:          iOS 9.1 (13B143)
Report Version:      105

Exception Type:  00000020
Exception Codes: 0x000000008badf00d
Exception Note:  SIMULATED (this is NOT a crash)
Highlighted by Thread:  0

Application Specific Information:
org.reactjs.native.example.crashTest failed to scene-create after 19.92s (launch took 0.08s of total time limit 20.00s)

Elapsed total CPU time (seconds): 9.230 (user 9.230, system 0.000), 23% CPU
Elapsed application CPU time (seconds): 0.113, 0% CPU

Filtered syslog:
None found

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0:
0   libsystem_kernel.dylib          0x0000000199ff0a7c semaphore_wait_trap + 8
1   libdispatch.dylib               0x0000000199ece614 _dispatch_semaphore_wait_slow + 244
2   CFNetwork                       0x0000000184246ac0 CFURLConnectionSendSynchronousRequest + 288
3   CFNetwork                       0x000000018426a07c +[NSURLConnection sendSynchronousRequest:returningResponse:error:] + 120
4   crashTest                       0x0000000100128858 -[RCTBundleURLProvider isPackagerRunning:] (RCTBundleURLProvider.m:76)
5   crashTest                       0x0000000100128b00 -[RCTBundleURLProvider guessPackagerHost] (RCTBundleURLProvider.m:92)
6   crashTest                       0x0000000100128d10 -[RCTBundleURLProvider packagerServerHost] (RCTBundleURLProvider.m:106)
7   crashTest                       0x0000000100128ed4 -[RCTBundleURLProvider jsBundleURLForBundleRoot:fallbackResource:] (RCTBundleURLProvider.m:123)
8   crashTest                       0x000000010006a8cc -[AppDelegate application:didFinishLaunchingWithOptions:] (AppDelegate.m:21)
9   UIKit                           0x000000018a0f5324 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 400
10  UIKit                           0x000000018a323acc -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 2904
11  UIKit                           0x000000018a327e0c -[UIApplication _runWithMainScene:transitionContext:completion:] + 1656
12  UIKit                           0x000000018a324f50 -[UIApplication workspaceDidEndTransaction:] + 168
13  FrontBoardServices              0x000000018e90b7c4 -[FBSSerialQueue _performNext] + 184
14  FrontBoardServices              0x000000018e90bb44 -[FBSSerialQueue _performNextFromRunLoopSource] + 56
15  CoreFoundation                  0x0000000184aa4544 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
16  CoreFoundation                  0x0000000184aa3fd8 __CFRunLoopDoSources0 + 540
17  CoreFoundation                  0x0000000184aa1cd8 __CFRunLoopRun + 724
18  CoreFoundation                  0x00000001849d0ca0 CFRunLoopRunSpecific + 384
19  UIKit                           0x000000018a0ee1c8 -[UIApplication _run] + 460
20  UIKit                           0x000000018a0e8ffc UIApplicationMain + 204
21  crashTest                       0x000000010006ad08 main (main.m:16)
22  libdyld.dylib                   0x0000000199eee8b8 start + 4
</code>```

I understand that my app is taking too long to launch and display. If I run directly from Xcode with my device tethered there are no issues (but it does take forever to launch)

I am testing this with the default react project produced with react-native init

When I build the project in Xcode I see the following warning:

```<code>[tid:com.facebook.react.JavaScript][RCTModuleData.mm:220] RCTBridge required dispatch_sync to load RCTDevSettings. This may lead to deadlocks
</code>```

I am new to react-native, and I am assuming maybe this is running in some sort of dev mode that does not allow me to launch the app when un-tethered or on a different network? Are there special instructions I am missing that I need to follow when building the app to run independently on the device without having to archive the app in Xcode?

答: Check if you're connected to the same WiFi network. Just had this.</p>

Body:
My react native app is crashing when launched outside of Xcode with the following exception showing up in the crash report on the device logs for thread 0.

    Incident Identifier: DB5E0F81-977F-44B0-BD8B-FAAF33F98119
CrashReporter Key:   e3b8d0751b47b37db0d7d6fcc5dde46051f8d30c
Hardware Model:      iPhone7,1
Process:             crashTest [388]
Path:                /var/mobile/Containers/Bundle/Application/CE56E818-7288-4A39-8220-16E17158C916/crashTest.app/crashTest
Identifier:          org.reactjs.native.example.crashTest
Version:             1 (1.0)
Code Type:           ARM-64 (Native)
Parent Process:      launchd [1]

Date/Time:           2017-04-25 12:42:30.30 -0400
Launch Time:         2017-04-25 12:42:10.10 -0400
OS Version:          iOS 9.1 (13B143)
Report Version:      105

Exception Type:  00000020
Exception Codes: 0x000000008badf00d
Exception Note:  SIMULATED (this is NOT a crash)
Highlighted by Thread:  0

Application Specific Information:
org.reactjs.native.example.crashTest failed to scene-create after 19.92s (launch took 0.08s of total time limit 20.00s)

Elapsed total CPU time (seconds): 9.230 (user 9.230, system 0.000), 23% CPU
Elapsed application CPU time (seconds): 0.113, 0% CPU

Filtered syslog:
None found

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0:
0   libsystem_kernel.dylib          0x0000000199ff0a7c semaphore_wait_trap + 8
1   libdispatch.dylib               0x0000000199ece614 _dispatch_semaphore_wait_slow + 244
2   CFNetwork                       0x0000000184246ac0 CFURLConnectionSendSynchronousRequest + 288
3   CFNetwork                       0x000000018426a07c +[NSURLConnection sendSynchronousRequest:returningResponse:error:] + 120
4   crashTest                       0x0000000100128858 -[RCTBundleURLProvider isPackagerRunning:] (RCTBundleURLProvider.m:76)
5   crashTest                       0x0000000100128b00 -[RCTBundleURLProvider guessPackagerHost] (RCTBundleURLProvider.m:92)
6   crashTest                       0x0000000100128d10 -[RCTBundleURLProvider packagerServerHost] (RCTBundleURLProvider.m:106)
7   crashTest                       0x0000000100128ed4 -[RCTBundleURLProvider jsBundleURLForBundleRoot:fallbackResource:] (RCTBundleURLProvider.m:123)
8   crashTest                       0x000000010006a8cc -[AppDelegate application:didFinishLaunchingWithOptions:] (AppDelegate.m:21)
9   UIKit                           0x000000018a0f5324 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 400
10  UIKit                           0x000000018a323acc -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 2904
11  UIKit                           0x000000018a327e0c -[UIApplication _runWithMainScene:transitionContext:completion:] + 1656
12  UIKit                           0x000000018a324f50 -[UIApplication workspaceDidEndTransaction:] + 168
13  FrontBoardServices              0x000000018e90b7c4 -[FBSSerialQueue _performNext] + 184
14  FrontBoardServices              0x000000018e90bb44 -[FBSSerialQueue _performNextFromRunLoopSource] + 56
15  CoreFoundation                  0x0000000184aa4544 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
16  CoreFoundation                  0x0000000184aa3fd8 __CFRunLoopDoSources0 + 540
17  CoreFoundation                  0x0000000184aa1cd8 __CFRunLoopRun + 724
18  CoreFoundation                  0x00000001849d0ca0 CFRunLoopRunSpecific + 384
19  UIKit                           0x000000018a0ee1c8 -[UIApplication _run] + 460
20  UIKit                           0x000000018a0e8ffc UIApplicationMain + 204
21  crashTest                       0x000000010006ad08 main (main.m:16)
22  libdyld.dylib                   0x0000000199eee8b8 start + 4

I understand that my app is taking too long to launch and display. If I run directly from Xcode with my device tethered there are no issues (but it does take forever to launch)

I am testing this with the default react project produced with react-native init

When I build the project in Xcode I see the following warning:

[tid:com.facebook.react.JavaScript][RCTModuleData.mm:220] RCTBridge required dispatch_sync to load RCTDevSettings. This may lead to deadlocks

I am new to react-native, and I am assuming maybe this is running in some sort of dev mode that does not allow me to launch the app when un-tethered or on a different network? Are there special instructions I am missing that I need to follow when building the app to run independently on the device without having to archive the app in Xcode?


问:
JS arguments.forEach is not a function
So this code works perfectly

```<code>var arr = [1, 2, 3, 4];
arr.forEach(function (el) {
    console.log(el);
})
</code>```

But if i try to do this:

```<code>function printArgsInfo() {
    arguments.forEach(function (el) {
        console.log(el);
    });
}
printArgsInfo(2, 3, 2.5, -110.5564, false);
</code>```

arguments.forEach is not a function

Even though arguments is an array and if Itry to do this with a for in loop it still works.

答:
arguments is an array-like object, but not an array:

var doThing = function() {
    console.log(arguments.constructor.name)
    console.log([].constructor.name)
}

doThing("someArgument")

```

<p>Will return <code>Object</code> for <code>arguments</code> and <code>Array</code> for the empty array <code>[]</code>.</p>

<h2>ES6 and newer</h2>

<p>With ES6, you could use rest parameters <code>...</code>, as <em>torazaburo</em> suggests.</p>

<blockquote>
  <p>The <strong>rest parameter</strong> syntax allows us to represent an indefinite number of arguments as an array.</p>
</blockquote>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function printArgsInfo(...args) {
    args.forEach(el => console.log(el));
}

printArgsInfo(2, 3, 2.5, -110.5564, false);</code>```

ES5 and older

For ES5 and older, you could borrow the method from Array#forEach and call it with argument as thisArg.

function printArgsInfo() {
    [].forEach.call(arguments, function (el) {
        console.log(el);
    });
}

printArgsInfo(2, 3, 2.5, -110.5564, false);```

Title: JS arguments.forEach is not a function

Body:
So this code works perfectly

var arr = [1, 2, 3, 4];
arr.forEach(function (el) {
    console.log(el);
})

But if i try to do this:

function printArgsInfo() {
    arguments.forEach(function (el) {
        console.log(el);
    });
}
printArgsInfo(2, 3, 2.5, -110.5564, false);

arguments.forEach is not a function

Even though arguments is an array and if Itry to do this with a for in loop it still works.

Body:
arguments is an array-like object, but not an array:

var doThing = function() {
    console.log(arguments.constructor.name)
    console.log([].constructor.name)
}

doThing("someArgument")

Will return Object for arguments and Array for the empty array [].

ES6 and newer

With ES6, you could use rest parameters ..., as torazaburo suggests.

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

function printArgsInfo(...args) {
    args.forEach(el => console.log(el));
}

printArgsInfo(2, 3, 2.5, -110.5564, false);

ES5 and older

For ES5 and older, you could borrow the method from Array#forEach and call it with argument as thisArg.

function printArgsInfo() {
    [].forEach.call(arguments, function (el) {
        console.log(el);
    });
}

printArgsInfo(2, 3, 2.5, -110.5564, false);


答:
Even though arguments is an array

It isn't.

function myFunc() {
    console.log(arguments instanceof Array);
}

myFunc(1,2,3);```

The Arguments object is an array-like object. It isn't an array.

Title: JS arguments.forEach is not a function

Body:
Even though arguments is an array

It isn't.

function myFunc() {
    console.log(arguments instanceof Array);
}

myFunc(1,2,3);

The Arguments object is an array-like object. It isn't an array.


问:
PouchDB sync deleted DB
I have a remote CouchDB named 'mydb', and a local PouchDB at client side sync with it. The situation is client can go offline and back, so during client offline, I DELETED the remote 'mydb' and re-create one with same name and added some random new files to the new db.

When the client come back online, is it going to sync back the old file and overwrite those with same name?

答:
If you need bi-directional replication you might do:

```<code>// use "sync"
localDB.sync(remoteDB)

// another option is to use "replicate" with both "to" and "from"
localDB.replicate.to(remoteDB)
localDB.replicate.from(remoteDB)
</code>```

If you need uni-directional replication, you might do:

```<code>// use "replicate" with only "to"
localDB.replicate.to(remoteDB)
</code>```

Take a look at this.

Title: PouchDB sync deleted DB

Body:
If you need bi-directional replication you might do:

// use "sync"
localDB.sync(remoteDB)

// another option is to use "replicate" with both "to" and "from"
localDB.replicate.to(remoteDB)
localDB.replicate.from(remoteDB)

If you need uni-directional replication, you might do:

// use "replicate" with only "to"
localDB.replicate.to(remoteDB)

Take a look at this.


问:
how to send through ServletOutputStream characters in UTF-8 encoding
My servlet code looks like that:

```<code>response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
ServletOutputStream out = response.getOutputStream();
out.println(...MY-UTF-8 CODE...);
</code>```

...

then I get the error:

```<code>java.io.CharConversionException: Not an ISO 8859-1 character: ש
 javax.servlet.ServletOutputStream.print(ServletOutputStream.java:89)
 javax.servlet.ServletOutputStream.println(ServletOutputStream.java:242)
 rtm.servlets.CampaignLogicServlet.doPost(CampaignLogicServlet.java:68)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
</code>```

How can I switch the charset of Servlet's outputstream ???

答:
```<code>public void output(String jsonStr, HttpServletResponse response) throws IOException {
    response.setContentType("text/html;charset=UTF-8;");
    response.setCharacterEncoding("UTF-8");
    ServletOutputStream out = response.getOutputStream();
    out.write(jsonStr.getBytes("UTF-8"));
    out.flush();
    out.close();
}
</code>```

Body:
My servlet code looks like that:

response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
ServletOutputStream out = response.getOutputStream();
out.println(...MY-UTF-8 CODE...);

...

then I get the error:

java.io.CharConversionException: Not an ISO 8859-1 character: ש
 javax.servlet.ServletOutputStream.print(ServletOutputStream.java:89)
 javax.servlet.ServletOutputStream.println(ServletOutputStream.java:242)
 rtm.servlets.CampaignLogicServlet.doPost(CampaignLogicServlet.java:68)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

How can I switch the charset of Servlet's outputstream ???


问:
creating a literal for a Point - C++
I am trying to do a simple library where the object is a point on the xy-axis.

I want to be able to use literals like this:

Point a = (3,4);

where (3,4) is a point literal.

I read about user defined literals, but (as I understood) this seems to be impossible.

May be "(3,4)"_P is possible as I understand it.

However, I found on this page interesting use of user defined literals as follows:

```<code>#include <iostream>
#include <complex>

int main()
{
    using namespace std::complex_literals;
    std::complex<double> c = 1.0 + 1i;
    std::cout << "abs" << c << " = " << abs(c) << '\n';
}
</code>```

I can under stand the part 1i as a user defined literal, but not the whole thing 1.0 + 1i.

What I am missing, and what is the nearest possible way of getting a literal similar to (x,y) without using ".

答:
As Some programmer dude shows, the best way is to use uniform initialization.

However, just for the fun of it, you can (sort of) do this with User Defined Literals. My idea is to to have 2 literals for each coordinate and overload operator+ between them to create the point.

Remember, this is just for fun, don't use this in a real code:

```<code>struct Px { int x; };
struct Py { int y; };

struct Point {
    int x;
    int y;
};

constexpr auto operator""_px(unsigned long long x) -> Px { return Px{(int)x}; }
constexpr auto operator""_py(unsigned long long y) -> Py { return Py{(int)y}; }

constexpr auto operator+(Px x, Py y) -> Point { return Point{x.x, y.y}; }
</code>```

then you can have:

```<code>auto p = 3_px + 4_py; // p is deduced to type `Point`
</code>```

Of course this is just a rough framework. Read this great article to learn more about UDLs. You would need to deal with the narrowing conversion in a better way and propper use namespaces to make it a better solution.

As a bonus, you could also use operator, to create a syntax more appropriate to what you had in mind. But, don't do this, as overloading operator, is just evil:

```<code>auto operator,(Px x, Py y) -> Point { return Point{x.x, y.y}; }
</code>```

```<code>auto p = (2_px, 1_py); // p is deduced to type `Point`
</code>```

Title: creating a literal for a Point - C++

Body:
I am trying to do a simple library where the object is a point on the xy-axis.

I want to be able to use literals like this:

Point a = (3,4);

where (3,4) is a point literal.

I read about user defined literals, but (as I understood) this seems to be impossible.

May be "(3,4)"_P is possible as I understand it.

However, I found on this page interesting use of user defined literals as follows:

#include <iostream>
#include <complex>

int main()
{
    using namespace std::complex_literals;
    std::complex<double> c = 1.0 + 1i;
    std::cout << "abs" << c << " = " << abs(c) << '\n';
}

I can under stand the part 1i as a user defined literal, but not the whole thing 1.0 + 1i.

What I am missing, and what is the nearest possible way of getting a literal similar to (x,y) without using ".

Body:
As Some programmer dude shows, the best way is to use uniform initialization.

However, just for the fun of it, you can (sort of) do this with User Defined Literals. My idea is to to have 2 literals for each coordinate and overload operator+ between them to create the point.

Remember, this is just for fun, don't use this in a real code:

struct Px { int x; };
struct Py { int y; };

struct Point {
    int x;
    int y;
};

constexpr auto operator""_px(unsigned long long x) -> Px { return Px{(int)x}; }
constexpr auto operator""_py(unsigned long long y) -> Py { return Py{(int)y}; }

constexpr auto operator+(Px x, Py y) -> Point { return Point{x.x, y.y}; }

then you can have:

auto p = 3_px + 4_py; // p is deduced to type `Point`

Of course this is just a rough framework. Read this great article to learn more about UDLs. You would need to deal with the narrowing conversion in a better way and propper use namespaces to make it a better solution.

As a bonus, you could also use operator, to create a syntax more appropriate to what you had in mind. But, don't do this, as overloading operator, is just evil:

auto operator,(Px x, Py y) -> Point { return Point{x.x, y.y}; }

auto p = (2_px, 1_py); // p is deduced to type `Point`


问:
expression of non-boolean type
Using this statement:

```<code>select * from qvalues where rowid ,name,compound in (
    select rowid,name,compound from qvalues where rowid in (select rowid from batchinfo where instrument='tf1')
    group by rowid,name,compound
    having COUNT(*)>1
    )
    group by rowid,name,compound
having rid=min(rid)
</code>```

This error occurs:

Msg 4145, Level 15, State 1, Line 3
  An expression of non-boolean type specified in a context where a condition is expected, near ','.
  Msg 156, Level 15, State 1, Line 8
  Incorrect syntax near the keyword 'group'.

What is wrong with this SQL statement? I need to find all the occurrences of those three fields in the table having min(rid).

Update
Using this query, the outer select is not working. What am I doing wrong?

```<code>select * from qvalues where rid not in (
select q.rowid, q.name, q.compound, min(q.rid)
    from qvalues q
        inner join batchinfo b
            on q.rowid = b.rowid
                and b.instrument = 'tf1'
    group by q.rowid, q.name, q.compound
    having count(*) > 1)
</code>```

答:
The final having min(rid) needs to have comparison

Saying that, there is no associated GROUP BY which you can see if you rearrange your code snippet

```<code>select * from qvalues
where rowid ,name,compound in (
               select rowid,name,compound from qvalues
               where rowid in (select rowid from batchinfo where instrument='tf1')
               group by rowid,name,compound
               having COUNT(*)>1
               )
--missing group by
having min(rid) -- > foo
</code>```

Edit: reformulated:

```<code>select
   *
from
    (
    select
       rowid,name,compound, min(q.rid) as minrid
    from
       qvalues q
    where
       EXISTS (SELECT * FROM batchinfo b where b.instrument='tf1' AND b.rowid = q.rowid)
    group by
        rowid,name,compound
    having
        COUNT(*)>1
    ) foo
    JOIN
    qvalues q2 On foo.rowid = q.rowid AND foo.name = q.name AND foo.compound = q.compound
                   AND foo.minrid = q2.rid
</code>```

And your original error probably comes from a lack of alias of the derived table, coupled with the fact that SQL Server does not support multi-column IN. I use EXISTS not JOIN because you may get more rows from qvalues JOIN batchinfo than you expect (based on Joe's answer)

Title: expression of non-boolean type

Body:
Using this statement:

select * from qvalues where rowid ,name,compound in (
    select rowid,name,compound from qvalues where rowid in (select rowid from batchinfo where instrument='tf1')
    group by rowid,name,compound
    having COUNT(*)>1
    )
    group by rowid,name,compound
having rid=min(rid)

This error occurs:

Msg 4145, Level 15, State 1, Line 3
  An expression of non-boolean type specified in a context where a condition is expected, near ','.
  Msg 156, Level 15, State 1, Line 8
  Incorrect syntax near the keyword 'group'.

What is wrong with this SQL statement? I need to find all the occurrences of those three fields in the table having min(rid).

Update
Using this query, the outer select is not working. What am I doing wrong?

select * from qvalues where rid not in (
select q.rowid, q.name, q.compound, min(q.rid)
    from qvalues q
        inner join batchinfo b
            on q.rowid = b.rowid
                and b.instrument = 'tf1'
    group by q.rowid, q.name, q.compound
    having count(*) > 1)

Body:
The final having min(rid) needs to have comparison

Saying that, there is no associated GROUP BY which you can see if you rearrange your code snippet

select * from qvalues
where rowid ,name,compound in (
               select rowid,name,compound from qvalues
               where rowid in (select rowid from batchinfo where instrument='tf1')
               group by rowid,name,compound
               having COUNT(*)>1
               )
--missing group by
having min(rid) -- > foo

Edit: reformulated:

select
   *
from
    (
    select
       rowid,name,compound, min(q.rid) as minrid
    from
       qvalues q
    where
       EXISTS (SELECT * FROM batchinfo b where b.instrument='tf1' AND b.rowid = q.rowid)
    group by
        rowid,name,compound
    having
        COUNT(*)>1
    ) foo
    JOIN
    qvalues q2 On foo.rowid = q.rowid AND foo.name = q.name AND foo.compound = q.compound
                   AND foo.minrid = q2.rid

And your original error probably comes from a lack of alias of the derived table, coupled with the fact that SQL Server does not support multi-column IN. I use EXISTS not JOIN because you may get more rows from qvalues JOIN batchinfo than you expect (based on Joe's answer)


问:
C++ Question about default constructor
What does it mean to call a class like this:

```<code>class Example
{
 public:
  Example(void);
  ~Example(void);
}

int main(void)
{
 Example ex(); // <<<<<< what is it called to call it like this?

 return(0);
}
</code>```

Like it appears that it isn't calling the default constructor in that case. Can someone give a reason why that would be bad?

Thanks for all answers.

答:
Currently you are trying to call the default constructor like so.

```<code>Example ex();
</code>```

This is not actually calling the default constructor.  Instead you are defining a function prototype with return type Example and taking no parameters.  In order to call the default constructor, omit the ()'s

```<code>Example ex;
</code>```

OwnerDisplayName: Daniel

Title: C++ Question about default constructor

Body:
What does it mean to call a class like this:

class Example
{
 public:
  Example(void);
  ~Example(void);
}

int main(void)
{
 Example ex(); // <<<<<< what is it called to call it like this?

 return(0);
}

Like it appears that it isn't calling the default constructor in that case. Can someone give a reason why that would be bad?

Thanks for all answers.

LastEditorDisplayName: codelogic

Body:
Currently you are trying to call the default constructor like so.

Example ex();

This is not actually calling the default constructor.  Instead you are defining a function prototype with return type Example and taking no parameters.  In order to call the default constructor, omit the ()'s

Example ex;

OwnerDisplayName: JaredPar

LastEditorDisplayName: JaredPar


问:
How I can read a paragraph from the keyboard and stored it in a linked list (each node has a one word)?
```<code>#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class node
{
private:
    string data;
    node *next;
public:
    node*head,*current,*tail;
    node()
    {
     head=current=tail=NULL;
    }
    void read()
    {
     string x;
     tail=new node;
     cin>>tail->data;
     tail->next=NULL;
     head=current=tail;
     cin>>x;
     while(x!=".")
     {
      current=new node;
      current->next=NULL;
      stringstream ss;//("plez help me");
      string s;
      //getline(cin,aa);
      while (getline(ss, s,' '))
        {
            cout << s << "\t";

        }
      current->data=s;
      tail->next=current;
      tail=tail->next;
      //cin>>x;
     }
    }
    void print()
    {
     current=head;
     while(current!=NULL)
     {
      cout<<current->data<<endl;
      current=current->next;
     }
    }
};
</code>```

答:
```<code>list<string> result;
typedef istreambuf_iterator<char> InIter;
typedef boost::char_separator<char> CharSep;
boost::tokenizer<CharSep, InIter> tok(
    InIter(cin.rdbuf()), InIter(), CharSep(" \t\r\n."));
copy(tok.begin(), tok.end(), back_inserter(result));
</code>```


问:
Deep sorting in 2d array
I need to achieve a functionality in java similar to sql sort where in i have a function where i pass a 2d array along with 2 column indexes, this function should return a sorted 2d array on the provided column indexes.

In short I need to sort the 2d array on 2 columns.

I was able to achieve the sort on 1 column wise , PFB the code for the same.

```<code>Arrays.sort(arr, new Comparator(){
        private int col ;
         public int compare(Object o1, Object o2) {
    String[] s1 = (String[])o1;
    String[] s2 = (String[])o2;
    return s1[col].compareTo(s2[col]);
    }

    private Comparator init(int var){
    col = var;
    return this;
}
}.init(0)
);
</code>```

But i need to enhance this functionality to sort based on 2 columns in 2d array.
I request experts to help me out in this.

Example
Input array ```
1 2 3 4
1 8 2 8
8 6 10 11
5 6 7 8
1 6 2 6 </p>

<p>Output :  On sorting with Column 2,3
1 2 3 4
1 6 2 6
5 6 7 8
8 6 10 11
1 8 2 8
```
Thanks in advance,
Raju

答:
Just compare by the second column when the first ones are equals, like that:

```<code>int equal = s1[col].compareTo(s2[col]);
return equal == 0 ? s1[col2].compareTo(s2[col2]) : equal;
</code>```

Please also note that you are comparing strings (a lexicographical comparison), not numbers, so "10" would be less then "2", resulting in:

```<code>1 2 3 4
8 6 10 11
1 6 2 6
5 6 7 8
1 8 2 8
</code>```

when you sort by columns 2 and 3.

If that is not what you want, just convert you data to integers and compare then numerically.

You can also use Comparator.thenComparing to do the same thing:

thenComparing(Comparator other)
  Returns a lexicographic-order comparator with another comparator.

If this Comparator considers two elements equal, i.e. compare(a, b) == 0, other is used to determine the order.

```<code>Arrays.sort(array,
    Comparator.<String[],String>
    comparing(row -> row[1])
   .thenComparing(row2 -> row2[2])
);
</code>```

Title: Deep sorting in 2d array

Body:
I need to achieve a functionality in java similar to sql sort where in i have a function where i pass a 2d array along with 2 column indexes, this function should return a sorted 2d array on the provided column indexes.

In short I need to sort the 2d array on 2 columns.

I was able to achieve the sort on 1 column wise , PFB the code for the same.

Arrays.sort(arr, new Comparator(){
        private int col ;
         public int compare(Object o1, Object o2) {
    String[] s1 = (String[])o1;
    String[] s2 = (String[])o2;
    return s1[col].compareTo(s2[col]);
    }

    private Comparator init(int var){
    col = var;
    return this;
}
}.init(0)
);

But i need to enhance this functionality to sort based on 2 columns in 2d array.
I request experts to help me out in this.

Example
Input array

1 2 3 4
1 8 2 8
8 6 10 11
5 6 7 8
1 6 2 6

Output :  On sorting with Column 2,3
1 2 3 4
1 6 2 6
5 6 7 8
8 6 10 11
1 8 2 8

Thanks in advance,
Raju

Body:
Just compare by the second column when the first ones are equals, like that:

int equal = s1[col].compareTo(s2[col]);
return equal == 0 ? s1[col2].compareTo(s2[col2]) : equal;

Please also note that you are comparing strings (a lexicographical comparison), not numbers, so "10" would be less then "2", resulting in:

1 2 3 4
8 6 10 11
1 6 2 6
5 6 7 8
1 8 2 8

when you sort by columns 2 and 3.

If that is not what you want, just convert you data to integers and compare then numerically.

You can also use Comparator.thenComparing to do the same thing:

thenComparing(Comparator other)
  Returns a lexicographic-order comparator with another comparator.

If this Comparator considers two elements equal, i.e. compare(a, b) == 0, other is used to determine the order.

Arrays.sort(array,
    Comparator.<String[],String>
    comparing(row -> row[1])
   .thenComparing(row2 -> row2[2])
);


问:
SimpleIOC with MVVMlight register and use
Hi i try to register my class into serviceLocator and reuse it my code is:

```<code>public ViewModelLocator()
{
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    SimpleIoc.Default.Register<IUnitOfWork, UnitOfWork>(true);

    SimpleIoc.Default.Register<MainViewModel>(() =>
    {
        return new MainViewModel(UnitOfWorkItem);
    });
    SimpleIoc.Default.Register<LoginViewModel>(() =>
    {
        return new LoginViewModel(UnitOfWorkItem);
    });
}

public UnitOfWork UnitOfWorkItem
{
    get
    {
        return ServiceLocator.Current.GetInstance<UnitOfWork>();
    }
}

public MainViewModel Main
{
    get
    {
        return ServiceLocator.Current.GetInstance<MainViewModel>();
    }
}
</code>```

when i try to give UnitOfWorkItem into the function that instance MainViewModel throw a exception like:

Type not found in cache: Client.Business.UnitOfWork.

my stack trace is:

in GalaSoft.MvvmLight.Ioc.SimpleIoc.DoGetService(Type serviceType,
  String key, Boolean cache) in
  D:\GalaSoft\mydotnet\MVVMLight\source\GalaSoft.MvvmLight\GalaSoft.MvvmLight.Extras
  (PCL)\Ioc\SimpleIoc.cs:riga 537    in
  GalaSoft.MvvmLight.Ioc.SimpleIoc.GetInstanceTService in
  D:\GalaSoft\mydotnet\MVVMLight\source\GalaSoft.MvvmLight\GalaSoft.MvvmLight.Extras
  (PCL)\Ioc\SimpleIoc.cs:riga 912    in
  PrivateVideoChat.Client.ViewModel.ViewModelLocator.get_UnitOfWorkItem()
  in C:\Users\c.fasolin\Documents\Visual Studio
  2013\Projects\PrivateVideoChat.Solution\PrivateVideoChat.Client\ViewModel\ViewModelLocator.cs:riga
  63    in
  PrivateVideoChat.Client.ViewModel.ViewModelLocator.<.ctor>b__0_1() in
  C:\Users\c.fasolin\Documents\Visual Studio
  2013\Projects\PrivateVideoChat.Solution\PrivateVideoChat.Client\ViewModel\ViewModelLocator.cs:riga
  52

Where I am wrong
thanks

答:
The UnitOfWorkItem property is looking for the registered UnitOfWork. But you never register anything with that class, you register the IUnitOfWork!

You need to fix your UnitOfWorkItem by changing UnitOfWork into IUnitOfWork:

```<code>public UnitOfWork UnitOfWorkItem
{
    get
    {
        return ServiceLocator.Current.GetInstance<IUnitOfWork>();
    }
}
</code>```

Even better:

Just for your information, the power of an IoC container is that you can chain the registration. For example, in your case, your LoginViewModel and your MainViewModel require a UnitOfWork as constructor parameter.

If you register both UnitOfWork, MainViewModel and LoginViewModel like this:

```<code>SimpleIoc.Default.Register<UnitOfWork>();
SimpleIoc.Default.Register<LoginViewModel>();
SimpleIoc.Default.Register<MainViewModel>();
</code>```

The container will automatically provide to the ViewModels constructor the registred UnitOfWork and so on.

This way you do not need to create a property getting the UnitOfWork for giving it to the LoginViewModel constructor.

Body:
Hi i try to register my class into serviceLocator and reuse it my code is:

public ViewModelLocator()
{
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    SimpleIoc.Default.Register<IUnitOfWork, UnitOfWork>(true);

    SimpleIoc.Default.Register<MainViewModel>(() =>
    {
        return new MainViewModel(UnitOfWorkItem);
    });
    SimpleIoc.Default.Register<LoginViewModel>(() =>
    {
        return new LoginViewModel(UnitOfWorkItem);
    });
}

public UnitOfWork UnitOfWorkItem
{
    get
    {
        return ServiceLocator.Current.GetInstance<UnitOfWork>();
    }
}

public MainViewModel Main
{
    get
    {
        return ServiceLocator.Current.GetInstance<MainViewModel>();
    }
}

when i try to give UnitOfWorkItem into the function that instance MainViewModel throw a exception like:

Type not found in cache: Client.Business.UnitOfWork.

my stack trace is:

in GalaSoft.MvvmLight.Ioc.SimpleIoc.DoGetService(Type serviceType,
  String key, Boolean cache) in
  D:\GalaSoft\mydotnet\MVVMLight\source\GalaSoft.MvvmLight\GalaSoft.MvvmLight.Extras
  (PCL)\Ioc\SimpleIoc.cs:riga 537    in
  GalaSoft.MvvmLight.Ioc.SimpleIoc.GetInstanceTService in
  D:\GalaSoft\mydotnet\MVVMLight\source\GalaSoft.MvvmLight\GalaSoft.MvvmLight.Extras
  (PCL)\Ioc\SimpleIoc.cs:riga 912    in
  PrivateVideoChat.Client.ViewModel.ViewModelLocator.get_UnitOfWorkItem()
  in C:\Users\c.fasolin\Documents\Visual Studio
  2013\Projects\PrivateVideoChat.Solution\PrivateVideoChat.Client\ViewModel\ViewModelLocator.cs:riga
  63    in
  PrivateVideoChat.Client.ViewModel.ViewModelLocator.<.ctor>b__0_1() in
  C:\Users\c.fasolin\Documents\Visual Studio
  2013\Projects\PrivateVideoChat.Solution\PrivateVideoChat.Client\ViewModel\ViewModelLocator.cs:riga
  52

Where I am wrong
thanks

Body:
The UnitOfWorkItem property is looking for the registered UnitOfWork. But you never register anything with that class, you register the IUnitOfWork!

You need to fix your UnitOfWorkItem by changing UnitOfWork into IUnitOfWork:

public UnitOfWork UnitOfWorkItem
{
    get
    {
        return ServiceLocator.Current.GetInstance<IUnitOfWork>();
    }
}

Even better:

Just for your information, the power of an IoC container is that you can chain the registration. For example, in your case, your LoginViewModel and your MainViewModel require a UnitOfWork as constructor parameter.

If you register both UnitOfWork, MainViewModel and LoginViewModel like this:

SimpleIoc.Default.Register<UnitOfWork>();
SimpleIoc.Default.Register<LoginViewModel>();
SimpleIoc.Default.Register<MainViewModel>();

The container will automatically provide to the ViewModels constructor the registred UnitOfWork and so on.

This way you do not need to create a property getting the UnitOfWork for giving it to the LoginViewModel constructor.