问:
Hyperledger Composer issue identity but missing business card
I am working in a proof of concept with a Node.js application and 'composer-client' npm module.

I have tried different commands such as adding a participant, adding an asset and performing a transaction and everything seems to work correctly.

However, when I try to issue a new identity I do not get the results that I expect. I execute my Node.js application with the following code:

```<code>var businessNetwork = new BusinessNetworkConnection();
return businessNetwork.connect('admin@tutorial-network')
.then(() => {
  return businessNetwork.issueIdentity('org.acme.biznet.Trader#Trader_001', 'usr001')
})
.then((result) => {
  console.log(`userID = ${result.userID}`);
  console.log(`userSecret = ${result.userSecret}`);
})
.catch((error) => {
  console.error(error);
});
</code>```

Then, UserId and UserSecret are displayed at console log. After that, I try to do a ping to Business Network:

```<code>var businessNetwork = new BusinessNetworkConnection();
return businessNetwork.connect('usr001@tutorial-network')
.then(() => {
  return businessNetwork.ping();
})
.then((result) => {
  console.log(`participant = ${result.participant ? result.participant : '<no participant found>'}`);
})
.catch((error) => {
  console.error(error);
});
</code>```

However, I get the following error message:

```<code>{ Error: Card not found: usr001@tutorial-network
at IdCard.fromDirectory.catch.cause (/home/user.name/git_repositories/nodejs/first.blockchain.test/node_modules/composer-common/lib/cardstore/filesystemcardstore.js:73:27)
at <anonymous>
cause:
{ Error: Unable to read card directory: /home/user.name/.composer/cards/user001@tutorial-network
</code>```

If I execute the command composer identity list -c admin@tutorial-network, I get the following output:

```<code>$class:      org.hyperledger.composer.system.Identity
  identityId:  9b49f67c262c0ae23e1e0c4a8dc61c4a12b5119df2b6a49fa2e02fa56b8818c3
  name:        usr001
  issuer:      27c582d674ddf0f230854814b7cfd04553f3d0eac55e37d915386c614a5a1de9
  certificate:
  state:       ISSUED
  participant: resource:org.acme.biznet.Trader#Trader_001
</code>```

But, I am not able to find the business card.

答:
It works for me. I'm using composer 0.15.1.

```<code>var businessNetwork = new BusinessNetworkConnection();

return businessNetwork.connect('admin@carauction-network')
.then(() => {
  return businessNetwork.ping();
})
.then((result) => {
  console.log(`participant = ${result.participant ? result.participant : '<no participant found>'}`);
})
.catch((error) => {
  console.error(error);
});
</code>```

Output is like this

```<code>linux1@fabric:~/eventclient$ node event.js
participant = org.hyperledger.composer.system.NetworkAdmin#admin
</code>```

You may need to import ID card to wallet ?

```<code>composer card import --file networkadmin.card
</code>```

Body:
I am working in a proof of concept with a Node.js application and 'composer-client' npm module.

I have tried different commands such as adding a participant, adding an asset and performing a transaction and everything seems to work correctly.

However, when I try to issue a new identity I do not get the results that I expect. I execute my Node.js application with the following code:

var businessNetwork = new BusinessNetworkConnection();
return businessNetwork.connect('admin@tutorial-network')
.then(() => {
  return businessNetwork.issueIdentity('org.acme.biznet.Trader#Trader_001', 'usr001')
})
.then((result) => {
  console.log(`userID = ${result.userID}`);
  console.log(`userSecret = ${result.userSecret}`);
})
.catch((error) => {
  console.error(error);
});

Then, UserId and UserSecret are displayed at console log. After that, I try to do a ping to Business Network:

var businessNetwork = new BusinessNetworkConnection();
return businessNetwork.connect('usr001@tutorial-network')
.then(() => {
  return businessNetwork.ping();
})
.then((result) => {
  console.log(`participant = ${result.participant ? result.participant : '<no participant found>'}`);
})
.catch((error) => {
  console.error(error);
});

However, I get the following error message:

