问:
Efficient way to copy or merge two ArrayList containing same objects
I have an Object like below

```<code>Product {

String name;

boolean isFiltered;

}
</code>```

We have two lists - masterProductList and filteredProductList containing product.

We have to copy values of filteredProductList(this list has property isFiltered set) to masterProductList.

I can do it with following approches -

Approach 1

```<code>for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        if (filterProduct.equals(masterProduct)) {
            // Copy Values
            masterProduct.setIsFiltered(filterProduct.getIsFiltered());
        }
    }
}
</code>```

Approach 2

```<code>for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        //Delete the old product having old values
        masterProduct.remove(filterProduct);
        //Add product with new values
        masterProduct.add(filterProduct);
    }
}
</code>```

Both of these approaches have n square complexity.

Is there any other better way to do this so that we can reduce the complexity?

答:
This also should work:

```<code>List<Product> merged = filteredProductList.stream().filter(masterProductList::contains).collect(Collectors.toList());
</code>```

EDIT: but I suppose it is n^2 because of contains method

Body:
I have an Object like below

Product {

String name;

boolean isFiltered;

}

We have two lists - masterProductList and filteredProductList containing product.

We have to copy values of filteredProductList(this list has property isFiltered set) to masterProductList.

I can do it with following approches -

Approach 1

for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        if (filterProduct.equals(masterProduct)) {
            // Copy Values
            masterProduct.setIsFiltered(filterProduct.getIsFiltered());
        }
    }
}

Approach 2

for (Product filterProduct: filteredPL) {
    for (Product masterProduct: masterPL) {
        //Delete the old product having old values
        masterProduct.remove(filterProduct);
        //Add product with new values
        masterProduct.add(filterProduct);
    }
}

Both of these approaches have n square complexity.

Is there any other better way to do this so that we can reduce the complexity?

Body:
This also should work:

List<Product> merged = filteredProductList.stream().filter(masterProductList::contains).collect(Collectors.toList());

EDIT: but I suppose it is n^2 because of contains method


来源: stackexchange

