问:
Display files in a folder along with the date modified of those files
```<code> <?php
    $filename = 'file:///C:/Users/xxx/Desktop/2017/cdr'
    $files = array();
    if ($handle = opendir($filename)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
               $files[filemtime($file)] = $file;
            }
        }
        closedir($handle);

        // sort
        ksort($files);
        // find the last modification
        $reallyLastModified = end($files);

        foreach($files as $file) {
            $lastModified = date('F d Y, H:i:s',filemtime($file));
            if(strlen($file)-strpos($file,".swf")== 4){
               if ($file == $reallyLastModified) {
                 // do stuff for the real last modified file
               }
               echo "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
            }
        }
    }
</code>```

I have been trying to use this code to list and show files in a folder along with the date modified. i keep getting an error filemtime(): stat failed.

İ am trying listing them as arrays as an alternative using the below code

```<code>    <?php
    $folder = 'file:///C:/Users/xxx/Desktop/2017/cdr';
    $backups = array();
    foreach (scandir($folder) as $node) {
        $nodePath = $folder . DIRECTORY_SEPARATOR . $node;
        if (is_dir($nodePath)) continue;
        $backups[$nodePath] = filemtime($nodePath);

    }
    ksort($backups);
    print_r($backups);
</code>```

when i run this code i get the result below and i dont know what the numbers represent.