{ Error: Card not found: usr001@tutorial-network
at IdCard.fromDirectory.catch.cause (/home/user.name/git_repositories/nodejs/first.blockchain.test/node_modules/composer-common/lib/cardstore/filesystemcardstore.js:73:27)
at <anonymous>
cause:
{ Error: Unable to read card directory: /home/user.name/.composer/cards/user001@tutorial-network

If I execute the command composer identity list -c admin@tutorial-network, I get the following output:

$class:      org.hyperledger.composer.system.Identity
  identityId:  9b49f67c262c0ae23e1e0c4a8dc61c4a12b5119df2b6a49fa2e02fa56b8818c3
  name:        usr001
  issuer:      27c582d674ddf0f230854814b7cfd04553f3d0eac55e37d915386c614a5a1de9
  certificate:
  state:       ISSUED
  participant: resource:org.acme.biznet.Trader#Trader_001

But, I am not able to find the business card.

Body:
It works for me. I'm using composer 0.15.1.

var businessNetwork = new BusinessNetworkConnection();

return businessNetwork.connect('admin@carauction-network')
.then(() => {
  return businessNetwork.ping();
})
.then((result) => {
  console.log(`participant = ${result.participant ? result.participant : '<no participant found>'}`);
})
.catch((error) => {
  console.error(error);
});

Output is like this

linux1@fabric:~/eventclient$ node event.js
participant = org.hyperledger.composer.system.NetworkAdmin#admin

You may need to import ID card to wallet ?

composer card import --file networkadmin.card


来源: stackexchange

问:
Activate certain functions based on percent
```<code>            if chance == 1:
                function1()

            elif chance == 4:
                function2()

            elif chance == 20:
                function3()

            elif chance == 10:
                functiongettingoutofideas()

            elif chance == 40:
               function_minecraft_club_was_not_on_today_insertcryingemoji()

            elif chance == 10:
               function8()

            elif chance == 4:
                functionthesearealotoffunctions()

            elif chance == 5:
                function_above_when_i_mean_5_i_mean_5_percent_chance()

            elif chance == 6:
                function_thank_you_for_your_help()
</code>```

In the if and the elifs when i put for example, chance == 10, that means there is a 10% chance of that function being activated.

Any help will be much appreciated

答:
This approach uses only Python standard libraries.

First convert percentages to probabilities.

```<code>>>> p = [1, 4, 20, 10, 40, 10, 4, 5, 6]
>>> p = [0.01*_ for _ in p]
</code>```

Then obtain cumulative probabilities. It's necessary to perform these preliminaries only once.

```<code>>>> cum_probs = [0]
>>> for _ in p:
...     cum_probs.append(_ + cum_probs[-1])
...
>>> cum_probs
[0, 0.01, 0.05, 0.25, 0.35, 0.75, 0.85, 0.89, 0.9400000000000001, 1.0]

>>> from random import random
</code>```

Make a random selection from the unit interval, [0, 1].

```<code>>>> selection = random()
</code>```

Starting on the left, find the first probability interval in which this random number belongs, then stop.

```<code>>>> for i, possibility in enumerate(cum_probs[1:]):
...     if selection < possibility:
...         print ('perform function number ', i)
...         break
...
perform function number  3
</code>```

This is the number of the function to perform.

These lines are just to verify that the random number selected is in the required interval.

```<code>>>> selection
0.33920981672706096
</code>```

You can assign functions to intervals in an array.

```<code>>>> functions = [function_one, another_fn, my_function, ...]
</code>```

More likely, you would put them in a dictionary. (I'm using your names.)

```<code>functions = {0: function1(); 1: function2(); ...}
</code>```

Then you would call the desired one like this.

```<code>functions[i]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
            if chance == 1:
                function1()

            elif chance == 4:
                function2()

            elif chance == 20:
                function3()

            elif chance == 10:
                functiongettingoutofideas()

            elif chance == 40:
               function_minecraft_club_was_not_on_today_insertcryingemoji()

            elif chance == 10:
               function8()

            elif chance == 4:
                functionthesearealotoffunctions()

            elif chance == 5:
                function_above_when_i_mean_5_i_mean_5_percent_chance()

            elif chance == 6:
                function_thank_you_for_your_help()

In the if and the elifs when i put for example, chance == 10, that means there is a 10% chance of that function being activated.

Any help will be much appreciated

Body:
This approach uses only Python standard libraries.

First convert percentages to probabilities.

>>> p = [1, 4, 20, 10, 40, 10, 4, 5, 6]
>>> p = [0.01*_ for _ in p]

Then obtain cumulative probabilities. It's necessary to perform these preliminaries only once.

>>> cum_probs = [0]
>>> for _ in p:
...     cum_probs.append(_ + cum_probs[-1])
...
>>> cum_probs
[0, 0.01, 0.05, 0.25, 0.35, 0.75, 0.85, 0.89, 0.9400000000000001, 1.0]

>>> from random import random

Make a random selection from the unit interval, [0, 1].

>>> selection = random()

Starting on the left, find the first probability interval in which this random number belongs, then stop.

>>> for i, possibility in enumerate(cum_probs[1:]):
...     if selection < possibility:
...         print ('perform function number ', i)
...         break
...
perform function number  3

This is the number of the function to perform.

These lines are just to verify that the random number selected is in the required interval.

>>> selection
0.33920981672706096

You can assign functions to intervals in an array.

>>> functions = [function_one, another_fn, my_function, ...]

More likely, you would put them in a dictionary. (I'm using your names.)

functions = {0: function1(); 1: function2(); ...}

Then you would call the desired one like this.

functions[i]


问:
Use of unresolved identifier 'displayAlertMessage'
I tried the moved the code around a bit. The errors I got was use of local variable displayMessage before its declaration. So I moved the func displayAlertMessage above the display an alert Message comment, the new error is use of unresolved identifier 'displayAlertMessage'

```<code>//
//  RegisterPageViewController.swift
//  UserLoginandRegistration
//
//  Created by Iyah Chulo on 17/11/2017.
//  Copyright © 2017 Iyah Chulo. All rights reserved.
//

import UIKit

class RegisterPageViewController: UIViewController {

    @IBOutlet weak var userEmailTextField: UITextField!
    @IBOutlet weak var userPasswordTextField: UITextField!
    @IBOutlet weak var ReenterPasswordTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func RegisterButtonTapped(_ sender: Any) {

        let userEmail = userEmailTextField.text;
        let userPassword = userPasswordTextField.text;
        let userReenterPassword = ReenterPasswordTextField.text;

        // Check for empty fields
        if((userEmail?.isEmpty)! || (userPassword?.isEmpty)! ||
        (userReenterPassword?.isEmpty)!)

        {

            func displayAlertMessage(userMessage: String) {  let myAlert = UIAlertController(title:"Alert", message: userMessage, preferredStyle:
                UIAlertControllerStyle.alert);

                let okAction = UIAlertAction(title:"Ok", style:
                    UIAlertActionStyle.default, handler:nil)

                myAlert.addAction(okAction);

                self.present(myAlert, animated: true,
                             completion:nil)
            }
</code>```

//Display alert message
            displayAlertMessage(userMessage: "All fields are required")
                return;
            }

```<code>        //Check if passwords match
        if(userPassword != userReenterPassword)
        {

// Display an alert message

    displayAlertMessage(userMessage: "Passwords do not match")

            return;

        }

        // Store data

        UserDefaults.standard.set(userEmail, forKey:"userEmail")
        UserDefaults.standard.set(userEmail, forKey:"userPassword")
        UserDefaults.standard.synchronize()

        // Display alert message with confirmation
        var myAlert = UIAlertController(title:"Alert", message: "Registration is successful.Thank you!", preferredStyle:
            UIAlertControllerStyle.alert);
        let okAction = UIAlertAction(title:"Ok", style:
        UIAlertActionStyle.default) { action in
            self.dismiss(animated: true, completion:nil)

    }

    }

}
</code>```

答:
Your displayAlertMessage function definition needs to be outside of the other functions in your class.

Also, please note that Swift does not require semicolons!

Try this:

```<code>import UIKit

class RegisterPageViewController: UIViewController {

    @IBOutlet weak var userEmailTextField: UITextField!
    @IBOutlet weak var userPasswordTextField: UITextField!
    @IBOutlet weak var ReenterPasswordTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func RegisterButtonTapped(_ sender: Any) {

        let userEmail = userEmailTextField.text
        let userPassword = userPasswordTextField.text
        let userReenterPassword = ReenterPasswordTextField.text

        // Check for empty fields
        if((userEmail?.isEmpty)! || (userPassword?.isEmpty)! ||
            (userReenterPassword?.isEmpty)!)
        {
            //Display alert message
            displayAlertMessage(userMessage: "All fields are required")
            return;
        }

        //Check if passwords match
        if(userPassword != userReenterPassword)
        {
            // Display an alert message
            displayAlertMessage(userMessage: "Passwords do not match")
            return;
        }

        // Store data
        UserDefaults.standard.set(userEmail, forKey:"userEmail")
        UserDefaults.standard.set(userEmail, forKey:"userPassword")
        UserDefaults.standard.synchronize()

        // Display an alert message
        displayAlertMessage(userMessage: "Registration is successful.Thank you!")
    }

    func displayAlertMessage(userMessage: String) {

        let myAlert = UIAlertController(title:"Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert)

        let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default) {
            action in
            self.dismiss(animated: true, completion:nil)
        }

        myAlert.addAction(okAction);

        self.present(myAlert, animated: true, completion: nil)
    }

}
</code>```

Body:
I tried the moved the code around a bit. The errors I got was use of local variable displayMessage before its declaration. So I moved the func displayAlertMessage above the display an alert Message comment, the new error is use of unresolved identifier 'displayAlertMessage'

//
//  RegisterPageViewController.swift
//  UserLoginandRegistration
//
//  Created by Iyah Chulo on 17/11/2017.
//  Copyright © 2017 Iyah Chulo. All rights reserved.
//

import UIKit

class RegisterPageViewController: UIViewController {

    @IBOutlet weak var userEmailTextField: UITextField!
    @IBOutlet weak var userPasswordTextField: UITextField!
    @IBOutlet weak var ReenterPasswordTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func RegisterButtonTapped(_ sender: Any) {

        let userEmail = userEmailTextField.text;
        let userPassword = userPasswordTextField.text;
        let userReenterPassword = ReenterPasswordTextField.text;

        // Check for empty fields
        if((userEmail?.isEmpty)! || (userPassword?.isEmpty)! ||
        (userReenterPassword?.isEmpty)!)

        {

            func displayAlertMessage(userMessage: String) {  let myAlert = UIAlertController(title:"Alert", message: userMessage, preferredStyle:
                UIAlertControllerStyle.alert);

                let okAction = UIAlertAction(title:"Ok", style:
                    UIAlertActionStyle.default, handler:nil)

                myAlert.addAction(okAction);

                self.present(myAlert, animated: true,
                             completion:nil)
            }

//Display alert message
            displayAlertMessage(userMessage: "All fields are required")
                return;
            }

        //Check if passwords match
        if(userPassword != userReenterPassword)
        {

// Display an alert message

    displayAlertMessage(userMessage: "Passwords do not match")

            return;

        }

        // Store data

        UserDefaults.standard.set(userEmail, forKey:"userEmail")
        UserDefaults.standard.set(userEmail, forKey:"userPassword")
        UserDefaults.standard.synchronize()

        // Display alert message with confirmation
        var myAlert = UIAlertController(title:"Alert", message: "Registration is successful.Thank you!", preferredStyle:
            UIAlertControllerStyle.alert);
        let okAction = UIAlertAction(title:"Ok", style:
        UIAlertActionStyle.default) { action in
            self.dismiss(animated: true, completion:nil)

    }

    }

}

Body:
Your displayAlertMessage function definition needs to be outside of the other functions in your class.

Also, please note that Swift does not require semicolons!

Try this:

import UIKit

class RegisterPageViewController: UIViewController {

    @IBOutlet weak var userEmailTextField: UITextField!
    @IBOutlet weak var userPasswordTextField: UITextField!
    @IBOutlet weak var ReenterPasswordTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func RegisterButtonTapped(_ sender: Any) {

        let userEmail = userEmailTextField.text
        let userPassword = userPasswordTextField.text
        let userReenterPassword = ReenterPasswordTextField.text

        // Check for empty fields
        if((userEmail?.isEmpty)! || (userPassword?.isEmpty)! ||
            (userReenterPassword?.isEmpty)!)
        {
            //Display alert message
            displayAlertMessage(userMessage: "All fields are required")
            return;
        }

        //Check if passwords match
        if(userPassword != userReenterPassword)
        {
            // Display an alert message
            displayAlertMessage(userMessage: "Passwords do not match")
            return;
        }

        // Store data
        UserDefaults.standard.set(userEmail, forKey:"userEmail")
        UserDefaults.standard.set(userEmail, forKey:"userPassword")
        UserDefaults.standard.synchronize()

        // Display an alert message
        displayAlertMessage(userMessage: "Registration is successful.Thank you!")
    }

    func displayAlertMessage(userMessage: String) {

        let myAlert = UIAlertController(title:"Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert)

        let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default) {
            action in
            self.dismiss(animated: true, completion:nil)
        }

        myAlert.addAction(okAction);

        self.present(myAlert, animated: true, completion: nil)
    }

}


问:
Unable to create s3 bucket in EU region
```<code>body = "<CreateBucketConfiguration><LocationConstraint>EU</LocationConstraint></CreateBucketConfiguration>"

        content_length = body.bytesize
        content_type = "text/plain"

        url = URI.parse("http://#{@name}.s3.amazonaws.com/")

        req = Net::HTTP::Put.new(url.path)
        req.body = body
        req.add_field 'Date' , @time
        req.add_field 'Host', "#{@name}.s3.amazonaws.com"
        req.add_field 'Content-Type', "#{content_type}"
        req.add_field 'Authorization', "#{signature}"
        req.add_field 'Content-Length', "#{content_length}"

        response = Net::HTTP.new(url.host, url.port).start do |http|
          http.request(req)
        end

        puts response.read_body
</code>```

returns 200 and creates bucket but in U.S Standard and not in EU. What am I missing here? Thanks for the help.

Here is the entire conversation

```<code>PUT / HTTP/1.1
Accept: */*
User-Agent: Ruby
Date: Wed, 19 Jan 2011 22:14:31 -0800
Host: mytest.s3.amazonaws.com
Content-Type: text/plain
Authorization: AWS AC8RVKAXAU8Q:41uTqvfncc2mE561YabgpGUouio=

Content-Length: 146

<CreateBucketConfiguration xmlns='http://s3.amazonaws.com/doc/2006-03-01/'>
    <LocationConstraint>EU</LocationConstraint>
</CreateBucketConfiguration>

HTTP/1.1 200 OK
x-amz-id-2: lrlPt8Y19ZxFXPbZf9Gf6dYxTGLYkkMzo0tSNXCNk29o9xghcob502mcttQ/oo4W
x-amz-request-id: 3504CCA0E7AFFE95
Date: Thu, 20 Jan 2011 06:14:32 GMT
Location: /mytest
Content-Length: 0
Server: AmazonS3

HTTP/1.1 400 Bad Request
Transfer-Encoding: chunked
Date: Thu, 20 Jan 2011 06:14:32 GMT
Connection: close
Server: AmazonS3

0
</code>```

答:
The only thing that I can see is that you haven't included the xmlns in the request body - not sure if that will make any difference though.

xmlns="http://s3.amazonaws.com/doc/2006-03-01/"

```<code>body = "<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><LocationConstraint>EU</LocationConstraint></CreateBucketConfiguration>"
</code>```

ContentLicense: CC BY-SA 2.5

Title: Unable to create s3 bucket in EU region

Body:
body = "<CreateBucketConfiguration><LocationConstraint>EU</LocationConstraint></CreateBucketConfiguration>"

        content_length = body.bytesize
        content_type = "text/plain"

        url = URI.parse("http://#{@name}.s3.amazonaws.com/")

        req = Net::HTTP::Put.new(url.path)
        req.body = body
        req.add_field 'Date' , @time
        req.add_field 'Host', "#{@name}.s3.amazonaws.com"
        req.add_field 'Content-Type', "#{content_type}"
        req.add_field 'Authorization', "#{signature}"
        req.add_field 'Content-Length', "#{content_length}"

        response = Net::HTTP.new(url.host, url.port).start do |http|
          http.request(req)
        end

        puts response.read_body

returns 200 and creates bucket but in U.S Standard and not in EU. What am I missing here? Thanks for the help.

Here is the entire conversation

PUT / HTTP/1.1
Accept: */*
User-Agent: Ruby
Date: Wed, 19 Jan 2011 22:14:31 -0800
Host: mytest.s3.amazonaws.com
Content-Type: text/plain
Authorization: AWS AC8RVKAXAU8Q:41uTqvfncc2mE561YabgpGUouio=

Content-Length: 146

<CreateBucketConfiguration xmlns='http://s3.amazonaws.com/doc/2006-03-01/'>
    <LocationConstraint>EU</LocationConstraint>
</CreateBucketConfiguration>

HTTP/1.1 200 OK
x-amz-id-2: lrlPt8Y19ZxFXPbZf9Gf6dYxTGLYkkMzo0tSNXCNk29o9xghcob502mcttQ/oo4W
x-amz-request-id: 3504CCA0E7AFFE95
Date: Thu, 20 Jan 2011 06:14:32 GMT
Location: /mytest
Content-Length: 0
Server: AmazonS3

HTTP/1.1 400 Bad Request
Transfer-Encoding: chunked
Date: Thu, 20 Jan 2011 06:14:32 GMT
Connection: close
Server: AmazonS3

0

Body:
The only thing that I can see is that you haven't included the xmlns in the request body - not sure if that will make any difference though.

xmlns="http://s3.amazonaws.com/doc/2006-03-01/"

body = "<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><LocationConstraint>EU</LocationConstraint></CreateBucketConfiguration>"


问:
MYSQL:Compare column of 1 table with column of another table
I have 1 table DATA,

```<code>ID,CLASS,CODE,DATE
1,123456,10,12-10-2017
2,987654,40,2017-11-10
3,456789,50,2017-11-11
4,234567,60,2017-11-12
5,872341,150,2017-11-13
</code>```

and another table PROPS,

```<code>ID,CLASS_ID,R_CODE
1,123456,20
2,987654,40
3,456789,50
4,234567,60
5,872341,100
6,746365,738
7,84264,8937
</code>```

I would like to select all rows from DATA where CODE from DATA Table is greater than or equal to(>=) R_CODE from PROPS Table.

Basically, i want to check each element of column CODE with every element of column R_CODE one-by-one.

Any help will be greatly appreciated.

答:
```<code>SELECT a.*, b.*
FROM data a, props b
WHERE a.code >= b.r_code
</code>```

I am assuming class and class_id do not need to match?

Edit: The example is cross join wherein every row of the first table is matched with every row of the second table.  The where then filters to what you want.

Body:
I have 1 table DATA,

ID,CLASS,CODE,DATE
1,123456,10,12-10-2017
2,987654,40,2017-11-10
3,456789,50,2017-11-11
4,234567,60,2017-11-12
5,872341,150,2017-11-13

and another table PROPS,

ID,CLASS_ID,R_CODE
1,123456,20
2,987654,40
3,456789,50
4,234567,60
5,872341,100
6,746365,738
7,84264,8937

I would like to select all rows from DATA where CODE from DATA Table is greater than or equal to(>=) R_CODE from PROPS Table.

Basically, i want to check each element of column CODE with every element of column R_CODE one-by-one.

Any help will be greatly appreciated.

Body:
SELECT a.*, b.*
FROM data a, props b
WHERE a.code >= b.r_code

I am assuming class and class_id do not need to match?

Edit: The example is cross join wherein every row of the first table is matched with every row of the second table.  The where then filters to what you want.


问:
XML serialization of interface property
I would like to XML serialize an object that has (among other) a property of type IModelObject (which is an interface).

```<code>public class Example
{
    public IModelObject Model { get; set; }
}
</code>```

When I try to serialize an object of this class,  I receive the following error:

"Cannot serialize member Example.Model of type Example because it is an interface."

I understand that the problem is that an interface cannot be serialized. However, the concrete Model object type is unknown until runtime.

Replacing the IModelObject interface with an abstract or concrete type and use inheritance with XMLInclude is possible, but seems like an ugly workaround.

Any suggestions?

答:
Unfortuantely for me, I had a case where the class to be serialized had properties that had interfaces as properties as well, so I needed to recursively process each property. Also, some of the interface properties were marked as [XmlIgnore], so I wanted to skip over those. I took ideas that I found on this thread and added some things to it to make it recursive. Only the deserialization code is shown here:</p>

```<code>void main()
{
    var serializer = GetDataContractSerializer<MyObjectWithCascadingInterfaces>();
    using (FileStream stream = new FileStream(xmlPath, FileMode.Open))
    {
        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
        var obj = (MyObjectWithCascadingInterfaces)serializer.ReadObject(reader);

        // your code here
    }
}

DataContractSerializer GetDataContractSerializer<T>() where T : new()
{
    Type[] types = GetTypesForInterfaces<T>();

    // Filter out duplicates
    Type[] result = types.ToList().Distinct().ToList().ToArray();

    var obj = new T();
    return new DataContractSerializer(obj.GetType(), types);
}

Type[] GetTypesForInterfaces<T>() where T : new()
{
    return GetTypesForInterfaces(typeof(T));
}

Type[] GetTypesForInterfaces(Type T)
{
    Type[] result = new Type[0];
    var obj = Activator.CreateInstance(T);

    // get the type for all interface properties that are not marked as "XmlIgnore"
    Type[] types = T.GetProperties()
        .Where(p => p.PropertyType.IsInterface &&
            !p.GetCustomAttributes(typeof(System.Xml.Serialization.XmlIgnoreAttribute), false).Any())
        .Select(p => p.GetValue(obj, null).GetType())
        .ToArray();

    result = result.ToList().Concat(types.ToList()).ToArray();

    // do the same for each of the types identified
    foreach (Type t in types)
    {
        Type[] embeddedTypes = GetTypesForInterfaces(t);
        result = result.ToList().Concat(embeddedTypes.ToList()).ToArray();
    }
    return result;
}
</code>```

Title: XML serialization of interface property

Body:
I would like to XML serialize an object that has (among other) a property of type IModelObject (which is an interface).

public class Example
{
    public IModelObject Model { get; set; }
}

When I try to serialize an object of this class,  I receive the following error:

"Cannot serialize member Example.Model of type Example because it is an interface."

I understand that the problem is that an interface cannot be serialized. However, the concrete Model object type is unknown until runtime.

Replacing the IModelObject interface with an abstract or concrete type and use inheritance with XMLInclude is possible, but seems like an ugly workaround.

Any suggestions?

Body:
Unfortuantely for me, I had a case where the class to be serialized had properties that had interfaces as properties as well, so I needed to recursively process each property. Also, some of the interface properties were marked as [XmlIgnore], so I wanted to skip over those. I took ideas that I found on this thread and added some things to it to make it recursive. Only the deserialization code is shown here:

void main()
{
    var serializer = GetDataContractSerializer<MyObjectWithCascadingInterfaces>();
    using (FileStream stream = new FileStream(xmlPath, FileMode.Open))
    {
        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
        var obj = (MyObjectWithCascadingInterfaces)serializer.ReadObject(reader);

        // your code here
    }
}

DataContractSerializer GetDataContractSerializer<T>() where T : new()
{
    Type[] types = GetTypesForInterfaces<T>();

    // Filter out duplicates
    Type[] result = types.ToList().Distinct().ToList().ToArray();

    var obj = new T();
    return new DataContractSerializer(obj.GetType(), types);
}

Type[] GetTypesForInterfaces<T>() where T : new()
{
    return GetTypesForInterfaces(typeof(T));
}

Type[] GetTypesForInterfaces(Type T)
{
    Type[] result = new Type[0];
    var obj = Activator.CreateInstance(T);

    // get the type for all interface properties that are not marked as "XmlIgnore"
    Type[] types = T.GetProperties()
        .Where(p => p.PropertyType.IsInterface &&
            !p.GetCustomAttributes(typeof(System.Xml.Serialization.XmlIgnoreAttribute), false).Any())
        .Select(p => p.GetValue(obj, null).GetType())
        .ToArray();

    result = result.ToList().Concat(types.ToList()).ToArray();

    // do the same for each of the types identified
    foreach (Type t in types)
    {
        Type[] embeddedTypes = GetTypesForInterfaces(t);
        result = result.ToList().Concat(embeddedTypes.ToList()).ToArray();
    }
    return result;
}


问:
Algorithm Help Needed! [Probabilities, Distribution, Sequence Analysis.]
I have this idea for a prediction algorithm that predicts a random value with accuracy based a sequence of previous occurrences of an item from the set being chosen and analyse the pattern to improve the accuracy.

So basically an algorithm that accepts two parameters, one being a set of possible choices; the other being an history of those numbers, analyse that pattern and predict the next number in the sequence.

Does this make sense to anyone else?

If it does, what would be your approach to writing such an algorithm?

What language would you refer?

The goal is pattern recognition in overlapping sample sets, find a correlation and establish an equation to predict that with some degree of accuracy.

答:
Well, there are thousands of algorithms based on this approach. For example look at the formula for Shortest-job-first to predict the CPU burst of next process based on the previous Processes time and their burst because short-term-schedular has to take decisions fast.

Formula is:"T(n+1) = a*t(n) + (1 − a)Tn.

Were T(n+1)  will be our predicted time, t(n) is the length of nth cpu burst. a is the relative weight of recent and path history, for example if a = 0 then next time is t(n).

For language it depends on you what language you are good with.


问:
Why does adding a space character at the end of a year string cause JavaScript (node) to apply the timezone offset?
This is in Node v8.9.0 specifically.

Consider these lines:

```<code>console.log(new Date("2006"));
console.log(new Date("2006 "));
</code>```

They produce this output:

```<code>2006-01-01T00:00:00.000Z
2006-01-01T08:00:00.000Z
</code>```

Note that the second line has an 8hr timezone offset.

Why would the presence or absence of a trailing space cause the date to be created with/without the timezone offset?

答:
Summary: The presence of the space causes the date parser to interpret the date as a different format which uses a different assumption for the time zone when there is no timezone specification in the string.

A complication with the Date() constructor or Date.parse() is that with incomplete or partial date strings the parser is trying to guess whether the string should be interpreted as a simplified form of the ISO 8601 format or the RFC2822 format.  If it thinks the format is ISO 8601 and no timezone is specified, then the UTC time zone will be assumed.  If it thinks the format is RFC2822, then the local computer time zone will be assumed.

So, for your two strings the first is apparently being assumed to be ISO 8601 and thus uses UTC time zone assumption and the second is apparently being assumed to be RFC2822 which uses the local time zone.

The ISO 8601 format that is supported contains no spaces, whereas the RFC2822 format can contain some spaces so it seems likely that the mere presence of the space in the string causes the parser to choose the RFC2822 format which uses the local time zone.

You can read about some of this in the Date.parse() doc on MDN.

For reference here's a piece of the simplified ISO 8601 format:

```<code>   Year:
      YYYY (eg 1997)
   Year and month:
      YYYY-MM (eg 1997-07)
   Complete date:
      YYYY-MM-DD (eg 1997-07-16)
   Complete date plus hours and minutes:
      YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
   Complete date plus hours, minutes and seconds:
      YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
   Complete date plus hours, minutes, seconds and a decimal fraction of a
second
      YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
where:

     YYYY = four-digit year
     MM   = two-digit month (01=January, etc.)
     DD   = two-digit day of month (01 through 31)
     hh   = two digits of hour (00 through 23) (am/pm NOT allowed)
     mm   = two digits of minute (00 through 59)
     ss   = two digits of second (00 through 59)
     s    = one or more digits representing a decimal fraction of a second
     TZD  = time zone designator (Z or +hh:mm or -hh:mm)
     T    = a literal T separating the time
</code>```

You can see that there are no spaces in this format.

Whereas the RFC2822 format contains spaces separate different pieces of the date/time.  The full grammar is in the linked RFC, but here's one example where you can see the spaces:

```<code>Mon, 25 Dec 1995 13:30:00 GMT
</code>```

Note that the ES2015 spec for Date.parse() describes the simplified ISO 8601 date format.  When you supply any string that does not match that format exactly you probably run into some implementation dependent parsing behavior.  Quoting from the ES2015 spec:

the value produced by Date.parse is implementation-dependent when
given any String value that does not conform to the Date Time String
Format (20.3.1.16)

where that referenced "Date Time String Format" is the simplified ISO 8601 format.

Body:
This is in Node v8.9.0 specifically.

Consider these lines:

console.log(new Date("2006"));
console.log(new Date("2006 "));

They produce this output:

2006-01-01T00:00:00.000Z
2006-01-01T08:00:00.000Z

Note that the second line has an 8hr timezone offset.

Why would the presence or absence of a trailing space cause the date to be created with/without the timezone offset?

Body:
Summary: The presence of the space causes the date parser to interpret the date as a different format which uses a different assumption for the time zone when there is no timezone specification in the string.

A complication with the Date() constructor or Date.parse() is that with incomplete or partial date strings the parser is trying to guess whether the string should be interpreted as a simplified form of the ISO 8601 format or the RFC2822 format.  If it thinks the format is ISO 8601 and no timezone is specified, then the UTC time zone will be assumed.  If it thinks the format is RFC2822, then the local computer time zone will be assumed.

So, for your two strings the first is apparently being assumed to be ISO 8601 and thus uses UTC time zone assumption and the second is apparently being assumed to be RFC2822 which uses the local time zone.

The ISO 8601 format that is supported contains no spaces, whereas the RFC2822 format can contain some spaces so it seems likely that the mere presence of the space in the string causes the parser to choose the RFC2822 format which uses the local time zone.

You can read about some of this in the Date.parse() doc on MDN.

For reference here's a piece of the simplified ISO 8601 format:

   Year:
      YYYY (eg 1997)
   Year and month:
      YYYY-MM (eg 1997-07)
   Complete date:
      YYYY-MM-DD (eg 1997-07-16)
   Complete date plus hours and minutes:
      YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
   Complete date plus hours, minutes and seconds:
      YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
   Complete date plus hours, minutes, seconds and a decimal fraction of a
second
      YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
where:

     YYYY = four-digit year
     MM   = two-digit month (01=January, etc.)
     DD   = two-digit day of month (01 through 31)
     hh   = two digits of hour (00 through 23) (am/pm NOT allowed)
     mm   = two digits of minute (00 through 59)
     ss   = two digits of second (00 through 59)
     s    = one or more digits representing a decimal fraction of a second
     TZD  = time zone designator (Z or +hh:mm or -hh:mm)
     T    = a literal T separating the time

You can see that there are no spaces in this format.

Whereas the RFC2822 format contains spaces separate different pieces of the date/time.  The full grammar is in the linked RFC, but here's one example where you can see the spaces:

Mon, 25 Dec 1995 13:30:00 GMT

Note that the ES2015 spec for Date.parse() describes the simplified ISO 8601 date format.  When you supply any string that does not match that format exactly you probably run into some implementation dependent parsing behavior.  Quoting from the ES2015 spec:

the value produced by Date.parse is implementation-dependent when
given any String value that does not conform to the Date Time String
Format (20.3.1.16)

where that referenced "Date Time String Format" is the simplified ISO 8601 format.


问:
Authenticating a REST request in an Excel Add-in
I am trying to develop an add-in for Excel with the goal that it will create calendar events based on data inside a spreadsheet.

I can do almost everything that I want except use the REST API to build the events in the calendar and I can't exactly figure out where I went wrong.

I have followed the documentation suggested by @MarcLaFleur.

I can build and run the application no problem, but when I click on the 'Get my files from OneDrive' button, I get the following:

```<code>Code: 5001
Message: An internal error has occurred.
name: Internal Error
</code>```

This is coming from the program.js file in the public directory somewhere in the else clause of this function.

function getDataWithoutAuthChallenge() {
    Office.context.auth.getAccessTokenAsync({ forceConsent: false },
        function (result) {
            if (result.status === "succeeded") {
                // TODO1: Use the access token to get Microsoft Graph data.
                accessToken = result.value;
                getData("/api/onedriveitems", accessToken);
            }
            else {
                console.log("Code: " + result.error.code);
                console.log("Message: " + result.error.message);
                console.log("name: " + result.error.name);
                document.getElementById("getGraphAccessTokenButton").disabled = true;
            }
        });
}
```

<p>Here are the scopes in my <code>manifest.xml</code></p>

<pre class="lang-xml prettyprint-override"><code>    ...
    <WebApplicationInfo>
      <Id>c931b396-7 ... </Id>
      <Resource>api://localhost:3000/c931b396-7 ... </Resource>
      <Scopes>
        <Scope>files.read.all</Scope>
        <Scope>profile</Scope>
      </Scopes>
    </WebApplicationInfo>
  </VersionOverrides>
</code>```

And here are the scopes on apps.dev.microsoft.com:

If you can shed any light for me, it would really help me out.

答:
The 5001 error often suggests something fundamentally wrong with the add-in API in Office. For example, your Office app doesn't support the API, the manifest is incorrect, or the version of office.js doesn't work with it. Since you're using the sample, two things come to mind:

You aren't running the latest Insiders
build

The wrong manifest is getting loaded (this sometimes happens if you're
on Windows and using a version of Visual Studio 2017 that has old
schema files, so you have to do a post-build clean up of the debug
Manifest XML)

Your manifest and Azure registration look mostly good, though Rick's comment about Scopes is relevant. profile must work with openid as a pair (profile alone won't work; openid alone won't work), and as discussed you need this consented. As the developer, you can try consenting for yourself at the protocol level. You’ll want to update the client_id, redirect_uri, and scope query parameters as appropriate, and add &prompt=consent.

To answer a later question, Excel and Mail add-ins are different, and my answer only applies to Excel. For Outlook there's a different sample.

Body:
I am trying to develop an add-in for Excel with the goal that it will create calendar events based on data inside a spreadsheet.

I can do almost everything that I want except use the REST API to build the events in the calendar and I can't exactly figure out where I went wrong.

I have followed the documentation suggested by @MarcLaFleur.

I can build and run the application no problem, but when I click on the 'Get my files from OneDrive' button, I get the following:

Code: 5001
Message: An internal error has occurred.
name: Internal Error

This is coming from the program.js file in the public directory somewhere in the else clause of this function.

function getDataWithoutAuthChallenge() {
    Office.context.auth.getAccessTokenAsync({ forceConsent: false },
        function (result) {
            if (result.status === "succeeded") {
                // TODO1: Use the access token to get Microsoft Graph data.
                accessToken = result.value;
                getData("/api/onedriveitems", accessToken);
            }
            else {
                console.log("Code: " + result.error.code);
                console.log("Message: " + result.error.message);
                console.log("name: " + result.error.name);
                document.getElementById("getGraphAccessTokenButton").disabled = true;
            }
        });
}

Here are the scopes in my manifest.xml

    ...
    <WebApplicationInfo>
      <Id>c931b396-7 ... </Id>
      <Resource>api://localhost:3000/c931b396-7 ... </Resource>
      <Scopes>
        <Scope>files.read.all</Scope>
        <Scope>profile</Scope>
      </Scopes>
    </WebApplicationInfo>
  </VersionOverrides>

And here are the scopes on apps.dev.microsoft.com:

If you can shed any light for me, it would really help me out.


问:
jpa query where the entity on a collection is in a list
Probably not best described in the title but i have 3 entities

Order -> OneToMany -> OrderProduct

and

OrderProduct <- ManyToOne -> Product

Product <- OneToMany -> OrderProduct ,

my native query that works is

```<code>SELECT t0.*
FROM isc_orders t0
INNER JOIN isc_customers t1 ON t0.ordcustid = t1.customerid
INNER JOIN isc_order_products t2 ON t0.orderid = t2.orderorderid
INNER JOIN isc_products t3 ON t2.ordprodid = t3.productid
where t3.productid in (359, 344, 345, 346, 347, 348)
</code>```

is there any way to do this in a JPA way in a single select as I have my collections and and entities eager loading with join so that the object graph is populated on one pass

答:
Something like this:

```<code>SELECT DISTINCT o
FROM Order o JOIN o.orderProducts op1
JOIN FETCH o.orderProducts op2 JOIN FETCH op2.product
WHERE op1.product.productid IN ?
</code>```

Note that you need two joins with OrderProducts - one for filtering, another for eager fetching.

Body:
Probably not best described in the title but i have 3 entities

Order -> OneToMany -> OrderProduct

and

OrderProduct <- ManyToOne -> Product

Product <- OneToMany -> OrderProduct ,

my native query that works is

SELECT t0.*
FROM isc_orders t0
INNER JOIN isc_customers t1 ON t0.ordcustid = t1.customerid
INNER JOIN isc_order_products t2 ON t0.orderid = t2.orderorderid
INNER JOIN isc_products t3 ON t2.ordprodid = t3.productid
where t3.productid in (359, 344, 345, 346, 347, 348)

is there any way to do this in a JPA way in a single select as I have my collections and and entities eager loading with join so that the object graph is populated on one pass

Body:
Something like this:

SELECT DISTINCT o
FROM Order o JOIN o.orderProducts op1
JOIN FETCH o.orderProducts op2 JOIN FETCH op2.product
WHERE op1.product.productid IN ?

Note that you need two joins with OrderProducts - one for filtering, another for eager fetching.


问:
Range bucket values and create grid using R
Trying to learn how more R... looking to find a clean and easy to follow way to take orders DF:

customerID  Timestamp freq  lat
1          1 2017-01-01    2 31.0
2          2 2017-01-01    3 90.5
3          3 2017-01-01    1  NaN
4          4 2017-01-01    1  NaN
5          1 2017-02-01    2 31.0
6          2 2017-03-01    3 90.5
7          2 2017-07-01    3 90.5

And create a grid, with counts, based on a range of buckets for lat and freq. Buckets:

freq (1, 2-4, 5+)

lat (0-30, 31-60, 61+)

e.g.

      lat
freq   61+    31-60      0-30
5+      0       0          0
2-4     3       2          0
1       0       0          2

Dput:

```<code>> dput(orders)
structure(list(customerID = c(1L, 2L, 3L, 4L, 1L, 2L, 2L), Timestamp =
structure(c(17167,
17167, 17167, 17167, 17198, 17226, 17348), class = "Date"), freq = c(2L,
3L, 1L, 1L, 2L, 3L, 3L), lat = c(31, 90.5, NaN, NaN, 31, 90.5,
90.5)), .Names = c("customerID", "Timestamp", "freq", "lat"), row.names =
c(NA, 7L), class = "data.frame")
</code>```

UPDATE

Been working through this... I used cut to do the bucketing ... not sure if the best route though. Not sure how to do the grid though however.

e.g.

orders$freq_range <- cut(orders$freq, breaks=c(0,1,4,100000), labels=c("1","2-4","5+"))

Body:
Trying to learn how more R... looking to find a clean and easy to follow way to take orders DF:

customerID  Timestamp freq  lat
1          1 2017-01-01    2 31.0
2          2 2017-01-01    3 90.5
3          3 2017-01-01    1  NaN
4          4 2017-01-01    1  NaN
5          1 2017-02-01    2 31.0
6          2 2017-03-01    3 90.5
7          2 2017-07-01    3 90.5

And create a grid, with counts, based on a range of buckets for lat and freq. Buckets:

freq (1, 2-4, 5+)

lat (0-30, 31-60, 61+)

e.g.

      lat
freq   61+    31-60      0-30
5+      0       0          0
2-4     3       2          0
1       0       0          2

Dput:

> dput(orders)
structure(list(customerID = c(1L, 2L, 3L, 4L, 1L, 2L, 2L), Timestamp =
structure(c(17167,
17167, 17167, 17167, 17198, 17226, 17348), class = "Date"), freq = c(2L,
3L, 1L, 1L, 2L, 3L, 3L), lat = c(31, 90.5, NaN, NaN, 31, 90.5,
90.5)), .Names = c("customerID", "Timestamp", "freq", "lat"), row.names =
c(NA, 7L), class = "data.frame")

UPDATE

Been working through this... I used cut to do the bucketing ... not sure if the best route though. Not sure how to do the grid though however.

e.g.

orders$freq_range <- cut(orders$freq, breaks=c(0,1,4,100000), labels=c("1","2-4","5+"))

Body:
You can use a table to get the cross table output:

df

customerID  Timestamp  freq   lat
1           2017-01-01  2    31.0
2           2017-01-01  3    90.5
3           2017-01-01  1      NA
4           2017-01-01  1      NA
1           2017-02-01  2    31.0
2           2017-03-01  3    90.5
2           2017-07-01  3    90.5
2           2017-07-01  5    90.5
3           2017-07-01  6   100.5

df$a<-cut(df$freq, breaks=c(0,1,4,100000), labels=c("1","2-4","5+"))

df$b <- cut(df$lat, breaks=c(0,30,60,100000), labels=c("0-30","31-60","60+"))

df

customerID  Timestamp freq   lat   a     b
 1          2017-01-01    2  31.0 2-4 31-60
 2          2017-01-01    3  90.5 2-4   60+
 3          2017-01-01    1    NA   1  <NA>
 4          2017-01-01    1    NA   1  <NA>
 1          2017-02-01    2  31.0 2-4 31-60
 2          2017-03-01    3  90.5 2-4   60+
 2          2017-07-01    3  90.5 2-4   60+
 2          2017-07-01    5  90.5  5+   60+
 3          2017-07-01    6 100.5  5+   60+

table(df$a, df$b)

       0-30 31-60 60+
  1      0     0   0
  2-4    0     2   3
  5+     0     0   2


问:
How to identify the difference between file and folder ondropping in javascript?
I have a container which allows dropping of files and folder. I want to identify the drop item type( file or folder ) and the exact folder or file path of dropped item.

Note: I am able to get item details if I use webkitGetAsEntry() but I don't want to use this.

Someone suggested me to use files[0].size == 4096 ( for identifying folder) and its not giving exactly 4096. Its varying.

Thanks in advance.

答:
You can check folder using if (!f.type && f.size % 4096 == 0) for folder detection. Please see below snippet.

function handleDrop(e) {
    e.stopPropagation();
    e.preventDefault();

    var files = e.dataTransfer.files,
        folders = 0,
        other = 0;

    for (var i = 0, f; f = files[i]; i++) { // iterate in the files dropped
        if (!f.type && f.size % 4096 == 0) folders++;
        else other++;
    }

    if (folders && !other) {
        if (folders > 1) info.innerHTML = 'You dropped ' + folders +' folders!';
        else info.innerHTML = 'You dropped 1 folder!';
    } else if (!folders && other) {
        if (other > 1) info.innerHTML = 'You dropped ' + other +' files!';
        else info.innerHTML = 'You dropped 1 file!';
    } else {
        if (folders > 1) info.innerHTML = 'You dropped ' + folders +' folders ';
        else info.innerHTML = 'You dropped 1 folder ';
        if (other > 1) info.innerHTML += 'and ' + other +' files!';
        else info.innerHTML += 'and 1 file!';
    }
}

function handleDragOver(e) {
    e.stopPropagation();
    e.preventDefault();
    e.dataTransfer.dropEffect = 'copy';
}

function handleDragEnter(e) {
    e.stopPropagation();
    e.preventDefault();
    info.innerHTML = 'Dragging...';
}

function handleDragLeave(e) {
    e.stopPropagation();
    e.preventDefault();
    info.innerHTML = '';
}

var dropZone = document.getElementById('drop_zone'),
    info = document.getElementById('info');

dropZone.addEventListener('dragenter', handleDragEnter, false);
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('dragleave', handleDragLeave, false);
dropZone.addEventListener('drop', handleDrop, false);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#drop_zone {
    border: 2px dashed #bbb;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    padding: 25px;
    text-align: center;
    font-family: sans-serif;
    font-size: 1.5em;
    color: #bbb;
}
#info {
    font-family: monospace;
    font-size: 18px;
}</code>```

Drop files here

```

Body:
You can check folder using if (!f.type && f.size % 4096 == 0) for folder detection. Please see below snippet.

function handleDrop(e) {
    e.stopPropagation();
    e.preventDefault();

    var files = e.dataTransfer.files,
        folders = 0,
        other = 0;

    for (var i = 0, f; f = files[i]; i++) { // iterate in the files dropped
        if (!f.type && f.size % 4096 == 0) folders++;
        else other++;
    }

    if (folders && !other) {
        if (folders > 1) info.innerHTML = 'You dropped ' + folders +' folders!';
        else info.innerHTML = 'You dropped 1 folder!';
    } else if (!folders && other) {
        if (other > 1) info.innerHTML = 'You dropped ' + other +' files!';
        else info.innerHTML = 'You dropped 1 file!';
    } else {
        if (folders > 1) info.innerHTML = 'You dropped ' + folders +' folders ';
        else info.innerHTML = 'You dropped 1 folder ';
        if (other > 1) info.innerHTML += 'and ' + other +' files!';
        else info.innerHTML += 'and 1 file!';
    }
}

function handleDragOver(e) {
    e.stopPropagation();
    e.preventDefault();
    e.dataTransfer.dropEffect = 'copy';
}

function handleDragEnter(e) {
    e.stopPropagation();
    e.preventDefault();
    info.innerHTML = '<b>Dragging...</b>';
}

function handleDragLeave(e) {
    e.stopPropagation();
    e.preventDefault();
    info.innerHTML = '';
}

var dropZone = document.getElementById('drop_zone'),
    info = document.getElementById('info');

dropZone.addEventListener('dragenter', handleDragEnter, false);
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('dragleave', handleDragLeave, false);
dropZone.addEventListener('drop', handleDrop, false);

#drop_zone {
    border: 2px dashed #bbb;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    padding: 25px;
    text-align: center;
    font-family: sans-serif;
    font-size: 1.5em;
    color: #bbb;
}
#info {
    font-family: monospace;
    font-size: 18px;
}