问:
How to get string between a character and first occurrence of double quotes?
I am trying to get tvg-logo string(http://awebsite/logos/TestChannel.png) but my current code only works on case one.For case 2 and 3 inputs the code outputs not only the tvg-logo value but also the rest of string after it!could you guys show me how to get ONLY tvg-logo url in all these case ?Thanks

```<code>public class HelloWorld {
  public static void main(String[] args) {

    //case 1:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\"";
    //case 2:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\" group-title=\"Movies\"";
    //case 3:
    String s="-1 tvg-logo=\"http://awebsite/logos/TestChannel.png\" tvg-name=\"Test Channel\" group-title=\"Movies\"";

    String icon = s.substring(s.indexOf("tvg-logo") + "tvg-logo".length()).replace("=", "").replace("\"", "").replace("\n", "");

    System.out.println("Logo:"+icon);
  }
}
</code>```

output for case 3 input:

```<code>Logo:http://awebsite/logos/TestChannel.png tvg-nameTest Channel group-titleMovies
</code>```

Expected output for all types of input cases:

```<code>Logo:http://awebsite/logos/TestChannel.png
</code>```

答:
```<code>public class HelloWorld
{
    public static void main (String[] args) throws java.lang.Exception
    {
        //case 1:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\"";
    //case 2:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\" group-title=\"Movies\"";
    //case 3:
    String s="-1 tvg-logo=\"http://awebsite/logos/TestChannel.png\" tvg-name=\"Test Channel\" group-title=\"Movies\"";

    String icon="";
    String[] splited = s.split("\\s+");
    for(int i=0;i<splited.length;i++){
        if(splited[i].contains("tvg-logo")){
            icon = splited[i].substring(10);
        }
    }
    //String icon = s.substring(s.indexOf("tvg-logo") + "tvg-logo".length()).replace("=", "").replace("\"", "").replace("\n", "");

    System.out.println("Logo:"+icon);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to get tvg-logo string(http://awebsite/logos/TestChannel.png) but my current code only works on case one.For case 2 and 3 inputs the code outputs not only the tvg-logo value but also the rest of string after it!could you guys show me how to get ONLY tvg-logo url in all these case ?Thanks

public class HelloWorld {
  public static void main(String[] args) {

    //case 1:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\"";
    //case 2:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\" group-title=\"Movies\"";
    //case 3:
    String s="-1 tvg-logo=\"http://awebsite/logos/TestChannel.png\" tvg-name=\"Test Channel\" group-title=\"Movies\"";

    String icon = s.substring(s.indexOf("tvg-logo") + "tvg-logo".length()).replace("=", "").replace("\"", "").replace("\n", "");

    System.out.println("Logo:"+icon);
  }
}

output for case 3 input:

Logo:http://awebsite/logos/TestChannel.png tvg-nameTest Channel group-titleMovies

Expected output for all types of input cases:

Logo:http://awebsite/logos/TestChannel.png


问:
cron file to update the database sequentially after every run
im redesigning a mmorpg game and im in a bit of a pickle on this one.
i have the following code on the daily cron file.

```<code>dbn("update mygame set event = '11' where event = '10'");
</code>```

now...

this file runs once a day. i would like to update the database in a way such
day 1 ----- event =10,
day 2 ----- event =11,
day 3 ----- event =12 ...etc,
in other words,
once the event is set it will automatically update itself till it dies out.
Hence day 1

```<code>dbn("update mygame set event = '10' where event = '9'");
</code>```

day 2

```<code>dbn("update mygame set event = '11' where event = '10'");
</code>```

so on and so forth.

Any ideas?
Thank you in advance for reading.

答:
1) Make your event column a numeric type like an int, not a string containing a number

2) dbn("UPDATE mygame SET event = event + 1")

However, you probably don't need this column at all. If all it does is count days, then store the start date and COMPUTE the number of days elapsed wherever you're using that value. You won't have to run any query each day.

ContentLicense: CC BY-SA 2.5

Body:
im redesigning a mmorpg game and im in a bit of a pickle on this one.
i have the following code on the daily cron file.

dbn("update mygame set event = '11' where event = '10'");

now...

this file runs once a day. i would like to update the database in a way such
day 1 ----- event =10,
day 2 ----- event =11,
day 3 ----- event =12 ...etc,
in other words,
once the event is set it will automatically update itself till it dies out.
Hence day 1

dbn("update mygame set event = '10' where event = '9'");

day 2

dbn("update mygame set event = '11' where event = '10'");

so on and so forth.

Any ideas?
Thank you in advance for reading.


问:
Trigger multiple links to download files
I have a webpage where I can find a random number of files to download. I wanted to develop a little FireFox extension to download all files at once. So far I have the following function to download these files:

```<code>function getFilesJQ () {
    var $dlLinks = $('a').filter(function(index) { return $(this).text() === "Download"; });

    $dlLinks.each(function () {
        $(this).trigger('click');
    });
}
</code>```

The problem is, that only the first link is clicked and the corresponding file starts to download. The others are not triggered.

Where lies the problem? Is this even possible?

Edit:

This is how $dlLinks looks like:

```<code>{…}
0: <a id="exerciseResourcesForm:a3:0:linkDownload" href="#" onclick="if(typeof jsfcljs == 'function'){jsfcljs(document.getElementById('exerciseResourcesForm'),{'exerciseResourcesForm:a3:0:linkDownload':'exerciseResourcesForm:a3:0:linkDownload'},'');}return false">
1: <a id="exerciseResourcesForm:a3:1:linkDownload" href="#" onclick="if(typeof jsfcljs == 'function'){jsfcljs(document.getElementById('exerciseResourcesForm'),{'exerciseResourcesForm:a3:1:linkDownload':'exerciseResourcesForm:a3:1:linkDownload'},'');}return false">
2: <a id="exerciseResourcesForm:a3:2:linkDownload" href="#" onclick="if(typeof jsfcljs == 'function'){jsfcljs(document.getElementById('exerciseResourcesForm'),{'exerciseResourcesForm:a3:2:linkDownload':'exerciseResourcesForm:a3:2:linkDownload'},'');}return false">
3: <a id="exerciseResourcesForm:a3:3:linkDownload" href="#" onclick="if(typeof jsfcljs == 'function'){jsfcljs(document.getElementById('exerciseResourcesForm'),{'exerciseResourcesForm:a3:3:linkDownload':'exerciseResourcesForm:a3:3:linkDownload'},'');}return false">
length: 4
prevObject: Object { 0: a, 1: a, 2: a, … }
__proto__: Object { jquery: "3.2.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector", constructor: r(), length: 0, … }
jack_download.js:10:2
</code>```

When one of those links is clicked, to POST requests are issued:

```<code>POST
https://*******/emp/ExerciseEdit.jsf
[HTTP/1.1 200 OK 28ms]
POST
https://sb-ssl.google.com/safebrowsing/clientreport/download
[HTTP/2.0 200 OK 109ms]
</code>```

答:
One thing to take into consideration it the target attribute of these links. If the target is not defined, then your click action is going to open a new session, and your subsequent downloads will be cancelled. One simple way around this is to "force" these links to open in new windows:

```<code>function getFilesJQ () {
    var $dlLinks = $('a').filter(function(index) { return $(this).text() === "Download"; });

    $dlLinks.each(function () {
        window.open(this.href);
    });
}
</code>```

However, please be aware that your browser may interpret this as multiple popups and try to block them. You may also have to turn off your popup blocker.

Body:
I have a webpage where I can find a random number of files to download. I wanted to develop a little FireFox extension to download all files at once. So far I have the following function to download these files:

function getFilesJQ () {
    var $dlLinks = $('a').filter(function(index) { return $(this).text() === "Download"; });

    $dlLinks.each(function () {
        $(this).trigger('click');
    });
}

The problem is, that only the first link is clicked and the corresponding file starts to download. The others are not triggered.

Where lies the problem? Is this even possible?

Edit:

This is how $dlLinks looks like:

{…}
0:
1:
2:
3:
length: 4
prevObject: Object { 0: a, 1: a, 2: a, … }
__proto__: Object { jquery: "3.2.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector", constructor: r(), length: 0, … }
jack_download.js:10:2

When one of those links is clicked, to POST requests are issued:

POST
https://*******/emp/ExerciseEdit.jsf
[HTTP/1.1 200 OK 28ms]
POST
https://sb-ssl.google.com/safebrowsing/clientreport/download
[HTTP/2.0 200 OK 109ms]

Body:
One thing to take into consideration it the target attribute of these links. If the target is not defined, then your click action is going to open a new session, and your subsequent downloads will be cancelled. One simple way around this is to "force" these links to open in new windows:

function getFilesJQ () {
    var $dlLinks = $('a').filter(function(index) { return $(this).text() === "Download"; });

    $dlLinks.each(function () {
        window.open(this.href);
    });
}

However, please be aware that your browser may interpret this as multiple popups and try to block them. You may also have to turn off your popup blocker.


问:
Neo4j lowest common ancestor node not found
I have loaded a hierarchical tree (DAG) of DNA SNPs. I want to identify lowest common ancestors.

This query works, yield the single correct node:

```<code>Match (n:SNPNode{SNP:'R-Z11'}), (m:SNPNode{SNP:'R-BY13828'})
match path=(n)-[:SNPParent*..99]->(MRCA)<-[:SNPParent*..99]-(m)
return MRCA.SNP
</code>```

However, this one yields no result:

```<code>Match (n:SNPNode{SNP:'R-Z11'}), (m:SNPNode{SNP:'R-S25289'})
match path=(n)-[:SNPParent*..99]->(MRCA)<-[:SNPParent*..99]-(m)
return MRCA.SNP
</code>```

even though the two queries seeking ancestors of both yield nodes some of which are shared:

```<code>MATCH p=(n:SNPNode{SNP:'R-Z11'})-[r:SNPParent*..66]->(m) RETURN m.SNP

m.SNP
R-Z338
R-Z8
R-Z7
R-Z2
R-Z345
R-Z27
R-Z30
R-Z9
R-L48
R-Z301
R-Z381
R-U106
R-L151
R-L51
R-L23
R-M269
R-P297
R-L389
R-L754
R-M343
</code>```

and

```<code>MATCH p=(n:SNPNode{SNP:'R-Z25289'})-[r:SNPParent*..66]->(m) RETURN m.SNP

m.SNP
R-S16701
R-S1774
R-Z341
**R-Z11**
R-Z338
R-Z8
R-Z7
R-Z2
R-Z345
R-Z27
R-Z30
R-Z9
R-L48
R-Z301
R-Z381
R-U106
R-L151
R-L51
R-L23
R-M269
R-P297
R-L389
R-L754
R-M343
</code>```

It seems the problem is that R-Z11 is in the path of the second query and is itself the ancestor. In other words, sometimes the LCA is at the end of a shortest path. Is there a way to address this so that R-Z11 returns as the result where or not it is in the shortest path?

答:
Here is the query that works:

```<code>match p=(n:SNPNode{SNP:'R-Z11'})<-[:SNPChild*0..99]-(MRCA:SNPNode)-[:SNPChild*0..99]->(m:SNPNode{SNP:'R-BY13828'})
return MRCA.SNP
</code>```

Or, to get the lowest common ancestor (MRCA) with a boolean flag:

```<code>match p=(n:SNPNode{SNP:'R-Z11'})<-[:SNPChild*0..99]-(MRCA:SNPNode)-[:SNPChild*0..99]->(m:SNPNode{SNP:'R-BY13828'}) unwind(nodes(p)) as pn
return case when pn.SNP=MRCA.SNP then True else False end as MRCA,pn.SNP
</code>```

with this output

MRCA    SNP

FALSE   R-Z11

FALSE   R-Z338

TRUE    R-Z8

FALSE   R-BY13828

Body:
I have loaded a hierarchical tree (DAG) of DNA SNPs. I want to identify lowest common ancestors.

This query works, yield the single correct node:

Match (n:SNPNode{SNP:'R-Z11'}), (m:SNPNode{SNP:'R-BY13828'})
match path=(n)-[:SNPParent*..99]->(MRCA)<-[:SNPParent*..99]-(m)
return MRCA.SNP

However, this one yields no result:

Match (n:SNPNode{SNP:'R-Z11'}), (m:SNPNode{SNP:'R-S25289'})
match path=(n)-[:SNPParent*..99]->(MRCA)<-[:SNPParent*..99]-(m)
return MRCA.SNP

even though the two queries seeking ancestors of both yield nodes some of which are shared:

MATCH p=(n:SNPNode{SNP:'R-Z11'})-[r:SNPParent*..66]->(m) RETURN m.SNP

m.SNP
R-Z338
R-Z8
R-Z7
R-Z2
R-Z345
R-Z27
R-Z30
R-Z9
R-L48
R-Z301
R-Z381
R-U106
R-L151
R-L51
R-L23
R-M269
R-P297
R-L389
R-L754
R-M343

and

MATCH p=(n:SNPNode{SNP:'R-Z25289'})-[r:SNPParent*..66]->(m) RETURN m.SNP

m.SNP
R-S16701
R-S1774
R-Z341
**R-Z11**
R-Z338
R-Z8
R-Z7
R-Z2
R-Z345
R-Z27
R-Z30
R-Z9
R-L48
R-Z301
R-Z381
R-U106
R-L151
R-L51
R-L23
R-M269
R-P297
R-L389
R-L754
R-M343

It seems the problem is that R-Z11 is in the path of the second query and is itself the ancestor. In other words, sometimes the LCA is at the end of a shortest path. Is there a way to address this so that R-Z11 returns as the result where or not it is in the shortest path?

Body:
Here is the query that works:

match p=(n:SNPNode{SNP:'R-Z11'})<-[:SNPChild*0..99]-(MRCA:SNPNode)-[:SNPChild*0..99]->(m:SNPNode{SNP:'R-BY13828'})
return MRCA.SNP

Or, to get the lowest common ancestor (MRCA) with a boolean flag:

match p=(n:SNPNode{SNP:'R-Z11'})<-[:SNPChild*0..99]-(MRCA:SNPNode)-[:SNPChild*0..99]->(m:SNPNode{SNP:'R-BY13828'}) unwind(nodes(p)) as pn
return case when pn.SNP=MRCA.SNP then True else False end as MRCA,pn.SNP

with this output

MRCA    SNP

FALSE   R-Z11

FALSE   R-Z338

TRUE    R-Z8

FALSE   R-BY13828


问:
How to filter specific query results on kibana queries
I have the follow query:

```<code>{
  "query": {
    "match": {
      "message": {
        "query": "Error",
        "type": "phrase"
      }
    }
  }
}
</code>```

However I get results with specific content which iam not interested on.

for example:

```<code>2017-12-05 15:51:54,012 ERROR io.vertx.spi.cluster.zookeeper.ZookeeperClusterManager - Failed to handle memberRemoved
io.vertx.core.VertxException: java.io.InvalidClassException: io.vertx.spi.cluster.zookeeper.impl.ZKSyncMap$KeyValue; local class
</code>```

so i want to upgrade my query not to return results which contain the word: ZookeeperClusterManager

how can I do that with my current query?

Thank you

答:
You need to use boolean query with must_not for negative search.

Query should be something like this

```<code>{
    "query": {
        "bool": {
            "must": {
                "match": {
                    "message": "Error"
                }
            },
            "must_not": {
                "match": {
                    "message": "io.vertx.spi.cluster.zookeeper.ZookeeperClusterManager"
                }
            }
        }
    }
}
</code>```

You need to use io.vertx.spi.cluster.zookeeper.ZookeeperClusterManager because of how indexing in ES works. ES uses analyzer to turn the long string into a list of values, that it can search on. One of the steps to do that is to split the text by spaces (tokenization). And that's what's happening here.

2017-12-05 15:51:54,012 ERROR io.vertx.spi.cluster.zookeeper.ZookeeperClusterManager - Failed to handle memberRemoved

Is converted to the following list

```<code>2017-12-05
15:51:54,012
ERROR
io.vertx.spi.cluster.zookeeper.ZookeeperClusterManager
-
Failed
to
handle
memberRemoved
</code>```

That is why your search for error works, but search for ZookeeperClusterManager does not. ZookeeperClusterManager on itself is not present in the list. For more information about how analysis works, I suggest you read this blogpost on ES website. Generally, you could fix this problem by making the tokenizer tokenize by spaces and dots instead of only spaces. How to setup custom analysis is described in this blogpost.

Body:
I have the follow query:

{
  "query": {
    "match": {
      "message": {
        "query": "Error",
        "type": "phrase"
      }
    }
  }
}

However I get results with specific content which iam not interested on.

for example:

2017-12-05 15:51:54,012 ERROR io.vertx.spi.cluster.zookeeper.ZookeeperClusterManager - Failed to handle memberRemoved
io.vertx.core.VertxException: java.io.InvalidClassException: io.vertx.spi.cluster.zookeeper.impl.ZKSyncMap$KeyValue; local class

so i want to upgrade my query not to return results which contain the word: ZookeeperClusterManager

how can I do that with my current query?

Thank you

Body:
You need to use boolean query with must_not for negative search.

Query should be something like this

{
    "query": {
        "bool": {
            "must": {
                "match": {
                    "message": "Error"
                }
            },
            "must_not": {
                "match": {
                    "message": "io.vertx.spi.cluster.zookeeper.ZookeeperClusterManager"
                }
            }
        }
    }
}

You need to use io.vertx.spi.cluster.zookeeper.ZookeeperClusterManager because of how indexing in ES works. ES uses analyzer to turn the long string into a list of values, that it can search on. One of the steps to do that is to split the text by spaces (tokenization). And that's what's happening here.

2017-12-05 15:51:54,012 ERROR io.vertx.spi.cluster.zookeeper.ZookeeperClusterManager - Failed to handle memberRemoved

Is converted to the following list

2017-12-05
15:51:54,012
ERROR
io.vertx.spi.cluster.zookeeper.ZookeeperClusterManager
-
Failed
to
handle
memberRemoved

That is why your search for error works, but search for ZookeeperClusterManager does not. ZookeeperClusterManager on itself is not present in the list. For more information about how analysis works, I suggest you read this blogpost on ES website. Generally, you could fix this problem by making the tokenizer tokenize by spaces and dots instead of only spaces. How to setup custom analysis is described in this blogpost.


问:
Dropbox API Uploading Document Size Is Zero
I am using PHP and Curl to upload a file into Dropbox but everytime it is creating empty files. Here is my code:

```<code>        // reading the remote file to get the file size...
        $file = 'https://upload.wikimedia.org/wikipedia/en/5/58/Penny_test.jpg';
        $ch = curl_init($file);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_exec($ch);
        $fileSize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);  // Response is 11201 bytes

        // upload file to dropbox
        $token = 'xxxxxxx'
        $headers = [
            "Authorization: Bearer ". $token,
            'Dropbox-API-Arg: {"path": "/Penny_test.jpg", "mode": "add", "autorename": true, "mute":false}',
            "Content-Type: application/octet-stream",
        ];

        $url = 'https://content.dropboxapi.com/2/files/upload';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);

        $file = 'https://upload.wikimedia.org/wikipedia/en/5/58/Penny_test.jpg';
        $fp = fopen($file, 'rb');
        curl_setopt($ch, CURLOPT_INFILE, $fp);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_INFILESIZE, $fileSize);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        $result = curl_exec($ch);
        print_r($result); die;
