问:
WP_Query 'post__in with CustomPost Type not working
I have a custom post type in WordPress called event. There are several hundred posts of type event, but two examples have the IDs 760 and 1545.

This code works and returns a format list containing the correct single post:

```<code>    $args = array( 'p' => '760', 'post_type' => 'event' );
    $query = new WP_Query($args);
    if ( $query->have_posts() ) :

        $output .= '<ul class="postlist">';
        while ( $query->have_posts() ) :
            $query->the_post();
            $output .= '<li>';
            $output .= '<a href="'.get_the_permalink(get_the_ID()).'" id="'.get_the_ID().'">'.get_the_title().'</a>';
            if ( $excerpt) {
                $output .= '<p>'.get_the_excerpt().'</p>';
            }
            $output .= '</li>';
        endwhile;
        $output .= '</ul>';

    endif;
    wp_reset_postdata();
    echo $output;
</code>```

If I modify the query as the following examples, nothing is returned.None of these ammendments return anything:

```<code>    $args = array( 'post__in' => array('760','1545'), 'post_type' => 'event' );
    $args = array( 'post__in' => array('760'), 'post_type' => 'event' );
    $args = array( 'post__in' => array('760','1545'));
</code>```

Note that the second ID does work correctly as follows so I have verified the posts exist and can be individually queried:

```<code>$args = array( 'p' => '1545', 'post_type' => 'event' );
</code>```

So My question is this, can I Custom Post Type be used with post__in?  All the information I'm seeing on the internet suggest it should work OK. Greatful for any thoughts on this.

答:
The problem was that for some reason the posts I was querying were set to draft. This only seems to affect WP_Query when using post__in which does check the post has a published status

The query produced by WordPress when using post__in looks like this:

```<code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE 1=1
AND wp_posts.ID IN (760,1545)
AND wp_posts.post_type = 'event'
AND (
    wp_posts.post_status = 'publish'
    OR wp_posts.post_status = 'private'
)
ORDER BY wp_posts.post_date DESC
</code>```

Where as the query produced for the 'p' argument looks like this, with no additional status filter:

```<code>SELECT wp_posts.*
FROM wp_posts
WHERE 1=1
AND wp_posts.ID = 760
AND wp_posts.post_type = 'event'
ORDER BY wp_posts.post_date DESC
</code>```

Body:
I have a custom post type in WordPress called event. There are several hundred posts of type event, but two examples have the IDs 760 and 1545.

This code works and returns a format list containing the correct single post:

    $args = array( 'p' => '760', 'post_type' => 'event' );
    $query = new WP_Query($args);
    if ( $query->have_posts() ) :

        $output .= '
';
        while ( $query->have_posts() ) :
            $query->the_post();
            $output .= '
';
            $output .= ''.get_the_title().'';
            if ( $excerpt) {
                $output .= '
'.get_the_excerpt().'
';
            }
            $output .= '
';
        endwhile;
        $output .= '
';

    endif;
    wp_reset_postdata();
    echo $output;

If I modify the query as the following examples, nothing is returned.None of these ammendments return anything:

    $args = array( 'post__in' => array('760','1545'), 'post_type' => 'event' );
    $args = array( 'post__in' => array('760'), 'post_type' => 'event' );
    $args = array( 'post__in' => array('760','1545'));

Note that the second ID does work correctly as follows so I have verified the posts exist and can be individually queried:

$args = array( 'p' => '1545', 'post_type' => 'event' );

So My question is this, can I Custom Post Type be used with post__in?  All the information I'm seeing on the internet suggest it should work OK. Greatful for any thoughts on this.

Body:
The problem was that for some reason the posts I was querying were set to draft. This only seems to affect WP_Query when using post__in which does check the post has a published status

The query produced by WordPress when using post__in looks like this:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE 1=1
AND wp_posts.ID IN (760,1545)
AND wp_posts.post_type = 'event'
AND (
    wp_posts.post_status = 'publish'
    OR wp_posts.post_status = 'private'
)
ORDER BY wp_posts.post_date DESC

Where as the query produced for the 'p' argument looks like this, with no additional status filter:

SELECT wp_posts.*
FROM wp_posts
WHERE 1=1
AND wp_posts.ID = 760
AND wp_posts.post_type = 'event'
ORDER BY wp_posts.post_date DESC


来源: stackexchange

问:
get the wanted objects from the array of objects
This is my first question in stackoverflow, So any kind of help is appreciated.

I have an array like this

```<code>var products = [{status:'available', ...},{status:'none', ...},{status:'available', ...},{status:'', ...},{status:'none', ...}]
</code>```

how can I get an array that contains only  products[i].status = 'available' .

I already did this with for loop but isn't there a better method? My code is practically full of loops now & it's not easy to read.

Thank you for you help.

答:
Use Array.filter method

```<code>products.filter(function(product){
    return product.status == 'available'
})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is my first question in stackoverflow, So any kind of help is appreciated.

I have an array like this

var products = [{status:'available', ...},{status:'none', ...},{status:'available', ...},{status:'', ...},{status:'none', ...}]

how can I get an array that contains only  products[i].status = 'available' .

I already did this with for loop but isn't there a better method? My code is practically full of loops now & it's not easy to read.

Thank you for you help.

Body:
Use Array.filter method

products.filter(function(product){
    return product.status == 'available'
})


问:
Array Doesn't Push Elements Node.js
I'm creating a simple form that allows user to submit input that is displayed on the page. Each input is added after the other, so if the user enters "1" and clicks submit, then "1" would be displayed on the page. If the user then enters "2", then "2" would be displayed right underneath "1". "1" is NOT removed.

I'm saving the user input into the array and I will iterate over that array to render the user input on the page. The problem I'm running into is that nothing in my array gets saved, so when I try to render the user input onto the page, nothing rendered.

```<code>    /* This is pseudocode */
    var list = [];

    for each value in list
        add value to page

    addToList = function() {
        var value = document.getElementById("userEntry").value;
        list.push(value);
    }