<div id="drop_zone">Drop files here</div>
<div id="info"></div>


问:
java.lang.NoClassDefFoundError: org/apache/beam/sdk/runners/PipelineRunner after migrating to dataflow 2.x
Getting runtime error:

```<code>"java.lang.NoClassDefFoundError: org/apache/beam/sdk/runners/PipelineRunner"
</code>```

even though I have below in my pom.xml

```<code><dependency>
        <groupId>com.google.cloud.dataflow</groupId>
        <artifactId>google-cloud-dataflow-java-sdk-all</artifactId>
        <version>[2.1.0, 2.99)</version>
    </dependency>
</code>```

All compile time errors have been resolved after moving to 2.X, started getting runtime error.

mvn compile on this project also reports success. Just when I attempt to run the  pipeline from eclipse get this error.

答:
I added below to my pom.xml and deleted any all run profiles in pom.xml and error was resolved.

```<code><dependency>
      <groupId>org.apache.beam</groupId>
      <artifactId>beam-runners-google-cloud-dataflow-java</artifactId>
      <version>[2.1.0, 2.99)</version>
    </dependency>
</code>```

Body:
Getting runtime error:

"java.lang.NoClassDefFoundError: org/apache/beam/sdk/runners/PipelineRunner"

even though I have below in my pom.xml