</code>```

Here's the response that I get:

```<code>{"name": "54.png", "path_lower": "/penny_test.jpg", "path_display": "/Penny_test.jpg", "id": "id:xxxxxxxxxxxxxxx", "client_modified": "2017-12-04T23:35:37Z", "server_modified": "2017-12-04T23:35:37Z", "rev": "bb3a7696db", "size": 0, "content_hash": "xxxxxxxxxxxxxxxxxxxxxxxxxx"}
</code>```

Why is Dropbox get 0 sized files from this upload & what am I doing wrong?

Thanks.

答:
The issue here does seem to be how the file data isn't being supplied in the request body properly.

To fix it, replace:

```<code>curl_setopt($ch, CURLOPT_POST, true);
</code>```

with:

```<code>curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST')
</code>```

Body:
I am using PHP and Curl to upload a file into Dropbox but everytime it is creating empty files. Here is my code:

        // reading the remote file to get the file size...
        $file = 'https://upload.wikimedia.org/wikipedia/en/5/58/Penny_test.jpg';
        $ch = curl_init($file);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_exec($ch);
        $fileSize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);  // Response is 11201 bytes

        // upload file to dropbox
        $token = 'xxxxxxx'
        $headers = [
            "Authorization: Bearer ". $token,
            'Dropbox-API-Arg: {"path": "/Penny_test.jpg", "mode": "add", "autorename": true, "mute":false}',
            "Content-Type: application/octet-stream",
        ];

        $url = 'https://content.dropboxapi.com/2/files/upload';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true);

        $file = 'https://upload.wikimedia.org/wikipedia/en/5/58/Penny_test.jpg';
        $fp = fopen($file, 'rb');
        curl_setopt($ch, CURLOPT_INFILE, $fp);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_INFILESIZE, $fileSize);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        $result = curl_exec($ch);
        print_r($result); die;

Here's the response that I get:

{"name": "54.png", "path_lower": "/penny_test.jpg", "path_display": "/Penny_test.jpg", "id": "id:xxxxxxxxxxxxxxx", "client_modified": "2017-12-04T23:35:37Z", "server_modified": "2017-12-04T23:35:37Z", "rev": "bb3a7696db", "size": 0, "content_hash": "xxxxxxxxxxxxxxxxxxxxxxxxxx"}

Why is Dropbox get 0 sized files from this upload & what am I doing wrong?

Thanks.

Body:
The issue here does seem to be how the file data isn't being supplied in the request body properly.

To fix it, replace:

curl_setopt($ch, CURLOPT_POST, true);

with:

curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST')


问:
Long press on Android menu item?
Is it possible to perform a long press on a menu item to perform a certain action?
I'm trying to have a menu dropdown when I long press a certain item.

Here's the menu xml

```<code><item
    android:id="@+id/add_item"
    android:icon="@drawable/ic_add_black_24dp"
    android:showAsAction="ifRoom"
    android:title="Add Item">
</item>

<item
    android:id="@+id/open_menu"
    android:icon="@drawable/ic_menu_black_24dp"
    android:showAsAction="ifRoom|withText"
    android:title="Open Menu">
</item>
</code>```

I want to have a dropdown appear when the first item is long pressed

答:
Here is another solution to your question.
I have used a menu in res/menu/menu.xml as below:

```<code><menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/action_send"
        android:orderInCategory="100"
        android:title="@string/send_menu"
        app:showAsAction="always" />
