问:
Docusign webhook message does not have way to differentiate different compositetemplate
I have created 1 envelope with 2 composite templates with embedded signing and I can hook it up with the webhook event notification to receive a message once users finish signing, so I can try to update my db and download the file. However, the webhook response does not have the custom fields that I need to identify which file belong to which for me to update the db row.

This is my json serialized envelope example. Notice the custom field on each inline template, that have the property of DocuInfoId. I will need the value of those to update my db row

```<code>{
  "status": "sent",
  "emailSubject": "DocuSign API - Template Example",
  "eventNotification": {
    "url": "https:\/\/mytestsite.net\/api\/documentstuff\/docusign\/available",
    "loggingEnabled": "false",
    "requireAcknowledgment": "true",
    "useSoapInterface": "false",
    "soapNameSpace": "",
    "includeCertificateWithSoap": "false",
    "signMessageWithX509Cert": "false",
    "includeDocuments": "false",
    "includeEnvelopeVoidReason": "false",
    "includeTimeZone": "true",
    "includeSenderAccountAsCustomField": "false",
    "includeDocumentFields": "false",
    "includeCertificateOfCompletion": "true",
    "envelopeEvents": [
      {
        "envelopeEventStatusCode": "Sent",
        "includeDocuments": null
      },
      {
        "envelopeEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ],
    "recipientEvents": [
      {
        "recipientEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ]
  },
  "compositeTemplates": [
    {
      "inlineTemplates": [
        {
          "sequence": "1",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just a bunch of text tabs, radio group, etc"
                }
              },
              {
                "clientUserId": "2",
                "recipientId": "2",
                "email": "testemail@test.com",
                "name": "Owner Name",
                "roleName": "Owner",
                "tabs": null
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId",
                "required": "True",
                "show": "False",
                "value": "77",
                "listItems": null
              },
              {
                "name": "OpportunityId",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "1",
          "templateId": "TemplateIDNumber1"
        }
      ]
    },
    {
      "inlineTemplates": [
        {
          "sequence": "2",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just another bunch of text tabs, radio group tab, etc"
                }
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId",
                "required": "True",
                "show": "False",
                "value": "88",
                "listItems": null
              },
              {
                "name": "OpportunityId",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "2",
          "templateId": "TemplateIDNumber2"
        }
      ]
    }
  ]
}
</code>```

And once I finished signing, the webhook event notification is triggered and called my api with this response message

```<code>{
  "EnvelopeStatus": {
    "EnvelopeID": "EnvelopeIDGivenByDocusign",
    "Status": "Completed",
    "CustomFields": [
      {
        "Name": "ContactID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "OpportunityID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "AccountID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "DocuInfoId",
        "Show": "False",
        "Required": "True",
        "Value": "88"
      },
      {
        "Name": "OpportunityId",
        "Show": "False",
        "Required": "True",
        "Value": "1"
      },
      {
        "Name": "LQAID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      }
    ],
    "DocumentStatuses": [
      {
        "ID": 1,
        "Name": "Document - TX - 1001.pdf",
        "TemplateName": "Document - TX",
        "Sequence": 1
      },
      {
        "ID": 2,
        "Name": "Rejection.pdf",
        "TemplateName": "Rejection Form",
        "Sequence": 2
      }
    ]
  },
  "DocumentPDFs": [
    {
      "Name": "Document - TX - 1001.pdf",
      "DocumentID": "1",
      "DocumentType": "CONTENT"
    },
    {
      "Name": "Rejection.pdf",
      "DocumentID": "2",
      "DocumentType": "CONTENT"
    },
    {
      "Name": "CertificateOfCompletion_78sd89fuas89sadf.pdf",
      "DocumentID": null,
      "DocumentType": "SUMMARY"
    }
  ]
}
</code>```

Looking at the response, there's only 1 docuinfoid with the value of 88, I'm also not sure where is the rest of custom field coming from e.g: "LQAID". Now, I'm not sure which docuinfoid is this belong to, the first pdf file (Document - TX - 1001.pdf) or the second pdf file (Rejection.pdf).

Is there anyway to know which pdf document belong to which docuinfoid, so that I can attach it to my database correctly?

答:
In DocuSign there are different types of custom fields.

Envelope custom fields associate metadata with the Envelope as a whole.

Document custom fields associate metadata with a specific Document in an Envelope.

To determine which type of custom fields your Create Envelope request is setting, you can execute the following requests for the envelope/document(s) and evaluate the results:

Get Envelope Custom Fields

GET /v2/accounts/{accountId}/envelopes/{envelopeId}/custom_fields

Get Document Custom Fields

GET /v2/accounts/{accountId}/envelopes/{envelopeId}/documents/{documentId}/fields

I'd suspect that perhaps your Create Envelope request is setting Envelope custom fields -- which associates that metadata with the Envelope as a whole, not with any specific document in the Envelope.

Based on what you've described, it sounds like you want to specify metadata for a particular document in an Envelope. If this is the case, you'll need to amend the structure/contents of your Create Envelope request to set Document custom field(s) (instead of setting Envelope custom fields).

Body:
I have created 1 envelope with 2 composite templates with embedded signing and I can hook it up with the webhook event notification to receive a message once users finish signing, so I can try to update my db and download the file. However, the webhook response does not have the custom fields that I need to identify which file belong to which for me to update the db row.

This is my json serialized envelope example. Notice the custom field on each inline template, that have the property of DocuInfoId. I will need the value of those to update my db row