[file:///C:/Users/xxx/Desktop/2017/cdr\2017_0622_1500.raw] =>1498136278

  [file:///C:/Users/xxx/Desktop/2017/cdr\2017_0622_1600.cdr] =>1498136430

  [file:///C:/Users/xxx/Desktop/2017/cdr\2017_0622_1600.raw] =>1498139955

  [file:///C:/Users/xxx/Desktop/2017/cdr\2017_0622_1700.raw] =>1498142424

what am trying to achieve is to be able to display the files in the CDR along with their modified dates.

答:
```<code><?php

    function cmp($a, $b) {
        if (filemtime($a) == filemtime($b))
            return 0;

        return (filemtime($a) < filemtime($b)) ? -1 : 1;
    }

    $files = glob("/Users/xxx/Desktop/2017/cdr/*.cdr");
    usort($files, "cmp");

    foreach($files as $file)
        //echo $file . "<br />";
        echo "$file was last modified: " . date ("d-m-Y H:i:s.", filemtime($file))."\n";
?>
</code>```

This seemed to work. And the out put looked like this.

/2017/cdr/2017_0330_1300.cdr last modified: 30-03-2017 10:53:23.
  /2017/cdr/2017_0330_1500.cdr last modified: 30-03-2017 12:18:05.
  /2017/cdr/2017_0330_1600.cdr last modified:30-03-2017 13:55:21.

Body:
 <?php
    $filename = 'file:///C:/Users/xxx/Desktop/2017/cdr'
    $files = array();
    if ($handle = opendir($filename)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
               $files[filemtime($file)] = $file;
            }
        }
        closedir($handle);

        // sort
        ksort($files);
        // find the last modification
        $reallyLastModified = end($files);

        foreach($files as $file) {
            $lastModified = date('F d Y, H:i:s',filemtime($file));
            if(strlen($file)-strpos($file,".swf")== 4){
               if ($file == $reallyLastModified) {
                 // do stuff for the real last modified file
               }
               echo "
<input type=\"checkbox\" name=\"box[]\">	$file	$lastModified
";
            }
        }
    }

I have been trying to use this code to list and show files in a folder along with the date modified. i keep getting an error filemtime(): stat failed.

İ am trying listing them as arrays as an alternative using the below code

    <?php
    $folder = 'file:///C:/Users/xxx/Desktop/2017/cdr';
    $backups = array();
    foreach (scandir($folder) as $node) {
        $nodePath = $folder . DIRECTORY_SEPARATOR . $node;
        if (is_dir($nodePath)) continue;
        $backups[$nodePath] = filemtime($nodePath);

    }
    ksort($backups);
    print_r($backups);

when i run this code i get the result below and i dont know what the numbers represent.

[file:///C:/Users/xxx/Desktop/2017/cdr\2017_0622_1500.raw] =>1498136278

  [file:///C:/Users/xxx/Desktop/2017/cdr\2017_0622_1600.cdr] =>1498136430

  [file:///C:/Users/xxx/Desktop/2017/cdr\2017_0622_1600.raw] =>1498139955

  [file:///C:/Users/xxx/Desktop/2017/cdr\2017_0622_1700.raw] =>1498142424

what am trying to achieve is to be able to display the files in the CDR along with their modified dates.

Body:
<?php

    function cmp($a, $b) {
        if (filemtime($a) == filemtime($b))
            return 0;

        return (filemtime($a) < filemtime($b)) ? -1 : 1;
    }

    $files = glob("/Users/xxx/Desktop/2017/cdr/*.cdr");
    usort($files, "cmp");

    foreach($files as $file)
        //echo $file . "<br />";
        echo "$file was last modified: " . date ("d-m-Y H:i:s.", filemtime($file))."\n";
?>

This seemed to work. And the out put looked like this.

/2017/cdr/2017_0330_1300.cdr last modified: 30-03-2017 10:53:23.
  /2017/cdr/2017_0330_1500.cdr last modified: 30-03-2017 12:18:05.
  /2017/cdr/2017_0330_1600.cdr last modified:30-03-2017 13:55:21.


来源: stackexchange

问:
Stubbing Task returning method in async unit test
Let's say I have the following class and an interface it depends on:

```<code>public class MyController
{
    private IRepository _repository;
    public MyController(IRepository repository)
    {
        _repository = repository;
    }

    public async Task MethodUnderTest(int someId)
    {
        var o = await _repository.FindById(someId);
        // update o
        await _repository.Commit();
    }
}

public interface IRepository
{
    Task Commit();
}
</code>```

When I unit test this method I can do the following (using xUnit and Rhino Mocks):

```<code>[Fact]
public async Task MyTest()
{
    IRepository repositoryStub = MockRepository.GenerateStub<IRepository>();

    MyController controller = new MyController(repositoryStub);

    await controller.MethodUnderTest(1);
}
</code>```

This fails with a System.NullReferenceException : Object reference not set to an instance of an object.

With the following StackTrace:

```<code>UnitTest.MyController.<MethodUnderTest>d__0.MoveNext() in
\UnitTest\Class1.cs:line 35
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at \UnitTest\Class1.cs:line 20
</code>```

Is it correct that this error occurs because the Commit() returns null and the statemachine generated for the async/await calls MoveNext() on a null?

I can fix this by doing something like:

```<code>repositoryStub.Expect(r => r.Commit()).Return(Task.FromResult<bool>(true);
</code>```

But this feels a little strange.. I can use any T for FromResult<T> and the test will run. I can't find a FromResult method that will return a non-generic Task.

Does it matter what I use for T? Or should I fix this some other way?

答: If you are targeting .NET Framework 4.6 or later, you can now use .Returns(Task.CompletedTask) instead which is slightly shorter.

ContentLicense: CC BY-SA 3.0

Body:
Let's say I have the following class and an interface it depends on:

public class MyController
{
    private IRepository _repository;
    public MyController(IRepository repository)
    {
        _repository = repository;
    }

    public async Task MethodUnderTest(int someId)
    {
        var o = await _repository.FindById(someId);
        // update o
        await _repository.Commit();
    }
}

public interface IRepository
{
    Task Commit();
}

When I unit test this method I can do the following (using xUnit and Rhino Mocks):

[Fact]
public async Task MyTest()
{
    IRepository repositoryStub = MockRepository.GenerateStub<IRepository>();

    MyController controller = new MyController(repositoryStub);

    await controller.MethodUnderTest(1);
}

This fails with a System.NullReferenceException : Object reference not set to an instance of an object.

With the following StackTrace:

UnitTest.MyController.<MethodUnderTest>d__0.MoveNext() in
\UnitTest\Class1.cs:line 35
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at \UnitTest\Class1.cs:line 20

Is it correct that this error occurs because the Commit() returns null and the statemachine generated for the async/await calls MoveNext() on a null?

I can fix this by doing something like:

repositoryStub.Expect(r => r.Commit()).Return(Task.FromResult<bool>(true);

But this feels a little strange.. I can use any T for FromResult<T> and the test will run. I can't find a FromResult method that will return a non-generic Task.

Does it matter what I use for T? Or should I fix this some other way?


问:
Sort order by multiple fields Magento Custom collection
here is my table structure:

```<code>+----+---------------------+
| id | event_date          |
+----+---------------------+
| 12 | 2017-07-03 01:12:00 |
| 42 | 2017-07-04 18:13:00 |
| 52 | 2017-07-22 23:52:00 |
| 62 | 2017-10-20 23:55:00 |
+----+---------------------+
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255) | YES  |     | NULL    |                |
| status     | tinyint(2)   | NO   |     | 0       |                |
| content    | text         | NO   |     | NULL    |                |
| event_date | datetime     | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
</code>```

I want to get latest two records with date order as ascending.

Following is the code I am using :

```<code>$collection = Mage::getModel("blogpromo/blogpromo")->getCollection()
        ->addFieldToFilter('status', 0)
        ->setOrder('id', 'DESC')
        ->setOrder('event_date', 'ASC')
        ->setPageSize(2);
</code>```

It is giving records using ID. I want to sort by using both fields.
Although, when I tried to sort using only date, it worked fine.

答:
You could use addAttributeToSort()

```<code>$collection = Mage::getModel("blogpromo/blogpromo")->getCollection()
    ->addFieldToFilter('status', 0)
    ->addAttributeToSort('id', 'DESC')
    ->addAttributeToSort('event_date', 'ASC')
    ->setPageSize(2);
</code>```

Body:
here is my table structure:

+----+---------------------+
| id | event_date          |
+----+---------------------+
| 12 | 2017-07-03 01:12:00 |
| 42 | 2017-07-04 18:13:00 |
| 52 | 2017-07-22 23:52:00 |
| 62 | 2017-10-20 23:55:00 |
+----+---------------------+
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255) | YES  |     | NULL    |                |
| status     | tinyint(2)   | NO   |     | 0       |                |
| content    | text         | NO   |     | NULL    |                |
| event_date | datetime     | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

I want to get latest two records with date order as ascending.

Following is the code I am using :

$collection = Mage::getModel("blogpromo/blogpromo")->getCollection()
        ->addFieldToFilter('status', 0)
        ->setOrder('id', 'DESC')
        ->setOrder('event_date', 'ASC')
        ->setPageSize(2);

It is giving records using ID. I want to sort by using both fields.
Although, when I tried to sort using only date, it worked fine.

Body:
You could use addAttributeToSort()

$collection = Mage::getModel("blogpromo/blogpromo")->getCollection()
    ->addFieldToFilter('status', 0)
    ->addAttributeToSort('id', 'DESC')
    ->addAttributeToSort('event_date', 'ASC')
    ->setPageSize(2);


问:
posting an image url to an api using requests and returning a json using flask view
I am new to flask or web applications, so I have an API running on this a virtual machine using flask, which takes an image as an input and returns the features in a JSON file. Here is the code:

`

```<code>from flask import Flask

from flask import send_file

from flask import Flask, request, send_from_directory, redirect, render_template, url_for, jsonify

import socket

import requests

import json

ip = socket.gethostbyname((socket.getfqdn()))

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

@app.route('/get_image')
def get_image():
    return send_from_directory("C:/images", "22_1.bmp")

@app.route('/goto_api')
def goto_api():
    return redirect("http://127.0.0.1/features/", code=302 )

@app.route('/post')
def post():

url = 'http://127.0.0.1/features/'

payload = {'image': 'http://127.0.0.10:6485/get_image'}
#payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image\"\r\n\r\nhttp://127.0.0.10:6485/get_image\r\n-----011000010111000001101001--"
headers = {'content-type': "application/json"}
response = requests.post(url, data=payload, headers=headers)

return json.loads(str(response)) #return json.loads(response)

if __name__ == '__main__':
    app.debug = True
    app.run(port=6485, host=ip)
</code>```

`

when I use return json.loads(response),
it returns an error:
TypeError: the JSON object must be str, bytes or bytearray, not 'Response'

when I use return json.loads(str(response)) it gives the following error:

```<code>json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

I have tried many other things as well. Please help :)
Here is how output of that API looks like

```<code>    HTTP 201 Created
    Allow: GET, POST, OPTIONS
    Content-Type: application/json
    Vary: Accept

{
    "features": [
        0.0,
        0.0,
    4.321675777435303,
    1.5690128803253174,
    0.0,
    4.284165859222412,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    9.667842864990234,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    3.6376543045043945,
    3.540004253387451,
    0.0,
    0.0,
    0.0,
    0.0,
    .
    .
    .
            0.0,
    0.0,
    2.088599681854248,
    5.591969013214111,
    3.5350821018218994,
    0.0,
    0.0,
    13.648137092590332,
    0.0,
    3.5895862579345703,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.9650025963783264,
    0.0,
    0.9726126194000244,
    0.0,
    2.707155704498291,
    0.40982359647750854,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    5.446600437164307
]
</code>```

}

答:
The type of the response object is not a string, but requests.Response. If you wish to get the response body as JSON you need to use json() method as described in the documentation. For convenience and correct MIME type, you can combine that with Flask's JSON  helper flask.json.jsonify:

```<code>from flask import jsonify

...

@app.route('/post')
def post():
    ...
    return jsonify(response.json())
</code>```

Body:
I am new to flask or web applications, so I have an API running on this a virtual machine using flask, which takes an image as an input and returns the features in a JSON file. Here is the code:

`

from flask import Flask

from flask import send_file

from flask import Flask, request, send_from_directory, redirect, render_template, url_for, jsonify

import socket

import requests

import json

ip = socket.gethostbyname((socket.getfqdn()))

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

@app.route('/get_image')
def get_image():
    return send_from_directory("C:/images", "22_1.bmp")

@app.route('/goto_api')
def goto_api():
    return redirect("http://127.0.0.1/features/", code=302 )

@app.route('/post')
def post():

url = 'http://127.0.0.1/features/'

payload = {'image': 'http://127.0.0.10:6485/get_image'}
#payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"image\"\r\n\r\nhttp://127.0.0.10:6485/get_image\r\n-----011000010111000001101001--"
headers = {'content-type': "application/json"}
response = requests.post(url, data=payload, headers=headers)

return json.loads(str(response)) #return json.loads(response)

if __name__ == '__main__':
    app.debug = True
    app.run(port=6485, host=ip)

`

when I use return json.loads(response),
it returns an error:
TypeError: the JSON object must be str, bytes or bytearray, not 'Response'

when I use return json.loads(str(response)) it gives the following error:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I have tried many other things as well. Please help :)
Here is how output of that API looks like

    HTTP 201 Created
    Allow: GET, POST, OPTIONS
    Content-Type: application/json
    Vary: Accept

{
    "features": [
        0.0,
        0.0,
    4.321675777435303,
    1.5690128803253174,
    0.0,
    4.284165859222412,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    9.667842864990234,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    3.6376543045043945,
    3.540004253387451,
    0.0,
    0.0,
    0.0,
    0.0,
    .
    .
    .
            0.0,
    0.0,
    2.088599681854248,
    5.591969013214111,
    3.5350821018218994,
    0.0,
    0.0,
    13.648137092590332,
    0.0,
    3.5895862579345703,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.9650025963783264,
    0.0,
    0.9726126194000244,
    0.0,
    2.707155704498291,
    0.40982359647750854,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    0.0,
    5.446600437164307
]

}

Body:
The type of the response object is not a string, but requests.Response. If you wish to get the response body as JSON you need to use json() method as described in the documentation. For convenience and correct MIME type, you can combine that with Flask's JSON  helper flask.json.jsonify:

from flask import jsonify

...

@app.route('/post')
def post():
    ...
    return jsonify(response.json())


问:
How to filter array based on id in angularJS
i have multiple data for one id , i want filter my data like this

```<code>$scope.mpArray =[
{ Id: 1, Name: Madhu, Address: Upal },
{ Id: 1, Name: Chandu, Address: Upal },
{ Id: 2, Name: Srinu, Address: Kphb },
{ Id: 2, Name: Vijay, Address: kphb },
{ Id: 3, Name: Ajay, Address: Banglore },
{ Id: 3, Name: Narsi, Address: Banglore },
{ Id: 3, Name: Peter, Address: Banglore },
];
</code>```

i want to filter my array like this

```<code>var FilterArray = [
{ Id: 1,Madhu, Chandu},
{ Id: 2, Srinu, Vijay},
{ Id: 3, Ajay, Narsi, Peter},
];
</code>```

答:
At first you need to change your FilterArray to

```<code>[
  {
    "Id": 1,
    "Name": [
      "Madhu",
      "Chandu"
    ]
  },
  {
    "Id": 2,
    "Name": [
      "Srinu",
      "Vijay"
    ]
  },
  {
    "Id": 3,
    "Name": [
      "Ajay",
      "Narsi",
      "Peter"
    ]
  }
]
</code>```

Notice that name is an array. The FilterArray of your question

```<code>var FilterArray = [
{ Id: 1,Madhu, Chandu},
{ Id: 2, Srinu, Vijay},
{ Id: 3, Ajay, Narsi, Peter},
];
</code>```

Do not contain a valid JSON object inside the array so you need to change the structure to the one where add a new key Name in the JSON object of FilterArray as like the first structure above. Then the below code works great.

$(document).ready(function(){
var myArray =[
{ Id: 1, Name: "Madhu", Address: "Upal" },
{ Id: 1, Name: "Chandu", Address: "Upal" },
{ Id: 2, Name: "Srinu", Address: "Kphb" },
{ Id: 2, Name: "Vijay", Address: "kphb" },
{ Id: 3, Name: "Ajay", Address: "Banglore" },
{ Id: 3, Name: "Narsi", Address: "Banglore" },
{ Id: 3, Name: "Peter", Address: "Banglore" },
];
var FilterArray = [];
var matched;
  for(var i=0;i<myArray.length; i++){
     matched = false;
     var myArrayId = myArray[i].Id;
       for(var j=0; j<FilterArray.length; j++){
         var FilterArrayId = FilterArray[j].Id;
          if(myArrayId === FilterArrayId){
              matched = true;
              FilterArray[j].Name.push(myArray[i].Name);
              // no need to loop further
              break;
          }
       }
       if(!matched){
           var obj = {
              'Id' : myArrayId,
              'Name' : [myArray[i].Name],
           }
           FilterArray.push(obj);
       }
  }
 console.log(FilterArray);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
i have multiple data for one id , i want filter my data like this

$scope.mpArray =[
{ Id: 1, Name: Madhu, Address: Upal },
{ Id: 1, Name: Chandu, Address: Upal },
{ Id: 2, Name: Srinu, Address: Kphb },
{ Id: 2, Name: Vijay, Address: kphb },
{ Id: 3, Name: Ajay, Address: Banglore },
{ Id: 3, Name: Narsi, Address: Banglore },
{ Id: 3, Name: Peter, Address: Banglore },
];

i want to filter my array like this

var FilterArray = [
{ Id: 1,Madhu, Chandu},
{ Id: 2, Srinu, Vijay},
{ Id: 3, Ajay, Narsi, Peter},
];

Body:
At first you need to change your FilterArray to

[
  {
    "Id": 1,
    "Name": [
      "Madhu",
      "Chandu"
    ]
  },
  {
    "Id": 2,
    "Name": [
      "Srinu",
      "Vijay"
    ]
  },
  {
    "Id": 3,
    "Name": [
      "Ajay",
      "Narsi",
      "Peter"
    ]
  }
]

Notice that name is an array. The FilterArray of your question

var FilterArray = [
{ Id: 1,Madhu, Chandu},
{ Id: 2, Srinu, Vijay},
{ Id: 3, Ajay, Narsi, Peter},
];

Do not contain a valid JSON object inside the array so you need to change the structure to the one where add a new key Name in the JSON object of FilterArray as like the first structure above. Then the below code works great.

$(document).ready(function(){
var myArray =[
{ Id: 1, Name: "Madhu", Address: "Upal" },
{ Id: 1, Name: "Chandu", Address: "Upal" },
{ Id: 2, Name: "Srinu", Address: "Kphb" },
{ Id: 2, Name: "Vijay", Address: "kphb" },
{ Id: 3, Name: "Ajay", Address: "Banglore" },
{ Id: 3, Name: "Narsi", Address: "Banglore" },
{ Id: 3, Name: "Peter", Address: "Banglore" },
];
var FilterArray = [];
var matched;
  for(var i=0;i<myArray.length; i++){
     matched = false;
     var myArrayId = myArray[i].Id;
       for(var j=0; j<FilterArray.length; j++){
         var FilterArrayId = FilterArray[j].Id;
          if(myArrayId === FilterArrayId){
              matched = true;
              FilterArray[j].Name.push(myArray[i].Name);
              // no need to loop further
              break;
          }
       }
       if(!matched){
           var obj = {
              'Id' : myArrayId,
              'Name' : [myArray[i].Name],
           }
           FilterArray.push(obj);
       }
  }
 console.log(FilterArray);
});

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


问:
Difference between using continue and stream filter operation
Is there any advantage of using stream filter operation over iterator with continue operation?

Example for iteration:

```<code>for (ApiSite apiSite : sites) {
    Site mSite = Site.getSiteByName(apiSite.getName());
    if (mSite == null || deletedSitesToSkip.contains(mSite)) {
        LOGGER.info("Skipping site: {} as this has been deleted ", apiSite.getName());
        continue;
    }
    // operation
}
</code>```

stream with filter example:

```<code>sites.stream().filter(apiSite -> {
    Site mSite = Site.getSiteByName(apiSite.getName());
    return (mSite != null && !deletedSitesToSkip.contains(mSite));
}).map(//some operation);
</code>```

答:
The stream version has better semantics: you clearly operate on a set of data, filter it by a condition, and apply an operation on the matching elements. This adds to the readability, and allows to easily extend the processing by elementar building blocks (filter, map) without the risk of breaking much (maintainability).

Moreso, the streams operations (for filtering, mapping, ...) can be designed as reusable building blocks (DRY principle), which can be individualy tested, thus gaining reliability.

All in all, those are non-functional benefits (the functionality of both variants is the same), adding to the quality of the code.

Besides, continue is worth avoiding completely, as it quickly leads to awkward code when nesting loop blocks, making it hard to read and maintain.

Body:
Is there any advantage of using stream filter operation over iterator with continue operation?

Example for iteration:

for (ApiSite apiSite : sites) {
    Site mSite = Site.getSiteByName(apiSite.getName());
    if (mSite == null || deletedSitesToSkip.contains(mSite)) {
        LOGGER.info("Skipping site: {} as this has been deleted ", apiSite.getName());
        continue;
    }
    // operation
}

stream with filter example:

sites.stream().filter(apiSite -> {
    Site mSite = Site.getSiteByName(apiSite.getName());
    return (mSite != null && !deletedSitesToSkip.contains(mSite));
}).map(//some operation);


问:
Translating default form validation error messages in Symfony 1.4
I want to translate the default form validation messages in symfony, like
 'required' => 'my own text'
Is there a way to do this? I searched in google, but haven't find anything useful. The XLIFF files are not working for me. :(

OR

Is there a way, to set default validation messages for like 'required' fields?

答:
I don't know if you can manipulate the default error messages globally but you can access the i18n Object where you want with these lines of code:

```<code>$i18n = sfContext::getInstance()->getI18N();
$i18n->__('your message');
</code>```

Maybe it helps you.

Body:
I don't know if you can manipulate the default error messages globally but you can access the i18n Object where you want with these lines of code:

$i18n = sfContext::getInstance()->getI18N();
$i18n->__('your message');

Maybe it helps you.

ContentLicense: CC BY-SA 2.5


问:
How to recover or reinstall .vim_runtime directory and contents
I downloaded this vim config but decided later I wanted to work using vanilla vim (because i'm still not used to it).

So I followed the instructions at the bottom of the README:

How to uninstall

Just do following:

Remove ~/.vim_runtime

Remove any lines that reference .vim_runtime in
  your ~/.vimrc

I deleted the hidden vim_runtime directory located in :home/user/ on Ubuntu 16.04, using

```<code>rm -rf ~/.vim_runtime/
</code>```

then realized this was a mistake. I now can't open vim without getting:

Error detected while processing /home/user/.vimrc:

line 3:

E484: Cannot open file /home/user/.vim_runtime/vimrcs/basic.vim

line 4:

E484: Cannot open file /home/user/.vim_runtime/vimrcs/filetypes.vim

line 5:

E484: Cannot open file /home/user/.vim_runtime/vimrcs/plugins_config.vim

line 6:

E484: Cannot open file /home/user/.vim_runtime/vimrcs/extended.vim

Press ENTER or type command to continue

I don't know what to do from here, It would be great if I could just purge it all and have vim as it was when you first install the OS, I've tried:

```<code>sudo apt-get purge vim && sudo apt-get install vim
</code>```

but still get the same error detection when opening vim after the command has completed.

答:
If you had no personal configuration other than that Vim distribution, just rm /home/user/.vimrc and start anew. You can also remove /home/user/.vim/ if it exists. That gives you a clean slate. There's no need to reinstall Vim; that distribution presumably was just user configuration (i.e. you didn't need sudo to install it), whereas Vim is installed system-wide (via apt). If there's something inside .vimrc that you want to save (and you have no other editor installed), you can launch Vim with vim -N -u NONE.

soapbox

Vim "distributions" like spf-13 and Janus lure you with a quick install and out-of-the-box settings, but you pay the price with increased complexity (you need to understand both Vim's runtime loading scheme and the arbitrary conventions of the distribution) and inflexibility (the distribution may make some things easier, but other things very difficult). Vim is incredibly customizable, using someone else's customization makes no sense.

new config

I would base your personal configuration on the example that ships with Vim. You can install it like this:

```<code>$ vim
:edit $VIMRUNTIME/vimrc_example
:saveas $MYVIMRC
:quit
</code>```

Also see :help defaults.vim.

Body:
I downloaded this vim config but decided later I wanted to work using vanilla vim (because i'm still not used to it).

So I followed the instructions at the bottom of the README:

How to uninstall

Just do following:

Remove ~/.vim_runtime

Remove any lines that reference .vim_runtime in
  your ~/.vimrc

I deleted the hidden vim_runtime directory located in :home/user/ on Ubuntu 16.04, using

rm -rf ~/.vim_runtime/

then realized this was a mistake. I now can't open vim without getting:

Error detected while processing /home/user/.vimrc:

line 3:

E484: Cannot open file /home/user/.vim_runtime/vimrcs/basic.vim

line 4:

E484: Cannot open file /home/user/.vim_runtime/vimrcs/filetypes.vim

line 5:

E484: Cannot open file /home/user/.vim_runtime/vimrcs/plugins_config.vim

line 6:

E484: Cannot open file /home/user/.vim_runtime/vimrcs/extended.vim

Press ENTER or type command to continue

I don't know what to do from here, It would be great if I could just purge it all and have vim as it was when you first install the OS, I've tried:

sudo apt-get purge vim && sudo apt-get install vim

but still get the same error detection when opening vim after the command has completed.

Body:
If you had no personal configuration other than that Vim distribution, just rm /home/user/.vimrc and start anew. You can also remove /home/user/.vim/ if it exists. That gives you a clean slate. There's no need to reinstall Vim; that distribution presumably was just user configuration (i.e. you didn't need sudo to install it), whereas Vim is installed system-wide (via apt). If there's something inside .vimrc that you want to save (and you have no other editor installed), you can launch Vim with vim -N -u NONE.

soapbox

Vim "distributions" like spf-13 and Janus lure you with a quick install and out-of-the-box settings, but you pay the price with increased complexity (you need to understand both Vim's runtime loading scheme and the arbitrary conventions of the distribution) and inflexibility (the distribution may make some things easier, but other things very difficult). Vim is incredibly customizable, using someone else's customization makes no sense.

new config

I would base your personal configuration on the example that ships with Vim. You can install it like this:

$ vim
:edit $VIMRUNTIME/vimrc_example
:saveas $MYVIMRC
:quit

Also see :help defaults.vim.


问:
google maps shows gray overlays on update
Good Morning,

I got some nasty trouble with google map api.

I know there are some other thread with a similar problem. But they did not really help to understand my problem.

I am working with yeoman in a angular.js 1.5 gulp project with angular-materials and need a map implementation where the marker changes by router.

For example: I got links like this:
http://myurl.de/#/expertise/1
http://myurl.de/#/expertise/2

If I use them in a new window, my map is well. But if I change the number at the end, my map got those grey areas (looks like the map size is not set to 100% of my DIV element)

Implementation off my HTML Direktive

```<code><div flex id="GoogleMap" class="google-map" lat="{{expertise.item.map.lat}}" long="{{expertise.item.map.long}}" zoom="{{expertise.item.map.zoom}}"></div>
</code>```

Implementation of my map service

```<code>(function() {
    'use strict';

    angular
        .module('espanioYoNg')
        .service('googleMapService', googleMapService);

    /** @ngInject */
    function googleMapService($window, $q) {
        var deferred = $q.defer();

        // Load Google map API script
        function loadScript() {
            // Use global document since Angular's $document is weak
            var script = document.createElement('script');
            script.src = '//maps.googleapis.com/maps/api/js?key=AIzaSyD42GBUhIFSTDEwcTSsM_xIh07B2RATEB4&sensor=false&language=en&callback=initMap';
            //script.src = '//maps.googleapis.com/maps/api/js?sensor=false&language=en&callback=initMap';

            document.body.appendChild(script);
        }

        // Script loaded callback, send resolve
        $window.initMap = function () {
            deferred.resolve();
        }

        loadScript();

        return deferred.promise;
    }

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

My map directive and controller

```<code>(function() {
    'use strict';

    angular
        .module('espanioYoNg')
        .directive('googleMap', ['googleMapService', googleMap]);

    /** @ngInject */
    function googleMap(googleMapService) {
        return {
            restrict: 'C', // restrict by class name
            scope: {
                mapId: '@id',   // map ID
                lat: '@',       // latitude
                long: '@',      // longitude
                zoom: '@'       // zoom on card
            },
            link: function( $scope, elem ) {

                // Check if latitude and longitude are specified
                if ( angular.isDefined($scope.lat) && angular.isDefined($scope.long) && angular.isDefined($scope.zoom) ) {

                    // Initialize the map
                    $scope.initialize = function() {
                        $scope.location = new google.maps.LatLng($scope.lat, $scope.long);

                        $scope.mapOptions = {
                            zoom: 14, //$scope.zoom,
                            center: $scope.location
                        };

                        $scope.map = new google.maps.Map(document.getElementById($scope.mapId), $scope.mapOptions);

                        new google.maps.Marker({
                            position: $scope.location,
                            map: $scope.map,
                        });
                    }

                    // Loads google map script
                    googleMapService.then(function () {
                        // Promised resolved
                        $scope.initialize();

                    }, function () {
                        // Promise rejected
                    });
                }
            }
        };
    }

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

I am searching for the problem over the whole day. Seems like CSS but I am not realy sure.

If necessary, you can have a look at it, here:
http://test.espanio.de/#/expertise/1
http://test.espanio.de/#/expertise/2

user: espanio

pass: oinapse

credentials are temporary to prevent search engines crawling the page before it is finished.

Afer Refreshing/Reloading (F5 on windows) the map is as it should be.

And I am sorry for the lines of code, but I didn't get the plunker running with my whole project.

Thanks for any help,....
n00n from germany...

答:
I think the issue is related to the size of the div when you initialize a map. When I open your page in the new window and put breakpoint on $scope.initialize(); I can see the following

Now if I change the URL in the browser I can see the following

Note the change in the div width during the second initialization. I believe you should trigger a resize event on the map when the map finished initialization and div size changed. Try the following

```<code>googleMapService.then(function () {
    // Promised resolved
    $scope.initialize();
    setTimeout(function(){
        google.maps.event.trigger($scope.map, 'resize');
    }, 1000);
}, function () {
    // Promise rejected
});
</code>```

Body:
Good Morning,

I got some nasty trouble with google map api.

I know there are some other thread with a similar problem. But they did not really help to understand my problem.

I am working with yeoman in a angular.js 1.5 gulp project with angular-materials and need a map implementation where the marker changes by router.

For example: I got links like this:
http://myurl.de/#/expertise/1
http://myurl.de/#/expertise/2

If I use them in a new window, my map is well. But if I change the number at the end, my map got those grey areas (looks like the map size is not set to 100% of my DIV element)

Implementation off my HTML Direktive

Implementation of my map service

(function() {
    'use strict';

    angular
        .module('espanioYoNg')
        .service('googleMapService', googleMapService);

    /** @ngInject */
    function googleMapService($window, $q) {
        var deferred = $q.defer();

        // Load Google map API script
        function loadScript() {
            // Use global document since Angular's $document is weak
            var script = document.createElement('script');
            script.src = '//maps.googleapis.com/maps/api/js?key=AIzaSyD42GBUhIFSTDEwcTSsM_xIh07B2RATEB4&sensor=false&language=en&callback=initMap';
            //script.src = '//maps.googleapis.com/maps/api/js?sensor=false&language=en&callback=initMap';

            document.body.appendChild(script);
        }

        // Script loaded callback, send resolve
        $window.initMap = function () {
            deferred.resolve();
        }

        loadScript();

        return deferred.promise;
    }

})();

My map directive and controller

(function() {
    'use strict';

    angular
        .module('espanioYoNg')
        .directive('googleMap', ['googleMapService', googleMap]);

    /** @ngInject */
    function googleMap(googleMapService) {
        return {
            restrict: 'C', // restrict by class name
            scope: {
                mapId: '@id',   // map ID
                lat: '@',       // latitude
                long: '@',      // longitude
                zoom: '@'       // zoom on card
            },
            link: function( $scope, elem ) {

                // Check if latitude and longitude are specified
                if ( angular.isDefined($scope.lat) && angular.isDefined($scope.long) && angular.isDefined($scope.zoom) ) {

                    // Initialize the map
                    $scope.initialize = function() {
                        $scope.location = new google.maps.LatLng($scope.lat, $scope.long);

                        $scope.mapOptions = {
                            zoom: 14, //$scope.zoom,
                            center: $scope.location
                        };

                        $scope.map = new google.maps.Map(document.getElementById($scope.mapId), $scope.mapOptions);

                        new google.maps.Marker({
                            position: $scope.location,
                            map: $scope.map,
                        });
                    }

                    // Loads google map script
                    googleMapService.then(function () {
                        // Promised resolved
                        $scope.initialize();

                    }, function () {
                        // Promise rejected
                    });
                }
            }
        };
    }

})();

I am searching for the problem over the whole day. Seems like CSS but I am not realy sure.

If necessary, you can have a look at it, here:
http://test.espanio.de/#/expertise/1
http://test.espanio.de/#/expertise/2

user: espanio

pass: oinapse

credentials are temporary to prevent search engines crawling the page before it is finished.

Afer Refreshing/Reloading (F5 on windows) the map is as it should be.

And I am sorry for the lines of code, but I didn't get the plunker running with my whole project.

Thanks for any help,....
n00n from germany...

Body:
I think the issue is related to the size of the div when you initialize a map. When I open your page in the new window and put breakpoint on $scope.initialize(); I can see the following

Now if I change the URL in the browser I can see the following

Note the change in the div width during the second initialization. I believe you should trigger a resize event on the map when the map finished initialization and div size changed. Try the following

googleMapService.then(function () {
    // Promised resolved
    $scope.initialize();
    setTimeout(function(){
        google.maps.event.trigger($scope.map, 'resize');
    }, 1000);
}, function () {
    // Promise rejected
});


问:
How to add a new item using Python Etsy HTTP API methods?
I am trying to use Etsy API to add a new listing on my store. In the documents section it says (below section how to do it). First fyi I  have never used HTTP Method before so I am not sure how to setup the code so that it adds a new item.

(Link to the Etsy API page https://www.etsy.com/developers/documentation/reference/listing).

```<code>Method Name createListing
Synopsis    Creates a new Listing.
HTTP Method POST
URI /listings
Parameters
Name    Required    Default Type
quantity    Y       int
title   Y       string
description Y       text
price   Y       float
materials   N       array(string)
shipping_template_id    N       int
shop_section_id N       int
image_ids   N       array(int)
is_customizable N       boolean
non_taxable N       boolean
image   N       image
state   N   active  enum(active, draft)
processing_min  N       int
processing_max  N       int
category_id N       int
taxonomy_id N       int
tags    N       array(string)
who_made    Y       enum(i_did, collective, someone_else)
is_supply   Y       boolean
when_made   Y       enum(made_to_order, 2010_2017, 2000_2009, 1998_1999, before_1998, 1990_1997, 1980s, 1970s, 1960s, 1950s, 1940s, 1930s, 1920s, 1910s, 1900s, 1800s, 1700s, before_1700)
recipient   N       enum(men, women, unisex_adults, teen_boys, teen_girls, teens, boys, girls, children, baby_boys, baby_girls, babies, birds, cats, dogs, pets, not_specified)
occasion    N       enum(anniversary, baptism, bar_or_bat_mitzvah, birthday, canada_day, chinese_new_year, cinco_de_mayo, confirmation, christmas, day_of_the_dead, easter, eid, engagement, fathers_day, get_well, graduation, halloween, hanukkah, housewarming, kwanzaa, prom, july_4th, mothers_day, new_baby, new_years, quinceanera, retirement, st_patricks_day, sweet_16, sympathy, thanksgiving, valentines, wedding)
style   N       array(string)
Requires OAuth  Y
Permission Scope    listings_w
Notes
A shipping_template_id is required when creating a listing.
All listings created on www.etsy.com must be actual items for sale. Please see our guidelines for testingwith live listings.
Creating a listing creates a single inventory products with the supplied price and quantity. Use updateInventory to add more products.
</code>```

The code I have right know looks like this

```<code>import urllib
import requests
url = 'https://openapi.etsy.com/v2/listings/active?api_key={YOUR KEY HERE)' # I put my API key here
r = requests.get(url)

payload = {'quantity': '1', 'title': 'testdfsdfdfs0','description': 'dfsdfsdfsdfdsf','price': '2.55','who_made': 'i_did','is_supply': '0','when_made': '2010_2017'}
rrr = requests.post(url,payload)
print rrr # I get an error 404
</code>```

How can I add an item for sale on Etsy through Python HTTP method?

Update

```<code>from requests_oauthlib import OAuth1Session
import requests
from requests_oauthlib import OAuth1
import json

tempory_token_url = []
oauth_response_bucket = []
client_key = '.......'
client_secret = '......'

oauth = OAuth1Session(client_key, client_secret=client_secret)

request_token_url = 'https://openapi.etsy.com/v2/oauth/request_token?scope=email_r%20listings_r'
fetch_response = oauth.fetch_request_token(request_token_url)
resource_owner_key = fetch_response.get('oauth_token') # Have it
resource_owner_secret = fetch_response.get('oauth_token_secret')
oauth_url_temp = tempory_token_url[0]['login_urI']
base_authorization_url = oauth_url_temp
authorization_url = oauth.authorization_url(base_authorization_url)
redirect_response = raw_input('Paste the full redirect URL here: ')
oauth_response = oauth.parse_authorization_response(redirect_response)
verifier = oauth_response.get('oauth_verifier')
access_token_url = redeirect_response
oauth = OAuth1Session(client_key=client_secret=client_secret,resource_owner_key=resource_owner_key,resource_owner_secret=resource_owner_secret,verifier=verifier)

oauth_tokens = oauth.fetch_access_token(access_token_url)
resource_owner_key = oauth_tokens.get('oauth_token')
resource_owner_secret = oauth_tokens.get('oauth_token_secret')
</code>```

Any ideas how to make this work? There is very little info regarding Etsy API and most of the stuff is in PHP which I have no clue how to work.

Image Uploading API

Everything looks the same like above this time I just changed the payload but I am getting a 403 Error. I am not sure what is causing it. My best guess would be something with oauth1.0 i think on their website it says you need oauth 1.1.

Here is how I set it up but I am getting 403 error:

```<code>url = 'https://openapi.etsy.com/v2/listings'
payload = {'listing_id':'342434342', 'image': ("test1.jpg", open('C:\\Users\\abc\\test1.jpg'),'image/jpeg'),'type':'image/jpeg'}
result = etsy.put(url, params=payload)
print result
</code>```

答:
Question: I am trying to upload a picture ... getting a 403 error

Your url Endpoint and  payload isn't correct.

```<code>url = 'https://openapi.etsy.com/v2/listings'
payload = {'listing_id':'342434342', 'image': ("test1.jpg", open('C:\\Users\\abc\\test1.jpg'),'image/jpeg'),'type':'image/jpeg'}
</code>```

Steps to do a etsy Request(uploadListingImage):

Read the Reference for your Method Name

```<code>Method Name   uploadListingImage
HTTP Method   POST
URI           /listings/:listing_id/images
Parameters  Name            Required    Default Type
        listing_id          Y                   int
        listing_image_id    N                   int
        image               N                   imagefile
        ...
Requires OAuth  Y
</code>```

Respect Supported Sizes Working with Images

Note: For me, it's unclear what the image Parameter is for.

  And as it's NOT required makes no sense.

  I assume its a Placeholder for the Parameter at Point 4 below: {'image':...

Build the URI

```<code>uri = 'https://openapi.etsy.com/v2/listings/342434342/images'
</code>```

Create the Params Dict according to the above Reference

I recommend to use a listing_image_id, as this seems the only way to delete a Image afterwards.

```<code>params = {'listing_id':'342434342', 'listing_image_id': 1}
</code>```

Create Multipart-Encoded File Dict

Image uploads can be performed using a POST request with the Content-Type: multipart/form-dataheader, following RFC1867

  # PHP example from Reference:

  # $params = array('@image' => '@'.$source_file.';type='.$mimetype);

```<code>files = {'image': ("test1.jpg", open('C:\\Users\\abc\\test1.jpg', 'rb'), 'image/jpeg')}
</code>```

Do the Request, according the Reference, you have to use OAuth and POST

```<code>result = etsy.post(uri, params=params, files=files)
</code>```

Please Comment if this is working for you or why not.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use Etsy API to add a new listing on my store. In the documents section it says (below section how to do it). First fyi I  have never used HTTP Method before so I am not sure how to setup the code so that it adds a new item.

(Link to the Etsy API page https://www.etsy.com/developers/documentation/reference/listing).

Method Name createListing
Synopsis    Creates a new Listing.
HTTP Method POST
URI /listings
Parameters
Name    Required    Default Type
quantity    Y       int
title   Y       string
description Y       text
price   Y       float
materials   N       array(string)
shipping_template_id    N       int
shop_section_id N       int
image_ids   N       array(int)
is_customizable N       boolean
non_taxable N       boolean
image   N       image
state   N   active  enum(active, draft)
processing_min  N       int
processing_max  N       int
category_id N       int
taxonomy_id N       int
tags    N       array(string)
who_made    Y       enum(i_did, collective, someone_else)
is_supply   Y       boolean
when_made   Y       enum(made_to_order, 2010_2017, 2000_2009, 1998_1999, before_1998, 1990_1997, 1980s, 1970s, 1960s, 1950s, 1940s, 1930s, 1920s, 1910s, 1900s, 1800s, 1700s, before_1700)
recipient   N       enum(men, women, unisex_adults, teen_boys, teen_girls, teens, boys, girls, children, baby_boys, baby_girls, babies, birds, cats, dogs, pets, not_specified)
occasion    N       enum(anniversary, baptism, bar_or_bat_mitzvah, birthday, canada_day, chinese_new_year, cinco_de_mayo, confirmation, christmas, day_of_the_dead, easter, eid, engagement, fathers_day, get_well, graduation, halloween, hanukkah, housewarming, kwanzaa, prom, july_4th, mothers_day, new_baby, new_years, quinceanera, retirement, st_patricks_day, sweet_16, sympathy, thanksgiving, valentines, wedding)
style   N       array(string)
Requires OAuth  Y
Permission Scope    listings_w
Notes
A shipping_template_id is required when creating a listing.
All listings created on www.etsy.com must be actual items for sale. Please see our guidelines for testingwith live listings.
Creating a listing creates a single inventory products with the supplied price and quantity. Use updateInventory to add more products.

The code I have right know looks like this

import urllib
import requests
url = 'https://openapi.etsy.com/v2/listings/active?api_key={YOUR KEY HERE)' # I put my API key here
r = requests.get(url)

payload = {'quantity': '1', 'title': 'testdfsdfdfs0','description': 'dfsdfsdfsdfdsf','price': '2.55','who_made': 'i_did','is_supply': '0','when_made': '2010_2017'}
rrr = requests.post(url,payload)
print rrr # I get an error 404

How can I add an item for sale on Etsy through Python HTTP method?

Update

from requests_oauthlib import OAuth1Session
import requests
from requests_oauthlib import OAuth1
import json

tempory_token_url = []
oauth_response_bucket = []
client_key = '.......'
client_secret = '......'

oauth = OAuth1Session(client_key, client_secret=client_secret)

request_token_url = 'https://openapi.etsy.com/v2/oauth/request_token?scope=email_r%20listings_r'
fetch_response = oauth.fetch_request_token(request_token_url)
resource_owner_key = fetch_response.get('oauth_token') # Have it
resource_owner_secret = fetch_response.get('oauth_token_secret')
oauth_url_temp = tempory_token_url[0]['login_urI']
base_authorization_url = oauth_url_temp
authorization_url = oauth.authorization_url(base_authorization_url)
redirect_response = raw_input('Paste the full redirect URL here: ')
oauth_response = oauth.parse_authorization_response(redirect_response)
verifier = oauth_response.get('oauth_verifier')
access_token_url = redeirect_response
oauth = OAuth1Session(client_key=client_secret=client_secret,resource_owner_key=resource_owner_key,resource_owner_secret=resource_owner_secret,verifier=verifier)

oauth_tokens = oauth.fetch_access_token(access_token_url)
resource_owner_key = oauth_tokens.get('oauth_token')
resource_owner_secret = oauth_tokens.get('oauth_token_secret')

Any ideas how to make this work? There is very little info regarding Etsy API and most of the stuff is in PHP which I have no clue how to work.

Image Uploading API

Everything looks the same like above this time I just changed the payload but I am getting a 403 Error. I am not sure what is causing it. My best guess would be something with oauth1.0 i think on their website it says you need oauth 1.1.

Here is how I set it up but I am getting 403 error:

url = 'https://openapi.etsy.com/v2/listings'
payload = {'listing_id':'342434342', 'image': ("test1.jpg", open('C:\\Users\\abc\\test1.jpg'),'image/jpeg'),'type':'image/jpeg'}
result = etsy.put(url, params=payload)
print result

Body:
Question: I am trying to upload a picture ... getting a 403 error

Your url Endpoint and  payload isn't correct.

url = 'https://openapi.etsy.com/v2/listings'
payload = {'listing_id':'342434342', 'image': ("test1.jpg", open('C:\\Users\\abc\\test1.jpg'),'image/jpeg'),'type':'image/jpeg'}

Steps to do a etsy Request(uploadListingImage):

Read the Reference for your Method Name

Method Name   uploadListingImage
HTTP Method   POST
URI           /listings/:listing_id/images
Parameters  Name            Required    Default Type
        listing_id          Y                   int
        listing_image_id    N                   int
        image               N                   imagefile
        ...
Requires OAuth  Y

Respect Supported Sizes Working with Images

Note: For me, it's unclear what the image Parameter is for.

  And as it's NOT required makes no sense.

  I assume its a Placeholder for the Parameter at Point 4 below: {'image':...

Build the URI

uri = 'https://openapi.etsy.com/v2/listings/342434342/images'

Create the Params Dict according to the above Reference

I recommend to use a listing_image_id, as this seems the only way to delete a Image afterwards.

params = {'listing_id':'342434342', 'listing_image_id': 1}

Create Multipart-Encoded File Dict

Image uploads can be performed using a POST request with the Content-Type: multipart/form-dataheader, following RFC1867

  # PHP example from Reference:

  # $params = array('@image' => '@'.$source_file.';type='.$mimetype);

files = {'image': ("test1.jpg", open('C:\\Users\\abc\\test1.jpg', 'rb'), 'image/jpeg')}

Do the Request, according the Reference, you have to use OAuth and POST

result = etsy.post(uri, params=params, files=files)

Please Comment if this is working for you or why not.


问:
SWCrypt public key VS PKCS8PEM Key
I want to user SWCrypt for RSA encryption and decryption. i should send my public key base64 decoded to server. but when i try send generated public key base64 i can't get this error in server side:

```<code>let (privateKey, publicKey) = try CC.RSA.generateKeyPair(2048)
let publicKeyBase64 = publicKey.base64EncodedString()
</code>```

error: java.security.InvalidKeyException: IOException: algid parse error, not a sequence

but when send PEMPublicKey getting successfully response.

```<code>let publicKeyPEM = SwKeyConvert.PublicKey.derToPKCS8PEM(publicKey)
</code>```

what is difference between  publicKeyBase64 and publicKeyPEM?

sample of generated key:

```<code>MIIBCgKCAQEAuWwCZpNXJtT2spBsDwrQaTFGVAjicM341Qzg+1whtlj9J60c/7HYe6AcGHa8Dinkiuk7Whs1Wpa34aa223WQsa+kFSNwkC6oDUXhewan3VEsv1uedzHc8JPlTXnItJsP8cIETFgHpdKWk462hU09mVCTtQTix0BEb8snS96wERvKq957OeaGtFasfT/bQfY0mbDu6eEMqswmfX8j84kuTfwWtqt6mLMTJaDwnsGc5WY1zkau68IQ/CBiiLpZ5hSVMs2pPj3Ao0+wNhR5MlMgdcwrU62SHWcMJ5cYssFgWZyZSvO3n/yW43fE5a1i+9Tm2trveGIdMR4d/MoA79/8IQIDAQAB
</code>```

sample of generated PEM key :

```<code>MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuWwCZpNXJtT2spBsDwrQaTFGVAjicM341Qzg+1whtlj9J60c/7HYe6AcGHa8Dinkiuk7Whs1Wpa34aa223WQsa+kFSNwkC6oDUXhewan3VEsv1uedzHc8JPlTXnItJsP8cIETFgHpdKWk462hU09mVCTtQTix0BEb8snS96wERvKq957OeaGtFasfT/bQfY0mbDu6eEMqswmfX8j84kuTfwWtqt6mLMTJaDwnsGc5WY1zkau68IQ/CBiiLpZ5hSVMs2pPj3Ao0+wNhR5MlMgdcwrU62SHWcMJ5cYssFgWZyZSvO3n/yW43fE5a1i+9Tm2trveGIdMR4d/MoA79/8IQIDAQAB
</code>```

how can send generated public key simple of PEM key format?

thanks.

答:
X509 is a standard for Public Key Infraestructure, not a encoding format. You can encode a X509 public key in PEM (base64), DER(binary) or XML. Also the binary data of the public key can be represented in PCKS#1 or X509 SubjectPublicKeyInfo.

In my knowledge PKCS#8 is a standard for private keys. See PKCS #8: Private-Key Information Syntax Standard. So I guess  SWCrypt is really using X509 SubjectPublicKeyInfo (Maybe i have not read some RFCs), which is what your server is waiting for.

```<code>let publicKeyPEM = SwKeyConvert.PublicKey.derToPKCS8PEM(publicKey)
</code>```

SubjectPublicKeyInfo encapsulates the public key into a ASN.1 structure adding a header. If you encode the raw data of the public key (DER) using  publicKey.base64EncodedString, that header is not added and your server does not know how to manage it.

Title: SWCrypt public key VS PKCS8PEM Key

Body:
I want to user SWCrypt for RSA encryption and decryption. i should send my public key base64 decoded to server. but when i try send generated public key base64 i can't get this error in server side:

let (privateKey, publicKey) = try CC.RSA.generateKeyPair(2048)
let publicKeyBase64 = publicKey.base64EncodedString()

error: java.security.InvalidKeyException: IOException: algid parse error, not a sequence

but when send PEMPublicKey getting successfully response.

let publicKeyPEM = SwKeyConvert.PublicKey.derToPKCS8PEM(publicKey)

what is difference between  publicKeyBase64 and publicKeyPEM?

sample of generated key:

MIIBCgKCAQEAuWwCZpNXJtT2spBsDwrQaTFGVAjicM341Qzg+1whtlj9J60c/7HYe6AcGHa8Dinkiuk7Whs1Wpa34aa223WQsa+kFSNwkC6oDUXhewan3VEsv1uedzHc8JPlTXnItJsP8cIETFgHpdKWk462hU09mVCTtQTix0BEb8snS96wERvKq957OeaGtFasfT/bQfY0mbDu6eEMqswmfX8j84kuTfwWtqt6mLMTJaDwnsGc5WY1zkau68IQ/CBiiLpZ5hSVMs2pPj3Ao0+wNhR5MlMgdcwrU62SHWcMJ5cYssFgWZyZSvO3n/yW43fE5a1i+9Tm2trveGIdMR4d/MoA79/8IQIDAQAB

sample of generated PEM key :

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuWwCZpNXJtT2spBsDwrQaTFGVAjicM341Qzg+1whtlj9J60c/7HYe6AcGHa8Dinkiuk7Whs1Wpa34aa223WQsa+kFSNwkC6oDUXhewan3VEsv1uedzHc8JPlTXnItJsP8cIETFgHpdKWk462hU09mVCTtQTix0BEb8snS96wERvKq957OeaGtFasfT/bQfY0mbDu6eEMqswmfX8j84kuTfwWtqt6mLMTJaDwnsGc5WY1zkau68IQ/CBiiLpZ5hSVMs2pPj3Ao0+wNhR5MlMgdcwrU62SHWcMJ5cYssFgWZyZSvO3n/yW43fE5a1i+9Tm2trveGIdMR4d/MoA79/8IQIDAQAB

how can send generated public key simple of PEM key format?

thanks.

Body:
X509 is a standard for Public Key Infraestructure, not a encoding format. You can encode a X509 public key in PEM (base64), DER(binary) or XML. Also the binary data of the public key can be represented in PCKS#1 or X509 SubjectPublicKeyInfo.

In my knowledge PKCS#8 is a standard for private keys. See PKCS #8: Private-Key Information Syntax Standard. So I guess  SWCrypt is really using X509 SubjectPublicKeyInfo (Maybe i have not read some RFCs), which is what your server is waiting for.

let publicKeyPEM = SwKeyConvert.PublicKey.derToPKCS8PEM(publicKey)

SubjectPublicKeyInfo encapsulates the public key into a ASN.1 structure adding a header. If you encode the raw data of the public key (DER) using  publicKey.base64EncodedString, that header is not added and your server does not know how to manage it.


答:
try this

var mpArray =[
{ Id: 1, Name: 'Madhu', Address: 'Upal' },
{ Id: 1, Name: 'Chandu', Address: 'Upal' },
{ Id: 2, Name: 'Srinu', Address: 'Kphb' },
{ Id: 2, Name: 'Vijay', Address: 'kphb' },
{ Id: 3, Name: 'Ajay', Address: 'Banglore' },
{ Id: 3, Name: 'Narsi', Address: 'Banglore' },
{ Id: 3, Name: 'Peter', Address: 'Banglore' },
];

var filterObject = {};

mpArray.forEach(function (item) {
    if (!filterObject[item.Id]) {
        filterObject[item.Id] = [];
    }

    filterObject[item.Id].push(item.Name);
});

console.log(filterObject);```

Title: How to filter array based on id in angularJS


问:
Has reCaptcha been cracked / hacked / OCR'd / defeated / broken?
Have any programming methods have been used to defeat reCAPTCHA?

I'm interested in seeing evidence and potentially demonstrations that reCAPTCHA in particular has been made obsolete by completely automated, humanless methods.

To clarify, not looking for reCAPTCHA-cheating solutions that involve humans in any way, whether teams tasked with filling out CAPCHAs, porn-seekers, or Mechanical Turk.

I'm also not looking for alternatives to reCAPTCHA, like picking the type of animal, or background fields or javascript trickery.

答:
Before giving in to the pressure of using captcha, consider creative workarounds such as having a field labeled "Your Comments" that is hidden by CSS. If the field is entered, the request is dropped by the server. Most bots will fall for it even if there is still not a good way to defeat the room full of underpaid laborers, which captcha does not help with anyways.

UPDATE: Just read a case study where removing CAPTCHA increased conversion rates by almost 10%. That would indicate to me that it is rather broken if you are losing 10% of your leads just to filter out bots. Imagine what 10% means to most businesses.

OwnerDisplayName: davebug

OwnerDisplayName: David Thomas Garcia

LastEditorDisplayName: David Thomas Garcia


问:
Strange output with Array.filter() method
In the code below I expected the result of destroyer([1, 2, 3, 1, 2, 3], 2, 3); would be [1,1].

But the result pops out to be [1,2,3,1,2,3].

Where am I going wrong?

```<code>function destroyer(arr) {
  function hlp(x) {
    for(var i=1; i<arguments.length ; i++) {
      if(x == arguments[i]) return false;
    }
    return true;
  }
  return arr.filter(hlp);
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
</code>```

答:
You've defined destroyer to only accept one argument, while you're passing in more than one. arguments is undefined, and iterating in a function passed to Array.filter() isn't a good idea. Array.filter() checks every element for you. Not that it would work in your code, but if it would, it would be better to just return x == arguments[i] instead of checking whether it's true or false. If you return x == arguments[i] you're actually returning a boolean. An example of that is where I in the code below return exclude.indexOf(i) == -1;. Try the following approach instead:

function destroyer(arr, exclude) {
  return arr.filter(function(i) {
    return exclude.indexOf(i) == -1;
  });
}
console.log(destroyer([1, 2, 3, 1, 2, 3], [2, 3]));```

Body:
In the code below I expected the result of destroyer([1, 2, 3, 1, 2, 3], 2, 3); would be [1,1].

But the result pops out to be [1,2,3,1,2,3].

Where am I going wrong?

function destroyer(arr) {
  function hlp(x) {
    for(var i=1; i<arguments.length ; i++) {
      if(x == arguments[i]) return false;
    }
    return true;
  }
  return arr.filter(hlp);
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));


问:
Converting a vector to an array - Is there a 'standard' way to do this?
I know you can just do: &theVector[0], but is this standard? Is this behavior always guaranteed?

If not, is there a better, less 'hackish' way to do this?

答:
We can do this using data() method. C++11 provides this method.
It returns a pointer to the first element in the vector. vector Even if it is empty, we can call this function itself without problems</p>

```<code>  vector<int>v;
  int *arr = v.data();
</code>```

Body:
We can do this using data() method. C++11 provides this method.
It returns a pointer to the first element in the vector. vector Even if it is empty, we can call this function itself without problems

  vector<int>v;
  int *arr = v.data();


Title: R Dichotomize dataframe over mulitple unique dimensions

Body:
I have a dataframe like this:

originalDF <- data.frame(A1=c(1, 1, 2, 3, 4, 5, 6, 6, 6, 6, 6),
                         A2=c(12.2, 12.2, 15.0, 34.123, 2.0, 66.0, 7.0, 7.0, 7.0, 7.0, 7.0),
                         A3=c('T1', 'T2', 'T1', 'T1', 'T2', 'T1', 'T1', 'T1', 'T1', 'T1', 'T1'),
                         A4=c('1234', '1234', '1234', '1234', '4321', '4321', '4321', '4321', '4321', '4321', '4321'),
                         A5=c('0245', '0245', '0500', '0500', '0600', '0600', '0600','0800','0700','0900', '0900'))

   A1     A2 A3   A4   A5
1   1 12.200 T1 1234 0245
2   1 12.200 T2 1234 0245
3   2 15.000 T1 1234 0500
4   3 34.123 T1 1234 0500
5   4  2.000 T2 4321 0600
6   5 66.000 T1 4321 0600
7   6  7.000 T1 4321 0600
8   6  7.000 T1 4321 0800
9   6  7.000 T1 4321 0700
10  6  7.000 T1 4321 0900
11  6  7.000 T1 4321 0900

I want now to dichotomize this dataframe that it finally looks like this:

uniqueoriginalDF <- unique(subset(originalDF, select=c(A1, A2, A3, A4)))
wantedDF <- cbind.data.frame(uniqueoriginalDF,
                             A5_0245=c(1, 1, 0, 0, 0, 0, 0),
                             A5_0500=c(0, 0, 1, 1, 0, 0, 0),
                             A5_0600=c(0, 0, 0, 0, 1, 1, 1),
                             A5_0800=c(0, 0, 0, 0, 0, 0, 1),
                             A5_0700=c(0, 0, 0, 0, 0, 0, 1),
                             A5_0900=c(0, 0, 0, 0, 0, 0, 1))

  A1     A2 A3   A4 A5_0245 A5_0500 A5_0600 A5_0800 A5_0700 A5_0900
1  1 12.200 T1 1234       1       0       0       0       0       0
2  1 12.200 T2 1234       1       0       0       0       0       0
3  2 15.000 T1 1234       0       1       0       0       0       0
4  3 34.123 T1 1234       0       1       0       0       0       0
5  4  2.000 T2 4321       0       0       1       0       0       0
6  5 66.000 T1 4321       0       0       1       0       0       0
7  6  7.000 T1 4321       0       0       1       1       1       1

How can I achieve this? (Base R solutions preferred!) Thanks in advance!

Body:
We can use reshape from base R

d1 <- reshape(transform(originalDF, A5N = 1), idvar =
             names(originalDF)[1:4], timevar = 'A5', direction = 'wide')
d1[is.na(d1)] <- 0

But it is easier with dcast

library(data.table)
dcast(setDT(originalDF), ...~ paste0("A5_", A5), function(x) as.integer(length(x) > 0))
#    A1     A2 A3   A4 A5_0245 A5_0500 A5_0600 A5_0700 A5_0800 A5_0900
#1:  1 12.200 T1 1234       1       0       0       0       0       0
#2:  1 12.200 T2 1234       1       0       0       0       0       0
#3:  2 15.000 T1 1234       0       1       0       0       0       0
#4:  3 34.123 T1 1234       0       1       0       0       0       0
#5:  4  2.000 T2 4321       0       0       1       0       0       0
#6:  5 66.000 T1 4321       0       0       1       0       0       0
#7:  6  7.000 T1 4321       0       0       1       1       1       1


问:
Azure: blob uri null when creating image from VM
I am using the Azure CLI v2.0 and when I try to create an image from a VM, the blob URI is null:
    {
      ...
      "osDisk": {
        "blobUri": null,
        ...
       }
      ...
    }

I followed the steps from the Microsoft doc and I used a Ubuntu LTS VM created on the Azure portal.

The weird thing is that I already created an image from a VM and at this time, I had a blob URI for my image.

I need the blob URI to get the SAS in order to publish an app in the Azure marketplace.

Also, the URI does not appear in the Azure portal as well and if I try to create a VM from this image, it is successful.

Does anyone have any suggestion on why this is happening?

Thank you.

答:
By default, we create image with CLI 2.0, the new create image not store in Azure storage account, we can find it in images:

========================================================

Update:

Create a image from a managed disk, we can't find the URI in Azure portal:

For now, we can't create SAS for managed image.

In your scenario, I think we should use snapshots. A snapshot is a copy of a disk at the point in time it is taken, it only applies to one disk. If you have a VM that only has one disks(the OS), we can take a snapshot of it(we should generalize it first).

After snapshot created, we can grant access to this snapshot, also we can copy this snapshot to target Azure subscription. Then we can use this snapshot to create a image and use this image to create a new vm.(snapshot can copy to a different region.)

About create SAS of this snapshot, we can use CLI 2.0 to do it.

```<code>C:\Users\jason>az snapshot grant-access --help

Command
    az snapshot grant-access: Grant read access to a snapshot.

Arguments
    --duration-in-seconds [Required]: Time duration in seconds until the SAS access expires.

Resource Id Arguments
    --ids                           : One or more resource IDs (space delimited). If provided, no
                                      other 'Resource Id' arguments should be specified.
    --name -n                       : The name of the snapshot.
    --resource-group -g             : Name of resource group. You can configure the default group
                                      using `az configure --defaults group=<name>`.
</code>```

More information about create new VM with snapshot, please refer to this link.

How to create a managed image from a snapshot, please refer to this link.

Update2:

we can use powershell to copy managed disk to azure storage account:

```<code>##create $SAS
$sas = Grant-AzureRmDiskAccess -ResourceGroupName shui -DiskName test -DurationInSecond 3600 -Access Read
$destContext = New-AzureStorageContext –StorageAccountName contosostorageav1 -StorageAccountKey 'YourStorageAccountKey'
Start-AzureStorageBlobCopy -AbsoluteUri $sas.AccessSAS -DestContainer 'vhds' -DestContext $destContext -DestBlob 'MyDestinationBlobName.vhd'
</code>```

Update3:

We can use CLI 2.0 to copy snapshot to azure storage account:

```<code>az account set --subscription $subscriptionId

sas=$(az snapshot grant-access --resource-group $resourceGroupName --name $snapshotName --duration-in-seconds $sasExpiryDuration --query [accessSas] -o tsv)

az storage blob copy start --destination-blob $destinationVHDFileName --destination-container $storageContainerName --account-name $storageAccountName --account-key $storageAccountKey --source-uri $sas
</code>```

More information about copy snapshot to storage account, please refer to this link.

Body:
By default, we create image with CLI 2.0, the new create image not store in Azure storage account, we can find it in images:

========================================================

Update:

Create a image from a managed disk, we can't find the URI in Azure portal:

For now, we can't create SAS for managed image.

In your scenario, I think we should use snapshots. A snapshot is a copy of a disk at the point in time it is taken, it only applies to one disk. If you have a VM that only has one disks(the OS), we can take a snapshot of it(we should generalize it first).

After snapshot created, we can grant access to this snapshot, also we can copy this snapshot to target Azure subscription. Then we can use this snapshot to create a image and use this image to create a new vm.(snapshot can copy to a different region.)

About create SAS of this snapshot, we can use CLI 2.0 to do it.

C:\Users\jason>az snapshot grant-access --help

Command
    az snapshot grant-access: Grant read access to a snapshot.

Arguments
    --duration-in-seconds [Required]: Time duration in seconds until the SAS access expires.

Resource Id Arguments
    --ids                           : One or more resource IDs (space delimited). If provided, no
                                      other 'Resource Id' arguments should be specified.
    --name -n                       : The name of the snapshot.
    --resource-group -g             : Name of resource group. You can configure the default group
                                      using `az configure --defaults group=<name>`.

More information about create new VM with snapshot, please refer to this link.

How to create a managed image from a snapshot, please refer to this link.

Update2:

we can use powershell to copy managed disk to azure storage account:

##create $SAS
$sas = Grant-AzureRmDiskAccess -ResourceGroupName shui -DiskName test -DurationInSecond 3600 -Access Read
$destContext = New-AzureStorageContext –StorageAccountName contosostorageav1 -StorageAccountKey 'YourStorageAccountKey'
Start-AzureStorageBlobCopy -AbsoluteUri $sas.AccessSAS -DestContainer 'vhds' -DestContext $destContext -DestBlob 'MyDestinationBlobName.vhd'

Update3:

We can use CLI 2.0 to copy snapshot to azure storage account:

az account set --subscription $subscriptionId

sas=$(az snapshot grant-access --resource-group $resourceGroupName --name $snapshotName --duration-in-seconds $sasExpiryDuration --query [accessSas] -o tsv)

az storage blob copy start --destination-blob $destinationVHDFileName --destination-container $storageContainerName --account-name $storageAccountName --account-key $storageAccountKey --source-uri $sas

More information about copy snapshot to storage account, please refer to this link.


问:
Integer (literal) union type, with NaN as valid return value
I have a (comparison) function with an union return type. It can return -1, 1 or 0. However, I need a special case ("result") for when at least one of the items being compared is not defined. The compiler allows me to add null as a potential return value, but not NaN (which, in some scenarios would make sense, e.g. comparing numbers or dates).

This compiles

```<code>function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | null {
   ...
}
</code>```

but for this one, the compiler says it "Cannot find name NaN":

```<code>function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | NaN {
   ...
}
</code>```

Why is NaN not allowed? Is there a way to use NaN?

答:
NaN itself is not a type, instead it is a const value of type Number. So there is no way to define anything as being of the type NaN.

That makes sense, because the literal types for numbers are all single values e.g. -1, or a union of the literal values 1 | 0 | -1 but NaN isn't a single value as no NaN ever compares equal to any other it is effectively an infinite set of values.

I would suggest that using NaN to indicate a particular result from your function is a bad idea as the only way you can test for getting that result is to call another function. Better to add null or undefined to the return type (or if you don't like that how about a literal string).

Keep in mind that:

```<code>let foo = NaN;
switch(foo) {
    case 1: console.log('got 1'); break
    case NaN: console.log('got NaN'); break;
    default: console.log('other');
}
</code>```

will output 'other'.

So you could just do this:

```<code>function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | 'not comparable' {
   ...
}
</code>```

and then you can just compare the result against 'not comparable'.

Body:
I have a (comparison) function with an union return type. It can return -1, 1 or 0. However, I need a special case ("result") for when at least one of the items being compared is not defined. The compiler allows me to add null as a potential return value, but not NaN (which, in some scenarios would make sense, e.g. comparing numbers or dates).

This compiles

function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | null {
   ...
}

but for this one, the compiler says it "Cannot find name NaN":

function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | NaN {
   ...
}

Why is NaN not allowed? Is there a way to use NaN?

Body:
NaN itself is not a type, instead it is a const value of type Number. So there is no way to define anything as being of the type NaN.

That makes sense, because the literal types for numbers are all single values e.g. -1, or a union of the literal values 1 | 0 | -1 but NaN isn't a single value as no NaN ever compares equal to any other it is effectively an infinite set of values.

I would suggest that using NaN to indicate a particular result from your function is a bad idea as the only way you can test for getting that result is to call another function. Better to add null or undefined to the return type (or if you don't like that how about a literal string).

Keep in mind that:

let foo = NaN;
switch(foo) {
    case 1: console.log('got 1'); break
    case NaN: console.log('got NaN'); break;
    default: console.log('other');
}

will output 'other'.

So you could just do this:

function myFunc(item1: MyType, item2: MyType): -1 | 0 | 1 | 'not comparable' {
   ...
}

and then you can just compare the result against 'not comparable'.


问:
Syntaxnet / Parsey McParseface python API
I've installed syntaxnet and am able to run the parser with the provided demo script. Ideally, I would like to run it directly from python.
The only code I found was this:

```<code>import subprocess
import os
os.chdir(r"../models/syntaxnet")
subprocess.call([
"echo 'Bob brought the pizza to Alice.' | syntaxnet/demo.sh"
], shell = True)
</code>```

which is a complete disaster - inefficient and over-complex (calling python from python should be done with python).

How can I call the python APIs directly, without going through shell scripts, standard I/O, etc?

EDIT - Why isn't this as easy as opening syntaxnet/demo.sh and reading it?

This shell script calls two python scripts (parser_eval and conll2tree) which are written as python scripts and can't be imported into a python module without causing multiple errors. A closer look yields additional script-like layers and native code. These upper layers need to be refactored in order to run the whole thing in a python context. Hasn't anyone forked syntaxnet with such a modification or intend to do so?

答:
There is a Rest API here for both syntaxnet and dragnn.

I had run them successfully on my cloud server. Some points I want to share:

build docker

sudo docker build -< ./Dockerfile

Some error may occur when build syntaxnet, just follow the ./Dockerfile and build the docker manually, it's easy to follow.

download pre-trained model

model for syntaxnet is here, eg the Chinese model
http://download.tensorflow.org/models/parsey_universal/Chinese.zip

model for dragnn located here

unzip them into folders
eg ./synataxnet_data, so you have something like ./synataxnet_data/Chinese

run and test

3.1 Synataxnet

```<code>run

    docker run -p 9000:9000 -v ./synataxnet_data/:/models ljm625/syntaxnet-rest-api

test

     curl -X POST -d '{ "strings": [["今天天气很好","猴子爱吃 桃子"]] }' -H "Content-Type: application/json" http://xxx.xxx.xxx.xxx:9000/api/v1/query/Chinese
</code>```

3.2 dragnn

```<code>run

    sudo docker run -p 9001:9000 -v ./dragnn_data:/models ljm625/syntaxnet-rest-api:dragnn

test

    http://Yourip:9001/api/v1/use/Chinse

    curl -X POST -d '{ "strings": ["今天 天气 很好","猴子 爱  吃 桃子"],"tree":true }' -H "Content-Type: application/json" http://xxx.xx.xx.xx:9001/api/v1/query
</code>```

4.test results and problems

From my testing with Chinese model, the syntaxnet is slow , it spend 3 seconds to process one query, and 9 seconds for a batch of 50 queries. There is a fixed cost for loading model.

For the dragnn model, it's fast, but I'm not satisfied with the parsing result (only test with Chinese).

PS: I don't like the way synataxnet works, like using bazel and reading data from stdin, if you want to customize it, you could find some info here

Other resource that help
https://github.com/dsindex/syntaxnet/blob/master/README_api.md

Body:
I've installed syntaxnet and am able to run the parser with the provided demo script. Ideally, I would like to run it directly from python.
The only code I found was this:

import subprocess
import os
os.chdir(r"../models/syntaxnet")
subprocess.call([
"echo 'Bob brought the pizza to Alice.' | syntaxnet/demo.sh"
], shell = True)

which is a complete disaster - inefficient and over-complex (calling python from python should be done with python).

How can I call the python APIs directly, without going through shell scripts, standard I/O, etc?

EDIT - Why isn't this as easy as opening syntaxnet/demo.sh and reading it?

This shell script calls two python scripts (parser_eval and conll2tree) which are written as python scripts and can't be imported into a python module without causing multiple errors. A closer look yields additional script-like layers and native code. These upper layers need to be refactored in order to run the whole thing in a python context. Hasn't anyone forked syntaxnet with such a modification or intend to do so?

Body:
There is a Rest API here for both syntaxnet and dragnn.

I had run them successfully on my cloud server. Some points I want to share:

build docker

sudo docker build -< ./Dockerfile

Some error may occur when build syntaxnet, just follow the ./Dockerfile and build the docker manually, it's easy to follow.

download pre-trained model

model for syntaxnet is here, eg the Chinese model
http://download.tensorflow.org/models/parsey_universal/Chinese.zip

model for dragnn located here

unzip them into folders
eg ./synataxnet_data, so you have something like ./synataxnet_data/Chinese

run and test

3.1 Synataxnet

run

    docker run -p 9000:9000 -v ./synataxnet_data/:/models ljm625/syntaxnet-rest-api

test

     curl -X POST -d '{ "strings": [["今天天气很好","猴子爱吃 桃子"]] }' -H "Content-Type: application/json" http://xxx.xxx.xxx.xxx:9000/api/v1/query/Chinese

3.2 dragnn

run

    sudo docker run -p 9001:9000 -v ./dragnn_data:/models ljm625/syntaxnet-rest-api:dragnn

test

    http://Yourip:9001/api/v1/use/Chinse

    curl -X POST -d '{ "strings": ["今天 天气 很好","猴子 爱  吃 桃子"],"tree":true }' -H "Content-Type: application/json" http://xxx.xx.xx.xx:9001/api/v1/query

4.test results and problems

From my testing with Chinese model, the syntaxnet is slow , it spend 3 seconds to process one query, and 9 seconds for a batch of 50 queries. There is a fixed cost for loading model.

For the dragnn model, it's fast, but I'm not satisfied with the parsing result (only test with Chinese).

PS: I don't like the way synataxnet works, like using bazel and reading data from stdin, if you want to customize it, you could find some info here

Other resource that help
https://github.com/dsindex/syntaxnet/blob/master/README_api.md


问:
Windows & Android: react native server crashes very often
```<code> ERROR  EPERM: operation not permitted, lstat '...\.idea\workspace.xml___jb_old___'
{"errno":-4048,"code":"EPERM","syscall":"lstat","path":"...\.idea\\workspace.xml___jb_old___"}
Error: EPERM: operation not permitted, lstat 'app\.idea\workspace.xml___jb_old___'
    at Error (native)
</code>```

After that I should again do:

```<code>npm start
</code>```

How to resolve this quite annoying problem?

答: The best temporary fix I found for this was that when you do react-native run-android, look out for the React Package Manager and as soon as it opens, close it and wait until the progress of react-native run-android says BUILD SUCCEEDED and then open another cmd in the same Directory of your react-native project and do npm start. If the server crashes again or you get any error, you can just do npm start again and continue your work.

Body:
 ERROR  EPERM: operation not permitted, lstat '...\.idea\workspace.xml___jb_old___'
{"errno":-4048,"code":"EPERM","syscall":"lstat","path":"...\.idea\\workspace.xml___jb_old___"}
Error: EPERM: operation not permitted, lstat 'app\.idea\workspace.xml___jb_old___'
    at Error (native)

After that I should again do:

npm start

How to resolve this quite annoying problem?


问:
C# async - Exception not handled
This code here is not handling the Exception thrown, when it cant connect to the Server. Any Ideas why? Thanks!</p>

```<code>public Form1()
        {
            InitializeComponent();
            StartClient();

        }
async private Task StartClient()
{
    try
    {
        await ConnectToServerAsync();
    }
    catch (System.Net.Sockets.SocketException)
    {
        MesssageBox.Show("TEST");
    }
}

private Task ConnectToServerAsync()
{
    return Task.Factory.StartNew(() => client.Connect(host, port));
}
</code>```

答:
The thing is: "async void" is very dangerous construct that should almost never appear in your production code. Async method is not a list of statements internally, it's kind of state machine that switches from one "await" statement to another, doing various things in-between while "awaiting". So, once you got an exception raised inside that state machine, you need special context to preserve the stack trace etc. Void methods do not provide such a context. Return Task or Task<something> instead.

As a further reading, I could recommend Phil Haack's very nice blogpost: http://haacked.com/archive/2014/11/11/async-void-methods/

Title: C# async - Exception not handled

Body:
This code here is not handling the Exception thrown, when it cant connect to the Server. Any Ideas why? Thanks!

public Form1()
        {
            InitializeComponent();
            StartClient();

        }
async private Task StartClient()
{
    try
    {
        await ConnectToServerAsync();
    }
    catch (System.Net.Sockets.SocketException)
    {
        MesssageBox.Show("TEST");
    }
}

private Task ConnectToServerAsync()
{
    return Task.Factory.StartNew(() => client.Connect(host, port));
}


问:
Javascript regex matching syntax not working
I would like to test a string to ensure it has the following pattern:

```<code>asas/asas2/asas
</code>```

The charatcers in between the slashes can be letters, digits or both.

I have a working example here, although i'm sure it could be improved.

Regex Example

But when tested in jsfiddle it doesn't work

Jsfiddle Example

```<code>var str = 'dfdfdf/dfdf/dfdf';
var patt = new RegExp("/(^\w+\/\w+\/\w+$)/g");
var res = patt.test(str);
alert(res);
</code>```

The above code example always returns false.

答: Remove the quotes new RegExp(/(^\w+\/\w+\/\w+$)/g);

Body:
I would like to test a string to ensure it has the following pattern:

asas/asas2/asas

The charatcers in between the slashes can be letters, digits or both.

I have a working example here, although i'm sure it could be improved.

Regex Example

But when tested in jsfiddle it doesn't work

Jsfiddle Example

var str = 'dfdfdf/dfdf/dfdf';
var patt = new RegExp("/(^\w+\/\w+\/\w+$)/g");
var res = patt.test(str);
alert(res);

The above code example always returns false.


问:
How to get the proper iOS version programmatically?
I want to get the current os version of user device for some analysis in backend. Im trying to get it as below,

```<code>[[[UIDevice currentDevice] systemVersion] floatValue]; **//not returning the minor version number**
</code>```

When I test this by running in my iPhone which is having iOS 8.0.2, this api returns me 8.000000 as the result but I need the exact iOS version which is 8.0.2

Any help in fixing this problem is appreciated in advance.

答:
```<code>NSString *osVersion = [[UIDevice currentDevice] systemVersion];
</code>```

Body:
I want to get the current os version of user device for some analysis in backend. Im trying to get it as below,

[[[UIDevice currentDevice] systemVersion] floatValue]; **//not returning the minor version number**

When I test this by running in my iPhone which is having iOS 8.0.2, this api returns me 8.000000 as the result but I need the exact iOS version which is 8.0.2

Any help in fixing this problem is appreciated in advance.


问:
R: using hatched fill in plots
I was using R to make some plots for a report. I see that the plots don't seem to be so smooth. I am new to R so don't know much. But how do I get smooth plots?

Also by default the plots are filled with solid colors but I want to have hatched fills in my pie charts and bar plots. Is there a way to do that in R, I couldn't find it through a basic google search so I put this question here.

答:
Did you try help(pie)?</p>

```<code>density: the density of shading lines, in lines per inch.  The default
          value of ‘NULL’ means that no shading lines are drawn.
          Non-positive values of ‘density’ also inhibit the drawing of
          shading lines.

pie(c(1,2,3),density=c(1,2,20))

hist(runif(200),density=c(10,20,30))
</code>```

Title: R: using hatched fill in plots

Body:
Did you try help(pie)?

density: the density of shading lines, in lines per inch.  The default
          value of ‘NULL’ means that no shading lines are drawn.
          Non-positive values of ‘density’ also inhibit the drawing of
          shading lines.

pie(c(1,2,3),density=c(1,2,20))

hist(runif(200),density=c(10,20,30))


问:
Spark Streaming - Best way to Split Input Stream based on filter Param
I currently try to create some kind of monitoring solution - some data is written to kafka and I read this data with Spark Streaming and process it.

For preprocessing the data for machine learning and anomaly detection I would like to split the stream based on some filter Parameters. So far I have learned that DStreams themselves cannot be split into several streams.

The problem I am mainly facing is that many algorithms(like KMeans) only take continues data and not discrete data like e.g. url or some other String.

My requirements would ideally be:

Read data from kafka and generate a list of strings based on what I read

Generate multiple streams based on that list of strings - (split stream, filter stream, or whatever is best practice)

Use those streams to train different models for each Stream to get a baseline and afterwards compare everything that comes later against the baseline

I would be happy to get any suggestions how to approach my problem. I cannot imagine that this scenario is not covered in Spark - however until now I did not discover a working solution.

答:
I think it should be sufficient to create derivate DStreams from the original, using filter and map:

```<code>val numericFeaturesDStream = originalDStream.filter(e => predicate(e)).map(e => extractFeatures(e))
val otherNumericFeaturesDStream = originalDStream.filter(e => predicate2(e)).map(e => extractOtherFeatures(e))
</code>```

Note that these filter and map steps could be combined in one collect step (not to be confused with the parameterless RDD.collect that takes data to the driver!!!)

```<code>val featuresStream = originalDStream.transform(rdd =>
  rdd.collect{case (a,b,c,d,e) if c=="client" => Vectors.parse(a)}
)
streamingKMeans.trainOn(featuresStream)
</code>```

We can also have a dynamic set of filtered DStreams held into some collection. Here we use a map that contains the key we used to filter:

```<code>originalDStream.cache() // important for performance when a DStream is branched out.
// filterKeys: Set[String]
val dstreamByFilterKey = filterKeys.map(key => key -> originalDStream.filter(e => (getKey(e)==key)))
// do something with the different DStreams in this structure ...
</code>```

These snippets are code examples to be completed with the actual logic.

Body:
I think it should be sufficient to create derivate DStreams from the original, using filter and map:

val numericFeaturesDStream = originalDStream.filter(e => predicate(e)).map(e => extractFeatures(e))
val otherNumericFeaturesDStream = originalDStream.filter(e => predicate2(e)).map(e => extractOtherFeatures(e))

Note that these filter and map steps could be combined in one collect step (not to be confused with the parameterless RDD.collect that takes data to the driver!!!)

val featuresStream = originalDStream.transform(rdd =>
  rdd.collect{case (a,b,c,d,e) if c=="client" => Vectors.parse(a)}
)
streamingKMeans.trainOn(featuresStream)

We can also have a dynamic set of filtered DStreams held into some collection. Here we use a map that contains the key we used to filter:

originalDStream.cache() // important for performance when a DStream is branched out.
// filterKeys: Set[String]
val dstreamByFilterKey = filterKeys.map(key => key -> originalDStream.filter(e => (getKey(e)==key)))
// do something with the different DStreams in this structure ...

These snippets are code examples to be completed with the actual logic.


答:
There are various problems with this code. First, using async void is only meant for event handlers. An async void method can't be awaited and any exceptions it throws can't be handled. Second, Task.Factory.StartNew(()=>client.Connect(host,port)) fakes asynchronous execution. It still blocks a thread. Asynchronous execution means that no thread is blocked while waiting for the operation to complete.

I assume you use TcpClient. This class already has a ConnectAsync method that connects in an asynchronous manner. You could simplify your code to this:

```<code>private async Task StartClient()
{
    try
    {
        await client.ConnectAsync(host,port);
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.ToString());
    }
}
</code>```

If you want to start the client in response to a UI event, eg a button click, you'd write :

```<code>async void Button1_Click(object sender, EventArgs e)
{
    await StartClient();
}
</code>```

or

```<code>async void Button1_Click(object sender, EventArgs e)
{
    try
    {
        await StartClient();
        //Work with the client
    }
    catch(Exception exc)
    {
        MessageBox.Show(exc.ToString());
    }
}
</code>```

Finally, use a logging library instead of MessageBox.Show, eg log4net so you don't lose exception messages due to threading issues.

Title: C# async - Exception not handled

Body:
There are various problems with this code. First, using async void is only meant for event handlers. An async void method can't be awaited and any exceptions it throws can't be handled. Second, Task.Factory.StartNew(()=>client.Connect(host,port)) fakes asynchronous execution. It still blocks a thread. Asynchronous execution means that no thread is blocked while waiting for the operation to complete.

I assume you use TcpClient. This class already has a ConnectAsync method that connects in an asynchronous manner. You could simplify your code to this:

private async Task StartClient()
{
    try
    {
        await client.ConnectAsync(host,port);
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.ToString());
    }
}

If you want to start the client in response to a UI event, eg a button click, you'd write :

async void Button1_Click(object sender, EventArgs e)
{
    await StartClient();
}

or

async void Button1_Click(object sender, EventArgs e)
{
    try
    {
        await StartClient();
        //Work with the client
    }
    catch(Exception exc)
    {
        MessageBox.Show(exc.ToString());
    }
}

Finally, use a logging library instead of MessageBox.Show, eg log4net so you don't lose exception messages due to threading issues.


问:
Reverse Regex Selection with Spring MongoDB
I have a mongo collection with objects like these:

```<code>[
{
    "_id" : "a2d",
    "entityType" : "Location",
    "type" : "STRING",
},
{
    "_id" : "a1_order",
    "entityType" : "Order",
    "type" : "STRING",
}
]
</code>```

Trying to append the _entityType to all document's id where it is not present at the end id the id (the first object in the above case).

Using mongo with Spring, but I'm already stuck with the first step, to get all the objects with no entityType in id.

Thinking about something like this, with regex, but I'm not sure how should it look like:

```<code>Query query = new Query();
query.addCriteria( Criteria.where( "id" ).regex( "here i need the entity type of the current document" ) );
</code>```

答:
You can build your regex by '^' ('starts with' Regex).

So you need a function who point in all documents and check this filter

```<code>    List<Document> result = new ArrayList<Document>();
    StringBuilder idPrefix = new StringBuilder();
    idPrefix.append("^");
    idPrefix.append(idCode);
    idPrefix.append("_");
    List<Bson> filters = new ArrayList<Bson>();
    filters.add(Filters.regex("_id", keyPrefix.toString()));
    for (Document d : yourCollections.find(Filters.and(filters)))
        list.add(d);
</code>```

Body:
I have a mongo collection with objects like these:

[
{
    "_id" : "a2d",
    "entityType" : "Location",
    "type" : "STRING",
},
{
    "_id" : "a1_order",
    "entityType" : "Order",
    "type" : "STRING",
}
]

Trying to append the _entityType to all document's id where it is not present at the end id the id (the first object in the above case).

Using mongo with Spring, but I'm already stuck with the first step, to get all the objects with no entityType in id.

Thinking about something like this, with regex, but I'm not sure how should it look like:

Query query = new Query();
query.addCriteria( Criteria.where( "id" ).regex( "here i need the entity type of the current document" ) );

Body:
You can build your regex by '^' ('starts with' Regex).

So you need a function who point in all documents and check this filter

    List<Document> result = new ArrayList<Document>();
    StringBuilder idPrefix = new StringBuilder();
    idPrefix.append("^");
    idPrefix.append(idCode);
    idPrefix.append("_");
    List<Bson> filters = new ArrayList<Bson>();
    filters.add(Filters.regex("_id", keyPrefix.toString()));
    for (Document d : yourCollections.find(Filters.and(filters)))
        list.add(d);


问:
Prevent columns from being renamed when using by_row(., collate = "col")
Code

```<code>library(purrrlyr)
mtcars[1:2, 1:2] %>%
    by_row(function(x)
               as.data.frame(setNames(as.list(1:5), LETTERS[1:5])),
           .collate = "cols")
# # tibble [2 x 7]
#     mpg   cyl    A1    B1    C1    D1    E1
#   <dbl> <dbl> <int> <int> <int> <int> <int>
# 1    21     6     1     2     3     4     5
# 2    21     6     1     2     3     4     5
</code>```

Question

Is there a way how I can avoid that by_row "decorates" the names of my data frame by adding 1 to the column names?

Expecetd Outcome

```<code># # tibble [2 x 7]
#     mpg   cyl     A     B     C     D     E
#   <dbl> <dbl> <int> <int> <int> <int> <int>
# 1    21     6     1     2     3     4     5
# 2    21     6     1     2     3     4     5
</code>```

答:
As stated in the comment, this method produces the desired columns but adds the .row column.

```<code>library(purrrlyr)
mtcars[1:2, 1:2] %>%
    by_row(function(x)
               as.data.frame(setNames(as.list(1:5), LETTERS[1:5])),
           .collate = "rows")

 #       mpg   cyl  .row     A     B     C     D     E
 #     <dbl> <dbl> <int> <int> <int> <int> <int> <int>
 #   1    21     6     1     1     2     3     4     5
 #   2    21     6     2     1     2     3     4     5
</code>```

Body:
Code

library(purrrlyr)
mtcars[1:2, 1:2] %>%
    by_row(function(x)
               as.data.frame(setNames(as.list(1:5), LETTERS[1:5])),
           .collate = "cols")
# # tibble [2 x 7]
#     mpg   cyl    A1    B1    C1    D1    E1
#   <dbl> <dbl> <int> <int> <int> <int> <int>
# 1    21     6     1     2     3     4     5
# 2    21     6     1     2     3     4     5

Question

Is there a way how I can avoid that by_row "decorates" the names of my data frame by adding 1 to the column names?

Expecetd Outcome

# # tibble [2 x 7]
#     mpg   cyl     A     B     C     D     E
#   <dbl> <dbl> <int> <int> <int> <int> <int>
# 1    21     6     1     2     3     4     5
# 2    21     6     1     2     3     4     5

Body:
As stated in the comment, this method produces the desired columns but adds the .row column.

library(purrrlyr)
mtcars[1:2, 1:2] %>%
    by_row(function(x)
               as.data.frame(setNames(as.list(1:5), LETTERS[1:5])),
           .collate = "rows")

 #       mpg   cyl  .row     A     B     C     D     E
 #     <dbl> <dbl> <int> <int> <int> <int> <int> <int>
 #   1    21     6     1     1     2     3     4     5
 #   2    21     6     2     1     2     3     4     5