<dependency>
        <groupId>com.google.cloud.dataflow</groupId>
        <artifactId>google-cloud-dataflow-java-sdk-all</artifactId>
        <version>[2.1.0, 2.99)</version>
    </dependency>

All compile time errors have been resolved after moving to 2.X, started getting runtime error.

mvn compile on this project also reports success. Just when I attempt to run the  pipeline from eclipse get this error.

Body:
I added below to my pom.xml and deleted any all run profiles in pom.xml and error was resolved.

<dependency>
      <groupId>org.apache.beam</groupId>
      <artifactId>beam-runners-google-cloud-dataflow-java</artifactId>
      <version>[2.1.0, 2.99)</version>
    </dependency>


问:
How to select next column when previous column meets certain condition using SQL
I'm using SQL on Impala

The table I'm querying on looks like

customer name   shop1   shop1number shop2   shop2number shop3   shop3number

TOM AB  111 AA  231 AC  321

AMY AC  121 AB  213 AD  231

Franck  AD  123 AE  233 AB  234

enter image description here
here, the numbers are customer loyalty number and the challenge is if I'm looking for the loyalty number of shop 1 (AB), I have no idea which column it falls in as when customer fills in their loyalty number, it's their choice to put in the number at whatever order they profile

答:
If i understand you correctly, you are looking for all the loyalty numbers associated with a shop, so one way could be  to bring rows data to columns first using union all and then search for a shop; lets say AB.