</code>```

The addToList function is called whenever the user clicks submit. I'm using Node.js and I feel that this doesn't work because the JavaScript file gets refreshed every time I submit and the page reloads, clearing the array.

What should I do if I want my array to save the values of the user inputs.

答:
You have initialised a reference to a Function instance with the name addToList but have never invoked this Function.

Add a console.log inside the addToList Function and you will see that this Function is never called.

Instead you need to declare the Function, and then execute it by calling it with parenthesis: addToList()

Title: Array Doesn't Push Elements Node.js

Body:
I'm creating a simple form that allows user to submit input that is displayed on the page. Each input is added after the other, so if the user enters "1" and clicks submit, then "1" would be displayed on the page. If the user then enters "2", then "2" would be displayed right underneath "1". "1" is NOT removed.

I'm saving the user input into the array and I will iterate over that array to render the user input on the page. The problem I'm running into is that nothing in my array gets saved, so when I try to render the user input onto the page, nothing rendered.

    /* This is pseudocode */
    var list = [];

    for each value in list
        add value to page

    addToList = function() {
        var value = document.getElementById("userEntry").value;
        list.push(value);
    }

The addToList function is called whenever the user clicks submit. I'm using Node.js and I feel that this doesn't work because the JavaScript file gets refreshed every time I submit and the page reloads, clearing the array.

What should I do if I want my array to save the values of the user inputs.


问:
Spring Web Flux (reactive) functional route not working as expected with Kotlin
Hello good people interested in writing spring apps in Kotlin. I am playing with Spring Boot 2.0.0 snapshot and spring-webflux. This piece of code:

```<code>@Component
class TestRouter() : RouterFunction<ServerResponse> {
  override fun route(request: ServerRequest) = route(request) {
    "/".route {
      GET("/hello") { ServerResponse.ok().body(BodyInserters.fromObject("World")) }
      "/{id}".route {
        GET("/hello") { ServerResponse.ok().body(BodyInserters.fromObject("World ${request.pathVariable("id")}")) }
      }
    }
  }
}
</code>```

does not work as expected (at least as I would expect:))

```<code>➜  ~ curl -i http://localhost:8080/hello
HTTP/1.1 200 OK
transfer-encoding: chunked
Content-Type: text/plain;charset=UTF-8