</menu>
</code>```

And here is my activity class. I have added a imagebutton to the menu item and set a image resource to it. Backgroud is set to null to have a transparent menuItem.

```<code>public class MyActivity extends AppCompatActivity {
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        MenuItem item = menu.findItem(R.id.action_send);
        ImageButton imageButton = new ImageButton(this);
        imageButton.setImageResource(R.drawable.ic_send_white_24dp);
        imageButton.setBackground(null);
        item.setActionView(imageButton);
        item.getActionView().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Log.d("Send Button", "Long pressed");
                Toast.makeText(MainActivity.this, "Send button long pressed", Toast.LENGTH_LONG).show();
                onSendMenuItemLongClick();
                return true;
            }
        });

        item.getActionView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onSendMenuItemClick(item);
            }
        });

        return super.onCreateOptionsMenu(menu);
    }

    private void onSendMenuItemLongClick() {

    }

    private void onSendMenuItemClick(MenuItem item) {
        Toast.makeText(this, "Send button clicked", Toast.LENGTH_LONG).show();
    }
}
</code>```

Title: Long press on Android menu item?

Body:
Is it possible to perform a long press on a menu item to perform a certain action?
I'm trying to have a menu dropdown when I long press a certain item.

Here's the menu xml

<item
    android:id="@+id/add_item"
    android:icon="@drawable/ic_add_black_24dp"
    android:showAsAction="ifRoom"
    android:title="Add Item">
</item>

<item
    android:id="@+id/open_menu"
    android:icon="@drawable/ic_menu_black_24dp"
    android:showAsAction="ifRoom|withText"
    android:title="Open Menu">
</item>

I want to have a dropdown appear when the first item is long pressed

Body:
Here is another solution to your question.
I have used a menu in res/menu/menu.xml as below:

<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/action_send"
        android:orderInCategory="100"
        android:title="@string/send_menu"
        app:showAsAction="always" />
</menu>

And here is my activity class. I have added a imagebutton to the menu item and set a image resource to it. Backgroud is set to null to have a transparent menuItem.

public class MyActivity extends AppCompatActivity {
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        MenuItem item = menu.findItem(R.id.action_send);
        ImageButton imageButton = new ImageButton(this);
        imageButton.setImageResource(R.drawable.ic_send_white_24dp);
        imageButton.setBackground(null);
        item.setActionView(imageButton);
        item.getActionView().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Log.d("Send Button", "Long pressed");
                Toast.makeText(MainActivity.this, "Send button long pressed", Toast.LENGTH_LONG).show();
                onSendMenuItemLongClick();
                return true;
            }
        });

        item.getActionView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onSendMenuItemClick(item);
            }
        });

        return super.onCreateOptionsMenu(menu);
    }

    private void onSendMenuItemLongClick() {

    }

    private void onSendMenuItemClick(MenuItem item) {
        Toast.makeText(this, "Send button clicked", Toast.LENGTH_LONG).show();
    }
}


问:
destroyFramebuffer method in an openGL app
in my OpenGL type of iphone app,  I have this method below in the GLView implementation.

i noticed everytime i started up the app during development that the last frame that was present when i shut the app down the last time,  would draw first before the app started its animation...

but when i commented out this method,   the app would start up just fine without the old end frame from the last time.

so i have something wrong in here. possibly directly in this method...    any ideas?

(now i'm getting a blank white screen (as a first frame) just before the animation,  so something is amiss here)

```<code>//------------------------------------------------------------------------------------
- (void)destroyFramebuffer
{
NSLog(@"destroyFramebuffer");
    glDeleteFramebuffersOES(1, &viewFramebuffer);
    viewFramebuffer = 0;
    glDeleteRenderbuffersOES(1, &viewRenderbuffer);
    viewRenderbuffer = 0;

    if(depthRenderbuffer)
    {
        glDeleteRenderbuffersOES(1, &depthRenderbuffer);
        depthRenderbuffer = 0;
    }
}
</code>```

here below is how the "createFrameBuffer" method looks
(the way the GLView implementation was starting up was with these 3 lines):

```<code>    [EAGLContext setCurrentContext:context];
//    [self destroyFramebuffer];
    [self createFramebuffer];

//------------------------------------------------------------------------------------
- (BOOL)createFramebuffer
{
NSLog(@"createFramebuffer");
    glGenFramebuffersOES(1, &viewFramebuffer);
    glGenRenderbuffersOES(1, &viewRenderbuffer);

    glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
    [context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer];
    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);

    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);

    if (USE_DEPTH_BUFFER)
    {
        glGenRenderbuffersOES(1, &depthRenderbuffer);
        glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
        glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
        glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
    }

    if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES)
    {
        NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
        return NO;
    }

    return YES;
}
</code>```

答:
When you destroy your renderbuffer the memory is reclaimed. The chances of the same memory being used again next time are quite high, but not always guaranteed. You simply need to clear the buffer on creation: (or at least render something that fills the buffer)

```<code>glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
</code>```

Also it's worth changing your destroy method to check that your framebuffer and renderbuffer even exist, otherwise you may be requesting GL to delete things that you haven't made. For eg:

```<code>if (viewFramebuffer) {
    glDeleteFramebuffers(1, &viewFramebuffer), viewFramebuffer = 0;
}
if (viewRenderbuffer) {
    glDeleteRenderbuffers(1, &viewRenderbuffer), viewRenderbuffer = 0;
}
</code>```

Body:
in my OpenGL type of iphone app,  I have this method below in the GLView implementation.

i noticed everytime i started up the app during development that the last frame that was present when i shut the app down the last time,  would draw first before the app started its animation...

but when i commented out this method,   the app would start up just fine without the old end frame from the last time.

so i have something wrong in here. possibly directly in this method...    any ideas?

(now i'm getting a blank white screen (as a first frame) just before the animation,  so something is amiss here)

//------------------------------------------------------------------------------------
- (void)destroyFramebuffer
{
NSLog(@"destroyFramebuffer");
    glDeleteFramebuffersOES(1, &viewFramebuffer);
    viewFramebuffer = 0;
    glDeleteRenderbuffersOES(1, &viewRenderbuffer);
    viewRenderbuffer = 0;

    if(depthRenderbuffer)
    {
        glDeleteRenderbuffersOES(1, &depthRenderbuffer);
        depthRenderbuffer = 0;
    }
}

here below is how the "createFrameBuffer" method looks
(the way the GLView implementation was starting up was with these 3 lines):

    [EAGLContext setCurrentContext:context];
//    [self destroyFramebuffer];
    [self createFramebuffer];

//------------------------------------------------------------------------------------
- (BOOL)createFramebuffer
{
NSLog(@"createFramebuffer");
    glGenFramebuffersOES(1, &viewFramebuffer);
    glGenRenderbuffersOES(1, &viewRenderbuffer);

    glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
    [context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer];
    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);

    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);

    if (USE_DEPTH_BUFFER)
    {
        glGenRenderbuffersOES(1, &depthRenderbuffer);
        glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
        glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
        glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
    }

    if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES)
    {
        NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
        return NO;
    }

    return YES;
}

Body:
When you destroy your renderbuffer the memory is reclaimed. The chances of the same memory being used again next time are quite high, but not always guaranteed. You simply need to clear the buffer on creation: (or at least render something that fills the buffer)

glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);

Also it's worth changing your destroy method to check that your framebuffer and renderbuffer even exist, otherwise you may be requesting GL to delete things that you haven't made. For eg:

if (viewFramebuffer) {
    glDeleteFramebuffers(1, &viewFramebuffer), viewFramebuffer = 0;
}
if (viewRenderbuffer) {
    glDeleteRenderbuffers(1, &viewRenderbuffer), viewRenderbuffer = 0;
}


问:
No match for 'Operator<<'
In this program I got the error

[Error] no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and 'numcall')

I can't understand how to get rid of it!!

```<code>#include<iostream>

using namespace::std;

class numcall
{
int a,b;

public:
     numcall(int c,int d)
    {
        c = a;
        c = b;
        cout<<"Your First num is " << c << endl << "Your Second num is "<< d << endl;
        cout << "You are in PARAMETER CONSTRUCTOR";
    }

    numcall(int u)
    {
        u = a;
        b = 0;
        cout << "Your First num is " << u << endl << "Your Second num is " << b << endl;
        cout << "You are in PARAMETER CONSTRUCTOR";
    }

    numcall()
    {

    }
};