```<code>select * from
(
select customername, shop1 as shop, shop1number as shopnumber
from table1
union all
select customername, shop2 as shop, shop2number as shopnumber
from table1
union all
select customername, shop3 as shop, shop3number as shopnumber
from table1
    ) t
where t.shop = 'AB';
</code>```

Result:

```<code>+--------------+------+------------+
| customername | shop | shopnumber |
+--------------+------+------------+
| AMY          | AB   |        213 |
| TOM          | AB   |        111 |
| Franck       | AB   |        234 |
+--------------+------+------------+
</code>```

DEMO

Body:
If i understand you correctly, you are looking for all the loyalty numbers associated with a shop, so one way could be  to bring rows data to columns first using union all and then search for a shop; lets say AB.

select * from
(
select customername, shop1 as shop, shop1number as shopnumber
from table1
union all
select customername, shop2 as shop, shop2number as shopnumber
from table1
union all
select customername, shop3 as shop, shop3number as shopnumber
from table1
    ) t
where t.shop = 'AB';

Result:

+--------------+------+------------+
| customername | shop | shopnumber |
+--------------+------+------------+
| AMY          | AB   |        213 |
| TOM          | AB   |        111 |
| Franck       | AB   |        234 |
+--------------+------+------------+

DEMO


问:
Add a reference to a class library which target .NET standard 2.0 to a Xamarin PCL which targets .NET Standard 4.5
I am building a Xamarin application and I have my shared code in a PCL which targets the .NET 4.5 framework. I also have a library, which basically implements the service access layer of my Xamarin application in another library, which targets .NET standard 2.0.