World
</code>```

but:

```<code>➜  ~ curl -i http://localhost:8080/1/hello
HTTP/1.1 404 Not Found
content-length: 0
</code>```

Working case trace:

```<code>2017-03-03 00:58:03.865 TRACE 7666 --- [ctor-http-nio-4] o.s.w.r.f.server.RequestPredicates       : Pattern "//**" matches against value "/hello"
2017-03-03 00:58:03.865 DEBUG 7666 --- [ctor-http-nio-4] o.s.w.r.function.server.RouterFunctions  : Nested predicate "//**" matches against "GET /hello"
2017-03-03 00:58:03.865 TRACE 7666 --- [ctor-http-nio-4] o.s.w.r.f.server.RequestPredicates       : Method "GET" matches against value "GET"
2017-03-03 00:58:03.866 TRACE 7666 --- [ctor-http-nio-4] o.s.w.r.f.server.RequestPredicates       : Pattern "/hello" matches against value "/hello"
2017-03-03 00:58:03.866 DEBUG 7666 --- [ctor-http-nio-4] o.s.w.r.function.server.RouterFunctions  : Predicate "(GET && /hello)" matches against "GET /hello"
</code>```

Not working case trace:

```<code>2017-03-03 00:59:26.958 TRACE 7666 --- [ctor-http-nio-1] o.s.w.r.f.server.RequestPredicates       : Pattern "//**" matches against value "/1/hello"
2017-03-03 00:59:26.958 DEBUG 7666 --- [ctor-http-nio-1] o.s.w.r.function.server.RouterFunctions  : Nested predicate "//**" matches against "GET /1/hello"
2017-03-03 00:59:26.958 TRACE 7666 --- [ctor-http-nio-1] o.s.w.r.f.server.RequestPredicates       : Method "GET" matches against value "GET"
2017-03-03 00:59:26.958 TRACE 7666 --- [ctor-http-nio-1] o.s.w.r.f.server.RequestPredicates       : Pattern "/hello" does not match against value "/1/hello"
2017-03-03 00:59:26.959 TRACE 7666 --- [ctor-http-nio-1] o.s.w.r.f.server.RequestPredicates       : Pattern "/{id}/**" matches against value "/1/hello"
2017-03-03 00:59:26.959 DEBUG 7666 --- [ctor-http-nio-1] o.s.w.r.function.server.RouterFunctions  : Nested predicate "/{id}/**" matches against "GET /1/hello"
2017-03-03 00:59:26.959 TRACE 7666 --- [ctor-http-nio-1] o.s.w.r.f.server.RequestPredicates       : Method "GET" matches against value "GET"
2017-03-03 00:59:26.959 TRACE 7666 --- [ctor-http-nio-1] o.s.w.r.f.server.RequestPredicates       : Pattern "/hello" does not match against value "/1/hello"
</code>```

This seems like a bug (as the "/{id}".route {...} supposedly is using RouterFunctions.nest), but I could be wrong. Your thoughts and help are welcome.

I obviously know that I can make /1/hello work by just writing GET("/{id}/hello") { ... }, but I am interested in the nested .route { ...} variant as it supports my use case of adding nested routes from another location (like a map, etc).

答: This issue has been fixed in SPR-15310.</p>

Body:
Hello good people interested in writing spring apps in Kotlin. I am playing with Spring Boot 2.0.0 snapshot and spring-webflux. This piece of code:

@Component
class TestRouter() : RouterFunction<ServerResponse> {
  override fun route(request: ServerRequest) = route(request) {
    "/".route {
      GET("/hello") { ServerResponse.ok().body(BodyInserters.fromObject("World")) }
      "/{id}".route {
        GET("/hello") { ServerResponse.ok().body(BodyInserters.fromObject("World ${request.pathVariable("id")}")) }
      }
    }
  }
}

does not work as expected (at least as I would expect:))

➜  ~ curl -i http://localhost:8080/hello
HTTP/1.1 200 OK
transfer-encoding: chunked
Content-Type: text/plain;charset=UTF-8

World

but:

➜  ~ curl -i http://localhost:8080/1/hello
HTTP/1.1 404 Not Found
content-length: 0

Working case trace:

2017-03-03 00:58:03.865 TRACE 7666 --- [ctor-http-nio-4] o.s.w.r.f.server.RequestPredicates       : Pattern "//**" matches against value "/hello"
2017-03-03 00:58:03.865 DEBUG 7666 --- [ctor-http-nio-4] o.s.w.r.function.server.RouterFunctions  : Nested predicate "//**" matches against "GET /hello"
2017-03-03 00:58:03.865 TRACE 7666 --- [ctor-http-nio-4] o.s.w.r.f.server.RequestPredicates       : Method "GET" matches against value "GET"
2017-03-03 00:58:03.866 TRACE 7666 --- [ctor-http-nio-4] o.s.w.r.f.server.RequestPredicates       : Pattern "/hello" matches against value "/hello"
2017-03-03 00:58:03.866 DEBUG 7666 --- [ctor-http-nio-4] o.s.w.r.function.server.RouterFunctions  : Predicate "(GET && /hello)" matches against "GET /hello"

Not working case trace:

2017-03-03 00:59:26.958 TRACE 7666 --- [ctor-http-nio-1] o.s.w.r.f.server.RequestPredicates       : Pattern "//**" matches against value "/1/hello"
2017-03-03 00:59:26.958 DEBUG 7666 --- [ctor-http-nio-1] o.s.w.r.function.server.RouterFunctions  : Nested predicate "//**" matches against "GET /1/hello"
2017-03-03 00:59:26.958 TRACE 7666 --- [ctor-http-nio-1] o.s.w.r.f.server.RequestPredicates       : Method "GET" matches against value "GET"
2017-03-03 00:59:26.958 TRACE 7666 --- [ctor-http-nio-1] o.s.w.r.f.server.RequestPredicates       : Pattern "/hello" does not match against value "/1/hello"
2017-03-03 00:59:26.959 TRACE 7666 --- [ctor-http-nio-1] o.s.w.r.f.server.RequestPredicates       : Pattern "/{id}/**" matches against value "/1/hello"
2017-03-03 00:59:26.959 DEBUG 7666 --- [ctor-http-nio-1] o.s.w.r.function.server.RouterFunctions  : Nested predicate "/{id}/**" matches against "GET /1/hello"
2017-03-03 00:59:26.959 TRACE 7666 --- [ctor-http-nio-1] o.s.w.r.f.server.RequestPredicates       : Method "GET" matches against value "GET"
2017-03-03 00:59:26.959 TRACE 7666 --- [ctor-http-nio-1] o.s.w.r.f.server.RequestPredicates       : Pattern "/hello" does not match against value "/1/hello"

This seems like a bug (as the "/{id}".route {...} supposedly is using RouterFunctions.nest), but I could be wrong. Your thoughts and help are welcome.

I obviously know that I can make /1/hello work by just writing GET("/{id}/hello") { ... }, but I am interested in the nested .route { ...} variant as it supports my use case of adding nested routes from another location (like a map, etc).

Body: This issue has been fixed in SPR-15310.


问:
Compare Items in two Lists and return non matching Items
So I have two Lists.

```<code>List<Farmer> CSVFarmer;
List<Farmer> Farmers;
</code>```

CSVFarmer List gets its items from a method that will read a csv file.

Farmers List gets its items from a table in a sql database;

Now what I want to do is compare the two lists and return a list of non matching items;

For example if List CSVFarmer has:

```<code>FarmerName     ContractNumber   ContactNumber
John           2468             12345
Mike           13579            15790
</code>```

And List Farmers has:

```<code>FarmerName     ContractNumber   ContactNumber
Mike           13579            15790
</code>```

The list being returned should only have one item in it : Farmer John.
Farmer Class:

```<code> public class Farmer:INotifyPropertyChanged
{
    int _id;
    string _firstName;
    string _farmerNo;
    string _contactNumber;

    public Farmer()
    {
        _firstName = string.Empty;
        _farmerNo = string.Empty;
        _contactNumber = string.Empty;
    }

    public int Id
    {
        get { return _id; }
        set
        {
            _id = value;
            OnPropertyChanged("Id");
        }
    }
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;
            OnPropertyChanged("FirstName");
        }
    }
    public string FarmerNo
    {
        get { return _farmerNo; }
        set
        {
            _farmerNo = value;
            OnPropertyChanged("FarmerNo");
        }
    }
    public string ContactNumber
    {
        get { return _contactNumber; }
        set
        {
            _contactNumber = value;
            OnPropertyChanged("ContactNumber");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged (string property)
    {
        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property));
    }

}
</code>```

Ive tried this:

```<code>public class vmUserManagement
{
public List<Farmer> Farmer { get; set; }
public List<Farmer> CSVFarmers { get; set; }
public List<Farmer> Farmers { get; set; }

public vmUserManagement()
    {
        CSVFarmers = new List<Farmer>();
        Farmers = new List<Farmer>();
        Farmer = new List<Farmer>();
   }

public List<Farmer> getAllFarmers()
    {
        Farmers = RepoDapper.getAllFarmers();
        return Farmers;
    }

public List<Farmer> CSVImportFarmer()
    {
        OpenFileDialog openFile = new OpenFileDialog();
        openFile.DefaultExt = ".csv";
        openFile.Filter = "(.csv) | *.csv";

        var browseFile = openFile.ShowDialog();
        if (browseFile == true)
        {
            string FilePath = openFile.FileName;
            List<Farmer> values = File.ReadAllLines(FilePath).Select(v => FromFarmerCsv(v)).ToList();
            CSVFarmers = values;
        }
        return CSVFarmers;
    }

 public static Farmer FromFarmerCsv(string csvLine)
    {
        string[] values = csvLine.Split(',');
        Farmer farmer = new Farmer();
        farmer.FirstName = values[0];
        farmer.FarmerNo = values[1];
        farmer.ContactNumber = values[2];
        return farmer;
    }

public List<Farmer> validateFarmerList()
    {

        foreach (var a in CSVFarmers)
        {
            foreach (var b in Farmers)
            {

                    if (a != b)
                    {
                        Farmer.Add(a);
                    }

            }
        }

        return Farmer;
    }
}
</code>```

The problem I'm having is that  I will end up with two entries in List Farmer. Both for Farmer John and Farmer Mike. When I should only be getting a List containing Farmer John. Why is that?

I've also tried using Except:

```<code> public List<Farmer> validateFarmerList()
    {

        Farmer = CSVFarmers.Except(Farmers).ToList();
        return Farmer;
    }