{
  "status": "sent",
  "emailSubject": "DocuSign API - Template Example",
  "eventNotification": {
    "url": "https:\/\/mytestsite.net\/api\/documentstuff\/docusign\/available",
    "loggingEnabled": "false",
    "requireAcknowledgment": "true",
    "useSoapInterface": "false",
    "soapNameSpace": "",
    "includeCertificateWithSoap": "false",
    "signMessageWithX509Cert": "false",
    "includeDocuments": "false",
    "includeEnvelopeVoidReason": "false",
    "includeTimeZone": "true",
    "includeSenderAccountAsCustomField": "false",
    "includeDocumentFields": "false",
    "includeCertificateOfCompletion": "true",
    "envelopeEvents": [
      {
        "envelopeEventStatusCode": "Sent",
        "includeDocuments": null
      },
      {
        "envelopeEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ],
    "recipientEvents": [
      {
        "recipientEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ]
  },
  "compositeTemplates": [
    {
      "inlineTemplates": [
        {
          "sequence": "1",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just a bunch of text tabs, radio group, etc"
                }
              },
              {
                "clientUserId": "2",
                "recipientId": "2",
                "email": "testemail@test.com",
                "name": "Owner Name",
                "roleName": "Owner",
                "tabs": null
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId",
                "required": "True",
                "show": "False",
                "value": "77",
                "listItems": null
              },
              {
                "name": "OpportunityId",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "1",
          "templateId": "TemplateIDNumber1"
        }
      ]
    },
    {
      "inlineTemplates": [
        {
          "sequence": "2",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just another bunch of text tabs, radio group tab, etc"
                }
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId",
                "required": "True",
                "show": "False",
                "value": "88",
                "listItems": null
              },
              {
                "name": "OpportunityId",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "2",
          "templateId": "TemplateIDNumber2"
        }
      ]
    }
  ]
}

And once I finished signing, the webhook event notification is triggered and called my api with this response message

{
  "EnvelopeStatus": {
    "EnvelopeID": "EnvelopeIDGivenByDocusign",
    "Status": "Completed",
    "CustomFields": [
      {
        "Name": "ContactID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "OpportunityID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "AccountID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "DocuInfoId",
        "Show": "False",
        "Required": "True",
        "Value": "88"
      },
      {
        "Name": "OpportunityId",
        "Show": "False",
        "Required": "True",
        "Value": "1"
      },
      {
        "Name": "LQAID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      }
    ],
    "DocumentStatuses": [
      {
        "ID": 1,
        "Name": "Document - TX - 1001.pdf",
        "TemplateName": "Document - TX",
        "Sequence": 1
      },
      {
        "ID": 2,
        "Name": "Rejection.pdf",
        "TemplateName": "Rejection Form",
        "Sequence": 2
      }
    ]
  },
  "DocumentPDFs": [
    {
      "Name": "Document - TX - 1001.pdf",
      "DocumentID": "1",
      "DocumentType": "CONTENT"
    },
    {
      "Name": "Rejection.pdf",
      "DocumentID": "2",
      "DocumentType": "CONTENT"
    },
    {
      "Name": "CertificateOfCompletion_78sd89fuas89sadf.pdf",
      "DocumentID": null,
      "DocumentType": "SUMMARY"
    }
  ]
}

Looking at the response, there's only 1 docuinfoid with the value of 88, I'm also not sure where is the rest of custom field coming from e.g: "LQAID". Now, I'm not sure which docuinfoid is this belong to, the first pdf file (Document - TX - 1001.pdf) or the second pdf file (Rejection.pdf).

Is there anyway to know which pdf document belong to which docuinfoid, so that I can attach it to my database correctly?


来源: stackexchange

问:
Error When Unwrapping Optional Element
I have an optional element, but am facing an error when displaying said element in a tableview. For reference, this element is an image, obtained from a JSON API feed. I understand that force unwrapping an element using ! is not a good idea, but it is what xcode suggests I do, giving me no other options. If I follow its suggestion, the app crashes, displaying "unexpectedly found nil while unwrapping an Optional value." Does anyone know how I can display an image from a URL. Here is the code I have thus far.

```<code>struct PlayerStats:Decodable {
    let personaname: String?
    let score: Double?
    let solo_competitive_rank: Int?
    let avatar: String?
}
</code>```

The Problem is with the "avatar" element, in the cellForRowAt func.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "rankCell") as? RankTableViewCell else { return UITableViewCell() }
    cell.nameLabel.text = rank[indexPath.row].personaname

    if let imageURL = URL(string: rank[indexPath.row].avatar) {
        DispatchQueue.global().async {
            let data = try? Data(contentsOf: imageURL)
            if let data = data {
            guard let avatar = UIImage(data: data) else { return }
                DispatchQueue.main.async {
                    cell.avatarImage.image = avatar
                }
            }
        }
    }

    return cell
}
</code>```

答:
Other than the fact that you need to safely unwrap the optional avatar property, there are several conceptual issues with your code.

First of all, you should never be performing asynchronous operations inside tableView(_:cellForRowAt:), since this is a synchronous method, so the UITableViewCell will be returned before the image could be downloaded from the network URL. You need to perform the image downloading in a separate function and reloading the table view (or at least the corresponding row/section) once the asynchronous operation finishes execution.

Secondly, don't use the initializer Data(contentsOf:) for downloading content from the internet. Even though by dispatching Data(contentsOf: imageURL), you won't be blocking the main thread, that initializer of Data shouldn't be used for downloading content from the internet. That initializer should only be used for loading content from a local file URL, not a network URL.

ContentLicense: CC BY-SA 3.0

Title: Error When Unwrapping Optional Element

Body:
I have an optional element, but am facing an error when displaying said element in a tableview. For reference, this element is an image, obtained from a JSON API feed. I understand that force unwrapping an element using ! is not a good idea, but it is what xcode suggests I do, giving me no other options. If I follow its suggestion, the app crashes, displaying "unexpectedly found nil while unwrapping an Optional value." Does anyone know how I can display an image from a URL. Here is the code I have thus far.

struct PlayerStats:Decodable {
    let personaname: String?
    let score: Double?
    let solo_competitive_rank: Int?
    let avatar: String?
}

The Problem is with the "avatar" element, in the cellForRowAt func.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "rankCell") as? RankTableViewCell else { return UITableViewCell() }
    cell.nameLabel.text = rank[indexPath.row].personaname

    if let imageURL = URL(string: rank[indexPath.row].avatar) {
        DispatchQueue.global().async {
            let data = try? Data(contentsOf: imageURL)
            if let data = data {
            guard let avatar = UIImage(data: data) else { return }
                DispatchQueue.main.async {
                    cell.avatarImage.image = avatar
                }
            }
        }
    }

    return cell
}


问:
How to read integers elegantly using C++ stream?
I have a file full of lines in this format:

```<code>1 - 2: 3
</code>```

I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.

答:
I think this one would be the fastest -yet elegant- way:</p>

```<code>int a, b, c;
scanf("%d-%d:%d", &a, &b, &c);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a file full of lines in this format:

1 - 2: 3

I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.

Body:
I think this one would be the fastest -yet elegant- way:

int a, b, c;
scanf("%d-%d:%d", &a, &b, &c);


问:
php-cgi not found in PhpStorm resulting in 502 bad gateway
I'm trying to run a simple php file with PhpStorm (v2017.3). It should output a var_dump, but I constantly encounter a 502 bad gateway error in my browser when running the script. I receive the following error in the PhpStorm:

php-cgi not found: Please ensure that configured PHP Interpreter built as CGI program (--enable-fastcgi was specified)

When I run php -v in my terminal here is the output:

```<code>PHP 7.1.7 (cli) (built: Jul 15 2017 18:08:09) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
</code>```

Here are the things I've tried so far:

Reinstalling PHP with homebrew with brew uninstall php71 and then brew install71.

Adding the --with-cgi option to my brew install php71 command

Read through the following threads: phpStorm problems with php-cgi, php cgi error in PhpStorm when php-cgi is installed

答:
Homebrew typically installs the binaries in the /usr/local/bin folder. To finalize this installation, you should tell PhpStorm which interpreter it is using. If you dont do the following step, PhpStorm will autodetect the php shipped with OSX.

Open preferences, go to Languages & Frameworks, select PHP, and you will see the appropriate settings. For the PHP Ececutable, there is a ..., click on it and you will see :

Just navigate to /usr/local/bin and click on the php binary, the one from homebrew.

ps : the 'ini' files you need to edit are in /usr/local/etc/php/M.m where M.m are major.minor version of the installed php (7.1 in your case).

Body:
I'm trying to run a simple php file with PhpStorm (v2017.3). It should output a var_dump, but I constantly encounter a 502 bad gateway error in my browser when running the script. I receive the following error in the PhpStorm:

php-cgi not found: Please ensure that configured PHP Interpreter built as CGI program (--enable-fastcgi was specified)

When I run php -v in my terminal here is the output:

PHP 7.1.7 (cli) (built: Jul 15 2017 18:08:09) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies

Here are the things I've tried so far:

Reinstalling PHP with homebrew with brew uninstall php71 and then brew install71.

Adding the --with-cgi option to my brew install php71 command

Read through the following threads: phpStorm problems with php-cgi, php cgi error in PhpStorm when php-cgi is installed


问:
Union All of SQL temporary tables created using dplyr?
How does one rbind or bind_rows temporary tables created in SQL (tested and failed in Postgres and SQLite) by dplyr?

E.g.

```<code>library(dplyr)
con <- DBI::dbConnect(RSQLite::SQLite(), path = ":memory:")

copy_to(con, nycflights13::flights, "flights",
        temporary = FALSE,
        indexes = list(
            c("year", "month", "day"),
            "carrier",
            "tailnum",
            "dest"
        )
)

copy_to(con, nycflights13::flights, "flights2",
        temporary = FALSE,
        indexes = list(
            c("year", "month", "day"),
            "carrier",
            "tailnum",
            "dest"
        )
)

flights_db <- tbl(con, "flights")
flights_db_2 <- tbl(con, "flights2")
</code>```

Calling bind_rows gives the following error:

```<code>> bind_rows(flights_db, flights_db_2)
Error in bind_rows_(x, .id) :
  Argument 1 must be a data frame or a named atomic vector, not a tbl_dbi/tbl_sql/tbl_lazy/tbl
</code>```

答:
With thanks to Akrun for pointing me to the union family, it is possible to somewhat replicate bind_rows with:

```<code>Reduce(union_all, list(flights_db, flights_db, flights_db))
</code>```

As noted in the comments to, and in Akrun's answer, union produces unique records in the result, and union_all is the equivalent to SQL's UNION ALL.

Body:
How does one rbind or bind_rows temporary tables created in SQL (tested and failed in Postgres and SQLite) by dplyr?

E.g.

library(dplyr)
con <- DBI::dbConnect(RSQLite::SQLite(), path = ":memory:")

copy_to(con, nycflights13::flights, "flights",
        temporary = FALSE,
        indexes = list(
            c("year", "month", "day"),
            "carrier",
            "tailnum",
            "dest"
        )
)

copy_to(con, nycflights13::flights, "flights2",
        temporary = FALSE,
        indexes = list(
            c("year", "month", "day"),
            "carrier",
            "tailnum",
            "dest"
        )
)

flights_db <- tbl(con, "flights")
flights_db_2 <- tbl(con, "flights2")

Calling bind_rows gives the following error:

> bind_rows(flights_db, flights_db_2)
Error in bind_rows_(x, .id) :
  Argument 1 must be a data frame or a named atomic vector, not a tbl_dbi/tbl_sql/tbl_lazy/tbl

Body:
With thanks to Akrun for pointing me to the union family, it is possible to somewhat replicate bind_rows with:

Reduce(union_all, list(flights_db, flights_db, flights_db))

As noted in the comments to, and in Akrun's answer, union produces unique records in the result, and union_all is the equivalent to SQL's UNION ALL.


问:
erlang elixir observer ui: what does reds/reductions mean in processes tab?
I was doing the exercise of making a dictionary module, implemented with Agent, that should output random word on random_word(pid) function call. After implementation was complete the author asked: "Using the observer (:observer.start), find this process. Double click on it to bring up the process details. Now generate some random words. Do you see any changes in the process display (you may have to wait a few seconds or refresh the process window to see a change)?"

The only change I have noticed is in the number of reds/reductions (it increases when I call the function from iex). However there was no explanation of what "Reds" is or why it increased.

After a quick web surf I could not find anything understandable for a beginner (a lot of elixir/erlang in production articles popup). Could you folks give a nice, simple answer to this.

答: In a BEAM application, you can potentially have millions of processes running at the same time. In order to ensure that each process gets (roughly) equal share of the available CPU(s), the VM counts reductions. One reduction is essentially equivalent to one function call. </p>


问:
PHP by keypress jquery
I want to make search in my username database but it doesnt recognize keypress function. also, I want to prevent search.php on first load (can't use isset because there is no button) this is my index.php

<!DOCTYPE html>

  <title></title>
  <?php  include 'search.php'; ?>

  <form method="POST">
    enter keyword to search

    <input type="text" name="textbox1" id="textbox1">

  </form>

```
</div>
</div>
</p>

<p>This is my <em>search.php</em>. the <em>connection.php</em> is working proper. so I'm not pasting it here</p>

```<?php

    include 'connection.php';

    $search_value = $_POST['textbox1'];
    $query = "SELECT username FROM users WHERE username LIKE '" . $search_value . "%'";
    $conn_status = mysqli_query($conn, $query);

    while($row = $conn_status->fetch_assoc())
    {
        echo $row['username'] . '
';
    }
?>
```

答:
This snippet is a working one with amendments since you have wrong HTML as well as forgetting to send data to the server.

<!DOCTYPE html>

  <title></title>

  <form method="POST">
    enter keyword to search

    <input type="text" name="textbox1" id="textbox1">

  </form>

```

Title: PHP by keypress jquery

Body:
I want to make search in my username database but it doesnt recognize keypress function. also, I want to prevent search.php on first load (can't use isset because there is no button) this is my index.php

<!DOCTYPE html>

  <title></title>
  <?php  include 'search.php'; ?>

  <form method="POST">
    enter keyword to search

    <input type="text" name="textbox1" id="textbox1">

  </form>

This is my search.php. the connection.php is working proper. so I'm not pasting it here

<?php

    include 'connection.php';

    $search_value = $_POST['textbox1'];
    $query = "SELECT username FROM users WHERE username LIKE '" . $search_value . "%'";
    $conn_status = mysqli_query($conn, $query);

    while($row = $conn_status->fetch_assoc())
    {
        echo $row['username'] . '
';
    }
?>

Body:
This snippet is a working one with amendments since you have wrong HTML as well as forgetting to send data to the server.

<!DOCTYPE html>
<html>

<head>
  <title></title>
</head>

<body>
  <form method="POST">
    enter keyword to search<br>
    <input type="text" name="textbox1" id="textbox1">
    <br><br>
    <div id="main"></div>
  </form>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {

      $("#textbox1").on('input',function() {

        var searchText = $(this).val();
        console.log("Calling PHP with value:" + searchText);

        $.ajax({
          type: "GET",
          data: "textbox1=" + searchText,
          url: "search.php",
          success: function(data) {
            $("#main").html(data);
          },
          error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.responseText);
          }
        });
      });
    });
  </script>
</body>

</html>


问:
Mongoose - Validate array of different subdocuments types
I have a schema which has an array of different sub document types.
Below schema is just an example:

VehicleSchema:

```<code>let BikeSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  type        : { type: String, required: true, default: "bike" },
  tyres       : { type: Number, required: true, min: 2}
});

let TruckSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  type        : { type: String, required: true, default: "truck" },
  tyres       : { type: Number, required: true, min: 4},
  doors       : { type: Number, required: true}
});

let VehicleSchema = new Schema({
  name: {type:String, required: [true, 'name is required']},
  vehiclesSelected: [BikeSchema, TruckSchema],
});

Below is the json that I need to validate:
vehicle = {
  "name": 'abc',
  "vehiclesSelected": [
    {"type": "truck", doors: 2},
    {"type": "bike", tyres: 3},
    {"type": "bike"}
  ]
}
</code>```