The problem is that when I try to reference the latter, Visual Studio gives me the following error:

Project [Service access library] targets '.NETStandard,Version=v2.0'. It cannot be referenced by a project that targets '.NETPortable,Version=v4.5,Profile=Profile111'.

I don't understand why, since, from what I understand, .NET standard stands on a lower abstraction level than the .NET 4.5 framework. Any insight would be much appreciated.

答:
No, minimum version of .net framework which supports .net standard 2.0 is .net 4.6.1 (with .net core 2.0 tooling of vs 2017.3+). .Net 4.7.1 has true support for .net standard 2.0 no matter what tooling you use.

.net standard 2.0 has a large API surface, entity framework core 2.0 and asp.net core 2.0 are developed based on .net standard 2.0 apis.

Note that pcl profile 111 stands for .net 4.5 and Windows 8.1 and they support .net standard 1.1 in common.

As latest xamarin forms 2.5 supports .net standard 2.0, I recommend you to stop using PCL projects, and use .net standard 2 everywhere.

Checkout my to do sample app with xamarin forms which targets both android & iOS using .net standard 2 and ef core 2 + SQL lite at https://github.com/ysmoradi/ToDo

You can also target nuget packages of .net framework libraries such as https://github.com/davideicardi/DynamicExpresso It works on mobile, but it targets .net framework only. You weren't able to use that before, now you can.

If you want to add nuget packages of pcl libraries to your project, take a look at https://github.com/ysmoradi/ToDo/blob/master/src/ToDo/ToDo.csproj#L5

So, update to xamarin forms 2.5, replace your pcl with .net standard 2.0 and you're good to go :)

Visual studio 2017.5 creates projects using .net standard instead of pcl as this is a future.


问:
What's the oldest version of RabbitMQ that works with Celery v2.1.4?
What's the minimum version of RabbitMQ that Celery v2.1.4 can work with?</p>

答:
It should work with versions all the way down to 1.7.

.. but CELERY_AMQP_TASK_RESULT_EXPIRES requires RabbitMQ 2.1+


问:
Getting cart products link and image in shortcode in WooCommerce
I have this code which lists the products added to cart via shortcode. However, these are only the titles. I need help in getting the products URL so the titles are hyperlinks to each product. Also, I would like to display the image of the product in front of the title. Thanks for your help and your time.

Code I currently have:

```<code>// Add Shortcode [bag_products]
function get_cart_products() {
$cart = WC()->cart->get_cart();
 foreach( $cart as $cart_item ){
$product = wc_get_product( $cart_item['product_id'] );
   $cart_items .= '– '.$cart_item['data']->get_title().'<br>';
 }
 return $cart_items;
}
add_shortcode( 'bag_products', 'get_cart_products' );
</code>```

答:
For Product link, use following:

```<code>$product->get_permalink();
</code>```

For Product image, use following:

```<code>$product->get_image( 'thumbnail' );
</code>```

Body:
I have this code which lists the products added to cart via shortcode. However, these are only the titles. I need help in getting the products URL so the titles are hyperlinks to each product. Also, I would like to display the image of the product in front of the title. Thanks for your help and your time.

Code I currently have:

// Add Shortcode [bag_products]
function get_cart_products() {
$cart = WC()->cart->get_cart();
 foreach( $cart as $cart_item ){
$product = wc_get_product( $cart_item['product_id'] );
   $cart_items .= '– '.$cart_item['data']->get_title().'
';
 }
 return $cart_items;
}
add_shortcode( 'bag_products', 'get_cart_products' );

Body:
For Product link, use following:

$product->get_permalink();

For Product image, use following:

$product->get_image( 'thumbnail' );


问:
which offline bootstrap files we need and which one is we don't?
I have downloaded the bootstrap but i'm curious which files we need and which one is we don't? I'm working on it but curious can anyone tell me please?</p>

答:
If you only care about the layout you only need bootstrap.min.css from the css folder.

If you planning to use modal or any components which uses jquery you need to import bootstrap.min.js from the js folder and also latest jquery and popper.js from here


问:
How do I prevent user from adding a duplicate entry into a MySQL database?
I am working on an inventory database program using Java. I wrote a method that adds new product and quantity to the database. I am stuck on how I can prevent user from adding a duplicate entry to the database.
If the user enters a name that already exists in the database, the program should display an error message and show the main menu again. The program should not ask the user to enter the data again. The program should not replace the existing entry.
Thanks in advance!</p>

```<code>public static void addData() {
    try (Connection conn = DriverManager.getConnection(db_url, user, password)) {

        String product = stringInput("Please enter the name of the product to store in inventory");
        int quantity = intInput("Please enter the quantity of the product");

        String addProduct = "INSERT INTO inventory VALUES (?,?)";
        PreparedStatement insertProduct = conn.prepareStatement(addProduct);

        insertProduct.setString(1, product);
        insertProduct.setInt(2, quantity);

        insertProduct.executeUpdate();
        conn.close();

        } catch(SQLException sqle){
            sqle.printStackTrace();
            System.exit(-1);
        }

    }
</code>```

答:
you must query inventory table first to check if product name already exist, something like this

"select i.id from inventory where name=?"

then check with if clause that query has result or not, if true then do whatever needed, like show error...

Body:
I am working on an inventory database program using Java. I wrote a method that adds new product and quantity to the database. I am stuck on how I can prevent user from adding a duplicate entry to the database.
If the user enters a name that already exists in the database, the program should display an error message and show the main menu again. The program should not ask the user to enter the data again. The program should not replace the existing entry.
Thanks in advance!

public static void addData() {
    try (Connection conn = DriverManager.getConnection(db_url, user, password)) {

        String product = stringInput("Please enter the name of the product to store in inventory");
        int quantity = intInput("Please enter the quantity of the product");

        String addProduct = "INSERT INTO inventory VALUES (?,?)";
        PreparedStatement insertProduct = conn.prepareStatement(addProduct);

        insertProduct.setString(1, product);
        insertProduct.setInt(2, quantity);

        insertProduct.executeUpdate();
        conn.close();

        } catch(SQLException sqle){
            sqle.printStackTrace();
            System.exit(-1);
        }

    }


问:
Scraping - Drop menu to select the number of items to show
I am trying to scrape a site that has a drop down menu where the user can select the number of items it displays.

Even if I select the option to see all results, when I parse the page's URL using  bs4 I obtain only the results for the elements displayed on the default page.

This is the URL: http://www.archivioelettorale.it/joomla/index.php?option=com_content&view=category&id=36:elezioni-comunali&Itemid=58

This is my (still rudimental) code:

```<code>headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'}
site = "http://www.archivioelettorale.it/joomla/index.php?option=com_content&view=category&id=36:elezioni-comunali"
soup = BeautifulSoup(requests.get(site,headers=headers,timeout=5).text, 'html.parser')

list_1 = []
list_2 = []
elections_anchors = soup.find_all(class_=re.compile('sectiontableentry'))
for extract in elections_anchors:
    list_1.extend(extract.select('a'))

for element in list_1:
list_2.append('http://www.archivioelettorale.it' + element['href'])
</code>```

The drop down menu is the one saying: "Mostra #"
Thanks a lot

答:
You can get the form data if you inspect the network traffic when you click the drop-down menu. Then submit the form data with a POST request.

```<code>data = {
    'filter':'', 'limit':0, 'id':36, 'sectionid':5,
    'task':'category', 'filter_order':'', 'filter_order_Dir':'',
    'limitstart':0, 'viewcache':0
    }
headers = {
    'user-agent':
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'
    }
site = "http://www.archivioelettorale.it/joomla/index.php?option=com_content&view=category&id=36:elezioni-comunali"
r = requests.post(site, data=data, headers=headers, timeout=20)
soup = BeautifulSoup(r.text, 'html.parser')
</code>```

The page takes some time to load, so i increased the timeout. You should now have 4888 results.

Body:
I am trying to scrape a site that has a drop down menu where the user can select the number of items it displays.

Even if I select the option to see all results, when I parse the page's URL using  bs4 I obtain only the results for the elements displayed on the default page.

This is the URL: http://www.archivioelettorale.it/joomla/index.php?option=com_content&view=category&id=36:elezioni-comunali&Itemid=58

This is my (still rudimental) code:

headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'}
site = "http://www.archivioelettorale.it/joomla/index.php?option=com_content&view=category&id=36:elezioni-comunali"
soup = BeautifulSoup(requests.get(site,headers=headers,timeout=5).text, 'html.parser')

list_1 = []
list_2 = []
elections_anchors = soup.find_all(class_=re.compile('sectiontableentry'))
for extract in elections_anchors:
    list_1.extend(extract.select('a'))

for element in list_1:
list_2.append('http://www.archivioelettorale.it' + element['href'])

The drop down menu is the one saying: "Mostra #"
Thanks a lot

Body:
You can get the form data if you inspect the network traffic when you click the drop-down menu. Then submit the form data with a POST request.

data = {
    'filter':'', 'limit':0, 'id':36, 'sectionid':5,
    'task':'category', 'filter_order':'', 'filter_order_Dir':'',
    'limitstart':0, 'viewcache':0
    }
headers = {
    'user-agent':
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'
    }
site = "http://www.archivioelettorale.it/joomla/index.php?option=com_content&view=category&id=36:elezioni-comunali"
r = requests.post(site, data=data, headers=headers, timeout=20)
soup = BeautifulSoup(r.text, 'html.parser')

The page takes some time to load, so i increased the timeout. You should now have 4888 results.


问:
How can I prevent reloading the page when we go back to the previous page?
Now I am working with Ionic3, Angular4 android app. It is reloading the page  in android app every time when i am going back to the previous page. How can prevent this. Still that page is already loaded. SO I don't want to reload again and again</p>

答:
Use Push and Pop in ionic framework  which works as a simple stack that new pages are pushed onto and popped off of, corresponding to moving forward and backward in history.

Refer Ionic documentation too