int main(void)
{
    numcall x = numcall();
    numcall y = numcall(3,4);
    numcall z = numcall(3);
    cout << x << endl << endl << y << endl << endl << z << endl;
}
</code>```

答:
You need to define a friend method for the << stream operator, otherwise he doesn't know what to print.

```<code>  friend ostream &operator<<(ostream &os, const numcall &numcall1) {
    os << "a: " << numcall1.a << " b: " << numcall1.b;
    return os;
}
</code>```

This is just an example of implementation.

By the way there are other mistakes: c=a means assign a to c, you want to do the other way around. Welcome to the programming world mate ;)

Title: No match for 'Operator<<'

Body:
In this program I got the error

[Error] no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and 'numcall')

I can't understand how to get rid of it!!

#include<iostream>

using namespace::std;

class numcall
{
int a,b;

public:
     numcall(int c,int d)
    {
        c = a;
        c = b;
        cout<<"Your First num is " << c << endl << "Your Second num is "<< d << endl;
        cout << "You are in PARAMETER CONSTRUCTOR";
    }

    numcall(int u)
    {
        u = a;
        b = 0;
        cout << "Your First num is " << u << endl << "Your Second num is " << b << endl;
        cout << "You are in PARAMETER CONSTRUCTOR";
    }

    numcall()
    {

    }
};

int main(void)
{
    numcall x = numcall();
    numcall y = numcall(3,4);
    numcall z = numcall(3);
    cout << x << endl << endl << y << endl << endl << z << endl;
}

Body:
You need to define a friend method for the << stream operator, otherwise he doesn't know what to print.

  friend ostream &operator<<(ostream &os, const numcall &numcall1) {
    os << "a: " << numcall1.a << " b: " << numcall1.b;
    return os;
}

This is just an example of implementation.

By the way there are other mistakes: c=a means assign a to c, you want to do the other way around. Welcome to the programming world mate ;)


问:
Check whether an element is in std::initializer_list
I want to be able to write in C++ something similar to the following Python code:

```<code>if x in [1, 2, 3, 5] ...
</code>```

to test whether an element is contained in a set of hard-coded values, defined in-place. Like this:

```<code>if (in(x, {1, 2, 3, 5})) ...
</code>```

Here is the possible implementation of the in function:

```<code>template<class T>
bool in(const T& x, std::initializer_list<T> c)
{
  return std::find(c.begin(), c.end(), x) != c.end();
}
</code>```

My question is: do I really have to write this function by myself? Are there any default implementations over there? Maybe in boost? I checked boost::contains, but it works only with strings.

答:
Indeed the STL does not have a simple std::contains() function. Recently, there was a discussion on reddit about this topic.

Unfortunately, what came out of this is that it is considered harmful to have std::contains(), since it encourages people to write slow algorithms. Think for instance of

```<code>if (!std::contains(my_set.begin(), my_set.end(), entry)) {
    my_set.insert(entry);
}
</code>```

This code example essentially searches for the correct position twice: Once in contains, and once to find the insert location.

In my opinion, it would still be very helpful to have std::contains(), but so far no one was convinced yet to write a proposal.

So either use boost (as suggested by other in this thread), or write your own function which you essentially already did :-)

Body:
I want to be able to write in C++ something similar to the following Python code:

if x in [1, 2, 3, 5] ...

to test whether an element is contained in a set of hard-coded values, defined in-place. Like this:

if (in(x, {1, 2, 3, 5})) ...

Here is the possible implementation of the in function:

template<class T>
bool in(const T& x, std::initializer_list<T> c)
{
  return std::find(c.begin(), c.end(), x) != c.end();
}

My question is: do I really have to write this function by myself? Are there any default implementations over there? Maybe in boost? I checked boost::contains, but it works only with strings.

Body:
Indeed the STL does not have a simple std::contains() function. Recently, there was a discussion on reddit about this topic.

Unfortunately, what came out of this is that it is considered harmful to have std::contains(), since it encourages people to write slow algorithms. Think for instance of

if (!std::contains(my_set.begin(), my_set.end(), entry)) {
    my_set.insert(entry);
}

This code example essentially searches for the correct position twice: Once in contains, and once to find the insert location.

In my opinion, it would still be very helpful to have std::contains(), but so far no one was convinced yet to write a proposal.

So either use boost (as suggested by other in this thread), or write your own function which you essentially already did :-)

ContentLicense: CC BY-SA 4.0


问:
Matplotlib 2.1 issue with log scale
I installed matplotlib 2.1 from version 2.0.2 and my simple 2D x-y plots are now showing the y-axis with a log scale, when before the scale was linear. I am not sure how this is happening.

```<code>import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.gridspec as gridspec
from numpy import sqrt, pi, exp, linspace, loadtxt
from lmfit import Model

path=r'C:\users\test.mca'
f=open(path,'r')
lines=f.readlines()[14:2060]
x=[]

for i in range(0,2046):
    x.append(i)

plt.figure(figsize=(10,6))
plt.xlim(0,600)
plt.ylim(0,1000)
plt.grid(True)

plt.xlabel('Channels')
plt.ylabel('Counts')

def gaussian(x, amp, cen, wid):
    "1-d gaussian: gaussian(x, amp, cen, wid)"
    return (amp/(sqrt(2*pi)*wid)) * exp(-(x-cen)**2 /(2*wid**2))

gmod = Model(gaussian)
pars = gmod.make_params(amp=15000, wid=14, cen=380)
result = gmod.fit(lines, pars, x=x)

print(result.fit_report())
fwhm=result.params['wid'].value*2.35
ER=100*fwhm/result.params['cen'].value
center=result.params['cen']

plt.title('Gaussian fit\n Center=%.1f FWHM=%.1f ER=%.1f%%' % (center, fwhm, ER))
plt.plot(x, lines,'bo', markersize=4)
plt.plot(x, result.best_fit, 'r-')

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

Version 2.1:

Version 2.0.2:

The top figure is plotted using 2.1 and the bottom figure is using 2.0.2. Having some trouble understanding why this is.

答:
It is not showing a log scale. The axis just has a label for each point.

In matplotlib 2.0 strings were automatically converted to floats internally. This was never the intended usage, but people tended to misuse this to circumvent converting the strings themselves.

From matplotlib 2.1 on, strings are interpreted as strings, meaning they are categories and there will be one label per category.

In both matplotlib 2.0 and 2.1 you should actually convert your strings to floats if they are meant to be interpreted as numbers before plotting them.

```<code>lines = np.array(lines).astype(float)
</code>```

Title: Matplotlib 2.1 issue with log scale

Body:
I installed matplotlib 2.1 from version 2.0.2 and my simple 2D x-y plots are now showing the y-axis with a log scale, when before the scale was linear. I am not sure how this is happening.

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.gridspec as gridspec
from numpy import sqrt, pi, exp, linspace, loadtxt
from lmfit import Model

path=r'C:\users\test.mca'
f=open(path,'r')
lines=f.readlines()[14:2060]
x=[]

for i in range(0,2046):
    x.append(i)

plt.figure(figsize=(10,6))
plt.xlim(0,600)
plt.ylim(0,1000)
plt.grid(True)

plt.xlabel('Channels')
plt.ylabel('Counts')

def gaussian(x, amp, cen, wid):
    "1-d gaussian: gaussian(x, amp, cen, wid)"
    return (amp/(sqrt(2*pi)*wid)) * exp(-(x-cen)**2 /(2*wid**2))

gmod = Model(gaussian)
pars = gmod.make_params(amp=15000, wid=14, cen=380)
result = gmod.fit(lines, pars, x=x)

print(result.fit_report())
fwhm=result.params['wid'].value*2.35
ER=100*fwhm/result.params['cen'].value
center=result.params['cen']

plt.title('Gaussian fit\n Center=%.1f FWHM=%.1f ER=%.1f%%' % (center, fwhm, ER))
plt.plot(x, lines,'bo', markersize=4)
plt.plot(x, result.best_fit, 'r-')

plt.show()

Version 2.1:

Version 2.0.2:

The top figure is plotted using 2.1 and the bottom figure is using 2.0.2. Having some trouble understanding why this is.

Body:
It is not showing a log scale. The axis just has a label for each point.

In matplotlib 2.0 strings were automatically converted to floats internally. This was never the intended usage, but people tended to misuse this to circumvent converting the strings themselves.

From matplotlib 2.1 on, strings are interpreted as strings, meaning they are categories and there will be one label per category.

In both matplotlib 2.0 and 2.1 you should actually convert your strings to floats if they are meant to be interpreted as numbers before plotting them.

lines = np.array(lines).astype(float)


问:
java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionFactoryImplementor.getProperties()Ljava/util/Properties
```<code>@Configuration
@EnableTransactionManagement
public class DataSourceConfig {

    @Bean(destroyMethod = "shutdown")
    public DataSource dataSource(){
        EmbeddedDatabaseBuilder databaseBuilder = new EmbeddedDatabaseBuilder();
        databaseBuilder.setType(EmbeddedDatabaseType.H2);
        databaseBuilder.addScript("classpath:db/migration/V1__Create_Books_Table.sql");
        databaseBuilder.addScript("classpath:db/migration/V2__Add_Books.sql");
        return databaseBuilder.build();
    }

    @Bean
    public JpaVendorAdapter vendorAdapter(){

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setDatabase(Database.H2);
        vendorAdapter.setShowSql(true);
        vendorAdapter.setDatabasePlatform("org.hibernate.dialect.H2Dialect");
        return vendorAdapter;
    }

    @Bean(name = "entityManagerFactory")
    public EntityManagerFactory managerFactory(){
    Properties jpaProperties = new Properties();
    jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop");

    LocalContainerEntityManagerFactoryBean managerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    managerFactoryBean.setDataSource(dataSource());
    managerFactoryBean.setJpaVendorAdapter(vendorAdapter());
    managerFactoryBean.setPackagesToScan("com.sammy");
    managerFactoryBean.setJpaProperties(jpaProperties);
    managerFactoryBean.afterPropertiesSet();
    return managerFactoryBean.getObject();
}

    @Bean
    public PlatformTransactionManager transactionManager(){
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(managerFactory());
        return transactionManager;
    }
}
</code>```

That is my configuration class and my gradle build file is