Now I need to validate the "vehiclesSelected" array based on the 'type' passed in the JSON. Can someone tell me how can I validate an
array of subdocuments based on a particular field (in this case 'type')?

Any help would be much appreciated.

答:
You can make use of Mongoose's discriminator() function.

In your case, what you can do is:

let BikeSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  tyres       : { type: Number, required: true, min: 2}
});

let TruckSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  tyres       : { type: Number, required: true, min: 4},
  doors       : { type: Number, required: true}
});

let typeVehicleSchema = new Schema({},
discriminatorKey: 'type', _id: false})

let VehicleSchema = new Schema({
  name: {type:String, required: [true, 'name is required']},
  vehiclesSelected: [typeVehicleSChema],
});

VehicleSchema.path('vehiclesSelected').discriminator('truck', new Schema(TruckSchema))
VehicleSchema.path('vehiclesSelected').discriminator('bike', new Schema(BikeSchema))```

That way, depending on vehicle type, your schema will validate with the appropriate subType, both inheriting the parent schema (in this case, the typeVehicleSchema), based on the 'type' passed in.

Body:
I have a schema which has an array of different sub document types.
Below schema is just an example:

VehicleSchema:

let BikeSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  type        : { type: String, required: true, default: "bike" },
  tyres       : { type: Number, required: true, min: 2}
});

let TruckSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  type        : { type: String, required: true, default: "truck" },
  tyres       : { type: Number, required: true, min: 4},
  doors       : { type: Number, required: true}
});

let VehicleSchema = new Schema({
  name: {type:String, required: [true, 'name is required']},
  vehiclesSelected: [BikeSchema, TruckSchema],
});

Below is the json that I need to validate:
vehicle = {
  "name": 'abc',
  "vehiclesSelected": [
    {"type": "truck", doors: 2},
    {"type": "bike", tyres: 3},
    {"type": "bike"}
  ]
}

Now I need to validate the "vehiclesSelected" array based on the 'type' passed in the JSON. Can someone tell me how can I validate an
array of subdocuments based on a particular field (in this case 'type')?

Any help would be much appreciated.

Body:
You can make use of Mongoose's discriminator() function.

In your case, what you can do is:

let BikeSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  tyres       : { type: Number, required: true, min: 2}
});

let TruckSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  tyres       : { type: Number, required: true, min: 4},
  doors       : { type: Number, required: true}
});

let typeVehicleSchema = new Schema({},
discriminatorKey: 'type', _id: false})

let VehicleSchema = new Schema({
  name: {type:String, required: [true, 'name is required']},
  vehiclesSelected: [typeVehicleSChema],
});

VehicleSchema.path('vehiclesSelected').discriminator('truck', new Schema(TruckSchema))
VehicleSchema.path('vehiclesSelected').discriminator('bike', new Schema(BikeSchema))

That way, depending on vehicle type, your schema will validate with the appropriate subType, both inheriting the parent schema (in this case, the typeVehicleSchema), based on the 'type' passed in.


问:
How to make string as an Array Object in JQuery
I have got below string values in a variable.

```<code>var mystring = '{"img_src":"/english/images/spa.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"},
     {"img_src":"/english/images/spa1.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"}'
</code>```

Now I want to convert this string variable into Array object. So that If I try to access it my function it should behave like an array object. For example.

some code to Convert(mystring) to an Array Object(myArryObject), then I want to pass it to my function like below

```<code>$.fn.liveBanner = function(myArryObject,optional_options)
    {
      //here I want to access my myArryObject as below
      alert(myArryObject[0].img_src) //then it should give "/english/images/spa.jpg"
});
</code>```

Please suggest using JQuery.

EDIT:

I did the changes as suggested by @Deceze, please see below:

```<code>             var myString = "'"+ $("#RotationImages #mainHidden").attr("value")+"'";

    var myArrayobj = jQuery.parseJSON('[' + myString + ']');
    alert(myArrayobj.img_src);
</code>```

the above code is giving below error

```<code>Error: uncaught exception: Invalid JSON:'{"img_src":"/english/images/spa.jpg", "img_title":"Enjoy a refreshing shower at 43,000 feet","img_alt":"Enjoy a refreshing shower at 43,000 feet", "img_height":"326","img_width":"980","header":"Enjoy a refreshing shower at 43,000 feet","subheader":"One of many groundbreaking amenities on the Flight","bg_color":"","url_href":"1"}'
</code>```

答:
Given your mystring as defined, executing var myArray = jQuery.parseJSON('[' + mystring } ']'); will result in an array of objects. See this jsfiddle for a live example.

The reason you are getting the invalid JSON error is because you wrap your valid JSON in single quotes, thereby making it invalid. That is, the first line in:

```<code>var myString = "'"+ $("#RotationImages #mainHidden").attr("value")+"'";

var myArrayobj = jQuery.parseJSON('[' + myString + ']');
alert(myArrayobj.img_src);
</code>```

is invalidating your JSON. The first line should be (provided the value is correct):

```<code>var myString = $("#RotationImages #mainHidden").attr("value");
</code>```

For more information on JSON see json.org and RFC 4627.

Body:
I have got below string values in a variable.

var mystring = '{"img_src":"/english/images/spa.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"},
     {"img_src":"/english/images/spa1.jpg",
    "img_title":"Enjoy a refreshing shower at 43,000 feet",
    "img_alt":"Enjoy a refreshing shower at 43,000 feet",
    "img_height":"326",
    "img_width":"980",
    "header":"Enjoy a refreshing shower at 43,000 feet",
    "subheader":"One of many groundbreaking amenities",
    "bg_color":"",
    "url_href":"1"}'

Now I want to convert this string variable into Array object. So that If I try to access it my function it should behave like an array object. For example.

some code to Convert(mystring) to an Array Object(myArryObject), then I want to pass it to my function like below

$.fn.liveBanner = function(myArryObject,optional_options)
    {
      //here I want to access my myArryObject as below
      alert(myArryObject[0].img_src) //then it should give "/english/images/spa.jpg"
});

Please suggest using JQuery.

EDIT:

I did the changes as suggested by @Deceze, please see below:

             var myString = "'"+ $("#RotationImages #mainHidden").attr("value")+"'";

    var myArrayobj = jQuery.parseJSON('[' + myString + ']');
    alert(myArrayobj.img_src);

the above code is giving below error

Error: uncaught exception: Invalid JSON:'{"img_src":"/english/images/spa.jpg", "img_title":"Enjoy a refreshing shower at 43,000 feet","img_alt":"Enjoy a refreshing shower at 43,000 feet", "img_height":"326","img_width":"980","header":"Enjoy a refreshing shower at 43,000 feet","subheader":"One of many groundbreaking amenities on the Flight","bg_color":"","url_href":"1"}'

Body:
Given your mystring as defined, executing var myArray = jQuery.parseJSON('[' + mystring } ']'); will result in an array of objects. See this jsfiddle for a live example.

The reason you are getting the invalid JSON error is because you wrap your valid JSON in single quotes, thereby making it invalid. That is, the first line in:

var myString = "'"+ $("#RotationImages #mainHidden").attr("value")+"'";

var myArrayobj = jQuery.parseJSON('[' + myString + ']');
alert(myArrayobj.img_src);

is invalidating your JSON. The first line should be (provided the value is correct):

var myString = $("#RotationImages #mainHidden").attr("value");

For more information on JSON see json.org and RFC 4627.


问:
Using grepl in a nested ifelse statement with other strings
```<code>#working example
col1 <- c("cat", "cats", "cat2", "dog", "carrot", "carrots", "broccoli",
"squash", "tundra", "grassland", "grasslands")
df <- as.data.frame(col1)
</code>```

I want to create a new column that identifies whether the string is an animal, vegetable, or biome.

Desired output:

```<code>         col1      col2
1         cat    animal
2        cats    animal
3        cat2    animal
4         dog    animal
5      carrot vegetable
6     carrots vegetable
7    broccoli vegetable
8      squash vegetable
9      tundra     biome
10  grassland     biome
11 grasslands     biome
</code>```

I'd like to understand why the grepl portion of the following code doesn't work.

```<code>df_new <- df %>% mutate(col2 = ifelse(col1 %in% c("dog", grepl("cat", col1)), "animal",
     ifelse(col1 %in% c(grepl("carrot", col1), "broccoli", "squash"), "vegetable",
     ifelse(col1 %in% c("tundra", grepl("grassland", col1)), "biome", NA))))
</code>```

答:
grepl returns a logical vector, you need grep(..., value=TRUE):

```<code>df %>%
    mutate(col2 = ifelse(col1 %in% c("dog", grep("cat", col1, value=T)), "animal",
                  ifelse(col1 %in% c(grep("carrot", col1, value=T), "broccoli", "squash"), "vegetable",
                  ifelse(col1 %in% c("tundra", grep("grassland", col1, value=T)), "biome", NA))))