```<code>@Component({
  template: `
  <ion-header>
    <ion-navbar>
      <ion-title>Login</ion-title>
    </ion-navbar>
  </ion-header>

  <ion-content>
    <button (click)="goToOtherPage()">
      Go to OtherPage
    </button>
  </ion-content>`
})
export class StartPage {
  constructor(public navCtrl: NavController) {}

  goToOtherPage() {
    //push another page onto the history stack
    //causing the nav controller to animate the new page in
    this.navCtrl.push(OtherPage);
  }
}

@Component({
  template: `
  <ion-header>
    <ion-navbar>
      <ion-title>Other Page</ion-title>
    </ion-navbar>
  </ion-header>

  <ion-content>I'm the other page!</ion-content>`
})
class OtherPage {}
</code>```

Body:
Use Push and Pop in ionic framework  which works as a simple stack that new pages are pushed onto and popped off of, corresponding to moving forward and backward in history.

Refer Ionic documentation too

@Component({
  template: `
  <ion-header>
    <ion-navbar>
      <ion-title>Login</ion-title>
    </ion-navbar>
  </ion-header>

  <ion-content>
    <button (click)="goToOtherPage()">
      Go to OtherPage
    </button>
  </ion-content>`
})
export class StartPage {
  constructor(public navCtrl: NavController) {}

  goToOtherPage() {
    //push another page onto the history stack
    //causing the nav controller to animate the new page in
    this.navCtrl.push(OtherPage);
  }
}

@Component({
  template: `
  <ion-header>
    <ion-navbar>
      <ion-title>Other Page</ion-title>
    </ion-navbar>
  </ion-header>

  <ion-content>I'm the other page!</ion-content>`
})
class OtherPage {}


问:
footer scrolls off screen when used in CoordinatorLayout
I have HomeActivity which contains fragment and at the bottom it has custom navigation view as shown below.

By clicking on profile pic, it replaces the fragment with UserProfileView fragment. userProfileView fragment has Collapsing toolbar inside coordinatorLayout.

userprofileview.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:bind="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="resource"
            type="com.example.app.model.ResourceData" />

        <import type="android.view.View" />

    </data>

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/bg_home"
        android:fitsSystemWindows="true">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/app_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/bg_home">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/toolbar_layout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                </LinearLayout>
            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/_10sdp"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/ic_list"
                    android:layout_width="@dimen/_17sdp"
                    android:layout_height="@dimen/_17sdp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="@dimen/_10sdp"
                    android:background="@drawable/ic_list_selected" />

                <ImageView
                    android:id="@+id/ic_grid_view"
                    android:layout_width="@dimen/_15sdp"
                    android:layout_height="@dimen/_15sdp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="@dimen/_10sdp"
                    android:background="@drawable/ic_grid_unselected" />
            </LinearLayout>

            <android.support.v7.widget.RecyclerView
                android:visibility="gone"
                android:id="@+id/rv_post"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:resource="@{resource}" />

        </LinearLayout>
    </android.support.design.widget.CoordinatorLayout>