</code>```

But I still get two items in my Farmer List (Farmer John and Mike) instead of one.
Am I missing something? Any help will be much appreciated.

答:
You will need to either create a class implementing IEqualityComparer<Farmer> and pass an instance of that as a second parameter to .Except() or implement IEquatable<Farmer> on your Farmer class.

The other answer already has a good implementation of the latter. If you always want farmers to be equal when their contract number is equal, use that one.

So if you want your Except work on contract numbers, but in other places you want other criteria, you need the first option:

```<code>class FarmerEqualWhenContractEqualComparer : IEqualityComparer<Farmer>
{
    public bool Equals(Farmer x, Farmer y)
    {
        //Check whether the compared objects reference the same data.
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether any of the compared objects is null.
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        //Check whether the farmers' contracts are equal.
        return x.ContractNumber == y.ContractNumber;
    }

    // If Equals() returns true for a pair of objects
    // then GetHashCode() must return the same value for these objects.
    public int GetHashCode(Farmer farmer)
    {
        //Check whether the object is null
        if (Object.ReferenceEquals(product, null)) return 0;

        //Get hash code for the Name field if it is not null.
        return farmer.ContractNumber?.GetHashCode() ?? 0;
    }
}
</code>```

Then you can do:

```<code>var changedOrNew = CSVFarmers.Except(Farmers, new FarmerEqualWhenContractEqualComparer()).ToList();
</code>```

Body:
So I have two Lists.

List<Farmer> CSVFarmer;
List<Farmer> Farmers;

CSVFarmer List gets its items from a method that will read a csv file.

Farmers List gets its items from a table in a sql database;

Now what I want to do is compare the two lists and return a list of non matching items;

For example if List CSVFarmer has:

FarmerName     ContractNumber   ContactNumber
John           2468             12345
Mike           13579            15790

And List Farmers has:

FarmerName     ContractNumber   ContactNumber
Mike           13579            15790

The list being returned should only have one item in it : Farmer John.
Farmer Class:

 public class Farmer:INotifyPropertyChanged
{
    int _id;
    string _firstName;
    string _farmerNo;
    string _contactNumber;

    public Farmer()
    {
        _firstName = string.Empty;
        _farmerNo = string.Empty;
        _contactNumber = string.Empty;
    }

    public int Id
    {
        get { return _id; }
        set
        {
            _id = value;
            OnPropertyChanged("Id");
        }
    }
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;
            OnPropertyChanged("FirstName");
        }
    }
    public string FarmerNo
    {
        get { return _farmerNo; }
        set
        {
            _farmerNo = value;
            OnPropertyChanged("FarmerNo");
        }
    }
    public string ContactNumber
    {
        get { return _contactNumber; }
        set
        {
            _contactNumber = value;
            OnPropertyChanged("ContactNumber");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged (string property)
    {
        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property));
    }

}

Ive tried this:

public class vmUserManagement
{
public List<Farmer> Farmer { get; set; }
public List<Farmer> CSVFarmers { get; set; }
public List<Farmer> Farmers { get; set; }

public vmUserManagement()
    {
        CSVFarmers = new List<Farmer>();
        Farmers = new List<Farmer>();
        Farmer = new List<Farmer>();
   }

public List<Farmer> getAllFarmers()
    {
        Farmers = RepoDapper.getAllFarmers();
        return Farmers;
    }

public List<Farmer> CSVImportFarmer()
    {
        OpenFileDialog openFile = new OpenFileDialog();
        openFile.DefaultExt = ".csv";
        openFile.Filter = "(.csv) | *.csv";

        var browseFile = openFile.ShowDialog();
        if (browseFile == true)
        {
            string FilePath = openFile.FileName;
            List<Farmer> values = File.ReadAllLines(FilePath).Select(v => FromFarmerCsv(v)).ToList();
            CSVFarmers = values;
        }
        return CSVFarmers;
    }

 public static Farmer FromFarmerCsv(string csvLine)
    {
        string[] values = csvLine.Split(',');
        Farmer farmer = new Farmer();
        farmer.FirstName = values[0];
        farmer.FarmerNo = values[1];
        farmer.ContactNumber = values[2];
        return farmer;
    }

public List<Farmer> validateFarmerList()
    {

        foreach (var a in CSVFarmers)
        {
            foreach (var b in Farmers)
            {

                    if (a != b)
                    {
                        Farmer.Add(a);
                    }

            }
        }

        return Farmer;
    }
}

The problem I'm having is that  I will end up with two entries in List Farmer. Both for Farmer John and Farmer Mike. When I should only be getting a List containing Farmer John. Why is that?

I've also tried using Except:

 public List<Farmer> validateFarmerList()
    {

        Farmer = CSVFarmers.Except(Farmers).ToList();
        return Farmer;
    }

But I still get two items in my Farmer List (Farmer John and Mike) instead of one.
Am I missing something? Any help will be much appreciated.

Body:
You will need to either create a class implementing IEqualityComparer<Farmer> and pass an instance of that as a second parameter to .Except() or implement IEquatable<Farmer> on your Farmer class.

The other answer already has a good implementation of the latter. If you always want farmers to be equal when their contract number is equal, use that one.

So if you want your Except work on contract numbers, but in other places you want other criteria, you need the first option:

class FarmerEqualWhenContractEqualComparer : IEqualityComparer<Farmer>
{
    public bool Equals(Farmer x, Farmer y)
    {
        //Check whether the compared objects reference the same data.
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether any of the compared objects is null.
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        //Check whether the farmers' contracts are equal.
        return x.ContractNumber == y.ContractNumber;
    }

    // If Equals() returns true for a pair of objects
    // then GetHashCode() must return the same value for these objects.
    public int GetHashCode(Farmer farmer)
    {
        //Check whether the object is null
        if (Object.ReferenceEquals(product, null)) return 0;

        //Get hash code for the Name field if it is not null.
        return farmer.ContractNumber?.GetHashCode() ?? 0;
    }
}

Then you can do:

var changedOrNew = CSVFarmers.Except(Farmers, new FarmerEqualWhenContractEqualComparer()).ToList();


问:
Javascript sort by digits sum doesn't work even with compare function. Why?
I have a function that sorts an array of integers by their digits sum, in case of equal digit sum than it sort by the numbers values. This is the function:

```<code>function s(g){
    var r=0;
    while(g)r+=g%10,g/=10;
    return r;
}
function digitalSumSort(a) {
    a.sort(function(x,y){
        return s(x)!=s(y)?s(x)-s(y):x-y;
    });
    return a;
}
</code>```

It sometimes works ok, but it failed at this test data:

Input: [100, 22, 4, 11, 31, 103]

Output: [100, 11, 31, 4, 22, 103]

Expected Output: [100, 11, 4, 22, 31, 103]

I couldn't figure out why it does that, and how to fix it?

Note: it is important that the code contains as least as possible characters!

Edit:
This question has already been answered but I recently made the same mistake and thought of this. Is there a way to make a var act as an integer (instead of a double) when given a numeric value. I learned the trick with using floor, but sometimes I just want integer operations instead of double (with some systems they are faster, and I may have other reasons).

答:
The main problem is with the s function, because it continues looping and collecting values when g is fraction.

In addition, instead of calculating the values while sorting, you can use a Schwartzian transform aka decorate-sort-undecorate. You create an array with the computed values you'll use to sort, sort the array, than map back to the original values.

function s(g) {
  var r = 0;
  while (g) r += g % 10, g = Math.floor(g/10); // round g down to skip redundent loops when g is a fraction
  return r;
}

function digitalSumSort(a) {
  return a
    .map(function(n) { // create an array with theorigina and the computed values
      return [s(n), n];
    })
    .sort(function(a, b) {
      return a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]; // sort by the computed or original values
    })
    .map(function(n) { // get back an array of the original values
      return n[1];
    });
}

console.log(digitalSumSort([100, 22, 4, 11, 31, 103])); // [100, 11, 4, 22, 31, 103]```