#         col1      col2
#1         cat    animal
#2        cats    animal
#3        cat2    animal
#4         dog    animal
#5      carrot vegetable
#6     carrots vegetable
#7    broccoli vegetable
#8      squash vegetable
#9      tundra     biome
#10  grassland     biome
#11 grasslands     biome
</code>```

Body:
#working example
col1 <- c("cat", "cats", "cat2", "dog", "carrot", "carrots", "broccoli",
"squash", "tundra", "grassland", "grasslands")
df <- as.data.frame(col1)

I want to create a new column that identifies whether the string is an animal, vegetable, or biome.

Desired output:

         col1      col2
1         cat    animal
2        cats    animal
3        cat2    animal
4         dog    animal
5      carrot vegetable
6     carrots vegetable
7    broccoli vegetable
8      squash vegetable
9      tundra     biome
10  grassland     biome
11 grasslands     biome

I'd like to understand why the grepl portion of the following code doesn't work.

df_new <- df %>% mutate(col2 = ifelse(col1 %in% c("dog", grepl("cat", col1)), "animal",
     ifelse(col1 %in% c(grepl("carrot", col1), "broccoli", "squash"), "vegetable",
     ifelse(col1 %in% c("tundra", grepl("grassland", col1)), "biome", NA))))

Body:
grepl returns a logical vector, you need grep(..., value=TRUE):

df %>%
    mutate(col2 = ifelse(col1 %in% c("dog", grep("cat", col1, value=T)), "animal",
                  ifelse(col1 %in% c(grep("carrot", col1, value=T), "broccoli", "squash"), "vegetable",
                  ifelse(col1 %in% c("tundra", grep("grassland", col1, value=T)), "biome", NA))))

#         col1      col2
#1         cat    animal
#2        cats    animal
#3        cat2    animal
#4         dog    animal
#5      carrot vegetable
#6     carrots vegetable
#7    broccoli vegetable
#8      squash vegetable
#9      tundra     biome
#10  grassland     biome
#11 grasslands     biome


问:
Axios stripe issues. "invalid_request_error"
I am at my wits end! I am trying to create a customer via the stripe api. Using their example with curl i have no problems.
Here is their example:

curl https://api.stripe.com/v1/customers \
   -u sk_test_apikey: \
   -d description="Customer for zoey.brown@example.com" \
   -d source=tok_visa

It is when i try to do this with axios that i get an error "invalid_request_error" because it isn't properly parsing my data. Here's what i've got:

```<code>export const registerNewUser = async (firstName, lastName, email, password) => {
  let config = {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': `Bearer ${stripeTestApiKey}`
    }
  }
  let data = {
      email: `${email}`,
      description: `Customer account for ${email}`
  }
  await axios.post(stripeCustomerUri, data, config)
    .then(res => {
      console.log("DEBUG-axios.post--res: ", res)
    })
    .catch(err => {
      console.log(JSON.stringify(err, null, 2))
    })
}
</code>```

and in my console i see that stripe isn't receiving my data in the correct manner. Here's the (useful part of my) response json:

```<code>"response": {
  "data": {
    "error": {
      "type": "invalid_request_error",
      "message": "Received unknown parameter: {\"email\":\"joe@blow.com\",\"description\":\"Customer account for joe@blow.com\"}", "param": "{\"email\":\"joe@blow.com\",\"description\":\"Customer account for joe@blow.com\"}" } },
</code>```

Judging by all of my other attempts and this example error, I am not passing my data in the correct format... However, when i pass -d to my curl command everything works as expected... If I send an empty string as data it works as well...

does anyone have an idea why / how this is? How is the "data" object via curl differ from my javascript data object?

答: The problem was that axios uses application/json content type by default and the stripe api requires form-url-encoded... this requires parsing the data object with a library like querystring before passing through to the stripe api... hope this helps someone!</p>

Body:
I am at my wits end! I am trying to create a customer via the stripe api. Using their example with curl i have no problems.
Here is their example:

curl https://api.stripe.com/v1/customers \
   -u sk_test_apikey: \
   -d description="Customer for zoey.brown@example.com" \
   -d source=tok_visa

It is when i try to do this with axios that i get an error "invalid_request_error" because it isn't properly parsing my data. Here's what i've got:

export const registerNewUser = async (firstName, lastName, email, password) => {
  let config = {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': `Bearer ${stripeTestApiKey}`
    }
  }
  let data = {
      email: `${email}`,
      description: `Customer account for ${email}`
  }
  await axios.post(stripeCustomerUri, data, config)
    .then(res => {
      console.log("DEBUG-axios.post--res: ", res)
    })
    .catch(err => {
      console.log(JSON.stringify(err, null, 2))
    })
}

and in my console i see that stripe isn't receiving my data in the correct manner. Here's the (useful part of my) response json:

"response": {
  "data": {
    "error": {
      "type": "invalid_request_error",
      "message": "Received unknown parameter: {\"email\":\"joe@blow.com\",\"description\":\"Customer account for joe@blow.com\"}", "param": "{\"email\":\"joe@blow.com\",\"description\":\"Customer account for joe@blow.com\"}" } },

Judging by all of my other attempts and this example error, I am not passing my data in the correct format... However, when i pass -d to my curl command everything works as expected... If I send an empty string as data it works as well...

does anyone have an idea why / how this is? How is the "data" object via curl differ from my javascript data object?


问:
Designing a Zend model for multiple tables together?
i am using Zend Framework to build a web interface for setting up ACL - permission rights - for users of a custom CMS. Since the ACL data is spread in 5 tables(users, groups, permissions, urls=action+controller, nice permission name for the user to understand) and i have only one controller with the four basic CRUD(create, list, update, delete) operations i was wondering what is the best way to do it?

All the examples in my books i've seen that each model extend Zend_Db_Table_Abstract and thus represents one table.

I was thinking i have to do a model that doesn't extend zend_db_table_abstract and then write the queries that i need by hand thus limiting myself to mysql database only?

p.s. please do not argue over the acl database structure

thank you

答:
The definition of the Table Data Gateway pattern is

An object that acts as a Gateway to a database table. One instance handles all the rows in the table.

That's why you won't see it used any differently in Zend Framework. It's a Data Source Architectural Patterns while the thing you are asking about is a Domain specific class.

What you are encountering is Impedance Mismatch, meaning your Business Objects dont match the structure of your Database Design. The common solution is to use a DataMapper or an ORM to handle that for you.

The other solution would be to create a View in your database that joins the tables in a way that maps 1:1 to your required business objects. Then add a Zend_Db_Table for that view. You'd still have to come up with custom create, update, delete logic though. That's not data mapping though, but if you don't have any Business/Domain classes to map to, it's fine.


问:
Iterate through Json Object with nested Array Javascript
I need to iterate this json and push the values into an other array

```<code>[
{
    "id": 1,
    "nombre": "Samson",
    "marcaModelo": [
        {
            "id": 6,
            "nombre": "API 6D "
        }
    ]
}
{
    "id": 6,
    "nombre": "Endress + Hauser",
    "marcaModelo": [
        {
            "id": 10,
            "nombre": "Proline t-mass 65F50-AK2AH1RCBBCA"
        },
        {
            "id": 8,
            "nombre": "Cerabar M"
        }
    ]
}
]
</code>```

I made out with this

```<code>Object.entries(res).forEach((value, key) => {
      console.log(key, value)
      this.marcas.push({
        'marcaId': res[key].id,
        'marcaNombre': res[key].nombre,
        'modeloId': res[key].marcaModelo[0].id,
        'modeloNombre': res[key].marcaModelo[0].nombre
      })
      console.log(this.marcas)
    })
</code>```

but only push one marcaModelo object into marcas array, if I replace marcaModelo[0] for marcaModelo[key] I get an undefined.

I need something like this

```<code>{
marcaId:6
marcaNombre:"Endress + Hauser"
modeloId:[10, 8]
modeloNombre:[Proline t-mass 65F50-AK2AH1RCBBCA, Cerabar M]
}
</code>```

答:
You need a nested loop for all the marcaModelo objects; you can use .map() to return an array of the results of a function on each element.. It also doesn't seem like you need to use Object.entries(). The original object is an array, you can use .forEach() directly on it.

```<code>res.forEach(value => {
    console.log(value);
    this.marcas.push({
        'marcaId': value.id,
        'marcaNombre': value.nombre,
        'modeloId': value.marcaModelo.map(o => o.id),
        'modeloNombre': value.marcaModelo.map(o => o.nombre)
    });
    console.log(this.marcas);
}
</code>```

Body:
I need to iterate this json and push the values into an other array

[
{
    "id": 1,
    "nombre": "Samson",
    "marcaModelo": [
        {
            "id": 6,
            "nombre": "API 6D "
        }
    ]
}
{
    "id": 6,
    "nombre": "Endress + Hauser",
    "marcaModelo": [
        {
            "id": 10,
            "nombre": "Proline t-mass 65F50-AK2AH1RCBBCA"
        },
        {
            "id": 8,
            "nombre": "Cerabar M"
        }
    ]
}
]

I made out with this

Object.entries(res).forEach((value, key) => {
      console.log(key, value)
      this.marcas.push({
        'marcaId': res[key].id,
        'marcaNombre': res[key].nombre,
        'modeloId': res[key].marcaModelo[0].id,
        'modeloNombre': res[key].marcaModelo[0].nombre
      })
      console.log(this.marcas)
    })

but only push one marcaModelo object into marcas array, if I replace marcaModelo[0] for marcaModelo[key] I get an undefined.

I need something like this

{
marcaId:6
marcaNombre:"Endress + Hauser"
modeloId:[10, 8]
modeloNombre:[Proline t-mass 65F50-AK2AH1RCBBCA, Cerabar M]
}

Body:
You need a nested loop for all the marcaModelo objects; you can use .map() to return an array of the results of a function on each element.. It also doesn't seem like you need to use Object.entries(). The original object is an array, you can use .forEach() directly on it.

res.forEach(value => {
    console.log(value);
    this.marcas.push({
        'marcaId': value.id,
        'marcaNombre': value.nombre,
        'modeloId': value.marcaModelo.map(o => o.id),
        'modeloNombre': value.marcaModelo.map(o => o.nombre)
    });
    console.log(this.marcas);
}


问:
UPS ShipmentRequest API JSON Notification shipping to access point
I'm at a loss at the moment, I'm trying to add the option to send a package to a UPS Access Point, the documentation tells me I need to add a notification object for UAP (013) and for ADL (012)

When I read the documentation the notification object is allowed maximum 3 times, normally in xml it would look like:

```<code><ShipmentServiceOptions>
  <Notification>
    <NotificationCode>012</NotificationCode>
    some other values ( here..)
  </Notification>
      <Notification>
    <NotificationCode>013</NotificationCode>
    some other values ( here..)
  </Notification>
</ShipmentServiceOptions>
</code>```

But since I'm using JSON I create an array of objects:

```<code>$Shipment['ShipmentServiceOptions']['Notification'][] = ['NotificationCode' => '012'];
$Shipment['ShipmentServiceOptions']['Notification'][] = ['NotificationCode' => '013'];
</code>```

when I json decode this complete array, it will look like:

```<code>{
"Notification": [{
    "NotificationCode": "013",
    "EmailMessage": {
        "EMailAddress": "info@tom-it.nl",
        "UndeliverableEMailAddr": "info@tom-it.nl",
        "FromEMailAddress ": "fromemail@test.com",
        "FromName": "From Email"
    },
    "Locale": {
        "Language": "ENG",
        "Dialect": "US"
    }
}, {
    "NotificationCode": "012",
    "EmailMessage": {
        "EMailAddress": "info@tom-it.nl",
        "UndeliverableEMailAddr": "info@tom-it.nl",
        "FromEMailAddress ": "From Email",
        "FromName": "From Name"
    },
    "Locale": {
        "Language": "ENG",
        "Dialect": "US"
    }
}]
</code>```

}

This is a valid json object, but for some reason I keep getting the error:

ADL notification code (012) and notification data (email or phone number) is required for hold for pickup at access point location shipment.

When I flip the array values around I will get the error:

UAP shipper notification code (013) and notification data (email or phone number) is required for UPS Access Point Delivery.

This looks to me like only 1 value is being read from the array, and reading the documentation it leads me to believe it expects multiple Notification keys, but I really have no idea how I would add multiple Notification keys in json, which would invalidate the json object.. Any help would be greatly appreciated

Edit

when I convert the JSON object to look like this:

```<code>"ShipmentServiceOptions": [{
            "Notification": {
                "NotificationCode": "013",
                "EmailMessage": {
                    "EMailAddress": "info@tom-it.nl",
                    "UndeliverableEMailAddr": "info@tom-it.nl",
                    "FromEMailAddress ": "fromemail",
                    "FromName": "From Name"
                },
                "Locale": {
                    "Language": "ENG",
                    "Dialect": "US"
                }
            }
        }, {
            "Notification": {
                "NotificationCode": "012",
                "EmailMessage": {
                    "EMailAddress": "info@tom-it.nl",
                    "UndeliverableEMailAddr": "info@tom-it.nl",
                    "FromEMailAddress ": "fromemail",
                    "FromName": "From Name"
                },
                "Locale": {
                    "Language": "ENG",
                    "Dialect": "US"
                }
            }
        }],
</code>```

It gives me the this error:

ADL notification code (012) and notification data (email or phone number) is required for hold for pickup at access point location shipment.

Swapping around the items doesn't change the error

答:
I knew it would be something simple, if something takes more than an hour to fix, you know it's simple ;-)

I swapped the xml documentation with the web service documentation, in xml the node where the notification email data is added is called:

/ShipmentConfirmRequest/Shipment/ShipmentServiceOptions/Notification/EMailMessage/

In the JSON documentation that same node that holds the mail data is called:

/ShipmentConfirmRequest/Shipment/ShipmentServiceOptions/Notification/EMail/

For completeness, this is the correct json part for the notification object:

```<code>{
"Notification": [{
    "NotificationCode": "013",
    "EMail": {
        "EMailAddress": "info@tom-it.nl",
        "UndeliverableEMailAddr": "info@tom-it.nl",
        "FromEMailAddress ": "fromemail",
        "FromName": "fromemail"
    },
    "Locale": {
        "Language": "ENG",
        "Dialect": "US"
    }
}, {
    "NotificationCode": "012",
    "EMail": {
        "EMailAddress": "info@tom-it.nl",
        "UndeliverableEMailAddr": "info@tom-it.nl",
        "FromEMailAddress ": "fromname",
        "FromName": "From Name"
    },
    "Locale": {
        "Language": "ENG",
        "Dialect": "US"
    }
}]
</code>```

}

Body:
I'm at a loss at the moment, I'm trying to add the option to send a package to a UPS Access Point, the documentation tells me I need to add a notification object for UAP (013) and for ADL (012)

When I read the documentation the notification object is allowed maximum 3 times, normally in xml it would look like:

<ShipmentServiceOptions>
  <Notification>
    <NotificationCode>012</NotificationCode>
    some other values ( here..)
  </Notification>
      <Notification>
    <NotificationCode>013</NotificationCode>
    some other values ( here..)
  </Notification>
</ShipmentServiceOptions>

But since I'm using JSON I create an array of objects:

$Shipment['ShipmentServiceOptions']['Notification'][] = ['NotificationCode' => '012'];
$Shipment['ShipmentServiceOptions']['Notification'][] = ['NotificationCode' => '013'];

when I json decode this complete array, it will look like:

{
"Notification": [{
    "NotificationCode": "013",
    "EmailMessage": {
        "EMailAddress": "info@tom-it.nl",
        "UndeliverableEMailAddr": "info@tom-it.nl",
        "FromEMailAddress ": "fromemail@test.com",
        "FromName": "From Email"
    },
    "Locale": {
        "Language": "ENG",
        "Dialect": "US"
    }
}, {
    "NotificationCode": "012",
    "EmailMessage": {
        "EMailAddress": "info@tom-it.nl",
        "UndeliverableEMailAddr": "info@tom-it.nl",
        "FromEMailAddress ": "From Email",
        "FromName": "From Name"
    },
    "Locale": {
        "Language": "ENG",
        "Dialect": "US"
    }
}]

}

This is a valid json object, but for some reason I keep getting the error:

ADL notification code (012) and notification data (email or phone number) is required for hold for pickup at access point location shipment.

When I flip the array values around I will get the error:

UAP shipper notification code (013) and notification data (email or phone number) is required for UPS Access Point Delivery.

This looks to me like only 1 value is being read from the array, and reading the documentation it leads me to believe it expects multiple Notification keys, but I really have no idea how I would add multiple Notification keys in json, which would invalidate the json object.. Any help would be greatly appreciated

Edit

when I convert the JSON object to look like this:

"ShipmentServiceOptions": [{
            "Notification": {
                "NotificationCode": "013",
                "EmailMessage": {
                    "EMailAddress": "info@tom-it.nl",
                    "UndeliverableEMailAddr": "info@tom-it.nl",
                    "FromEMailAddress ": "fromemail",
                    "FromName": "From Name"
                },
                "Locale": {
                    "Language": "ENG",
                    "Dialect": "US"
                }
            }
        }, {
            "Notification": {
                "NotificationCode": "012",
                "EmailMessage": {
                    "EMailAddress": "info@tom-it.nl",
                    "UndeliverableEMailAddr": "info@tom-it.nl",
                    "FromEMailAddress ": "fromemail",
                    "FromName": "From Name"
                },
                "Locale": {
                    "Language": "ENG",
                    "Dialect": "US"
                }
            }
        }],

It gives me the this error:

ADL notification code (012) and notification data (email or phone number) is required for hold for pickup at access point location shipment.

Swapping around the items doesn't change the error

Body:
I knew it would be something simple, if something takes more than an hour to fix, you know it's simple ;-)

I swapped the xml documentation with the web service documentation, in xml the node where the notification email data is added is called:

/ShipmentConfirmRequest/Shipment/ShipmentServiceOptions/Notification/EMailMessage/

In the JSON documentation that same node that holds the mail data is called:

/ShipmentConfirmRequest/Shipment/ShipmentServiceOptions/Notification/EMail/

For completeness, this is the correct json part for the notification object:

{
"Notification": [{
    "NotificationCode": "013",
    "EMail": {
        "EMailAddress": "info@tom-it.nl",
        "UndeliverableEMailAddr": "info@tom-it.nl",
        "FromEMailAddress ": "fromemail",
        "FromName": "fromemail"
    },
    "Locale": {
        "Language": "ENG",
        "Dialect": "US"
    }
}, {
    "NotificationCode": "012",
    "EMail": {
        "EMailAddress": "info@tom-it.nl",
        "UndeliverableEMailAddr": "info@tom-it.nl",
        "FromEMailAddress ": "fromname",
        "FromName": "From Name"
    },
    "Locale": {
        "Language": "ENG",
        "Dialect": "US"
    }
}]

}


问:
Prevent css from changing elements width
they look normal when i have my windows on full mode(see picture)

But when its on a smaller screen:

It becomes long shaped. I just want it to stay a square and not change form.

My html and css:

```<code><div id="logo">
<img src="http://i.cubeupload.com/jmdKlW.png"/>
</div>
<div id="title">
<h3>Who's watching</h3>
</div>
<div class="divOuter">
 <div class="divInner1">First DIV</div>
 <div class="divInner2">Second DIV</div>
 <div class="divInner3">Third DIV</div>
 <div class="divInner4">Third DIV</div>

</div>
<div class="divOuter">
 <div class="divInner5">Desseh</div>
 <div class="divInner6">Anna</div>
 <div class="divInner7">Sia</div>
 <div class="divInner8">Lucas</div>
</div>
</code>```

CSS:

```<code>.divOuter {
  width: 50%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

.divInner1,
.divInner2,
.divInner3,
.divInner4  {
  border: .3em solid rgba(0,0,0,.4);
  width: 150px;
  height: auto;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;
  display: inline-block;
  flex:1;}

.divInner1  {
  background:grey;
}
.divInner2  {
  background:grey;
}
.divInner3  {
  background:grey;
}
.divInner4  {
  background:grey;
}

  .divInner1:hover  {
  border: .3em solid white;
}
  .divInner2:hover  {
  border: .3em solid white;
}
  .divInner3:hover  {
  border: .3em solid white;
}
  .divInner4:hover  {
  border: .3em solid white;
}

.divInner5,
.divInner6,
.divInner7,
.divInner8  {
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 20px;
  text-align: center;
  display: inline-block;
  flex:1;
  color:grey;
  font-size: 24px;
</code>```

A working example can be found at xat.me/madses1996?
I think this has something to do with the fact that im using flex to center things. Is there a way to have it like this but when i shrink my browser it stays square shaped?

I cant seem to edit the boxes individually

答:
An option is to place those inside of your divs that have the flex property on them.

```<code><div class="divOuter">
  <div class="divInner1"><div class="stay-square">First DIV</div></div>
  <div class="divInner2"><div class="stay-square">Second DIV</div></div>
  <div class="divInner3"><div class="stay-square">Third DIV</div></div>
  <div class="divInner4"><div class="stay-square">Third DIV</div></div>
</div>
</code>```

Set the styling for them so that the height and width are the same:

```<code>.stay-square { height:150px; width:150px; }
</code>```

You can always use @media to adjust the styling depending upon screen size as well.

Also transfer some of the styling from the outer div to the inner div:

```<code>.divInner1,
.divInner2,
.divInner3,
.divInner4  {
  text-align: center;
  display: inline-block;
  flex:1;
}
</code>```

to... (I also removed the background styling from the outer divs and placed it in the inner div)

```<code>.stay-square {
  width:150px;
  height:150px;
  border: .3em solid rgba(0,0,0,.4);
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  background:grey;
 }
</code>```

Body:
they look normal when i have my windows on full mode(see picture)

But when its on a smaller screen:

It becomes long shaped. I just want it to stay a square and not change form.

My html and css:

Who's watching

First DIV

Second DIV

Third DIV

Third DIV

Desseh

Anna

Sia

Lucas

CSS:

.divOuter {
  width: 50%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

.divInner1,
.divInner2,
.divInner3,
.divInner4  {
  border: .3em solid rgba(0,0,0,.4);
  width: 150px;
  height: auto;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;
  display: inline-block;
  flex:1;}

.divInner1  {
  background:grey;
}
.divInner2  {
  background:grey;
}
.divInner3  {
  background:grey;
}
.divInner4  {
  background:grey;
}

  .divInner1:hover  {
  border: .3em solid white;
}
  .divInner2:hover  {
  border: .3em solid white;
}
  .divInner3:hover  {
  border: .3em solid white;
}
  .divInner4:hover  {
  border: .3em solid white;
}

.divInner5,
.divInner6,
.divInner7,
.divInner8  {
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 20px;
  text-align: center;
  display: inline-block;
  flex:1;
  color:grey;
  font-size: 24px;

A working example can be found at xat.me/madses1996?
I think this has something to do with the fact that im using flex to center things. Is there a way to have it like this but when i shrink my browser it stays square shaped?

I cant seem to edit the boxes individually

Body:
An option is to place those inside of your divs that have the flex property on them.

<div class="divOuter">
  <div class="divInner1"><div class="stay-square">First DIV</div></div>
  <div class="divInner2"><div class="stay-square">Second DIV</div></div>
  <div class="divInner3"><div class="stay-square">Third DIV</div></div>
  <div class="divInner4"><div class="stay-square">Third DIV</div></div>
</div>

Set the styling for them so that the height and width are the same:

.stay-square { height:150px; width:150px; }

You can always use @media to adjust the styling depending upon screen size as well.

Also transfer some of the styling from the outer div to the inner div:

.divInner1,
.divInner2,
.divInner3,
.divInner4  {
  text-align: center;
  display: inline-block;
  flex:1;
}

to... (I also removed the background styling from the outer divs and placed it in the inner div)

.stay-square {
  width:150px;
  height:150px;
  border: .3em solid rgba(0,0,0,.4);
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  background:grey;
 }


问:
Subset a list with date conditions
I have a list

```<code>CLUST_K <- structure(list(LONGITUDE = c(118.5, 118.5, 118.5, 118.5, 118.5,
                    118.5), LATITUDE = c(-11.5, -11.5, -11.5, -11.5, -11.5, -11.5
                    ), DATE_START = structure(c(1419897600, 1419984000, 1420070400,
                    1420156800, 1420243200, 1420329600), class = c("POSIXct", "POSIXt"
                    )), DATE_END = structure(c(1420502400, 1420588800, 1420675200,
                    1420761600, 1420848000, 1420934400), class = c("POSIXct", "POSIXt"
                    )), FLAG = c(2, 1, 2, 2, 2, 2), SURFSKINTEMP = c(13L, 1L, 16L,
                    16L, 7L, 13L), SURFAIRTEMP = c(6L, 6L, 6L, 6L, 6L, 6L), TOTH2OVAP = c(5L,
                    17L, 17L, 17L, 17L, 17L), TOTO3 = c(16L, 16L, 16L, 10L, 7L, 7L
                    ), TOTCO = c(12L, 12L, 8L, 4L, 12L, 12L), TOTCH4 = c(13L, 14L,
                    6L, 6L, 11L, 7L), OLR_ARIS = c(10L, 4L, 4L, 7L, 5L, 10L), CLROLR_ARIS = c(10L,
                    4L, 4L, 7L, 5L, 10L), OLR_NOAA = c(10L, 10L, 10L, 10L, 7L, 9L
                    ), MODIS_LST = c(1L, 1L, 1L, 1L, 1L, 1L)), .Names = c("LONGITUDE",
                    "LATITUDE", "DATE_START", "DATE_END", "FLAG", "SURFSKINTEMP",
                    "SURFAIRTEMP", "TOTH2OVAP", "TOTO3", "TOTCO", "TOTCH4", "OLR_ARIS",
                    "CLROLR_ARIS", "OLR_NOAA", "MODIS_LST"), row.names = c(NA, 6L
                    ), class = "data.frame")
</code>```

and how to subset the list with date_start and date_end between 2014-01-01 and 2015-01-08, and FLAG = 2

my expect result is like

```<code>LONGITUDE LATITUDE DATE_START   DATE_END FLAG SURFSKINTEMP SURFAIRTEMP TOTH2OVAP TOTO3 TOTCO TOTCH4 OLR_ARIS    CLROLR_ARIS OLR_NOAA MODIS_LST
  118.5    -11.5 2014-12-30 2015-01-06    2           13           6         5    16    12     13       10           10       10         1
  118.5    -11.5 2015-01-01 2015-01-08    2           16           6        17    16     8      6        4            4       10         1
</code>```

答:
You can use the subset function

```<code>subs = subset(CLUST_K, FLAG == 2 & DATE_START > startdate & DATE_END > enddate)
</code>```

Alternatively, you can use which() to select desired rows

```<code>subs = CLUST_K[which(FLAG == 2 & DATE_START > startdate & DATE_END > enddate),]
</code>```

Edit: you may need to convert the structure to a DataFrame when you define CLUST_K

Title: Subset a list with date conditions

Body:
I have a list

CLUST_K <- structure(list(LONGITUDE = c(118.5, 118.5, 118.5, 118.5, 118.5,
                    118.5), LATITUDE = c(-11.5, -11.5, -11.5, -11.5, -11.5, -11.5
                    ), DATE_START = structure(c(1419897600, 1419984000, 1420070400,
                    1420156800, 1420243200, 1420329600), class = c("POSIXct", "POSIXt"
                    )), DATE_END = structure(c(1420502400, 1420588800, 1420675200,
                    1420761600, 1420848000, 1420934400), class = c("POSIXct", "POSIXt"
                    )), FLAG = c(2, 1, 2, 2, 2, 2), SURFSKINTEMP = c(13L, 1L, 16L,
                    16L, 7L, 13L), SURFAIRTEMP = c(6L, 6L, 6L, 6L, 6L, 6L), TOTH2OVAP = c(5L,
                    17L, 17L, 17L, 17L, 17L), TOTO3 = c(16L, 16L, 16L, 10L, 7L, 7L
                    ), TOTCO = c(12L, 12L, 8L, 4L, 12L, 12L), TOTCH4 = c(13L, 14L,
                    6L, 6L, 11L, 7L), OLR_ARIS = c(10L, 4L, 4L, 7L, 5L, 10L), CLROLR_ARIS = c(10L,
                    4L, 4L, 7L, 5L, 10L), OLR_NOAA = c(10L, 10L, 10L, 10L, 7L, 9L
                    ), MODIS_LST = c(1L, 1L, 1L, 1L, 1L, 1L)), .Names = c("LONGITUDE",
                    "LATITUDE", "DATE_START", "DATE_END", "FLAG", "SURFSKINTEMP",
                    "SURFAIRTEMP", "TOTH2OVAP", "TOTO3", "TOTCO", "TOTCH4", "OLR_ARIS",
                    "CLROLR_ARIS", "OLR_NOAA", "MODIS_LST"), row.names = c(NA, 6L
                    ), class = "data.frame")

and how to subset the list with date_start and date_end between 2014-01-01 and 2015-01-08, and FLAG = 2

my expect result is like

LONGITUDE LATITUDE DATE_START   DATE_END FLAG SURFSKINTEMP SURFAIRTEMP TOTH2OVAP TOTO3 TOTCO TOTCH4 OLR_ARIS    CLROLR_ARIS OLR_NOAA MODIS_LST
  118.5    -11.5 2014-12-30 2015-01-06    2           13           6         5    16    12     13       10           10       10         1
  118.5    -11.5 2015-01-01 2015-01-08    2           16           6        17    16     8      6        4            4       10         1

Body:
You can use the subset function

subs = subset(CLUST_K, FLAG == 2 & DATE_START > startdate & DATE_END > enddate)

Alternatively, you can use which() to select desired rows

subs = CLUST_K[which(FLAG == 2 & DATE_START > startdate & DATE_END > enddate),]

Edit: you may need to convert the structure to a DataFrame when you define CLUST_K


问:
Django filter icontains - find matches going the other way
In the code below, Django's icontains filter finds matches where the user_input is contained within the name. How do I find matches where the name is contained within the user_input?</p>

```<code>names = "Jim", "Bob", "James"
user_input = "Jimbo"

Names.objects.filter(names__icontains=user_input)
#returns empty queryset

Names.objects.filter(???=user_input)
#returns queryset with "Jim"
</code>```

Body:
In the code below, Django's icontains filter finds matches where the user_input is contained within the name. How do I find matches where the name is contained within the user_input?

names = "Jim", "Bob", "James"
user_input = "Jimbo"

Names.objects.filter(names__icontains=user_input)
#returns empty queryset

Names.objects.filter(???=user_input)
#returns queryset with "Jim"

Body:
Try:

Names.objects.filter(user_input__in=names)


问:
Type-signature vs. function equation in Haskell
I'm new to Haskell and to functional programming.  I'm reading through Real World Haskell, and I've realized I'm confused by a few examples.

Specifically this is in Chapter 9, in the section "A Domain specific language for predicates", the examples which have the w x y z parameters.

I've boiled it down to this:

Why does this code compile?

```<code>f :: Int -> (Int -> Int)
f x y = x+y

main = do
  let q = f 4 5
  putStr  (show (q))
</code>```

According to the type signature, f is clearly accepting 1 parameter and returning a function.
However, it seems I can write the function equation so it will accept two parameters and return an int.
Why is this possible?  Does this mean the type signature is ignored?

Is this currying?  Is this some kind of closure?
If I understand this http://www.haskell.org/haskellwiki/Currying correctly, then it seems to be somewhat in reverse to currying as defined there - my f function is taking multiple arguments instead of a single one!

Also, can anyone answering please provide a link to some sort of Haskell documentation where this ability is stated (if possible at all).

EDIT:

After thinking about this for some time, what you two seem to be implying is that:

1) This syntax is syntactic sugar, f will always have a single parameter, no matter how many parameters are written in the equation

2) Upon application of f, the function body will (always?) be transformed into a stub (in effect, the returned function), where x is fixed to the parameter given (4), and y is a parameter.

3) Then this new function is applied to 5 which replaces y, and then the + function is evaluated.

What I was really interested in was, where exactly does it say something like "in the function equation, if you write more than one parameter, it's really syntactic sugar, and the following actually happens..." as I wrote above.
Or is that so obvious to everyone except me?

Edit II:

The real eye-opener answer was in @luqui comment below, unfortunately I don't think I can mark a comment as an answer.

It is the fact that
f x y = ...
is actually syntactic sugar for:
f = \x -> \y -> ...

And for me, everything else everyone below said follows from this.

I found a sort of source for this in the Gentle Introduction to Haskell, here: http://haskell.cs.yale.edu/tutorial/functions.html in section 3.1, called Lambda Abstractions.

In fact, the equations:

inc x                  = x+1
    add x y                = x+y

are really shorthand for:

inc                    = \x   -> x+1
    add                    = \x y -> x+y

While it doesn't use the phrase "syntactic sugar", it uses the more, uh, mathematically oriented word "shorthand", but as a programmer I read this as "sugar" :-)

答:
It is currying. As the type signature says, f takes only one parameter. That would be 4. It then returns a function, which is immediately applied to 5. In fact, these two type signatures:

Int -> Int -> Int

and

Int -> (Int -> Int)

are equivalent in Haskell.

EDIT: this link about Partial Application, which I found inside the page you provided, explains this.

EDIT 2: You asked where the currying behavior of Haskell is defined. I don't know if this is what you're looking for: the Haskell 98 Revised Report, in section 3.3 Curried Applications and Lambda Abstractions, says:

Function application is written e1 e2. Application associates to the left, so the parentheses may be omitted in (f x) y.

Body:
I'm new to Haskell and to functional programming.  I'm reading through Real World Haskell, and I've realized I'm confused by a few examples.

Specifically this is in Chapter 9, in the section "A Domain specific language for predicates", the examples which have the w x y z parameters.

I've boiled it down to this:

Why does this code compile?

f :: Int -> (Int -> Int)
f x y = x+y

main = do
  let q = f 4 5
  putStr  (show (q))

According to the type signature, f is clearly accepting 1 parameter and returning a function.
However, it seems I can write the function equation so it will accept two parameters and return an int.
Why is this possible?  Does this mean the type signature is ignored?

Is this currying?  Is this some kind of closure?
If I understand this http://www.haskell.org/haskellwiki/Currying correctly, then it seems to be somewhat in reverse to currying as defined there - my f function is taking multiple arguments instead of a single one!

Also, can anyone answering please provide a link to some sort of Haskell documentation where this ability is stated (if possible at all).

EDIT:

After thinking about this for some time, what you two seem to be implying is that:

1) This syntax is syntactic sugar, f will always have a single parameter, no matter how many parameters are written in the equation

2) Upon application of f, the function body will (always?) be transformed into a stub (in effect, the returned function), where x is fixed to the parameter given (4), and y is a parameter.

3) Then this new function is applied to 5 which replaces y, and then the + function is evaluated.

What I was really interested in was, where exactly does it say something like "in the function equation, if you write more than one parameter, it's really syntactic sugar, and the following actually happens..." as I wrote above.
Or is that so obvious to everyone except me?

Edit II:

The real eye-opener answer was in @luqui comment below, unfortunately I don't think I can mark a comment as an answer.

It is the fact that
f x y = ...
is actually syntactic sugar for:
f = \x -> \y -> ...

And for me, everything else everyone below said follows from this.

I found a sort of source for this in the Gentle Introduction to Haskell, here: http://haskell.cs.yale.edu/tutorial/functions.html in section 3.1, called Lambda Abstractions.

In fact, the equations:

inc x                  = x+1
    add x y                = x+y

are really shorthand for:

inc                    = \x   -> x+1
    add                    = \x y -> x+y

While it doesn't use the phrase "syntactic sugar", it uses the more, uh, mathematically oriented word "shorthand", but as a programmer I read this as "sugar" :-)


问:
more efficient approximate String matching with MongoDB
I have this relatively large (almost 130000 documents) MongoDB collection of names, that contains a lot of duplicates due to OCR Noise and I'm trying to group these duplicates together using approximate String matching.

I've Implemented this in Java using the Simmetrics library like so:

```<code>DBCursor persons = coll.find(query).addOption(Bytes.QUERYOPTION_NOTIMEOUT);
        try{
            while(persons.hasNext()){
                DBObject p = persons.next();

                DBObject personName = (DBObject) p.get("person");
                String n1 = personName.get("Name").toString();
                System.out.println("\n"+ personName + ":");

                DBCursor aliases = coll.find(query).addOption(Bytes.QUERYOPTION_NOTIMEOUT);
                try{
                    while(aliases.hasNext()){
                        DBObject a = aliases.next();

                        DBObject aliasName = (DBObject) a.get("person");
                        String n2 = aliasName.get("Name").toString();

                        float simLev = new Levenshtein().getSimilarity(n1, n2);

                        if (simLev >= 0.65){
                        System.out.println("    "+ aliasName + ", Sim: " + simLev);
                        }
                    }
                } finally{
                    aliases.close();
                }

            }
        } finally{
            persons.close();
        }
</code>```

So I'm comparing every document with every document using two cursors and (for testing purposes atm) am only printing out matches with a 65% or higher similarity (using Levenshtein distance as an example).

Example output for 1 name:

```<code>{ "Name" : "Baldaino, Manene M."}:
    { "Name" : "Baldaino, Manene M."}, Sim: 1.0
    { "Name" : "Baldaino, Marlene C4."}, Sim: 0.8095238
    { "Name" : "Baldaino Marlene M"}, Sim: 0.78947365
    { "Name" : "BaldainD, Marlene M."}, Sim: 0.85
    { "Name" : "Baldaino Madene M."}, Sim: 0.8947368
    { "Name" : "Baidaino, Marlene M"}, Sim: 0.78947365
    { "Name" : "Baldaino, Marlene M. 0C"}, Sim: 0.7826087
    { "Name" : "Baldaino, Marlene M. (0"}, Sim: 0.7826087
    { "Name" : "8aldaino, Marlene M,"}, Sim: 0.8
    { "Name" : "Baldaino Madene"}, Sim: 0.7368421
    { "Name" : "Baldaino, Marlene 00"}, Sim: 0.8
    { "Name" : "Baldaino, Marlene hi."}, Sim: 0.8095238
    { "Name" : "BaWaino, Marlene M."}, Sim: 0.78947365
    { "Name" : "Baldaino, Marlene M. (3i"}, Sim: 0.75
    { "Name" : "Bedainc, Marlene M."}, Sim: 0.7368421
    { "Name" : "Baldaino, Marlene M. cfl"}, Sim: 0.75
</code>```

this Implementation isn't very efficient though, running it on the whole Collection would I think take at least 40 hours on my PC.

Does anyone know how I could get a better performance?

I've read about using ElasticSearch with Mongo Connector, but would prefer not having to learn to use a new tool just for this.

答:
Currently you are only looking at the person.Name subfield in the document,
but you are loading the entire document from the database - wasting RAM and bandwidth.

Doing this:

```<code>find(query).projection(new Document("person.Name", 1))
</code>```

should speed things up a bit.

Body:
I have this relatively large (almost 130000 documents) MongoDB collection of names, that contains a lot of duplicates due to OCR Noise and I'm trying to group these duplicates together using approximate String matching.

I've Implemented this in Java using the Simmetrics library like so:

DBCursor persons = coll.find(query).addOption(Bytes.QUERYOPTION_NOTIMEOUT);
        try{
            while(persons.hasNext()){
                DBObject p = persons.next();

                DBObject personName = (DBObject) p.get("person");
                String n1 = personName.get("Name").toString();
                System.out.println("\n"+ personName + ":");

                DBCursor aliases = coll.find(query).addOption(Bytes.QUERYOPTION_NOTIMEOUT);
                try{
                    while(aliases.hasNext()){
                        DBObject a = aliases.next();

                        DBObject aliasName = (DBObject) a.get("person");
                        String n2 = aliasName.get("Name").toString();

                        float simLev = new Levenshtein().getSimilarity(n1, n2);

                        if (simLev >= 0.65){
                        System.out.println("    "+ aliasName + ", Sim: " + simLev);
                        }
                    }
                } finally{
                    aliases.close();
                }

            }
        } finally{
            persons.close();
        }

So I'm comparing every document with every document using two cursors and (for testing purposes atm) am only printing out matches with a 65% or higher similarity (using Levenshtein distance as an example).

Example output for 1 name:

{ "Name" : "Baldaino, Manene M."}:
    { "Name" : "Baldaino, Manene M."}, Sim: 1.0
    { "Name" : "Baldaino, Marlene C4."}, Sim: 0.8095238
    { "Name" : "Baldaino Marlene M"}, Sim: 0.78947365
    { "Name" : "BaldainD, Marlene M."}, Sim: 0.85
    { "Name" : "Baldaino Madene M."}, Sim: 0.8947368
    { "Name" : "Baidaino, Marlene M"}, Sim: 0.78947365
    { "Name" : "Baldaino, Marlene M. 0C"}, Sim: 0.7826087
    { "Name" : "Baldaino, Marlene M. (0"}, Sim: 0.7826087
    { "Name" : "8aldaino, Marlene M,"}, Sim: 0.8
    { "Name" : "Baldaino Madene"}, Sim: 0.7368421
    { "Name" : "Baldaino, Marlene 00"}, Sim: 0.8
    { "Name" : "Baldaino, Marlene hi."}, Sim: 0.8095238
    { "Name" : "BaWaino, Marlene M."}, Sim: 0.78947365
    { "Name" : "Baldaino, Marlene M. (3i"}, Sim: 0.75
    { "Name" : "Bedainc, Marlene M."}, Sim: 0.7368421
    { "Name" : "Baldaino, Marlene M. cfl"}, Sim: 0.75

this Implementation isn't very efficient though, running it on the whole Collection would I think take at least 40 hours on my PC.

Does anyone know how I could get a better performance?

I've read about using ElasticSearch with Mongo Connector, but would prefer not having to learn to use a new tool just for this.

Body:
Currently you are only looking at the person.Name subfield in the document,
but you are loading the entire document from the database - wasting RAM and bandwidth.

Doing this:

find(query).projection(new Document("person.Name", 1))

should speed things up a bit.


问:
"File" command error - how to update magic file
I have been using the "file" command in terminal (Mac) for a while.

Now encountering this error:
file: File 5.31 supports only version 14 magic files. `/usr/share/file/magic.mgc' is version 13

Seems like a fairly simple solution to update the magic file, but can't find any instructions to complete this. Can someone advise?

Any help is much appreciated here.

答:
Perhaps you have more than one file executable in your $PATH.  It can get confused if it finds a different database (magic) than it expected.  File 5.29 (tagged October 2016) bumped the format to version 14.  File 5.31 appears to be the current version on MacOS (works for me).

The "magic" file is built up from many smaller files (see git repository (mirror)).  If you needed a specific version that's not prepackaged, you could download the source and compile it, starting with the project page, which points to an ftp site.

However, replacing that magic.mgc file runs into Apple's "system protection" (limited permissions).  It's possible to turn that off (perhaps not a Good Idea®) But it's doable.

While you could replace the data file, it might be simpler to just install MacPorts and use the file package from that.  It's currently at 5.32 (a step ahead of Apple's package), and if you did not like that, it's simpler to remove/alter.


问:
Make a spring-batch job exit with non-zero code if an exception is thrown
I'm trying to fix a spring-batch job which is launched from a shell script. The script then checks the process exit code to determine whether the job has succeeded. Java, however, exits 0 even if the program ended with an exception, unless System.exit was specifically called with a different code, so the script always reports success.

Is there a way to make spring-batch return a non-zero code on failure? To be clear, I'm not talking about the ExitStatus or BatchStatus, but the actual exit code of the java process.

If there's no way to tell spring-batch to return non-zero, can I safely use System.exit in a Tasklet (or a Listener) without interfering with anything that spring-batch does under the hood after an exception?

Failing that, can anyone suggest a way to get the BatchStatus or some other indicator of failure back to the shell script?

答:
I solved this some time ago - apologies that I did not update sooner.

Spring Batch does exit non-zero on an failed job, but there's a subtle catch.

If a job step has no transitions explicitly defined it will by default end the job on success and fail the job on failure (of the step).

If, however, the step has a transition defined for any result (e.g. to the next step on success), there is no default transition for any other result, and if it fails the job won't be properly failed. So you have to explicitly define a "fail on FAILED" transition (typically, for all steps except the last).


问:
I want to test presence of objects in Decision Table
Drools 5 - I want to test for presence of BLueReport object AND SSCData object, and if both are present, then assign some default values.  I've tried a number of conditions, but no luck.

```<code>6-------------------------------------------------------------------------------
 7| CONDITION           | CONDITION           | ACTION                          |
 8| exists BlueReport   | exists SSCData      | sscData.setORIG_LOC_CD($param); |
 9|                     |                     | Set Location Code               |
10|                     |                     | "SLR"                           |
11-------------------------------------------------------------------------------
</code>```

... and I also tried this:

```<code>     6-------------------------------------------------------------------------------
 7| CONDITION           | CONDITION           | ACTION                          |
 8| exists BlueReport   | exists SSCData      | sscData.setORIG_LOC_CD($param); |
 9| eval(true)          | eval(true)          | Set Location Code               |
10|                     |                     | "SLR"                           |
11-------------------------------------------------------------------------------
</code>```

I have a test agent that compiles the Excel DT to a DRL file and it reports this as a result:

```<code>//generated from Decision Table
import mypackage.cost.model.*;
// rule values at A11, header at A6
rule "DIV 07"
    salience 65525
    when
    then
        sscData.setORIG_LOC_CD("SLR");
        sscData.setSERVICE_CD("SLIC");
        sscData.appendRuleAudit(drools.getRule().getName());
end
</code>```

I have arrived at this, but don't know what to put in Row 9:

答: Here is what I came up with for the final solution:

Body:
Drools 5 - I want to test for presence of BLueReport object AND SSCData object, and if both are present, then assign some default values.  I've tried a number of conditions, but no luck.

6-------------------------------------------------------------------------------
 7| CONDITION           | CONDITION           | ACTION                          |
 8| exists BlueReport   | exists SSCData      | sscData.setORIG_LOC_CD($param); |
 9|                     |                     | Set Location Code               |
10|                     |                     | "SLR"                           |
11-------------------------------------------------------------------------------

... and I also tried this:

     6-------------------------------------------------------------------------------
 7| CONDITION           | CONDITION           | ACTION                          |
 8| exists BlueReport   | exists SSCData      | sscData.setORIG_LOC_CD($param); |
 9| eval(true)          | eval(true)          | Set Location Code               |
10|                     |                     | "SLR"                           |
11-------------------------------------------------------------------------------

I have a test agent that compiles the Excel DT to a DRL file and it reports this as a result:

//generated from Decision Table
import mypackage.cost.model.*;
// rule values at A11, header at A6
rule "DIV 07"
    salience 65525
    when
    then
        sscData.setORIG_LOC_CD("SLR");
        sscData.setSERVICE_CD("SLIC");
        sscData.appendRuleAudit(drools.getRule().getName());
end

I have arrived at this, but don't know what to put in Row 9:


问:
using USE and Namespace (composer)in sample php file
I have sample PHP file, i run composer install and got Monolog library.
when I trying their installation guide I get error 500.

When I put the following code in sample file I get error 500 on new Logger row. Maybe I have autoloader? Is it possible to use without it?

```<code>use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

// add records to the log
$log->warning('Foo');
$log->error('Bar');
</code>```

答:
You need to require the autoloader. It will be created by composer.</p>

```<code>require __DIR__ . '/vendor/autoload.php';
</code>```

Body:
I have sample PHP file, i run composer install and got Monolog library.
when I trying their installation guide I get error 500.

When I put the following code in sample file I get error 500 on new Logger row. Maybe I have autoloader? Is it possible to use without it?

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

// add records to the log
$log->warning('Foo');
$log->error('Bar');

Body:
You need to require the autoloader. It will be created by composer.

require __DIR__ . '/vendor/autoload.php';


问:
WebRTC browser-to-browser
I am trying to use WebRTC to implement browser to browser communication.

I want to allow communication between two browsers running on two different computers in the same LAN.

Can somebody confirm is this possible and if so, how.

I tried looking up the demos and seems they all have examples for application running in the same page. But I would like to connect to a peer computer using some IP address.

Regards

答: I have just solved your problem using https://github.com/feross/simple-peer</p>

Title: WebRTC browser-to-browser


问:
How to set subprotocol list for Client (Twisted)

Hey everyone,

I have created a Client and a Server to communicate over websockets. The Twisted library is used for the websockets, and eventually I will be sending GraphQL strings from Client to Server.

However, I am getting an error that states:

failing WebSocket opening handshake ('subprotocol selected by server (graphql-ws) not in subprotocol list requested by client ([])')

Here is the example code that I have created:

server.py

```<code>class MyServerProtocol(WebSocketServerProtocol):

  def onConnect(self, request):
    custom_header = {}
    if request.headers['sec-websocket-key']:
      custom_header['sec-websocket-protocol'] = 'graphql-ws'
    return (None, custom_header)

  def onOpen(self):
    print "Websocket connection open"

  def onMessage(self, payload, isBinary):
    # Handle GraphQL query string here
    try:
      parsed_message = json.loads(payload)
    except Exception as exp:
      logger.error('Could not parse websocket payload', exc_info=True)
      self.sendClose()
      return 1

  def onClose(self, wasClean, code, reason):
    print("WebSocket connection closed: {0}".format(reason))
</code>```

client.py

```<code>class MyClientProtocol(WebSocketClientProtocol):

  def onConnect(self, response):
    response.protocol = 'graphql-ws'

  def onOpen(self):
    print "Websocket connection open"

  def onMessage(self, payload, isBinary):
    if isBinary:
        print("Binary message received: {0} bytes".format(len(payload)))
    else:
        print("Text message received: {0}".format(payload.decode('utf8')))

  def onClose(self, wasClean, code, reason):
    print("WebSocket connection closed: {0}".format(reason))
</code>```

Does anyone know how to set the subprotocol list on the Client side? Any help would be greatly appreciated.

Thanks,

Brian

答: new WebSocket( Url , Protocol[]) second parameter is optional. Check allowed characters in protocol parameter. Second one is string or string[] . Iam not sure if you ask for that.</p>

Body:
Hey everyone,

I have created a Client and a Server to communicate over websockets. The Twisted library is used for the websockets, and eventually I will be sending GraphQL strings from Client to Server.

However, I am getting an error that states:

failing WebSocket opening handshake ('subprotocol selected by server (graphql-ws) not in subprotocol list requested by client ([])')

Here is the example code that I have created:

server.py

class MyServerProtocol(WebSocketServerProtocol):

  def onConnect(self, request):
    custom_header = {}
    if request.headers['sec-websocket-key']:
      custom_header['sec-websocket-protocol'] = 'graphql-ws'
    return (None, custom_header)

  def onOpen(self):
    print "Websocket connection open"

  def onMessage(self, payload, isBinary):
    # Handle GraphQL query string here
    try:
      parsed_message = json.loads(payload)
    except Exception as exp:
      logger.error('Could not parse websocket payload', exc_info=True)
      self.sendClose()
      return 1

  def onClose(self, wasClean, code, reason):
    print("WebSocket connection closed: {0}".format(reason))

client.py

class MyClientProtocol(WebSocketClientProtocol):

  def onConnect(self, response):
    response.protocol = 'graphql-ws'

  def onOpen(self):
    print "Websocket connection open"

  def onMessage(self, payload, isBinary):
    if isBinary:
        print("Binary message received: {0} bytes".format(len(payload)))
    else:
        print("Text message received: {0}".format(payload.decode('utf8')))

  def onClose(self, wasClean, code, reason):
    print("WebSocket connection closed: {0}".format(reason))

Does anyone know how to set the subprotocol list on the Client side? Any help would be greatly appreciated.

Thanks,

Brian


问:
WebClient.UploadValuesAsync not updating progress properly
I have a WebClient which I use to upload a file in the following way, base64Encoded is a picture encoded as a base64 string as that is what the imgur server expects:

```<code>    public Upload()
    {
        WebClient webClient = new WebClient();
        webClient.UploadProgressChanged += new UploadProgressChangedEventHandler(webClient_UploadProgressChanged);
        webClient.UploadValuesCompleted += new UploadValuesCompletedEventHandler(webClient_UploadValuesCompleted);

        NameValueCollection values = new NameValueCollection();
        values.Add("key", "imgur api key");
        values.Add("image", base64Encoded);
        webClient.UploadValuesAsync(new Uri("http://api.imgur.com/2/upload"), "POST", values);
    }
</code>```

This is the event handler for the UploadProgressChanged:

```<code>    private void webClient_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
    {
        int percentage = e.ProgressPercentage * 2;

        progressBar.Value = percentage;
        percentageTextBlock.Text = (percentage).ToString() + "%";
    }
</code>```

Now my problem is that the event handler is only called once right at the start, reports a ProgressPercentage of 50 and is then not being called anymore. The file uploads successfully, but my progressbar is not working. This is not because I'm uploading a small file as I've also tried this with files of several mb which also report a ProgressPercentage of 50 right away. e.BytesSent is no help either because that one is equal to e.TotalBytesToSend right away as well. What is going on here?

答: There was a bug with this event which was fixed in .NET 4.0. And here's a related post.</p>

Body:
I have a WebClient which I use to upload a file in the following way, base64Encoded is a picture encoded as a base64 string as that is what the imgur server expects:

    public Upload()
    {
        WebClient webClient = new WebClient();
        webClient.UploadProgressChanged += new UploadProgressChangedEventHandler(webClient_UploadProgressChanged);
        webClient.UploadValuesCompleted += new UploadValuesCompletedEventHandler(webClient_UploadValuesCompleted);

        NameValueCollection values = new NameValueCollection();
        values.Add("key", "imgur api key");
        values.Add("image", base64Encoded);
        webClient.UploadValuesAsync(new Uri("http://api.imgur.com/2/upload"), "POST", values);
    }

This is the event handler for the UploadProgressChanged:

    private void webClient_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
    {
        int percentage = e.ProgressPercentage * 2;

        progressBar.Value = percentage;
        percentageTextBlock.Text = (percentage).ToString() + "%";
    }

Now my problem is that the event handler is only called once right at the start, reports a ProgressPercentage of 50 and is then not being called anymore. The file uploads successfully, but my progressbar is not working. This is not because I'm uploading a small file as I've also tried this with files of several mb which also report a ProgressPercentage of 50 right away. e.BytesSent is no help either because that one is equal to e.TotalBytesToSend right away as well. What is going on here?