</layout>
</code>```

The problem is when i click to any other menu from bottom navigation menu, it scrolls off the screen as shown below.

This issue is occurring after adding CoordinatorLayout in UserProfileView framgment.

If i replace CoordinatorLayout with LinearLayout then it works fine but doesn't get the functionality of collapsing toolbar.

Thank you!

答:
android:fitsSystemWindows="true" in your fragment_user_profile.xml causes problem. Simply... it makes your drawer layout looks fullscreen.

Roughly, user screen maintains top indicator margin and home screen doesn't. So home screen moved up as indicator size. (Actually it isn't, Details about fitsSystemWindows:
Why would I want to fitsSystemWindows)

So, remove fitsSystemWindows from fragment_user_profile.xml will fix your problem.

And I suggest you add fitsSystemWindows to your container_body in activity_main.xml, but I'm not sure that what is the actual code, so it is your call.

Body:
I have HomeActivity which contains fragment and at the bottom it has custom navigation view as shown below.

By clicking on profile pic, it replaces the fragment with UserProfileView fragment. userProfileView fragment has Collapsing toolbar inside coordinatorLayout.

userprofileview.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:bind="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="resource"
            type="com.example.app.model.ResourceData" />

        <import type="android.view.View" />

    </data>

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/bg_home"
        android:fitsSystemWindows="true">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/app_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/bg_home">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/toolbar_layout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                </LinearLayout>
            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/_10sdp"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/ic_list"
                    android:layout_width="@dimen/_17sdp"
                    android:layout_height="@dimen/_17sdp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="@dimen/_10sdp"
                    android:background="@drawable/ic_list_selected" />

                <ImageView
                    android:id="@+id/ic_grid_view"
                    android:layout_width="@dimen/_15sdp"
                    android:layout_height="@dimen/_15sdp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="@dimen/_10sdp"
                    android:background="@drawable/ic_grid_unselected" />
            </LinearLayout>

            <android.support.v7.widget.RecyclerView
                android:visibility="gone"
                android:id="@+id/rv_post"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:resource="@{resource}" />

        </LinearLayout>
    </android.support.design.widget.CoordinatorLayout>
</layout>

The problem is when i click to any other menu from bottom navigation menu, it scrolls off the screen as shown below.

This issue is occurring after adding CoordinatorLayout in UserProfileView framgment.

If i replace CoordinatorLayout with LinearLayout then it works fine but doesn't get the functionality of collapsing toolbar.

Thank you!


答:
You can define UNIQUE constraint in your DB. Then if a duplicate entry is added it will throw an SQLIntegrityConstraintViolationException. Catch the exception and handle the error in your app.

May not be applicable to you, but just for your information spring-data exposes org.springframework.dao.DataIntegrityViolationException for achieving the same. When the same issue encountered spring-data wraps the underneath exception and re-throws a DataIntegrityViolationException so that the client can handle them inside the Error handling aspect using @ControllerAdvice.

Title: How do I prevent user from adding a duplicate entry into a MySQL database?


问:
How to run MSBuild from Powershell without spawning msbuild.exe process?
I am considering running MSBuild from a Powershell script by tapping directly to the MSBuild assemblies (as opposed to looking up MSBuild install path and starting msbuild.exe as a child process).

Has anyone done this? What would be the simplest, most straightforward way to run the build? Are there any pros/cons to either technique you'd like to point out? (I'm especially interested in any issues that might arise from running msbuild in the same process/appdomain as the rest of the script).

Currently my thinking is something along these lines:

```<code>[void][System.Reflection.Assembly]::Load('Microsoft.Build.Engine, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][Microsoft.Build.BuildEngine.Engine]::GlobalEngine.BuildProjectFile("path/main.proj")
</code>```

答:
The simplest embedded-build invocation that worked and produced output was:

```<code>[void][System.Reflection.Assembly]::Load('Microsoft.Build.Engine, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
$engine = New-Object Microsoft.Build.BuildEngine.Engine
$engine.RegisterLogger((New-Object Microsoft.Build.BuildEngine.ConsoleLogger))
$engine.BuildProjectFile('fullPath\some.proj')
</code>```

However, it turns out embedding MSBuild directly in Powershell (V1) is problematic:

```<code>'MSBUILD : warning MSB4056: The MSBuild engine must be called on
a single-threaded-apartment. Current threading model is "MTA".
Proceeding, but some tasks may not function correctly.'
</code>```

Why oh why are we still paying COM tax in 2009 while working in a managed environment?

My conclusion is that embedding MSBuild in Powershell (V1) is not a good idea. For reference, I'm also including the process-based approach I ended up using:

```<code>[void][System.Reflection.Assembly]::Load('Microsoft.Build.Utilities.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
$msbuild = [Microsoft.Build.Utilities.ToolLocationHelper]::GetPathToDotNetFrameworkFile("msbuild.exe", "VersionLatest")
&$msbuild fullPath\some.proj
</code>```

OwnerDisplayName: Milan Gardian

Body:
I am considering running MSBuild from a Powershell script by tapping directly to the MSBuild assemblies (as opposed to looking up MSBuild install path and starting msbuild.exe as a child process).

Has anyone done this? What would be the simplest, most straightforward way to run the build? Are there any pros/cons to either technique you'd like to point out? (I'm especially interested in any issues that might arise from running msbuild in the same process/appdomain as the rest of the script).

Currently my thinking is something along these lines:

[void][System.Reflection.Assembly]::Load('Microsoft.Build.Engine, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][Microsoft.Build.BuildEngine.Engine]::GlobalEngine.BuildProjectFile("path/main.proj")

Body:
The simplest embedded-build invocation that worked and produced output was:

[void][System.Reflection.Assembly]::Load('Microsoft.Build.Engine, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
$engine = New-Object Microsoft.Build.BuildEngine.Engine
$engine.RegisterLogger((New-Object Microsoft.Build.BuildEngine.ConsoleLogger))
$engine.BuildProjectFile('fullPath\some.proj')

However, it turns out embedding MSBuild directly in Powershell (V1) is problematic:

'MSBUILD : warning MSB4056: The MSBuild engine must be called on
a single-threaded-apartment. Current threading model is "MTA".
Proceeding, but some tasks may not function correctly.'

Why oh why are we still paying COM tax in 2009 while working in a managed environment?

My conclusion is that embedding MSBuild in Powershell (V1) is not a good idea. For reference, I'm also including the process-based approach I ended up using:

[void][System.Reflection.Assembly]::Load('Microsoft.Build.Utilities.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
$msbuild = [Microsoft.Build.Utilities.ToolLocationHelper]::GetPathToDotNetFrameworkFile("msbuild.exe", "VersionLatest")
&$msbuild fullPath\some.proj


问:
using an input variable in multiple functions in python
I would like to know how to use the 'name' variable in the entername() function in the hello() function.

It is an input variable, does anyone know how to use it across multiple functions?

```<code>def entername():
    name = input("Please enter your name: ")
    return

def hello():
    text = "Hello " + name + ", welcome to the simulator..."
    for char in text:
        sys.stdout.write(char)
        sys.stdout.flush()
        char, time.sleep(0.1)
    print(char)
    return
</code>```

答:
If you want to use the same "name" variable from different functions you have to define in globally.
Here, we define our variable inside the global scope and force functions to use the global variable instead of defining their own local variables.</p>

```<code>import sys, time

name=''

def entername( ):
    global name
    name = input("Please enter your name: ")
    return

def hello():
    global name
    text = "Hello " + name + ", welcome to the simulator..."
    for char in text:
        sys.stdout.write(char)
        sys.stdout.flush()
        char, time.sleep(0.1)
    print(char)
    return

entername()
hello()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to know how to use the 'name' variable in the entername() function in the hello() function.

It is an input variable, does anyone know how to use it across multiple functions?

def entername():
    name = input("Please enter your name: ")
    return

def hello():
    text = "Hello " + name + ", welcome to the simulator..."
    for char in text:
        sys.stdout.write(char)
        sys.stdout.flush()
        char, time.sleep(0.1)
    print(char)
    return

Body:
If you want to use the same "name" variable from different functions you have to define in globally.
Here, we define our variable inside the global scope and force functions to use the global variable instead of defining their own local variables.

import sys, time

name=''

def entername( ):
    global name
    name = input("Please enter your name: ")
    return

def hello():
    global name
    text = "Hello " + name + ", welcome to the simulator..."
    for char in text:
        sys.stdout.write(char)
        sys.stdout.flush()
        char, time.sleep(0.1)
    print(char)
    return

entername()
hello()


问:
Instantiating a generic class in Java
I know Java's generics are somewhat inferior to .Net's.

I have a generic class Foo<T>, and I really need to instantiate a T in Foo using a parameter-less constructor. How can one work around Java's limitation?

答:
For Java 8 ....

There is a good solution at https://stackoverflow.com/a/36315051/2648077 post.

This uses Java 8 Supplier functional interface

Title: Instantiating a generic class in Java


问:
When to use getX method
Coming from a C# background we use properties for something that would not take long to retrieve and a getX method if something would take long (msdn link). In Java, since there are no properties, do you use getX for both cases or is there some other convention to indicate a quick access from a not so quick access (other than documenting it)?

Edit:
For example would you use a different naming convention for a time consuming get operation like database access or also use the getX naming convention?

答:
The getX convention comes from JavaBean specification. More recently, usage of POJOs (Plain Old Java Objects) has become very popular since many frameworks manipulate your objects using getters and setters, including Spring and Hibernate.

More specifically:

getX for a nonboolean X (getter)

isX for a boolean X (getter)

setX for any value of X (setter)

If you won't use a framework that requires usage of POJOs, then by all means name your methods so you know what they do at first glance.

Title: When to use getX method


问:
Comparing multiple database row values with Laravel Eloquent / MySQL
I'm using Laravel for my project and have a MySQL table as follows:

```<code>| User_id | technology | years_experience |
| 1       | PHP        |  4               |
| 2       | AngularJS  |  2               |
| 1       | HTML       |  2               |
</code>```

At the moment I'm using a standard where query which only supports one criteria

```<code>Table::where([
['technology', '=', 'PHP'],
['years_experience', '>', 2]
])->get()->pluck('user_id');
</code>```

How can I filter and group results by User_id if I wanted to retrieve all User_ids with PHP > 2 AND HTML > 1?

答:
Question is (condition1 AND condition2) AND (condition3 AND condition4)

This is how you can do it:

```<code>Table::where(function($query){
    $query->where('technology', '=', 'PHP')->where('years_experience', '>', 2);
})->where(function($query) {
    $query->where('technology', '=', 'HTML')->where('years_experience', '=', 1);
})->get()->pluck('user_id');
</code>```

Body:
I'm using Laravel for my project and have a MySQL table as follows:

| User_id | technology | years_experience |
| 1       | PHP        |  4               |
| 2       | AngularJS  |  2               |
| 1       | HTML       |  2               |

At the moment I'm using a standard where query which only supports one criteria

Table::where([
['technology', '=', 'PHP'],
['years_experience', '>', 2]
])->get()->pluck('user_id');

How can I filter and group results by User_id if I wanted to retrieve all User_ids with PHP > 2 AND HTML > 1?

Body:
Question is (condition1 AND condition2) AND (condition3 AND condition4)

This is how you can do it:

Table::where(function($query){
    $query->where('technology', '=', 'PHP')->where('years_experience', '>', 2);
})->where(function($query) {
    $query->where('technology', '=', 'HTML')->where('years_experience', '=', 1);
})->get()->pluck('user_id');


问:
jQuery auto refresh every minute based on current rest second time
I have an jQuery Auto Refresh my data. I'm running it every 60 seconds/1 minute.

```<code>setInterval(function()
{
    //if every 60 seconds based on current time (count the rest of second from current time) then run the AJAX.
    $.ajax(
    {
        url: "chkProfile.php",
        type: "POST",
        data:
        {
        },
        dataType: "JSON",
        success: function (jsonStr)
        {
        }
    })
},60000);
</code>```

And now  I want when anytime I refresh my page manually, Example I'm on 12:20:40 and as We know the rest of seconds is 20 then run the AJAX.

The current If I'm on 12:20:40 then it will run the ajax on 12:21:40

What I want is, If I'm on 12:20:40 then it should run the ajax on 12:21:00

答:
easy solution:

You could check it every second if second was 0 ajax must run.
Try this:

```<code>setInterval(function()
{
   var second = parseInt((new Date().getTime() / 1000) % 60);
    if(second === 0) {
       $.ajax({
                url: "chkProfile.php",
                type: "POST",
                data:{},
                dataType: "JSON",
                success: function (jsonStr){}
             });
      }
},1000); // or less than 1 sec
</code>```

optimized solution:

first calculate how seconds is remained to next minutes and set interval every 60 minutes.

```<code>   // define fetch data function
   var fetchData  = function(){
       $.ajax({
            url: "chkProfile.php",
            type: "POST",
            data:{},
            dataType: "JSON",
            success: function (jsonStr){}
        });
   }

   // begin when dom is ready
   $(document).ready(function(){
      fetchData(); // run fetchData(); here if you want to ajax at first load time
      // get remain time to next minute
      var remainTime = 60 - parseInt((new Date().getTime() / 1000) % 60);
      setTimeout(function(){
         fetchData();
         // redo every minute
         setInterval(fetchData, 60000);
      }, remainTime*1000)
    })
</code>```

Snippet for none ajax example:

// define fetch data function
var fetchData = function() {
  document.write(new Date())
}

// begin when dom is ready
$(document).ready(function() {
  fetchData(); // run fetchData(); here if you want to ajax at first load time
  // get remain time to next minute
  var remainTime = 60 - parseInt((new Date().getTime() / 1000) % 60);
  setTimeout(function() {
    fetchData();
    // redo every minute
    setInterval(fetchData, 60000);
  }, remainTime * 1000)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I have an jQuery Auto Refresh my data. I'm running it every 60 seconds/1 minute.

setInterval(function()
{
    //if every 60 seconds based on current time (count the rest of second from current time) then run the AJAX.
    $.ajax(
    {
        url: "chkProfile.php",
        type: "POST",
        data:
        {
        },
        dataType: "JSON",
        success: function (jsonStr)
        {
        }
    })
},60000);

And now  I want when anytime I refresh my page manually, Example I'm on 12:20:40 and as We know the rest of seconds is 20 then run the AJAX.

The current If I'm on 12:20:40 then it will run the ajax on 12:21:40

What I want is, If I'm on 12:20:40 then it should run the ajax on 12:21:00

Body:
easy solution:

You could check it every second if second was 0 ajax must run.
Try this:

setInterval(function()
{
   var second = parseInt((new Date().getTime() / 1000) % 60);
    if(second === 0) {
       $.ajax({
                url: "chkProfile.php",
                type: "POST",
                data:{},
                dataType: "JSON",
                success: function (jsonStr){}
             });
      }
},1000); // or less than 1 sec

optimized solution:

first calculate how seconds is remained to next minutes and set interval every 60 minutes.

   // define fetch data function
   var fetchData  = function(){
       $.ajax({
            url: "chkProfile.php",
            type: "POST",
            data:{},
            dataType: "JSON",
            success: function (jsonStr){}
        });
   }

   // begin when dom is ready
   $(document).ready(function(){
      fetchData(); // run fetchData(); here if you want to ajax at first load time
      // get remain time to next minute
      var remainTime = 60 - parseInt((new Date().getTime() / 1000) % 60);
      setTimeout(function(){
         fetchData();
         // redo every minute
         setInterval(fetchData, 60000);
      }, remainTime*1000)
    })

Snippet for none ajax example:

// define fetch data function
var fetchData = function() {
  document.write(new Date())
}

// begin when dom is ready
$(document).ready(function() {
  fetchData(); // run fetchData(); here if you want to ajax at first load time
  // get remain time to next minute
  var remainTime = 60 - parseInt((new Date().getTime() / 1000) % 60);
  setTimeout(function() {
    fetchData();
    // redo every minute
    setInterval(fetchData, 60000);
  }, remainTime * 1000)
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
getting a segmentation fault when trying to read a file?
I am passing in argv[1] for the fileName and i am getting a segfault but i do not know why. i am using a linked list to hold instances of a car struct that holds 2 chars and an int. i feel like the problem is in my fscanf statement but i am not sure.</p>

```<code>void readFile(List *north, List *east, List *south, List *west, char *fileName) {
    char *file = fileName;
    FILE *fp = fopen(file, "r");

    if(!fp) {
        printf("File could not be opened...");
        return;
    }

    while(!feof(fp)) {
        Car *temp = NULL; //Initialize a blank car
        fscanf(fp, "%s %s %d", &temp->direc, &temp->turn, &temp->time); //scan the direction path and time
        //into the Car Node

        //Add to North List
        if(temp->direc == 'N') {
            insertBack(north, temp);
        }

        //Add to East List
        if(temp->direc == 'E') {
            insertBack(east, temp);
        }

        //Add to South List
        if(temp->direc == 'S') {
            insertBack(south, temp);
        }

        //Add to West List
        if(temp->direc == 'W') {
            insertBack(west, temp);
        }

        else {
            printf("Something went wrong...");
            return;
        }
    }
    fclose(fp);
}
</code>```

答:
Car *temp = NULL; //Initialize a blank car

You are not initializing a "blank" car here. The temp variable is just NULL. Use malloc to allocate space before you do fscanf:

Car *temp = malloc(sizeof(Car));

If by "blank" you mean zeroing out the allocated space, use calloc.

Body:
I am passing in argv[1] for the fileName and i am getting a segfault but i do not know why. i am using a linked list to hold instances of a car struct that holds 2 chars and an int. i feel like the problem is in my fscanf statement but i am not sure.

void readFile(List *north, List *east, List *south, List *west, char *fileName) {
    char *file = fileName;
    FILE *fp = fopen(file, "r");

    if(!fp) {
        printf("File could not be opened...");
        return;
    }

    while(!feof(fp)) {
        Car *temp = NULL; //Initialize a blank car
        fscanf(fp, "%s %s %d", &temp->direc, &temp->turn, &temp->time); //scan the direction path and time
        //into the Car Node

        //Add to North List
        if(temp->direc == 'N') {
            insertBack(north, temp);
        }

        //Add to East List
        if(temp->direc == 'E') {
            insertBack(east, temp);
        }

        //Add to South List
        if(temp->direc == 'S') {
            insertBack(south, temp);
        }

        //Add to West List
        if(temp->direc == 'W') {
            insertBack(west, temp);
        }

        else {
            printf("Something went wrong...");
            return;
        }
    }
    fclose(fp);
}