ContentLicense: CC BY-SA 4.0

Body:
I have a function that sorts an array of integers by their digits sum, in case of equal digit sum than it sort by the numbers values. This is the function:

function s(g){
    var r=0;
    while(g)r+=g%10,g/=10;
    return r;
}
function digitalSumSort(a) {
    a.sort(function(x,y){
        return s(x)!=s(y)?s(x)-s(y):x-y;
    });
    return a;
}

It sometimes works ok, but it failed at this test data:

Input: [100, 22, 4, 11, 31, 103]

Output: [100, 11, 31, 4, 22, 103]

Expected Output: [100, 11, 4, 22, 31, 103]

I couldn't figure out why it does that, and how to fix it?

Note: it is important that the code contains as least as possible characters!

Edit:
This question has already been answered but I recently made the same mistake and thought of this. Is there a way to make a var act as an integer (instead of a double) when given a numeric value. I learned the trick with using floor, but sometimes I just want integer operations instead of double (with some systems they are faster, and I may have other reasons).


问:
Repeat File Printing Using Scanner
I'm trying to make a program which reprints the text file simple.txt every time the user presses "c", but with my code, it will only print once:

```<code>public static void main(String[] args) throws FileNotFoundException {
    Scanner console = new Scanner(System.in);
    Scanner fileSearch = new Scanner(new File("simple.txt"));
    UI(console, fileSearch);
}

public static void UI (Scanner console, Scanner fileSearch) {
    String choice = "Start";
    while (!choice.equals("q")) {
        System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
        choice = console.next();
        choice = choice.toLowerCase();
        if (choice.equals("c")) {
            System.out.println("Create");
            CreateMadLibs(fileSearch);
        } else if (!choice.equals("q")) {
            System.out.println("I don't understand.");
        }
    }
}

public static File FileGrab (Scanner fileSearch) {
    File thing = new File(fileSearch.next());
    while (fileSearch.hasNextLine()){
        System.out.println(fileSearch.nextLine());
    }
return thing;
}

public static void CreateMadLibs (Scanner fileSearch) {
    FileGrab(fileSearch);
}
</code>```

I think the issue is that I create the scanner fileSearch in main instead of in UI. I tried initializing fileSearch in the if statement, but that gave me a fileNotFoundException.  As is, I get this:

```<code>Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at test.FileGrab(test.java:28)
    at test.CreateMadLibs(test.java:36)
    at test.UI(test.java:20)
    at test.main(test.java:9)
</code>```

答:
You have some lines in your code that functionally do nothing, I suggest to modify the FileGrabmethod by doing something like this :