```<code>buildscript {

    repositories {
        jcenter()
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:${sonarVersion}"
        classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
    }
}

apply plugin: 'java'
apply plugin: 'jacoco'
apply plugin: 'org.sonarqube'
apply plugin: 'org.springframework.boot'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}

jar{
    group 'com.sammy'
    version '1.0-SNAPSHOT'
}

dependencies {

    testCompile "junit:junit:${junitVersion}"
    testCompile "info.cukes:cucumber-java:${cucumberVersion}"
    testCompile "info.cukes:cucumber-junit:${cucumberVersion}"
    //testCompile "info.cukes:cucumber-spring:${cucumberVersion}"
    testCompile 'org.springframework.boot:spring-boot-starter-test'

    compile 'com.h2database:h2'
    compile "org.flywaydb:flyway-core:${flywayVersion}"
    compile "org.projectlombok:lombok:${lombokVersion}"
    compile("org.springframework.boot:spring-boot-starter-web") {
        exclude module: "spring-boot-starter-tomcat"
    }

    compile "org.hibernate:hibernate-core:${hibernateVersion}"
    compile 'org.springframework.boot:spring-boot-starter-aop'
    compile 'org.springframework.boot:spring-boot-starter-jetty'
    compile "io.springfox:springfox-swagger2:${swaggerVersion}"
    compile "org.jadira.usertype:usertype.core:${jadiraVersion}"
    compile "io.springfox:springfox-swagger-ui:${swaggerVersion}"
    compile 'org.springframework.boot:spring-boot-starter-actuator'
    compile 'org.springframework.cloud:spring-cloud-starter-config'
    compile 'org.springframework.boot:spring-boot-starter-data-jpa'
    //compile 'org.springframework.boot:spring-boot-starter-data-mongodb'
}

task wrapper(type :Wrapper){
    gradleVersion = '3.4.1'
}
</code>```

While my gradle properties file is

```<code>junitVersion = 4.12
sonarVersion = 2.2.1
flywayVersion = 4.1.2
swaggerVersion = 2.6.1
cucumberVersion = 1.2.5
lombokVersion = 1.16.14
jadiraVersion = 6.0.1.GA
hibernateVersion = 5.2.9.Final
springBootVersion = 1.5.2.RELEASE
</code>```

This issue is, I want to use Java 8's LocalDate in my entity class but, this still doesn't work without throwing this error message:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/sammy/config/DataSourceConfig.class]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionFactoryImplementor.getProperties()Ljava/util/Properties;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at com.sammy.SpringDataTutorials.main(SpringDataTutorials.java:18) [main/:na]
Caused by: java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionFactoryImplementor.getProperties()Ljava/util/Properties;
    at org.hibernate.jpa.internal.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:124) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:890) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 16 common frames omitted
</code>```

Whether I add jadira core or spi library to my gradle build file, I still get the same error. SpringBoot uses spring-orm-4.3.7.RELEASE as is in the stacktrace then adding hibernate core version 5.2.9.FINAL upgrades it to that version. I've looked at almost all the different issues mentioned here but none deals with this version. I've also read through the hibernate current version document which says it should just work but it isn't for me so not sure why.

INFO 26648 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found. I changed the JpaTransactionManager to use the injected entityManagerFactory as one of those answers suggested but it still didn't work even after rebuilding the project with gradle and intellij. I looked at the Hibernate 5.2.9.FINAL docs and that method getProperties() no longer exists but inherited from entitiyManagerFactory. Also, most of the answers were done in xml config not the Java one as I've got up there and none of the answers described how to change it into a map in a java config situation rather than using the properties. When I drop hibiernates version to 5.1.x, that error message goes but the error message for the Java 8 LocalDate type is displayed which I found is because there's no support for Java's feature in that version of hibernate.

答:
What version of the Gradle do you have?

I ask, because I have the same error which occurs after upgrade Gradle from 3.5 to 4.3. The same Hibernate version (5.2.9), the same Spring Boot (1.5.8) but in Gradle 3.5. - OK, 4.3 fail.

I've tested and latest version working fine was for me 3.5.1. I've tested versions from 4.0 to 4.4-rc-6 (latest at this moment).

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-3.5.1-all.zip
</code>```

Body:
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {

    @Bean(destroyMethod = "shutdown")
    public DataSource dataSource(){
        EmbeddedDatabaseBuilder databaseBuilder = new EmbeddedDatabaseBuilder();
        databaseBuilder.setType(EmbeddedDatabaseType.H2);
        databaseBuilder.addScript("classpath:db/migration/V1__Create_Books_Table.sql");
        databaseBuilder.addScript("classpath:db/migration/V2__Add_Books.sql");
        return databaseBuilder.build();
    }

    @Bean
    public JpaVendorAdapter vendorAdapter(){

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setDatabase(Database.H2);
        vendorAdapter.setShowSql(true);
        vendorAdapter.setDatabasePlatform("org.hibernate.dialect.H2Dialect");
        return vendorAdapter;
    }

    @Bean(name = "entityManagerFactory")
    public EntityManagerFactory managerFactory(){
    Properties jpaProperties = new Properties();
    jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop");

    LocalContainerEntityManagerFactoryBean managerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    managerFactoryBean.setDataSource(dataSource());
    managerFactoryBean.setJpaVendorAdapter(vendorAdapter());
    managerFactoryBean.setPackagesToScan("com.sammy");
    managerFactoryBean.setJpaProperties(jpaProperties);
    managerFactoryBean.afterPropertiesSet();
    return managerFactoryBean.getObject();
}

    @Bean
    public PlatformTransactionManager transactionManager(){
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(managerFactory());
        return transactionManager;
    }
}

That is my configuration class and my gradle build file is

buildscript {

    repositories {
        jcenter()
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:${sonarVersion}"
        classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
    }
}

apply plugin: 'java'
apply plugin: 'jacoco'
apply plugin: 'org.sonarqube'
apply plugin: 'org.springframework.boot'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}

jar{
    group 'com.sammy'
    version '1.0-SNAPSHOT'
}

dependencies {

    testCompile "junit:junit:${junitVersion}"
    testCompile "info.cukes:cucumber-java:${cucumberVersion}"
    testCompile "info.cukes:cucumber-junit:${cucumberVersion}"
    //testCompile "info.cukes:cucumber-spring:${cucumberVersion}"
    testCompile 'org.springframework.boot:spring-boot-starter-test'

    compile 'com.h2database:h2'
    compile "org.flywaydb:flyway-core:${flywayVersion}"
    compile "org.projectlombok:lombok:${lombokVersion}"
    compile("org.springframework.boot:spring-boot-starter-web") {
        exclude module: "spring-boot-starter-tomcat"
    }

    compile "org.hibernate:hibernate-core:${hibernateVersion}"
    compile 'org.springframework.boot:spring-boot-starter-aop'
    compile 'org.springframework.boot:spring-boot-starter-jetty'
    compile "io.springfox:springfox-swagger2:${swaggerVersion}"
    compile "org.jadira.usertype:usertype.core:${jadiraVersion}"
    compile "io.springfox:springfox-swagger-ui:${swaggerVersion}"
    compile 'org.springframework.boot:spring-boot-starter-actuator'
    compile 'org.springframework.cloud:spring-cloud-starter-config'
    compile 'org.springframework.boot:spring-boot-starter-data-jpa'
    //compile 'org.springframework.boot:spring-boot-starter-data-mongodb'
}

task wrapper(type :Wrapper){
    gradleVersion = '3.4.1'
}

While my gradle properties file is

junitVersion = 4.12
sonarVersion = 2.2.1
flywayVersion = 4.1.2
swaggerVersion = 2.6.1
cucumberVersion = 1.2.5
lombokVersion = 1.16.14
jadiraVersion = 6.0.1.GA
hibernateVersion = 5.2.9.Final
springBootVersion = 1.5.2.RELEASE

This issue is, I want to use Java 8's LocalDate in my entity class but, this still doesn't work without throwing this error message:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/sammy/config/DataSourceConfig.class]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionFactoryImplementor.getProperties()Ljava/util/Properties;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
    at com.sammy.SpringDataTutorials.main(SpringDataTutorials.java:18) [main/:na]
Caused by: java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionFactoryImplementor.getProperties()Ljava/util/Properties;
    at org.hibernate.jpa.internal.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:124) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:890) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 16 common frames omitted

Whether I add jadira core or spi library to my gradle build file, I still get the same error. SpringBoot uses spring-orm-4.3.7.RELEASE as is in the stacktrace then adding hibernate core version 5.2.9.FINAL upgrades it to that version. I've looked at almost all the different issues mentioned here but none deals with this version. I've also read through the hibernate current version document which says it should just work but it isn't for me so not sure why.

INFO 26648 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found. I changed the JpaTransactionManager to use the injected entityManagerFactory as one of those answers suggested but it still didn't work even after rebuilding the project with gradle and intellij. I looked at the Hibernate 5.2.9.FINAL docs and that method getProperties() no longer exists but inherited from entitiyManagerFactory. Also, most of the answers were done in xml config not the Java one as I've got up there and none of the answers described how to change it into a map in a java config situation rather than using the properties. When I drop hibiernates version to 5.1.x, that error message goes but the error message for the Java 8 LocalDate type is displayed which I found is because there's no support for Java's feature in that version of hibernate.

Body:
What version of the Gradle do you have?

I ask, because I have the same error which occurs after upgrade Gradle from 3.5 to 4.3. The same Hibernate version (5.2.9), the same Spring Boot (1.5.8) but in Gradle 3.5. - OK, 4.3 fail.

I've tested and latest version working fine was for me 3.5.1. I've tested versions from 4.0 to 4.4-rc-6 (latest at this moment).

distributionUrl=https\://services.gradle.org/distributions/gradle-3.5.1-all.zip