```<code>    public static void /*File*/ FileGrab ( Scanner fileSearch ) {
    //File thing = new File(fileSearch.next());  // this line is useless
    while (fileSearch.hasNextLine()){
        System.out.println(fileSearch.nextLine());
    }
    //return thing; // this either
   }
</code>```

Title: Repeat File Printing Using Scanner

Body:
I'm trying to make a program which reprints the text file simple.txt every time the user presses "c", but with my code, it will only print once:

public static void main(String[] args) throws FileNotFoundException {
    Scanner console = new Scanner(System.in);
    Scanner fileSearch = new Scanner(new File("simple.txt"));
    UI(console, fileSearch);
}

public static void UI (Scanner console, Scanner fileSearch) {
    String choice = "Start";
    while (!choice.equals("q")) {
        System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
        choice = console.next();
        choice = choice.toLowerCase();
        if (choice.equals("c")) {
            System.out.println("Create");
            CreateMadLibs(fileSearch);
        } else if (!choice.equals("q")) {
            System.out.println("I don't understand.");
        }
    }
}

public static File FileGrab (Scanner fileSearch) {
    File thing = new File(fileSearch.next());
    while (fileSearch.hasNextLine()){
        System.out.println(fileSearch.nextLine());
    }
return thing;
}

public static void CreateMadLibs (Scanner fileSearch) {
    FileGrab(fileSearch);
}

I think the issue is that I create the scanner fileSearch in main instead of in UI. I tried initializing fileSearch in the if statement, but that gave me a fileNotFoundException.  As is, I get this:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at test.FileGrab(test.java:28)
    at test.CreateMadLibs(test.java:36)
    at test.UI(test.java:20)
    at test.main(test.java:9)

Body:
You have some lines in your code that functionally do nothing, I suggest to modify the FileGrabmethod by doing something like this :

    public static void /*File*/ FileGrab ( Scanner fileSearch ) {
    //File thing = new File(fileSearch.next());  // this line is useless
    while (fileSearch.hasNextLine()){
        System.out.println(fileSearch.nextLine());
    }
    //return thing; // this either
   }


问:
Ionic 3 error, exec proxy not found for :: PayPalMobile :: init
I follow the steps to install and work with PayPal-Cordova-Plugin

and everything goes ok!
But when I run the command:

```<code>ionic cordova run browser
</code>```

I got this error :

```<code>Error: exec proxy not found for :: PayPalMobile :: init
( Missing Command Error cdv-plugin-paypal-mobile-sdk.js:41 )
</code>```

and even when I try it on my android device I get the same problem.

can anyone help me to understand what happens and what wrong I have done !?

答:
I solve it,
all what i do is : run this command after plugged in my device

ionic cordova run android --device

(ionic cordova run browser is not working with me)

and i add this lines to my main.ts

import {enableProdMode} from '';
  enableProdMode();

Body:
I follow the steps to install and work with PayPal-Cordova-Plugin

and everything goes ok!
But when I run the command:

ionic cordova run browser

I got this error :

Error: exec proxy not found for :: PayPalMobile :: init
( Missing Command Error cdv-plugin-paypal-mobile-sdk.js:41 )

and even when I try it on my android device I get the same problem.

can anyone help me to understand what happens and what wrong I have done !?


问:
Move_uploaded_file() function is not working
I'm working on a website and I want the user to be able to upload files. So I'm trying to learn how to do that. I researched and it said that I had to use the function move_uploaded_file(). I wrote the code just like it was on the example (changing the data), but it wouldn't work. Please help me, I'm new at these. Here's what I've done so far:

```<code><!DOCTYPE html>
<html>
   <head>
   </head>
<body>
   <form action="upload_file.php" method="POST" enctype="multipart/form-data">
      <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
      <input type="file"name="file">
      <input type="submit">
   </form>
</body>
<html>
</code>```

This is the upload_file.php:

```<code><!DOCTYPE html>
<html>
  <head>
  <head>
     <body>
        <?php
          $move = "/Users/George/Desktop/uploads/";
          echo $_FILES["file"]['name']."<br>";
          echo $_FILES["file"]['tmp_name']."<br>";
          echo $_FILES["file"]['size']."<br>";
          echo $_FILES['file']['error']."<br>";
          move_uploaded_file($_FILES['file']['name'], $move);
        ?>
     <body>
<html>
</code>```

答:
If you are on a windows machine, there won't be any problems with uploading or writing to the specified folder path, except the syntactical errors.

But in case of Linux users, there is a workaround to this problem, even if there are no syntactical errors visible.

First of all, I am assuming that you are using this in a Linux environment and you need to upload something to your project folder in the public directory.

Even if you are having the write and read access to the project folder, PHP is not handled by the end user. It is and can be handled by a www-data user, or group.

So in order to make this www-data get access
 first type in;

```<code>sudo chgrp "www-data" your_project_folder
</code>```

once its done, if there is no write access to the following as well;

```<code>sudo chown g+w your_project_folder
</code>```

That will do the trick in Linux.

Please, not that this is done in a Linux environment, with phpmyadmin, and mysql running.

Body:
I'm working on a website and I want the user to be able to upload files. So I'm trying to learn how to do that. I researched and it said that I had to use the function move_uploaded_file(). I wrote the code just like it was on the example (changing the data), but it wouldn't work. Please help me, I'm new at these. Here's what I've done so far:

<!DOCTYPE html>

   <form action="upload_file.php" method="POST" enctype="multipart/form-data">
      <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
      <input type="file"name="file">
      <input type="submit">
   </form>

This is the upload_file.php:

<!DOCTYPE html>

        <?php
          $move = "/Users/George/Desktop/uploads/";
          echo $_FILES["file"]['name']."
";
          echo $_FILES["file"]['tmp_name']."
";
          echo $_FILES["file"]['size']."
";
          echo $_FILES['file']['error']."
";
          move_uploaded_file($_FILES['file']['name'], $move);
        ?>

Body:
If you are on a windows machine, there won't be any problems with uploading or writing to the specified folder path, except the syntactical errors.

But in case of Linux users, there is a workaround to this problem, even if there are no syntactical errors visible.

First of all, I am assuming that you are using this in a Linux environment and you need to upload something to your project folder in the public directory.

Even if you are having the write and read access to the project folder, PHP is not handled by the end user. It is and can be handled by a www-data user, or group.

So in order to make this www-data get access
 first type in;

sudo chgrp "www-data" your_project_folder

once its done, if there is no write access to the following as well;

sudo chown g+w your_project_folder

That will do the trick in Linux.

Please, not that this is done in a Linux environment, with phpmyadmin, and mysql running.


问:
Extract text from html tags using reduce in Javascript
I'm trying to concatenate the inner HTML of each paragraph tag on my page in one single string using reduce. Here's my try:

// JS
let par = Array.from(document.getElementsByTagName("p"));
document.write(par.reduce((a, b) => a + ", " + b.innerHTML));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- HTML -->
<p>Apple</p>
<p>Strawberry</p>
<p>Banana</p></code>```

And here's the (wrong) output:

[object HTMLParagraphElement], Strawberry, Banana

What am I doing wrong?

Many thanks for your help!

答:
how about something like: </p>

```<code>let par = Array.from(document.getElementsByTagName("p"));
document.write(par.map(a=> a.innerHTML).join())
</code>```

Body:
I'm trying to concatenate the inner HTML of each paragraph tag on my page in one single string using reduce. Here's my try:

// JS
let par = Array.from(document.getElementsByTagName("p"));
document.write(par.reduce((a, b) => a + ", " + b.innerHTML));

Apple

Strawberry

Banana

And here's the (wrong) output:

[object HTMLParagraphElement], Strawberry, Banana

What am I doing wrong?

Many thanks for your help!

Body:
how about something like:

let par = Array.from(document.getElementsByTagName("p"));
document.write(par.map(a=> a.innerHTML).join())


问:
Laravel 5.5 Error Base table or view already exists: 1050 Table 'users' already exists
Specifications:

Laravel Version: 5.5.3

PHP Version: 7.1

Database Driver & Version: MariaDB 10.1.26

Description:

```<code>C:/Users/user/code/blog/>php artisan migrate

[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists (SQL: create table users (id int unsigned not null aut
o_increment primary key, name varchar(255) not null, email varchar(255) not null, password varchar(255) not null, remember_token varchar
(100) null, created_at timestamp null, updated_at timestamp null) default character set utf8mb4 collate utf8mb4_unicode_ci engine = InnoDB R
OW_FORMAT=DYNAMIC)

[PDOException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists
</code>```

Steps To Reproduce:

```<code> C:/Users/user/code/blog/>laravel new website

 C:/Users/user/code/blog/>php artisan make:migration create_lists_table --create=lists

 C:/Users/user/code/blog/>php artisan migrate
</code>```

Problem

It Creates users table and give error but not creating lists table

答:
Here are the steps I took to solve the same issue:

In the console I wrote php artisan tinker

Then, again in the console,  Schema::drop('users')

At the end php artisan migrate and it all worked.

Body:
Specifications:

Laravel Version: 5.5.3

PHP Version: 7.1

Database Driver & Version: MariaDB 10.1.26

Description:

C:/Users/user/code/blog/>php artisan migrate

[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists (SQL: create table users (id int unsigned not null aut
o_increment primary key, name varchar(255) not null, email varchar(255) not null, password varchar(255) not null, remember_token varchar
(100) null, created_at timestamp null, updated_at timestamp null) default character set utf8mb4 collate utf8mb4_unicode_ci engine = InnoDB R
OW_FORMAT=DYNAMIC)

[PDOException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists

Steps To Reproduce:

 C:/Users/user/code/blog/>laravel new website

 C:/Users/user/code/blog/>php artisan make:migration create_lists_table --create=lists

 C:/Users/user/code/blog/>php artisan migrate

Problem

It Creates users table and give error but not creating lists table


问:
jQuery attr() method to change a class name
I'm trying to use the attr() jQuery method to change the class name of an h1 element when an option is selected from a drop-down form. I want the classes name to change to access different CSS properties (fonts)

I think I am not digging down into the DOM further enough to change the class?

function myFontStyle() {
  $('#font').on("change", function() {
    var fontChange = this.value
    console.log(this.value);
    $('h1').attr('class', + fontChange);
  });
}
myFontStyle();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.handwriting{
  font-family: 'Pacifico', cursive;
}
.sketch{
  font-family: 'Fredericka the Great', cursive;
}
.print{
  font-family: 'Sigmar One', cursive;
}</code>```

Choose font
<select name="font" id="font">
  <option value="handwriting">Handwriting</option>
  <option value="sketch">Sketch</option>
  <option value="print">Print</option>
</select>

Happy birthday to you

```

答:
```<code>$("h1").attr('class', fontChange);
</code>```

or

```<code>$("h1").addClass(fontChange);
</code>```

you can view details form

http://api.jquery.com/category/manipulation/class-attribute/

Body:
I'm trying to use the attr() jQuery method to change the class name of an h1 element when an option is selected from a drop-down form. I want the classes name to change to access different CSS properties (fonts)

I think I am not digging down into the DOM further enough to change the class?

function myFontStyle() {
  $('#font').on("change", function() {
    var fontChange = this.value
    console.log(this.value);
    $('h1').attr('class', + fontChange);
  });
}
myFontStyle();

.handwriting{
  font-family: 'Pacifico', cursive;
}
.sketch{
  font-family: 'Fredericka the Great', cursive;
}
.print{
  font-family: 'Sigmar One', cursive;
}

Choose font
<select name="font" id="font">
  <option value="handwriting">Handwriting</option>
  <option value="sketch">Sketch</option>
  <option value="print">Print</option>
</select>

Happy birthday to you

Body:
$("h1").attr('class', fontChange);

or

$("h1").addClass(fontChange);

you can view details form

http://api.jquery.com/category/manipulation/class-attribute/


问:
Angular 4 file upload in form post
Hi In a form I have several HTML controls and one file upload control. I’m filling all HTML controls with some text as well as one file for file upload.now I need to post all these data and file to my api.Can any one help me how to do this in angular 4</p>

答:
My solution for this was as below :

In The html file get an input for the file

```<code>    <p >
      <label for="idFile" class="label-file">Choisir un Fichier</label>
      <input id="idFile" class="input-file" type="file" (change)="fileChange($event)" placeholder="Upload file">
    </p>
</code>```

And in your ts write the method file change to get data

```<code>  fileChange(event) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      this.file = fileList[0];
     }
  }