问:
Error converting Retrofit response to local model
I am using Retrofit to communicate with a REST based service and in my Android App I have a local domain model. To isolate my App from any changes and dependencies on the REST service I want to convert the objects returned from the REST service to my local domain model.

Currently I am doing this by passing the object returned by the response.body() to the constructor of the corresponding class in my model. This works great for all basic properties like ints, Strings etc. except for more complex objects like List<>. Here is my class:

```<code>public abstract class MetadataAsset<T> implements Comparable<T> {

    protected Long id;
    protected String title;
    protected String description;
    protected List<String> genres;
    protected List<CastMember> cast;

    public MetadataAsset(no.external.entities.MetadataAsset metadataAsset) {
        this.id = metadataAsset.id;
        this.title = metadataAsset.title;
        this.description = metadataAsset.description;
        this.genres = metadataAsset.genres;

        this.cast = new ArrayList<>();
        if(metadataAsset.cast != null) {
            for (no.external.entities.CastMember castMember : metadataAsset.cast) {
                this.cast.add(new CastMember(castMember));
            }
        }

    }

    public Long getId() {
        return id;
    }

    public String getTitle() {
         return title;
    }

    public String getDescription() {
         return description;
    }

    public List<String> getGenres() {
         return genres;
    }

    public List<CastMember> getCast() {
         return cast;
    }
}
</code>```

The object passed to the constructor is the object returned by the response.body() by Retrofit. Before passing this object to the MetadataAsset constructor I check that the size of the cast list is not null and the number of elements in the list is > 0 and I get the correct number of elements, but when I do the same test inside the constructor, the list is now null.

Looking at the genres list, the result is different. The list has the same number of elements both before passing the object to the constructor and inside the constructor.

Is there some sort of GC going on here that I do not understand? Why would the list be NULL inside the constructor when it is not outside?

And how should this be structured?

答:
Can't you just use Serializable and let the converter you chose to work with Retrofit do the work?

For instance, in your code, you can make your custom objects implement Serializable and then also annotate fields that you want mapped from the JSON with @SerializedName annotation on them, passing the json attribute name as a parameter to the annotation, like this.

Hope this might help.

Body:
I am using Retrofit to communicate with a REST based service and in my Android App I have a local domain model. To isolate my App from any changes and dependencies on the REST service I want to convert the objects returned from the REST service to my local domain model.

Currently I am doing this by passing the object returned by the response.body() to the constructor of the corresponding class in my model. This works great for all basic properties like ints, Strings etc. except for more complex objects like List<>. Here is my class:

public abstract class MetadataAsset<T> implements Comparable<T> {

    protected Long id;
    protected String title;
    protected String description;
    protected List<String> genres;
    protected List<CastMember> cast;

    public MetadataAsset(no.external.entities.MetadataAsset metadataAsset) {
        this.id = metadataAsset.id;
        this.title = metadataAsset.title;
        this.description = metadataAsset.description;
        this.genres = metadataAsset.genres;

        this.cast = new ArrayList<>();
        if(metadataAsset.cast != null) {
            for (no.external.entities.CastMember castMember : metadataAsset.cast) {
                this.cast.add(new CastMember(castMember));
            }
        }

    }

    public Long getId() {
        return id;
    }

    public String getTitle() {
         return title;
    }

    public String getDescription() {
         return description;
    }

    public List<String> getGenres() {
         return genres;
    }

    public List<CastMember> getCast() {
         return cast;
    }
}

The object passed to the constructor is the object returned by the response.body() by Retrofit. Before passing this object to the MetadataAsset constructor I check that the size of the cast list is not null and the number of elements in the list is > 0 and I get the correct number of elements, but when I do the same test inside the constructor, the list is now null.

Looking at the genres list, the result is different. The list has the same number of elements both before passing the object to the constructor and inside the constructor.

Is there some sort of GC going on here that I do not understand? Why would the list be NULL inside the constructor when it is not outside?

And how should this be structured?


问:
Are Merkle trees generated from a single SSTable?
When Cassandra is doing the data integrity check, it does a validation compaction, but what does this mean exactly? My understanding is that it creates a single SSTable that will be stored temporarily (until the repair finishes), and then it generates the Merkle trees from that single created SSTable. If any of the Merkle trees leafs fails validation, then the partitions used to create that leaf (from the SSTable created during the validation compaction) will be streamed to the other node.
However, a friend told me that the Merkle trees are generated from each (previously existing) SSTable.

So, how many Merkle trees are generated, one or as many as SSTables?

答:
The validation compaction iterates over all the sstables that are included in the range to build the merkle tree. It doesn't actually write a new sstable, but the compaction interfaces perform same type of task (iterating over data) so its reused. The compaction manager is also used for cleanup, secondary index rebuild, MV building, scrubbing, and verify processes.

A single merkle tree is generated. Each node of it represents a hash of all the data in a token range, each child of the node is half of its token range. The depth of the tree is dynamic, ideally the leaf represents 1 partition each but it could end up representing much more if the root node represents a wide range containing many partitions. Since the depth of the merkle tree is capped at 20 (or else it will be too large, and cause issues transferring) you generally dont want to repair a range that has much more than 2^20 or 1 million partitions in it. Can use getsplits or the size_estimates table to determine this when picking how to subdivide range for a subrange repair.

Worth noting, that a repair can kick off many sub repairs, each will have its own validation compaction/merkle tree/streaming session.


答:
You need to add a second parameter to the substring call to limit the length of the subtring, like so:

```<code>public class Main {
  public static void main(final String[] args) {

    // case 1:
    // String s = "-1 tvg-name=\"Test Channel\"
    // tvg-logo=\"http://awebsite/logos/TestChannel.png\"";
    // case 2:
    String s =
            "-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\" group-title=\"Movies\"";
    // case 3:
    // String s =
    // "-1 tvg-logo=\"http://awebsite/logos/TestChannel.png\" tvg-name=\"Test
    // Channel\" group-title=\"Movies\"";

    String tvgLogo = "tvg-logo=\"";
    int tvgLogoIndex = s.indexOf(tvgLogo) + tvgLogo.length();
    String icon = s.substring(tvgLogoIndex, s.indexOf('"', tvgLogoIndex)).replace("=", "")
            .replace("\"", "").replace("\n", "");

    System.out.println("Logo:" + icon);
  }
}
</code>```

The s.indexOf('"', tvLogoIndex) call searches for the double quote that closes off the tvg-logo attribute so that you select only the logo url.

Note that if you're parsing HTML documents there are probably cleaner solutions than using subtrings.

Title: How to get string between a character and first occurrence of double quotes?

Body:
I am trying to get tvg-logo string(http://awebsite/logos/TestChannel.png) but my current code only works on case one.For case 2 and 3 inputs the code outputs not only the tvg-logo value but also the rest of string after it!could you guys show me how to get ONLY tvg-logo url in all these case ?Thanks

public class HelloWorld {
  public static void main(String[] args) {

    //case 1:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\"";
    //case 2:
    //String s="-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\" group-title=\"Movies\"";
    //case 3:
    String s="-1 tvg-logo=\"http://awebsite/logos/TestChannel.png\" tvg-name=\"Test Channel\" group-title=\"Movies\"";

    String icon = s.substring(s.indexOf("tvg-logo") + "tvg-logo".length()).replace("=", "").replace("\"", "").replace("\n", "");

    System.out.println("Logo:"+icon);
  }
}

output for case 3 input:

Logo:http://awebsite/logos/TestChannel.png tvg-nameTest Channel group-titleMovies

Expected output for all types of input cases:

Logo:http://awebsite/logos/TestChannel.png

Body:
You need to add a second parameter to the substring call to limit the length of the subtring, like so:

public class Main {
  public static void main(final String[] args) {

    // case 1:
    // String s = "-1 tvg-name=\"Test Channel\"
    // tvg-logo=\"http://awebsite/logos/TestChannel.png\"";
    // case 2:
    String s =
            "-1 tvg-name=\"Test Channel\" tvg-logo=\"http://awebsite/logos/TestChannel.png\" group-title=\"Movies\"";
    // case 3:
    // String s =
    // "-1 tvg-logo=\"http://awebsite/logos/TestChannel.png\" tvg-name=\"Test
    // Channel\" group-title=\"Movies\"";

    String tvgLogo = "tvg-logo=\"";
    int tvgLogoIndex = s.indexOf(tvgLogo) + tvgLogo.length();
    String icon = s.substring(tvgLogoIndex, s.indexOf('"', tvgLogoIndex)).replace("=", "")
            .replace("\"", "").replace("\n", "");

    System.out.println("Logo:" + icon);
  }
}

The s.indexOf('"', tvLogoIndex) call searches for the double quote that closes off the tvg-logo attribute so that you select only the logo url.

Note that if you're parsing HTML documents there are probably cleaner solutions than using subtrings.


问:
How to set client certificate chain in WinHttp
I am working on a client-server application where server is a web server which performs client validation based on SSL certificate. Server trust a Root CA certificate. Client is a windows application developed in C++ which has a certificate signed by intermediate CA which in turn signed by Root CA.
I am able to set client certificate during https connection by calling WinHttpSetOption api with WINHTTP_OPTION_CLIENT_CERT_CONTEXT as option. However this will set only client certificate but not the entire chain. Server does not have intermediate CA in its store hence it is not able to authenticate the client.

Is there a way to set the full client certificate chain in WinHttp, provided the full chain is already present in certificate store of client?

答:
The server has to have the CA certificate beforehand, it's not going to trust the root CA the client hands it. (I'm not sure about whether it (the server-side) would trust an intermediate CA signed by a trusted CA but my inclination says no).

Trusting some random CA a client sends would break the entire point of certificate verification, you would have no idea of whether the data the client submits is actually meaningful. So add the root and intermediate CA certificates to the server's certificate stores. (If you don't have access to that you'll have to talk to an admin and have them do it).


问:
org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
I am trying run a spring-boot application which uses hibernate via spring-jpa, but i am getting this error:

```<code>Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
        at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
        at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
        at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:205)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
        at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
        at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
        at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:336)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1613)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1550)
        ... 21 more
</code>```

my pom.xml file is this:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.1.8.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
       </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
    </dependency>
</dependencies>
</code>```

my hibernate configuration is that (the dialect configuration is in the last method from this class):

```<code>@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.spring.app" })
public class HibernateConfig {

   @Bean
   public LocalSessionFactoryBean sessionFactory() {
      LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

      sessionFactory.setDataSource(restDataSource());
      sessionFactory.setPackagesToScan(new String[] { "com.spring.app.model" });
      sessionFactory.setHibernateProperties(hibernateProperties());

      return sessionFactory;
   }

   @Bean
   public DataSource restDataSource() {
      BasicDataSource dataSource = new BasicDataSource();

      dataSource.setDriverClassName("org.postgresql.Driver");
      dataSource.setUrl("jdbc:postgresql://localhost:5432/teste?charSet=LATIN1");
      dataSource.setUsername("klebermo");
      dataSource.setPassword("123");

      return dataSource;
   }

   @Bean
   @Autowired
   public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
      HibernateTransactionManager txManager = new HibernateTransactionManager();
      txManager.setSessionFactory(sessionFactory);
      return txManager;
   }

   @Bean
   public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
      return new PersistenceExceptionTranslationPostProcessor();
   }

   Properties hibernateProperties() {
      return new Properties() {
         /**
         *
         */
        private static final long serialVersionUID = 1L;

        {
            setProperty("hibernate.hbm2ddl.auto", "create");
            setProperty("hibernate.show_sql", "false");
            setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
         }
      };
   }
}
</code>```

what I am doing wrong here?

答:
This happened to me because I hadn't added the conf.configure(); before beginning the session:

```<code>Configuration conf = new Configuration();
conf.configure();
</code>```

Body:
I am trying run a spring-boot application which uses hibernate via spring-jpa, but i am getting this error:

Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
        at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
        at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
        at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:205)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
        at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
        at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
        at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:336)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1613)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1550)
        ... 21 more

my pom.xml file is this:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.1.8.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
       </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
    </dependency>
</dependencies>

my hibernate configuration is that (the dialect configuration is in the last method from this class):

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.spring.app" })
public class HibernateConfig {

   @Bean
   public LocalSessionFactoryBean sessionFactory() {
      LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

      sessionFactory.setDataSource(restDataSource());
      sessionFactory.setPackagesToScan(new String[] { "com.spring.app.model" });
      sessionFactory.setHibernateProperties(hibernateProperties());

      return sessionFactory;
   }

   @Bean
   public DataSource restDataSource() {
      BasicDataSource dataSource = new BasicDataSource();

      dataSource.setDriverClassName("org.postgresql.Driver");
      dataSource.setUrl("jdbc:postgresql://localhost:5432/teste?charSet=LATIN1");
      dataSource.setUsername("klebermo");
      dataSource.setPassword("123");

      return dataSource;
   }

   @Bean
   @Autowired
   public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
      HibernateTransactionManager txManager = new HibernateTransactionManager();
      txManager.setSessionFactory(sessionFactory);
      return txManager;
   }

   @Bean
   public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
      return new PersistenceExceptionTranslationPostProcessor();
   }

   Properties hibernateProperties() {
      return new Properties() {
         /**
         *
         */
        private static final long serialVersionUID = 1L;

        {
            setProperty("hibernate.hbm2ddl.auto", "create");
            setProperty("hibernate.show_sql", "false");
            setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
         }
      };
   }
}

what I am doing wrong here?

Body:
This happened to me because I hadn't added the conf.configure(); before beginning the session:

Configuration conf = new Configuration();
conf.configure();


问:
Using redux-form, how can I reset the form values from another component?
Here is a demo of my issue: https://stackblitz.com/edit/redux-form-reset-problems

I am using redux-form 7.2.0 and am trying to reset the form values from another component that is not wrapped by the ReduxForm HOC.

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { reset } from 'redux-form';

class MoodAnnouncement extends Component {
  constructor(props) {
    super(props);
    this.resetMood = this.resetMood.bind(this, event);
  }

  resetMood(event) {
    event.preventDefault();
    this.props.dispatch(this.props.reset('SearchFiltersForm'));
  }

  render() {
    return (
      <div className="mui-panel">
        <button
          className="mui-btn mui-btn--primary mui-btn--raised"
          disabled={this.props.MoodCheckerForm.values === undefined}
          onClick={this.resetMood}
        >Reset Mood
        </button>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    MoodCheckerForm: state.form.MoodCheckerForm,
  };
};

export default connect(mapStateToProps, { reset })(MoodAnnouncement);
</code>```

When I click the reset mood button that is in another component away from the form, I'm receiving the error this.props.dispatch is not a function, so I assume there is a different way to dispatch the reset action from within the connect HOC.

How can I reset the form values from another component that is using the react-redux connect HOC?

答:
Please see the Remote Submit example.

There are a couple issues.

Your form names do not match. The only reason MoodChecker.resetMood() works is because the reduxForm() HoC binds the form name to reset() when passing in the prop. So the incorrect name passed is actually being ignored.

MoodControls.resetMood() only has to call the bound action creator reset() from the props, making sure to pass in the right form name. When using the connect(mapStateToProps: func, mapDispatchToProps: object) form, the object passed as the second argument is automatically bound to dispatch via  bindActionCreators().

```<code>class MoodControls extends Component {
  // ...

  resetMood(event) {
    event.preventDefault();
    this.props.reset('MoodCheckerForm');
  }

  render() {
    // ...
  }
}

const mapStateToProps = state => ({
  MoodCheckerForm: state.form.MoodCheckerForm
});

export default connect(mapStateToProps, { reset })(MoodControls)
</code>```

Body:
Here is a demo of my issue: https://stackblitz.com/edit/redux-form-reset-problems

I am using redux-form 7.2.0 and am trying to reset the form values from another component that is not wrapped by the ReduxForm HOC.

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { reset } from 'redux-form';

class MoodAnnouncement extends Component {
  constructor(props) {
    super(props);
    this.resetMood = this.resetMood.bind(this, event);
  }

  resetMood(event) {
    event.preventDefault();
    this.props.dispatch(this.props.reset('SearchFiltersForm'));
  }

  render() {
    return (

        <button
          className="mui-btn mui-btn--primary mui-btn--raised"
          disabled={this.props.MoodCheckerForm.values === undefined}
          onClick={this.resetMood}
        >Reset Mood
        </button>

    );
  }
}

const mapStateToProps = state => {
  return {
    MoodCheckerForm: state.form.MoodCheckerForm,
  };
};

export default connect(mapStateToProps, { reset })(MoodAnnouncement);

When I click the reset mood button that is in another component away from the form, I'm receiving the error this.props.dispatch is not a function, so I assume there is a different way to dispatch the reset action from within the connect HOC.

How can I reset the form values from another component that is using the react-redux connect HOC?

Body:
Please see the Remote Submit example.

There are a couple issues.

Your form names do not match. The only reason MoodChecker.resetMood() works is because the reduxForm() HoC binds the form name to reset() when passing in the prop. So the incorrect name passed is actually being ignored.

MoodControls.resetMood() only has to call the bound action creator reset() from the props, making sure to pass in the right form name. When using the connect(mapStateToProps: func, mapDispatchToProps: object) form, the object passed as the second argument is automatically bound to dispatch via  bindActionCreators().

class MoodControls extends Component {
  // ...

  resetMood(event) {
    event.preventDefault();
    this.props.reset('MoodCheckerForm');
  }

  render() {
    // ...
  }
}

const mapStateToProps = state => ({
  MoodCheckerForm: state.form.MoodCheckerForm
});

export default connect(mapStateToProps, { reset })(MoodControls)