</code>```

Then you should post a formData containing your file and your data like this

```<code>  private docToFormData(doc) {
    let formData: FormData = new FormData();
    formData.append('file', doc.file, doc.file.name);
    formData.append('metadata', new Blob([JSON.stringify(doc)], {type: "application/json"}));
    return formData;
  }

  submitDocument(doc): Observable<any> {

    let formData = this.docToFormData(doc);
    return this._http.post(this._http.backendURL.submitDocument, formData)
      .map((res: Response) => {
        // TODO : return res.json and update back to return doc dto
        return res;
      });
  }
</code>```

In my case doc is an object with metadata

I hope this could help.

Title: Angular 4 file upload in form post

Body:
My solution for this was as below :

In The html file get an input for the file

    <p >
      <label for="idFile" class="label-file">Choisir un Fichier</label>
      <input id="idFile" class="input-file" type="file" (change)="fileChange($event)" placeholder="Upload file">
    </p>

And in your ts write the method file change to get data

  fileChange(event) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      this.file = fileList[0];
     }
  }

Then you should post a formData containing your file and your data like this

  private docToFormData(doc) {
    let formData: FormData = new FormData();
    formData.append('file', doc.file, doc.file.name);
    formData.append('metadata', new Blob([JSON.stringify(doc)], {type: "application/json"}));
    return formData;
  }

  submitDocument(doc): Observable<any> {

    let formData = this.docToFormData(doc);
    return this._http.post(this._http.backendURL.submitDocument, formData)
      .map((res: Response) => {
        // TODO : return res.json and update back to return doc dto
        return res;
      });
  }

In my case doc is an object with metadata

I hope this could help.


问:
What would a program that I created in Powerbuilder launch right away on my computer, but takes up to 2 minutes on a virtual machine?
I created a program in Powerbuilder, and when ran on a personal computer it launches right away, however whenever I launch it on a Virtual machine, it takes up to two minutes before it actually launches.</p>

答: Look at where runtime are. If they are in LAN you could have performance problem. Put them in a local disk of you VM</p>


问:
How to set Selected item of ComboBox in C# Windows Forms?
I am trying to set selected item of comboBox on click event of DataGrid, but I could not. I have googled and tried different ways but without success.

For me SelectedIndex is working, but I could not find the index of items in ComboBox, so I could not select the item.

Not working code:

```<code>for (int i = 0; i < cmbVendor.Items.Count; i++)

    if (cmbVendor.Items[i].ToString() == Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor")))
    {
        cmbVendor.SelectedIndex = i;
        break;
    }
</code>```

答:
this works for me.....</p>

```<code>string displayMember = ComboBox.DataSource.To<DataTable>().Select("valueMemberColumn = '" + value + "'")[0]["displayMember"].ToString();
ComboBox.FindItemExact(displayMember, true).Selected = true;
</code>```

Body:
I am trying to set selected item of comboBox on click event of DataGrid, but I could not. I have googled and tried different ways but without success.

For me SelectedIndex is working, but I could not find the index of items in ComboBox, so I could not select the item.

Not working code:

for (int i = 0; i < cmbVendor.Items.Count; i++)

    if (cmbVendor.Items[i].ToString() == Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor")))
    {
        cmbVendor.SelectedIndex = i;
        break;
    }

Body:
this works for me.....

string displayMember = ComboBox.DataSource.To<DataTable>().Select("valueMemberColumn = '" + value + "'")[0]["displayMember"].ToString();
ComboBox.FindItemExact(displayMember, true).Selected = true;


问:
Check for value definedness in C++
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

```<code>class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}
</code>```

Is it possible in C++?

Thanks

答:
As the other answers says, C++ doesn't have this concept. You can easily work around it though.

Either you can have an undefined value which you initialize bar to in the constructor, typically -1.0 or something similar.

If you know that calculate_bar never returns negative values you can implement the undefined function as a check for < 0.0.

A more general solution is having a bool saying whether bar is defined yet that you initialized to false in the constructor and when you first set it you change it to true. boost::optional does this in an elegant templated way.

This is what the code example you have would look like.

```<code>class Foo {
public:
    double get_bar();
    Foo() : barDefined(false) {}
private:
    double bar;
    bool barDefined;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( barDefined == false ) {
        calculate_bar();
        barDefined = true;
    }
    return bar;
}
</code>```

OwnerDisplayName: Tunnuz

ContentLicense: CC BY-SA 2.5

Title: Check for value definedness in C++

Body:
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}

Is it possible in C++?

Thanks

Body:
As the other answers says, C++ doesn't have this concept. You can easily work around it though.

Either you can have an undefined value which you initialize bar to in the constructor, typically -1.0 or something similar.

If you know that calculate_bar never returns negative values you can implement the undefined function as a check for < 0.0.

A more general solution is having a bool saying whether bar is defined yet that you initialized to false in the constructor and when you first set it you change it to true. boost::optional does this in an elegant templated way.

This is what the code example you have would look like.

class Foo {
public:
    double get_bar();
    Foo() : barDefined(false) {}
private:
    double bar;
    bool barDefined;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( barDefined == false ) {
        calculate_bar();
        barDefined = true;
    }
    return bar;
}

OwnerDisplayName: Laserallan

LastEditorDisplayName: Laserallan