问:
Multidimensional Arrays Nested to Unlimited Depth
I have a multidimensional array nested to an unknown/unlimited depth.
I'd like to be able to loop through every element.
I don't want to use, foreach(){foreach(){foreach(){}}} as I don't know the depth.

I'm eventually looking for all nested arrays called "xyz".  Has anyone got any suggestions?

答:
Have you thought about using array_walk_recursive for this?

Another (slower) approach would be to flatten the array first before performing a search, ie:

```<code>$myarray = array('a','b',array(array(array('x'),'y','z')),array(array('p')));

function array_flatten($array,$return)
{
    for($x = 0; $x <= count($array); $x++)
    {
        if(is_array($array[$x]))
        {
            $return = array_flatten($array[$x],$return);
        }
        else
        {
            if($array[$x])
            {
                $return[] = $array[$x];
            }
        }
    }
    return $return;
}

$res = array_flatten($myarray,array());
</code>```

Or, for a recursive search, see here for an example:

```<code>function arrayRecursiveSearch($needle, $haystack, $path=""){
  if(!is_array($haystack)){
    die("second argument is not array");
  }

  global $matches;

  foreach($haystack as $key=>$value)
  {
    if(preg_match("/$needle/i", $key)){
      $matches[] = array($path . "$key/", "KEY: $key");
    }

    if(is_array($value)){
      $path .= "$key/";
      arrayRecursiveSearch($needle, $value, $path);
      unset($path);
    }else{
      if(preg_match("/$needle/i", $value)){
        $matches[] = array($path . "$key/", "VALUE: $value");
      }
    }
  }

  return $matches;
}

$arr = array("Asia"=>array('rambutan','duku'),
              "Australia"=>array('pear','kiwi'),
              "Arab"=>array('kurma'));

print_r(arrayRecursiveSearch("ra",$arr));
</code>```

Body:
Have you thought about using array_walk_recursive for this?

Another (slower) approach would be to flatten the array first before performing a search, ie:

$myarray = array('a','b',array(array(array('x'),'y','z')),array(array('p')));

function array_flatten($array,$return)
{
    for($x = 0; $x <= count($array); $x++)
    {
        if(is_array($array[$x]))
        {
            $return = array_flatten($array[$x],$return);
        }
        else
        {
            if($array[$x])
            {
                $return[] = $array[$x];
            }
        }
    }
    return $return;
}

$res = array_flatten($myarray,array());

Or, for a recursive search, see here for an example:

function arrayRecursiveSearch($needle, $haystack, $path=""){
  if(!is_array($haystack)){
    die("second argument is not array");
  }

  global $matches;

  foreach($haystack as $key=>$value)
  {
    if(preg_match("/$needle/i", $key)){
      $matches[] = array($path . "$key/", "KEY: $key");
    }

    if(is_array($value)){
      $path .= "$key/";
      arrayRecursiveSearch($needle, $value, $path);
      unset($path);
    }else{
      if(preg_match("/$needle/i", $value)){
        $matches[] = array($path . "$key/", "VALUE: $value");
      }
    }
  }

  return $matches;
}

$arr = array("Asia"=>array('rambutan','duku'),
              "Australia"=>array('pear','kiwi'),
              "Arab"=>array('kurma'));

print_r(arrayRecursiveSearch("ra",$arr));


来源: stackexchange

问:
Calculated fields in Laravel using Query Builder
I've been working in a Laravel Project and I want to know how can I show a calculated field in a blade view? I want to retrieve some information from an invoice and a Total calculated field.

I would like to get this result, but using Eloquent ORM. The query is this:

```<code>SELECT
    invoiceheader.id,
    invoiceheader.customerlastname,
    invoiceheader.customerfirstname,
    invoiceheader.customernit,
    invoicedetail.productid,
    invoicedetail.quantity,
    invoicedetail.saleprice,
    (quantity * saleprice) as Total
FROM invoiceheader
INNER JOIN invoicedetail
    ON invoiceheader.id = invoicedetail.invoiceid
</code>```

Thank you so much in advance.

答:
You can do this by utlizing Eloquent relations and accessors.

In your InvoiceHeader model:

```<code>/*
Relation with the invoicedetail table
 */
public function detail()
{
    return $this->hasOne(InvoiceDetail::class, 'invoiceid', 'id');
}
</code>```

In your InvoiceDetail model:

```<code>/*
The accessor field
 */
protected $appends = ['total_price'];

/*
Accessor for the total price
 */
public function getTotalPriceAttribute()
{
    return $this->quantity * $this->saleprice;
}
</code>```

To understand the created accessor name from the method name, here's a text from the laravel docs:

To define an accessor, create a getFooAttribute method on your model
  where Foo is the "studly" cased name of the column you wish to access.
  In this example, we'll define an accessor for the first_name
  attribute. The accessor will automatically be called by Eloquent when
  attempting to retrieve the value of the first_name attribute:

For your query you could do:

```<code>// get all invoices in descending order of creation
$invoices = InvoiceHeader::recent()->get();

// loop invoice data to get the desired fields
foreach ($invoices as $invoice) {
    $customerfirstname = $invoice->customerfirstname;

    $totalprice = $invoice->detail->total_price;

    // more code
}
</code>```

You can read more about Accessors & Mutators on the official documentation here. Read about eloquent relations here.

ContentLicense: CC BY-SA 3.0

Body:
I've been working in a Laravel Project and I want to know how can I show a calculated field in a blade view? I want to retrieve some information from an invoice and a Total calculated field.

I would like to get this result, but using Eloquent ORM. The query is this:

SELECT
    invoiceheader.id,
    invoiceheader.customerlastname,
    invoiceheader.customerfirstname,
    invoiceheader.customernit,
    invoicedetail.productid,
    invoicedetail.quantity,
    invoicedetail.saleprice,
    (quantity * saleprice) as Total
FROM invoiceheader
INNER JOIN invoicedetail
    ON invoiceheader.id = invoicedetail.invoiceid

Thank you so much in advance.

Body:
You can do this by utlizing Eloquent relations and accessors.

In your InvoiceHeader model:

/*
Relation with the invoicedetail table
 */
public function detail()
{
    return $this->hasOne(InvoiceDetail::class, 'invoiceid', 'id');
}

In your InvoiceDetail model:

/*
The accessor field
 */
protected $appends = ['total_price'];

/*
Accessor for the total price
 */
public function getTotalPriceAttribute()
{
    return $this->quantity * $this->saleprice;
}

To understand the created accessor name from the method name, here's a text from the laravel docs:

To define an accessor, create a getFooAttribute method on your model
  where Foo is the "studly" cased name of the column you wish to access.
  In this example, we'll define an accessor for the first_name
  attribute. The accessor will automatically be called by Eloquent when
  attempting to retrieve the value of the first_name attribute:

For your query you could do:

// get all invoices in descending order of creation
$invoices = InvoiceHeader::recent()->get();

// loop invoice data to get the desired fields
foreach ($invoices as $invoice) {
    $customerfirstname = $invoice->customerfirstname;

    $totalprice = $invoice->detail->total_price;

    // more code
}

You can read more about Accessors & Mutators on the official documentation here. Read about eloquent relations here.


问:
Angular js, how to append html inside div? (using controller)
i'm trying to append inside the div "otherfield", a directive element,

using while loop in the controller, who is binded to html using updateBoxes function:

HTML

```<code><input type="number" min="2" class="form-control" id="numero_campi" ng-model="numerovoices" ng-change="updateBoxes(numerovoices)">

<div id="otherfield"></div>
</code>```

JS

```<code>//DIRECTIVE
app.directive("listDirective", function() {
return {
    restrict:  'E',
    template : "<h1>This will repeated!</h1>"
};

$scope.updateBoxes = function(param){
    var el = document.getElementById('otherfield');
    var i = 0;
    while (i < param) {
        angular.element(el).append('<list-directive></list-directive>');
        i++;
    }
}
</code>```

I'm doing right? it do't work for me...

答:
For binding in Angular 1.x, you can use ng-bind-html for binding string as HTML.

```<code><div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>
</code>```

You can also use $sce service for that.Use $sce.trustAsHtml() in the controller to convert the html string.

```<code>$sce.trustAsHtml('<list-directive></list-directive>')
</code>```

Do check this link for more information

Body:
i'm trying to append inside the div "otherfield", a directive element,

using while loop in the controller, who is binded to html using updateBoxes function:

HTML

<input type="number" min="2" class="form-control" id="numero_campi" ng-model="numerovoices" ng-change="updateBoxes(numerovoices)">

JS

//DIRECTIVE
app.directive("listDirective", function() {
return {
    restrict:  'E',
    template : "
This will repeated!
"
};

$scope.updateBoxes = function(param){
    var el = document.getElementById('otherfield');
    var i = 0;
    while (i < param) {
        angular.element(el).append('<list-directive></list-directive>');
        i++;
    }
}

I'm doing right? it do't work for me...

Body:
For binding in Angular 1.x, you can use ng-bind-html for binding string as HTML.

<div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>

You can also use $sce service for that.Use $sce.trustAsHtml() in the controller to convert the html string.

$sce.trustAsHtml('<list-directive></list-directive>')

Do check this link for more information


问:
Why is dotted line poppinng up in excel?
why is dotted line appearing in excel as in attached picture and how do i remove it ? Also is there any repo where I can refer for excel features ?

答:
It's difficult to tell from your image, but it looks like what you're seeing are page breaks, indicating where your sheet would generate a new page if you printed it.

That is, if you printed your sheet, columns R through Z would print on a separate page from column Q.  I suspect that there is another vertical line somewhere between columns A and Q as well.

You can ignore them; I'm not sure there's a way to get rid of them.  You can, of course, set your own print area -- on recent versions of Excel, it's under "Page Layout" and "Print Area".  You highlight the area you want to print and select "Set Print Area".  (You can also clear it, should you decide to print the entire sheet.)

Hope this helps!


问:
I have installed FIM portal but I am not the administrator
I have installed FIM Portal and the installation is successful. However, I am unable to view Navigation bar and admin controls on the FI</p>

答: Under Sets --> Search for Administrators --> Add your User ID to that set.</p>

ContentLicense: CC BY-SA 2.5


问:
Why is my value nil when i try to read from shared group using UserDefaults (watchOS)
Hi i use a shared group to store a value in that i need to read from my watch but because of some reson, the value is nil.

i made a app group in the developer portal and i enabled and checked the app group in the application and watchkit extension under capabilities.

what else am i forgetting?
can someone help me please?

IOS APP:
MainViewController.swift

```<code>    let defaults = UserDefaults.standard
    defaults.set(newUsername, forKey: "username")
    defaults.set(newCode, forKey: "password")
    defaults.synchronize()

    // when i print  defaults.string(forKey: "username")   here it
       returns me the username
</code>```

Watch Extension InterfaceController.swift

```<code>    let defaults = UserDefaults.standard
    let userName = defaults.string(forKey: "username")!
    let password = defaults.string(forKey: "password")!

    // when i print  defaults.string(forKey: "username")   here it
       returns me nil
</code>```

I also tried to specify the defaults without luck.

```<code>let appGroupID = "group.tld.domain.appname"
if let defaults = UserDefaults(suiteName: appGroupID) {
   defaults.setValue(username, forKey: "username")
   defaults.setValue(password, forKey: "password")
}
</code>```

答: If you needed to share data from iOS app to watch extension then you should use Session. Actually Userdefaults or core data's store data can not pass without session. </p>

Body:
Hi i use a shared group to store a value in that i need to read from my watch but because of some reson, the value is nil.

i made a app group in the developer portal and i enabled and checked the app group in the application and watchkit extension under capabilities.

what else am i forgetting?
can someone help me please?

IOS APP:
MainViewController.swift

    let defaults = UserDefaults.standard
    defaults.set(newUsername, forKey: "username")
    defaults.set(newCode, forKey: "password")
    defaults.synchronize()

    // when i print  defaults.string(forKey: "username")   here it
       returns me the username

Watch Extension InterfaceController.swift

    let defaults = UserDefaults.standard
    let userName = defaults.string(forKey: "username")!
    let password = defaults.string(forKey: "password")!

    // when i print  defaults.string(forKey: "username")   here it
       returns me nil

I also tried to specify the defaults without luck.

let appGroupID = "group.tld.domain.appname"
if let defaults = UserDefaults(suiteName: appGroupID) {
   defaults.setValue(username, forKey: "username")
   defaults.setValue(password, forKey: "password")
}


问:
Buttons not working with onclick and JavaScript
I am trying to make buttons that adds 10, 100, and 1000 to an input and that can clear the input field, but i can't get it to work. I have tried alle the different ways i know to add the script to my document(inline and external) but i can't seem to crack the code. The debug console tells me that The functions is not defined

EDIT:

The problem seems to be that when clicking the buttons the site redirects to the index file

var bet = document.getElementById('coincredits');
var cur = document.getElementById('coincredits').value;
var coins = document.getElementById('coins').value;

function clear() {
 bet.value = "";
}
function ten() {
 bet.value = cur + 10;
}
function hundred() {
 bet.value = cur + 100;
}
function thousand() {
 bet.value = cur + 1000;
}
function xtwo() {
 bet.value = cur * 2;
}
function max() {
 bet.value = coins;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h4>Coins:</h4><p id="coins">123456789</p>

<input type="number" name="coincredits" id="coincredits" required="" parsley-type="text" data-parsley-id="40">

<div>
  <button onclick="clear()">Clear</button>
  <button onclick="ten()">+10</button>
  <button onclick="hundred()">+100</button>
  <button onclick="thousand()">+1000</button>
  <button onclick="xtwo()">x2</button>
  <button onclick="max()">Max</button>
</div></code>```

答:
The issue here is you only set the value of cur when the document loads.

You need to set cur to the new value before running each function.

You also need to parse your value to a number, here its an int

var bet = document.getElementById('coincredits');
var cur = document.getElementById('coincredits').value;
var coins = document.getElementById('coins').value;

function updateCur() {
    var value = parseInt(document.getElementById('coincredits').value)
    if (!value)
        value = 0;
    cur = value;
}

function clear() {
 bet.value = "";
        updateCur();
}
function ten() {
        updateCur();
 bet.value = cur + 10;
}
function hundred() {
        updateCur();
 bet.value = cur + 100;
}
function thousand() {
        updateCur();
 bet.value = cur + 1000;
}
function xtwo() {
        updateCur();
 bet.value = cur * 2;
}
function max() {
        updateCur();
 bet.value = coins;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h4>Coins:</h4><p id="coins">123456789</p>

<input type="number" name="coincredits" id="coincredits" required="" parsley-type="text" data-parsley-id="40">

<div>
  <button onclick="clear()">Clear</button>
  <button onclick="ten()">+10</button>
  <button onclick="hundred()">+100</button>
  <button onclick="thousand()">+1000</button>
  <button onclick="xtwo()">x2</button>
  <button onclick="max()">Max</button>
</div></code>```

Body:
I am trying to make buttons that adds 10, 100, and 1000 to an input and that can clear the input field, but i can't get it to work. I have tried alle the different ways i know to add the script to my document(inline and external) but i can't seem to crack the code. The debug console tells me that The functions is not defined

EDIT:

The problem seems to be that when clicking the buttons the site redirects to the index file

var bet = document.getElementById('coincredits');
var cur = document.getElementById('coincredits').value;
var coins = document.getElementById('coins').value;

function clear() {
 bet.value = "";
}
function ten() {
 bet.value = cur + 10;
}
function hundred() {
 bet.value = cur + 100;
}
function thousand() {
 bet.value = cur + 1000;
}
function xtwo() {
 bet.value = cur * 2;
}
function max() {
 bet.value = coins;
}

Coins:

123456789

<input type="number" name="coincredits" id="coincredits" required="" parsley-type="text" data-parsley-id="40">

  <button onclick="clear()">Clear</button>
  <button onclick="ten()">+10</button>
  <button onclick="hundred()">+100</button>
  <button onclick="thousand()">+1000</button>
  <button onclick="xtwo()">x2</button>
  <button onclick="max()">Max</button>

Body:
The issue here is you only set the value of cur when the document loads.

You need to set cur to the new value before running each function.

You also need to parse your value to a number, here its an int

var bet = document.getElementById('coincredits');
var cur = document.getElementById('coincredits').value;
var coins = document.getElementById('coins').value;

function updateCur() {
    var value = parseInt(document.getElementById('coincredits').value)
    if (!value)
        value = 0;
    cur = value;
}

function clear() {
 bet.value = "";
        updateCur();
}
function ten() {
        updateCur();
 bet.value = cur + 10;
}
function hundred() {
        updateCur();
 bet.value = cur + 100;
}
function thousand() {
        updateCur();
 bet.value = cur + 1000;
}
function xtwo() {
        updateCur();
 bet.value = cur * 2;
}
function max() {
        updateCur();
 bet.value = coins;
}

<h4>Coins:</h4><p id="coins">123456789</p>

<input type="number" name="coincredits" id="coincredits" required="" parsley-type="text" data-parsley-id="40">

<div>
  <button onclick="clear()">Clear</button>
  <button onclick="ten()">+10</button>
  <button onclick="hundred()">+100</button>
  <button onclick="thousand()">+1000</button>
  <button onclick="xtwo()">x2</button>
  <button onclick="max()">Max</button>
</div>


问:
How to trigger a function whenever a mongoose document is updated
I have a user model schema in mongoose which contains a list of friends and groups and stats info like so...

```<code>var user = new Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true, select: false },
  roles: [{ type: String, required: true }],
  friends: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  groups: [{ type: Schema.Types.ObjectId, ref: 'Group' }],
  stats : {
    nbrFriends: { type: Number, required: false },
    nbrGroups: { type: Number, required: false }
  }
}, {
  timestamps: true
});
</code>```

I need to update the users stats whenever a change is made to the friends or groups fields to contain the new number of friends or groups etc. For example, when the following function is called on a user:

```<code>var addGroup = function(user, group, cb) {

  user.groups.push(group);
  User.findOneAndUpdate({ _id: user._id }, { $set: { groups: user.groups }}, { new: true }, function(err, savedResult) {
    if(err) {
      return cb(err);
    }
    console.log('updated user: ' + JSON.stringify(savedResult));
    return cb(null, savedResult);
  });
};
</code>```

How could I make sure the stats is automatically updated to contain the new number of groups the user has? It seems like a middleware function would be the best approach here. I tried the following but this never seems to get called...

```<code>user.pre('save', function(next) {
  var newStats = {
    nbrGroups: this.groups.length,
    nbrPatients: this.friends.length
  };
  this.stats = newStats;
  this.save(function(err, result) {
    if(err) {
      console.log('error saving: ' + err);
    } else {
      console.log('saved');
    }
    next();
  });
});
</code>```

答:
You need to use the middleware a.k.a. hooks:

Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions.

See the docs:

http://mongoosejs.com/docs/middleware.html

Body:
I have a user model schema in mongoose which contains a list of friends and groups and stats info like so...

var user = new Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true, select: false },
  roles: [{ type: String, required: true }],
  friends: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  groups: [{ type: Schema.Types.ObjectId, ref: 'Group' }],
  stats : {
    nbrFriends: { type: Number, required: false },
    nbrGroups: { type: Number, required: false }
  }
}, {
  timestamps: true
});

I need to update the users stats whenever a change is made to the friends or groups fields to contain the new number of friends or groups etc. For example, when the following function is called on a user:

var addGroup = function(user, group, cb) {

  user.groups.push(group);
  User.findOneAndUpdate({ _id: user._id }, { $set: { groups: user.groups }}, { new: true }, function(err, savedResult) {
    if(err) {
      return cb(err);
    }
    console.log('updated user: ' + JSON.stringify(savedResult));
    return cb(null, savedResult);
  });
};

How could I make sure the stats is automatically updated to contain the new number of groups the user has? It seems like a middleware function would be the best approach here. I tried the following but this never seems to get called...

user.pre('save', function(next) {
  var newStats = {
    nbrGroups: this.groups.length,
    nbrPatients: this.friends.length
  };
  this.stats = newStats;
  this.save(function(err, result) {
    if(err) {
      console.log('error saving: ' + err);
    } else {
      console.log('saved');
    }
    next();
  });
});


问:
Is it possible to sort in a JSP?
Is there any way to sort alphabetically two strings variables in a JSP, for example by using jstl? Or at least determinate which string would be first alphabetically?

I have been trying with a code like this one. It seems to work with some simple examples, but I'm not sure that it is considering alphabetical order. Can anyone confirm whether "gt" operator takes alphabetical order when the variable is not a number?

```<code><c:set value="abc" var="var1"/>
<c:set value="def" var="var2"/>
<c:if test="${var2 gt var1}">
    <p>var1 is first</p>
</c:if>
<c:if test="${var1 gt var2}">
    <p>var2 is first</p>
</c:if>
</code>```

Thanks

答:
Regarding the part of your question about doing the EL operators on Strings, the example at http://java.sun.com/products/jsp/syntax/2.0/syntaxref207.html and some practical tests confirm that gt takes alphabetical precedence on Strings.

In your example def > abc will be true, since d > a

Title: Is it possible to sort in a JSP?

Body:
Is there any way to sort alphabetically two strings variables in a JSP, for example by using jstl? Or at least determinate which string would be first alphabetically?

I have been trying with a code like this one. It seems to work with some simple examples, but I'm not sure that it is considering alphabetical order. Can anyone confirm whether "gt" operator takes alphabetical order when the variable is not a number?

<c:set value="abc" var="var1"/>
<c:set value="def" var="var2"/>
<c:if test="${var2 gt var1}">

var1 is first

</c:if>
<c:if test="${var1 gt var2}">

var2 is first

</c:if>

Thanks


答:
If you insist regex... here it is.

```<code>.*?\=.*?(?:&|$)
</code>```

It captures 24 groups. And

```<code>len(input.split('&'))
</code>```

is 24 too.

Title: Why won't my regex parse this http request correctly?

Body:
I have the following http request payload.

X-gmsv=9879480&X-subtype=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&X-X-subscription=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&X-gcm.topic=%2Ftopics%2Fphenotype_com.google.android.gms.icing%25servingVersion&X-X-subtype=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&X-app_ver=9879480&X-kid=%7CID%7C7%7C&X-osv=25&X-sig=vWteecmhHl5q2AsrHaGcOOgaF956SpVk6KAdjijNyeX1uADvPgpgvMkNH-Nu-N8IHc-1Z1ujTytjkQDPZot4zjf_FLSjR0ucPIkFXkZhrRi5RU6uFq-ZlQCEBSPpYuHsx27lC5H3xv-TNe_zC0PaX8h8bTqrImtArVSZjMY6-RFG9TUEj2VkCvs1ixAK21vHxE4ladiXALZO-lhZIvbDIGkY4c-fUMaMBN8EhMr1zH31N41S6cUItkPRe0lTOB4YddkrS2FNRI_LZGfW-cc9h9om-80MskZD0IyJtM4AFsumHxVIQQJwSScASSoFd7e7tANTp5ZPJi2hwr6wQqpveQ&X-cliv=iid-9879000&X-gmsv=9879480&X-pub2=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA9VWXXfudfnoAAl-u_RbBClmI6uvaOH8AFEMvjrtOpL1FuLrUYQzdntRwlMyiL4Nba7WUGeb6CrkEAbwTFcR689QYQ87ytkyY65rD2InSUD3eMLWpiaTciFj-n5sUK6hyci5Je5T8Svgsb-VHSy6vWVKQZ4vGsiGqmkj8sDhCa1UbltWOyhywfG95ENiGKuO_ec55Rmvrew9tFNGIit7FzcNiEAmfSrkEifK6dydjnpahu3lAx4U_MTw5Yo0ou5EGrsByXY2P_tkWg78hq1E_SQORk7q7droAY_wupXHlqSwGCAfbGtRs2gXM-64MSZ1iQX7N7pPojkT4akomcyP2JQIDAQAB&X-X-kid=%7CID%7C7%7C&X-appid=cIIP-1V_bTg&X-scope=%2Ftopics%2Fphenotype_com.google.android.gms.icing%25servingVersion&X-subscription=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&X-app_ver_name=9.8.79+%28480-137224771%29&app=com.google.android.gms&sender=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&device=4374365252386389758&cert=58e1c4133f7441ec3d2c270270a14802da47ba0e&app_ver=9879480&info=AoehgPKryS4XzDpwLBRWN3IuplGtswI&gcm_ver=987948

I want to pull out all the pairs of <key>=<value>.  For example the first key value pair is X-gmsv=9879480.

The best regex I have come up with is .*?\=.*?& but it get's everything but the last key value pair because there is no ampersand at the end of the last variable.  So I tried .*?\=.*?[&|$] which in theory should either match a key value pair ending with an ampersand or the end of the string.

It doesn't get the last string.  I've played around with a couple other regexes and can't figure out what's going on.

Any ideas?

Body:
If you insist regex... here it is.

.*?\=.*?(?:&|$)

It captures 24 groups. And

len(input.split('&'))

is 24 too.


问:
Run exe with custom arguments using powershell
I need to run(install) an exe which takes some custom parameter (arguments)

```<code>install.exe --no-prompt -u username -p password
</code>```

The above command is provided by the 3rd party team to allow silent installation of the agent

Since I am trying to install this via powershell, I want to know how to pass the custom parameters.

Note: This exe is a 3rd party component. I can run command to install an exe with credentials object. But the same is not working in this case.

答:
Executables can be run in PowerShell. Try:

```<code>& install.exe --no-prompt -u username -p password
</code>```

It might require giving a full path to the executable.

```<code>& C:\Users\me\Downloads\newapp\install.exe --no-prompt -u username -p password
</code>```

If this does not do it, be sure to copy and paste any messages into the question.

Body:
I need to run(install) an exe which takes some custom parameter (arguments)

install.exe --no-prompt -u username -p password

The above command is provided by the 3rd party team to allow silent installation of the agent

Since I am trying to install this via powershell, I want to know how to pass the custom parameters.

Note: This exe is a 3rd party component. I can run command to install an exe with credentials object. But the same is not working in this case.

Body:
Executables can be run in PowerShell. Try:

& install.exe --no-prompt -u username -p password

It might require giving a full path to the executable.

& C:\Users\me\Downloads\newapp\install.exe --no-prompt -u username -p password

If this does not do it, be sure to copy and paste any messages into the question.


问:
How to create multiple instances to an implementation of an interface?
Let A be an interface which has a method a.
Let B be a class which implements A and has method a and has three fields 1,2,3.
I want to use two instances of A (meaning B), both of which have different values of 1,2,3 (present in cfg file) at two different places.  </p>

<p>Can someone provide a simple and elegant solution to this problem using Guice. </p>

答:
if I do understand you correctly, you might want to make B abstract so that you can override the methods which you want to change, if this is the case.

Now I can only assume that by fields you mean field-varriables. I would then recommend you to make them NON-static and change them in the constructor when you make an object. Then read the values of 1,2,3 in the public static void main method and send them upon creating a new object:

```<code>public class B implements A {
    private int x,y,z;

    /**
    * This would now be the constructror
    */
    public B(int x, int y, int z){
        this.x = x;
        this.y = y;
        this.z = z;
    }

    /**
    * Then some return functions
    */
    public get1() { return this.x; }
    public get2() { return this.y; }
    public get3() { return this.z; }

    /**
    * Then whatever methods you get from A
    */
    public int someMethodFromA(int x, int y){
        return x*y;
    }
}

public static void main(String[] args) {
    /**
    * Some random method to read inn from CFG file
    */

    int x1 = readXFromCFG();
    int y1 = readYFromCFG();
    int z1 = readZFromCFG();

    B objectB1 = new B(x1,y1,z1);

    int x2 = readXFromCFG();
    int y2 = readYFromCFG();
    int z2 = readZFromCFG();

    B objectB2 = new B(x2,y2,z2);

    int x3 = readXFromCFG();
    int y3 = readYFromCFG();
    int z3 = readZFromCFG();

    B objectB3 = new B(x3,y3,z3);
}
</code>```

Body:
Let A be an interface which has a method a.
Let B be a class which implements A and has method a and has three fields 1,2,3.
I want to use two instances of A (meaning B), both of which have different values of 1,2,3 (present in cfg file) at two different places.

Can someone provide a simple and elegant solution to this problem using Guice.

Body:
if I do understand you correctly, you might want to make B abstract so that you can override the methods which you want to change, if this is the case.

Now I can only assume that by fields you mean field-varriables. I would then recommend you to make them NON-static and change them in the constructor when you make an object. Then read the values of 1,2,3 in the public static void main method and send them upon creating a new object:

public class B implements A {
    private int x,y,z;

    /**
    * This would now be the constructror
    */
    public B(int x, int y, int z){
        this.x = x;
        this.y = y;
        this.z = z;
    }

    /**
    * Then some return functions
    */
    public get1() { return this.x; }
    public get2() { return this.y; }
    public get3() { return this.z; }

    /**
    * Then whatever methods you get from A
    */
    public int someMethodFromA(int x, int y){
        return x*y;
    }
}

public static void main(String[] args) {
    /**
    * Some random method to read inn from CFG file
    */

    int x1 = readXFromCFG();
    int y1 = readYFromCFG();
    int z1 = readZFromCFG();

    B objectB1 = new B(x1,y1,z1);

    int x2 = readXFromCFG();
    int y2 = readYFromCFG();
    int z2 = readZFromCFG();

    B objectB2 = new B(x2,y2,z2);

    int x3 = readXFromCFG();
    int y3 = readYFromCFG();
    int z3 = readZFromCFG();

    B objectB3 = new B(x3,y3,z3);
}


问:
Scala HTTPS post including JSON input and output along with authentication
I cannot find a single example of Scala HTTPS post including JSON input and output along with authentication.  I can't even find such an example in Java.  I can do this easily in Python:

```<code>def main(user_name, password):
    headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}

    eta_data = """{
      "contact": {
        "longitude": "-151.7200",
        "latitude": "-16.4400",
        "timestamp": "2016-04-22 15:14:55",
        "speedKnots": "15.4"
      },
      "destination": {
        "longitude": "-149.869722",
        "latitude": "-17.491667"
      }
    }"""

    r = requests.post('https://www4.demo.exactearth.com/eta', data=eta_data, auth=(user_name, password), headers=headers)
    print()
    print("eta:")
    print(r.text)
    print(r.json())
</code>```

I'm not asking anyone to translate this to Scala for me, but how hard can this be?  Can someone please point me to an up-to-date Scala book that covers this?  Scala HTTPS post AND JSON input AND JSON output AND simple username/password authentication

答:
Examples of POST, HTTPS, JSON input/output, and Basic Authentication in Scala can be found in the Akka HTTP docs for example here:

http://doc.akka.io/docs/akka-http/current/scala/http/client-side/host-level.html

and here:

http://doc.akka.io/docs/akka-http/current/scala/http/client-side/websocket-support.html

Body:
I cannot find a single example of Scala HTTPS post including JSON input and output along with authentication.  I can't even find such an example in Java.  I can do this easily in Python:

def main(user_name, password):
    headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}

    eta_data = """{
      "contact": {
        "longitude": "-151.7200",
        "latitude": "-16.4400",
        "timestamp": "2016-04-22 15:14:55",
        "speedKnots": "15.4"
      },
      "destination": {
        "longitude": "-149.869722",
        "latitude": "-17.491667"
      }
    }"""

    r = requests.post('https://www4.demo.exactearth.com/eta', data=eta_data, auth=(user_name, password), headers=headers)
    print()
    print("eta:")
    print(r.text)
    print(r.json())

I'm not asking anyone to translate this to Scala for me, but how hard can this be?  Can someone please point me to an up-to-date Scala book that covers this?  Scala HTTPS post AND JSON input AND JSON output AND simple username/password authentication


问:
Is there a way to escape and use reserved words in TypeScript class definitions?
Here's a simple example of what I'd like to do:

```<code>export class UserInfoPrivate {
    constructor(
        public repEmail: string,
        public repPhone: string,
        public agreedToTnC: boolean
    ) { }
}

export class UserInfo {
    constructor(
        public $uid: string,
        public orgApproved: false,
        public private: UserInfoPrivate, // <-- private is a reserved word
        public open: UserInfoOpen,
    ) { }
}
</code>```

Since the datebase is a NoSQL (Firebase) and returns simple JSON structured objects, and I have a node under users called "private" I'd like to just map my class directly to it without extra parsing. Is there a way to use a reserved word such as "private" in a class definition or do I have to go change the node?

My research thus far seems to point to no but I have a hard time accepting that this just isn't possible.

答:
You can always put property names (in classes or object literals) in quotes - and for those that are not valid identifier names, you need to. You can access them using bracket notation then.

```<code>export class UserInfo {
    public "private": UserInfoPrivate
    constructor(
        public $uid: string,
        public orgApproved: false,
        privateParam: UserInfoPrivate,
        public open: UserInfoOpen,
    ) {
        this.private = privateParam;
    }
}
</code>```

(I hope that looks like valid Typescript not only to my eye but also the compiler)

Body:
Here's a simple example of what I'd like to do:

export class UserInfoPrivate {
    constructor(
        public repEmail: string,
        public repPhone: string,
        public agreedToTnC: boolean
    ) { }
}

export class UserInfo {
    constructor(
        public $uid: string,
        public orgApproved: false,
        public private: UserInfoPrivate, // <-- private is a reserved word
        public open: UserInfoOpen,
    ) { }
}

Since the datebase is a NoSQL (Firebase) and returns simple JSON structured objects, and I have a node under users called "private" I'd like to just map my class directly to it without extra parsing. Is there a way to use a reserved word such as "private" in a class definition or do I have to go change the node?

My research thus far seems to point to no but I have a hard time accepting that this just isn't possible.

Body:
You can always put property names (in classes or object literals) in quotes - and for those that are not valid identifier names, you need to. You can access them using bracket notation then.

export class UserInfo {
    public "private": UserInfoPrivate
    constructor(
        public $uid: string,
        public orgApproved: false,
        privateParam: UserInfoPrivate,
        public open: UserInfoOpen,
    ) {
        this.private = privateParam;
    }
}

(I hope that looks like valid Typescript not only to my eye but also the compiler)


问:
iPhone, error: object cannot be set - either readonly property or no setter found
I know there's another question like this on stack overflow, but my problem is from my own class not a UIButton. My method is a lot more complicated. The first commented line works.

```<code>@implementation GettingStartedViewController
- (void)actionSheet:(UIActionSheet *)actionSheet
  clickedButtonAtIndex:(NSInteger)buttonIndex {

//[cui showHelpClickButtonAtIndex:buttonIndex:self.view:
  //theController:FALSE:HelpPageGettingStarted];

  // Error from this next line error: object cannot be set - either
  //readonly property or no setter found
  self.theController = [cui showHelpClickButtonAtIndex:buttonIndex:
      self.view:theController:FALSE:HelpPageGettingStarted];
}
- (void)viewDidLoad {
   [super viewDidLoad];
cui = [CommonUI alloc]; // Used for several functions
}
</code>```

And heres the function it calls. I've trying to reuse code and keep things in one function. the function uses addSubView and presentModalViewController.

```<code>@implementation CommonUI
-(UIViewController *)showHelpClickButtonAtIndex:(int)buttonIndex:
  (UIView *)vw:(UIViewController *)vc:(BOOL)useNav:(HelpPage)page{

  if (buttonIndex == CommonUIInfoHelpPagesBtnIdx) {
    if (useNav == TRUE) {
        // snip
    } else {
        vc = [[HelpViewController alloc] initWithNibName:@"HelpView"
             bundle:nil onPage:page];
        [vw addSubview:vc.view];
        return [vc autorelease];
    }
  } else {
    // Snip
  }
// Snip
}
</code>```

答:
The message says that there is no property for theController in GettingStartedViewController. Your method call works just fine.

self.theController = someObject is the same as calling the setter method: [self setTheController:someObject]

Properties automatically generate those getters and setters; so if you did not define a property, it is not going to create a setter and this is your problem here.

Add the following to your header file:

```<code>@property (nonatomic, retain) UIViewController* theController;
</code>```

And synthesize it in your implementation file:

```<code>@synthesize theController;
</code>```

Do not forget to release it in the -dealloc method, as you told the setter to retain the object:

```<code>-(void) dealloc {
    [theController release];
    theController = nil;
}
</code>```

Body:
I know there's another question like this on stack overflow, but my problem is from my own class not a UIButton. My method is a lot more complicated. The first commented line works.

@implementation GettingStartedViewController
- (void)actionSheet:(UIActionSheet *)actionSheet
  clickedButtonAtIndex:(NSInteger)buttonIndex {

//[cui showHelpClickButtonAtIndex:buttonIndex:self.view:
  //theController:FALSE:HelpPageGettingStarted];

  // Error from this next line error: object cannot be set - either
  //readonly property or no setter found
  self.theController = [cui showHelpClickButtonAtIndex:buttonIndex:
      self.view:theController:FALSE:HelpPageGettingStarted];
}
- (void)viewDidLoad {
   [super viewDidLoad];
cui = [CommonUI alloc]; // Used for several functions
}

And heres the function it calls. I've trying to reuse code and keep things in one function. the function uses addSubView and presentModalViewController.

@implementation CommonUI
-(UIViewController *)showHelpClickButtonAtIndex:(int)buttonIndex:
  (UIView *)vw:(UIViewController *)vc:(BOOL)useNav:(HelpPage)page{

  if (buttonIndex == CommonUIInfoHelpPagesBtnIdx) {
    if (useNav == TRUE) {
        // snip
    } else {
        vc = [[HelpViewController alloc] initWithNibName:@"HelpView"
             bundle:nil onPage:page];
        [vw addSubview:vc.view];
        return [vc autorelease];
    }
  } else {
    // Snip
  }
// Snip
}

Body:
The message says that there is no property for theController in GettingStartedViewController. Your method call works just fine.

self.theController = someObject is the same as calling the setter method: [self setTheController:someObject]

Properties automatically generate those getters and setters; so if you did not define a property, it is not going to create a setter and this is your problem here.

Add the following to your header file:

@property (nonatomic, retain) UIViewController* theController;

And synthesize it in your implementation file:

@synthesize theController;

Do not forget to release it in the -dealloc method, as you told the setter to retain the object:

-(void) dealloc {
    [theController release];
    theController = nil;
}


问:
array to string conversion in laravel
I am trying to fetch some data from table in laravel 5.0 like so

```<code>public function index()
    {
        $data = DB::table('modules')->get();

        return view("BaseView.home")->with('data',$data);
    }
</code>```

this is my view

```<code> @foreach($data as $modules)
    <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            {{ $modules->module_name }}<i class="plusMinus fa fa-plus-square plusMinusSpacing" aria-hidden="true"></i>
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
            {!! $moduleCategories = DB::table('module_categories')->where('modules_id','=',$modules->id)->get() !!}
            @foreach($moduleCategories as $category)
            <a class="dropdown-item" href="#">{{ $category->categories_name }}</a>
            @endforeach
        </div>
    </li>
    @endforeach
</code>```

$module->id is obtained from another query result. Now when I try to run this I am getting Array to string conversion. Can someone point out the mistake. The expected output is > 1 in the sense there can be multiple categories names matching that condition.

答:
The problem is that you are trying to put php logic inside an echo {{ ... }}. You are trying to echo out a collection or an array of data, hence the error you are getting, Array to string conversion. The proper way to do this is to do the logic in the controller. But for a quick fix, replace:

```<code>{!! $moduleCategories = DB::table('module_categories')->where('modules_id','=',$modules->id)->get() !!}
</code>```

to

```<code><php $moduleCategories = DB::table('module_categories')->where('modules_id','=',$modules->id)->get(); ?>
</code>```

Never use {{ ... }} or {!! ... !!} to put logic, those are to echo out a string.

==EDIT==

I suggest to use laravels eloquent relationship methods, this will simplify the code, and seperate the logic from the view.

Note: Expecting if you are using laravel naming convention.

On your Modules model, add a relationship to ModuleCategory like so:

```<code>public function module_categories()
{
    return $this->hasMany('App\ModuleCategory');
}
</code>```

On your controller, on the index method replace :

```<code>$data = DB::table('modules')->get();
</code>```

with

```<code>$data = Modules::get();
</code>```

and finally on the view, change it like so:

```<code>@foreach($data as $modules)
<li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        {{ $modules->module_name }}<i class="plusMinus fa fa-plus-square plusMinusSpacing" aria-hidden="true"></i>
    </a>
    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
        @foreach($modules->module_categories as $category)
        <a class="dropdown-item" href="#">{{ $category->categories_name }}</a>
        @endforeach
    </div>
</li>
@endforeach
</code>```

Title: array to string conversion in laravel

Body:
I am trying to fetch some data from table in laravel 5.0 like so

public function index()
    {
        $data = DB::table('modules')->get();

        return view("BaseView.home")->with('data',$data);
    }

this is my view

 @foreach($data as $modules)

            {{ $modules->module_name }}

            {!! $moduleCategories = DB::table('module_categories')->where('modules_id','=',$modules->id)->get() !!}
            @foreach($moduleCategories as $category)
            {{ $category->categories_name }}
            @endforeach

    @endforeach

$module->id is obtained from another query result. Now when I try to run this I am getting Array to string conversion. Can someone point out the mistake. The expected output is > 1 in the sense there can be multiple categories names matching that condition.

Body:
The problem is that you are trying to put php logic inside an echo {{ ... }}. You are trying to echo out a collection or an array of data, hence the error you are getting, Array to string conversion. The proper way to do this is to do the logic in the controller. But for a quick fix, replace:

{!! $moduleCategories = DB::table('module_categories')->where('modules_id','=',$modules->id)->get() !!}

to

<php $moduleCategories = DB::table('module_categories')->where('modules_id','=',$modules->id)->get(); ?>

Never use {{ ... }} or {!! ... !!} to put logic, those are to echo out a string.

==EDIT==

I suggest to use laravels eloquent relationship methods, this will simplify the code, and seperate the logic from the view.

Note: Expecting if you are using laravel naming convention.

On your Modules model, add a relationship to ModuleCategory like so:

public function module_categories()
{
    return $this->hasMany('App\ModuleCategory');
}

On your controller, on the index method replace :

$data = DB::table('modules')->get();

with

$data = Modules::get();

and finally on the view, change it like so:

@foreach($data as $modules)
<li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        {{ $modules->module_name }}<i class="plusMinus fa fa-plus-square plusMinusSpacing" aria-hidden="true"></i>
    </a>
    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
        @foreach($modules->module_categories as $category)
        <a class="dropdown-item" href="#">{{ $category->categories_name }}</a>
        @endforeach
    </div>
</li>
@endforeach


答:
1) put console.log('test') in the 1-st line of your javascript code, maybe it doesn't loads

2) when browser renders and binds your html code maybe he doesn't know anything about this functions

3) your javascript maybe doesn't see any html elements in the document when it implement's in this case you should wrap all your js code into $(function(){  ..... })  - it will start your js code only after DOM will be ready

Title: Buttons not working with onclick and JavaScript

Body:
I am trying to make buttons that adds 10, 100, and 1000 to an input and that can clear the input field, but i can't get it to work. I have tried alle the different ways i know to add the script to my document(inline and external) but i can't seem to crack the code. The debug console tells me that The functions is not defined

EDIT:

The problem seems to be that when clicking the buttons the site redirects to the index file

var bet = document.getElementById('coincredits');
var cur = document.getElementById('coincredits').value;
var coins = document.getElementById('coins').value;

function clear() {
 bet.value = "";
}
function ten() {
 bet.value = cur + 10;
}
function hundred() {
 bet.value = cur + 100;
}
function thousand() {
 bet.value = cur + 1000;
}
function xtwo() {
 bet.value = cur * 2;
}
function max() {
 bet.value = coins;
}

Coins:

123456789

<input type="number" name="coincredits" id="coincredits" required="" parsley-type="text" data-parsley-id="40">

  <button onclick="clear()">Clear</button>
  <button onclick="ten()">+10</button>
  <button onclick="hundred()">+100</button>
  <button onclick="thousand()">+1000</button>
  <button onclick="xtwo()">x2</button>
  <button onclick="max()">Max</button>


问:
Unable to map JSON response to a predefined class in C# / dynamic property name
I have a class which basically contains a property like this:

```<code>public class Msg
{
    [JsonProperty(PropertyName = "XD1703301059485299")]
    public Shipping shipping { get; set; }
}
</code>```

the problem is in this part:

```<code> [JsonProperty(PropertyName = "XD1703301059485299")]
</code>```

And the dynamic property name that I get from server...

This property name can be any name that server returns. In this particular case it's able to map the JSON to my class since the property names are same... But when server returns something like this:

```<code>XS12394124912841
</code>```

The object is the null....

How can I resolve property name to be dynamic ? Can someone help me out?

P.S. This is the JSON response itself:

```<code>{"status":1,"msg":{"dynamic_name":{"order_sn":"12312313123123123","order_status":"0","shipping_info":[{"shipping_name":"","shipping_no":"","shipping_img":"","shipping_code":"","shipping_time":"","track_goods":""}]}},"errcode":0}
</code>```

答:
So I don't think this problem is as dynamic as it sounds. You can probably just convert to a dyanmic object and explicitly handle conversions.

Sample solution below. I inserted a few values to show conversion works as expected.

Add nuget package Newtonsoft.Json

```<code>using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace Serialize
{
    public class Shipping
    {
        [JsonProperty(PropertyName = "shipping_name")]
        public String Name { get; set; }

        [JsonProperty(PropertyName = "shipping_img")]
        public String Img { get; set; }

        [JsonProperty(PropertyName = "shipping_code")]
        public String Code { get; set; }
    }

    public class Order
    {
        public Shipping shipping { get; set; }

        [JsonProperty(PropertyName = "order_sn")]
        public string SerialNumber { get; set; }

        [JsonProperty(PropertyName = "order_status")]
        public string Status { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            /*
             {
             "status":1,
             "msg": {
                 "dynamic_name": {
                     "order_sn": "12312313123123123",
                     "order_status":"0",
                     "shipping_info": [{
                         "shipping_name":"name",
                         "shipping_no":"",
                         "shipping_img":"img",
                         "shipping_code":"code",
                         "shipping_time":"",
                         "track_goods":""
                     }]
                 }
             },
             "errcode":0
             }
             * */
            var raw = "{ \"status\":1, \"msg\":{\"dynamic_name\":{\"order_sn\":\"12312313123123123\",\"order_status\":\"0\",\"shipping_info\":[{\"shipping_name\":\"name\",\"shipping_no\":\"\",\"shipping_img\":\"img\",\"shipping_code\":\"code\",\"shipping_time\":\"\",\"track_goods\":\"\"}]}},\"errcode\":0}";

            var incomingOrder = new Order();

            // properties on dynamic objects are evaluated at runtime
            dynamic msgJson = JObject.Parse(raw);

            // you'll want exception handling around all of this
            var order = msgJson.msg.dynamic_name;

            // accessing properties is easy (if they exist, as these do)
            incomingOrder.SerialNumber = order.order_sn;
            incomingOrder.Status = order.order_status;

            // JObject cast might not be necessary. need to check for array elements, etc.
            // but it's simple to serialize into a known type
            incomingOrder.shipping = ((JObject)(order.shipping_info[0])).ToObject<Shipping>();

        }
    }
}
</code>```

Alternatively, if the property name is given at runtime, you can dereference properties with the indexer getter

```<code>        dynamic msgJson = JObject.Parse(raw);

        JObject order = msgJson.msg["XS12394124912841"];

        incomingOrder.SerialNumber = order["order_sn"].ToObject<string>();
        incomingOrder.Status = order["order_status"].ToObject<string>();
        incomingOrder.shipping = order["shipping_info"][0].ToObject<Shipping>();
</code>```

Body:
I have a class which basically contains a property like this:

public class Msg
{
    [JsonProperty(PropertyName = "XD1703301059485299")]
    public Shipping shipping { get; set; }
}

the problem is in this part:

 [JsonProperty(PropertyName = "XD1703301059485299")]

And the dynamic property name that I get from server...

This property name can be any name that server returns. In this particular case it's able to map the JSON to my class since the property names are same... But when server returns something like this:

XS12394124912841

The object is the null....

How can I resolve property name to be dynamic ? Can someone help me out?

P.S. This is the JSON response itself:

{"status":1,"msg":{"dynamic_name":{"order_sn":"12312313123123123","order_status":"0","shipping_info":[{"shipping_name":"","shipping_no":"","shipping_img":"","shipping_code":"","shipping_time":"","track_goods":""}]}},"errcode":0}

Body:
So I don't think this problem is as dynamic as it sounds. You can probably just convert to a dyanmic object and explicitly handle conversions.

Sample solution below. I inserted a few values to show conversion works as expected.

Add nuget package Newtonsoft.Json

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace Serialize
{
    public class Shipping
    {
        [JsonProperty(PropertyName = "shipping_name")]
        public String Name { get; set; }

        [JsonProperty(PropertyName = "shipping_img")]
        public String Img { get; set; }

        [JsonProperty(PropertyName = "shipping_code")]
        public String Code { get; set; }
    }

    public class Order
    {
        public Shipping shipping { get; set; }

        [JsonProperty(PropertyName = "order_sn")]
        public string SerialNumber { get; set; }

        [JsonProperty(PropertyName = "order_status")]
        public string Status { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            /*
             {
             "status":1,
             "msg": {
                 "dynamic_name": {
                     "order_sn": "12312313123123123",
                     "order_status":"0",
                     "shipping_info": [{
                         "shipping_name":"name",
                         "shipping_no":"",
                         "shipping_img":"img",
                         "shipping_code":"code",
                         "shipping_time":"",
                         "track_goods":""
                     }]
                 }
             },
             "errcode":0
             }
             * */
            var raw = "{ \"status\":1, \"msg\":{\"dynamic_name\":{\"order_sn\":\"12312313123123123\",\"order_status\":\"0\",\"shipping_info\":[{\"shipping_name\":\"name\",\"shipping_no\":\"\",\"shipping_img\":\"img\",\"shipping_code\":\"code\",\"shipping_time\":\"\",\"track_goods\":\"\"}]}},\"errcode\":0}";

            var incomingOrder = new Order();

            // properties on dynamic objects are evaluated at runtime
            dynamic msgJson = JObject.Parse(raw);

            // you'll want exception handling around all of this
            var order = msgJson.msg.dynamic_name;

            // accessing properties is easy (if they exist, as these do)
            incomingOrder.SerialNumber = order.order_sn;
            incomingOrder.Status = order.order_status;

            // JObject cast might not be necessary. need to check for array elements, etc.
            // but it's simple to serialize into a known type
            incomingOrder.shipping = ((JObject)(order.shipping_info[0])).ToObject<Shipping>();

        }
    }
}

Alternatively, if the property name is given at runtime, you can dereference properties with the indexer getter

        dynamic msgJson = JObject.Parse(raw);

        JObject order = msgJson.msg["XS12394124912841"];

        incomingOrder.SerialNumber = order["order_sn"].ToObject<string>();
        incomingOrder.Status = order["order_status"].ToObject<string>();
        incomingOrder.shipping = order["shipping_info"][0].ToObject<Shipping>();


问:
ArgumentCaptor for generic method in Mockito
I have an object that I've mocked. This object has the following method:

```<code><R, M extends SomeAbstractClass<R>> List<R> execute(List<M> list)
</code>```

And there are two calls for this method:

```<code>execute(List<A>);
execute(List<B>);
</code>```

where class A extends SomeAbstractClass<String> and B extends SomeAbstractClass<Void>.

Is there any way to use ArgumentCaptor for this case?
I want to do something like this:

```<code>verify(..., times(3)).execute(argumentCaptor.capture())
</code>```

I think (but not sure) this problem can't be solved since A and B doesn't have common ancestor which extends SomeAbstractClass<R>.

Anyway, thank you for any suggestions.

答:
I've found the solution. If anybody interested we can use the following syntax for ArgumentCaptor:</p>

```<code>ArgumentCaptor<List<? extends SomeAbstractClass>>
</code>```

Body:
I have an object that I've mocked. This object has the following method:

<R, M extends SomeAbstractClass<R>> List<R> execute(List<M> list)

And there are two calls for this method:

execute(List);
execute(List);

where class A extends SomeAbstractClass<String> and B extends SomeAbstractClass<Void>.

Is there any way to use ArgumentCaptor for this case?
I want to do something like this:

verify(..., times(3)).execute(argumentCaptor.capture())

I think (but not sure) this problem can't be solved since A and B doesn't have common ancestor which extends SomeAbstractClass<R>.

Anyway, thank you for any suggestions.

Body:
I've found the solution. If anybody interested we can use the following syntax for ArgumentCaptor:

ArgumentCaptor<List<? extends SomeAbstractClass>>


答: iPhone, error: object cannot be set - either readonly property or no setter found error comes when you have not synthesized it and still accessing its setter or/and getter method.</p>


问:
Swift + GIDSignIn - hasAuthInKeyChain returns true but currentUser is still nil after calling signInSilently
I'm attempting to integrate Google sign-in into my app. Right now, I'm able to successfully log in a user with a Google account and the app works as expected - I'm able to access currentUser, get some information from it, and fill my app's views with the information. The problem is that when I relaunch the app, I'm unable to get a GIDGoogleUser even after calling signInSilently. hasAuthInKeychain returns true, so I know that an auth token must exist in the keychain. I just can't figure out why currentUser still returns nil after signing a user back into the app. The code I've written is below:

```<code>    guard let signIn = GIDSignIn.sharedInstance() else { fatalError() }
    signIn.scopes = ["https://www.googleapis.com/auth/plus.stream.read", "https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/plus.login"]
    signIn.clientID = FIRApp.defaultApp()?.options.clientID
    signIn.delegate = self
    if signIn.hasAuthInKeychain() {
        signIn.signInSilently()
    }

    if signIn.hasAuthInKeychain() || FBSDKAccessToken.current() != nil {

        var token = String()
        if let user = signIn.currentUser{
            token = user.userID
        } else{
            token = FBSDKAccessToken.current().userID
        }
    }
</code>```

The app tries to sign in silently since hasAuthInKeychain returns true. But it skips past the if let statement because currentUser is nil and goes directly into trying to find a FBSDKAccessToken. I've tried all the suggestions I've found including setting the sign-in scopes. Am I missing something?

答:
I had a similar issue. First I thought it was a timing issue. By invoking signIn.signInSilently() after fully loading the root viewController it did work. I am now 99% sure I solved it by executing signIn.signInSilently() on the main thread through:

```<code>DispatchQueue.main.async {
    gidSignIn.signInSilently()
}
</code>```

Body:
I'm attempting to integrate Google sign-in into my app. Right now, I'm able to successfully log in a user with a Google account and the app works as expected - I'm able to access currentUser, get some information from it, and fill my app's views with the information. The problem is that when I relaunch the app, I'm unable to get a GIDGoogleUser even after calling signInSilently. hasAuthInKeychain returns true, so I know that an auth token must exist in the keychain. I just can't figure out why currentUser still returns nil after signing a user back into the app. The code I've written is below:

    guard let signIn = GIDSignIn.sharedInstance() else { fatalError() }
    signIn.scopes = ["https://www.googleapis.com/auth/plus.stream.read", "https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/plus.login"]
    signIn.clientID = FIRApp.defaultApp()?.options.clientID
    signIn.delegate = self
    if signIn.hasAuthInKeychain() {
        signIn.signInSilently()
    }

    if signIn.hasAuthInKeychain() || FBSDKAccessToken.current() != nil {

        var token = String()
        if let user = signIn.currentUser{
            token = user.userID
        } else{
            token = FBSDKAccessToken.current().userID
        }
    }

The app tries to sign in silently since hasAuthInKeychain returns true. But it skips past the if let statement because currentUser is nil and goes directly into trying to find a FBSDKAccessToken. I've tried all the suggestions I've found including setting the sign-in scopes. Am I missing something?

Body:
I had a similar issue. First I thought it was a timing issue. By invoking signIn.signInSilently() after fully loading the root viewController it did work. I am now 99% sure I solved it by executing signIn.signInSilently() on the main thread through:

DispatchQueue.main.async {
    gidSignIn.signInSilently()
}


问:
Transferring data between two computers connected with a switch from a high level language
I'll start with stating that I know very little about networking and the whole OSI model.

My goal is to create a tiny network(for now my laptop and a raspberry Pi) using an unmanaged network switch. On higher layer transmissions(level 3+) I would simply set the destination IP address for a packet. From what I've read on Wikipedia a network switch operates at the data link layer which means it uses MAC addresses.

How does one send data to a device on a local area network when it's connecting with something that only supports MAC addresses. More importantly, how does one do it from a high level language like Java or C#?

答:
TL;DR The the OSI model is about abstraction and programing languages use operating system calls to implement this abstraction. The Rasberry Pi is running a full OS and will send and receive network data addressed to its assigned IP address. You do not need to specify MAC address.

You want to communicate with a Raspberry Pi from your Laptop. To do this you first connect them to the dumb switch and assign both devices an IP address in the same subnet, on physical interfaces connected to the dumb switch. Let say that your laptop's physical ethernet connection is assigned 10.0.0.1/24 and Rasberry Pi's physical ethernet connection is assigned 10.0.0.2/24 (If you do not understand my notation look at CIDR). IP addresses are Layer 3 constructs. Now your application will use an Operating System socket to create a TCP or UDP connection(see UDP java example here) with a layer 4 address (application port). Everything higher than Layer 4 is handled by your application.

Layer 2 and lower is handled by the OS. When your application tries to send data through the socket, the Operating System determines which physical interface to send data from by looking at the destination IP address. This lookup uses the OS Routing Table. Assuming you have a normal routing table, the OS will pick the interface that has ab IP with the same subnet as the destination IP. So if you send data to 10.0.0.2, your OS will send data from 10.0.0.1 because it has the same subnet of 10.0.0. Now the OS has selected an interface, it still does not know what Layer 2 MAC address to send the Layer 3 IP packet to. The main reason the OS does not know this is because IP addresses can change, but Layer 2 MAC addresses should not. Anyhow the OS sends out an ARP request which tries to get the MAC address for an IP address. If the devices are connected properly, the OS gets a MAC address for the desired IP address and begins to send data to that MAC address. The switch (smart or dumb) makes sure the message gets to the desired MAC address. At the receiving end, the OS receives the packet and send the data in the packet to sockets bound to the Layer 4 address (application port).

Side note: it is technically possible to send data to just a MAC address using RAW sockets but it is extremely technical.


问:
How to remove black borders around License Plate using opencv for android app
I want to remove black borders around License Plate. I am using opencv + android.

Please reply with code using which i can remove the borders.

I have also attached the image.image 1

答:
You can perform (DoG) Difference of Gaussians to detect the high frequency details in your image. By high frequency in an image I mean distinct edges and corners.

Here is the code as requested. The explanations are placed as comments by the side:

```<code>import cv2
img = cv2.imread('number_plate.jpg')     #---Reading the image---
img1 = img.copy()    #----The final contour will be drawn on the copy of the original image---
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)   #---converting to gray scale---
</code>```

Before performing DoG, I enhanced the gray sale image by applying Adaptive histogram equalization:

```<code>clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
enhanced = clahe.apply(gray_img)
cv2.imshow(enhanced_gray_img', enhanced)
</code>```

Now I performed Gaussian blur using two separate kernels and subtracted the resulting images as follows:

```<code>blur1 = cv2.GaussianBlur(enhanced, (15, 15), 0)
blur2 = cv2.GaussianBlur(enhanced, (25, 25), 0)
difference = blur2 - blur1
cv2.imshow('Difference_of_Gaussians', difference)
</code>```

Then I performed binary threshold on the image above and found contours. I drew the contour having the largest area:

```<code>ret, th = cv2.threshold(difference, 127,255, 0)    #---performed binary threshold ---

_, contours, hierarchy = cv2.findContours(th, cv2.RETR_EXTERNAL, 1)    #---Find contours---
cnts = contours
max = 0    #----Variable to keep track of the largest area----
c = 0      #----Variable to store the contour having largest area---
for i in range(len(contours)):
    if (cv2.contourArea(cnts[i]) > max):
        max = cv2.contourArea(cnts[i])
        c = i

rep = cv2.drawContours(img1, contours[c], -1, (0,255,0), 3)    #----Draw the contour having the largest area on the image---
cv2.imshow('Final_Image.jpg', rep)
</code>```

And voila!!! There you go.

Now you can obtain bounding rectangles for the contours you found and fed those coordinates as regions to the OCR to extract the text present

Body:
You can perform (DoG) Difference of Gaussians to detect the high frequency details in your image. By high frequency in an image I mean distinct edges and corners.

Here is the code as requested. The explanations are placed as comments by the side:

import cv2
img = cv2.imread('number_plate.jpg')     #---Reading the image---
img1 = img.copy()    #----The final contour will be drawn on the copy of the original image---
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)   #---converting to gray scale---

Before performing DoG, I enhanced the gray sale image by applying Adaptive histogram equalization:

clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
enhanced = clahe.apply(gray_img)
cv2.imshow(enhanced_gray_img', enhanced)

Now I performed Gaussian blur using two separate kernels and subtracted the resulting images as follows:

blur1 = cv2.GaussianBlur(enhanced, (15, 15), 0)
blur2 = cv2.GaussianBlur(enhanced, (25, 25), 0)
difference = blur2 - blur1
cv2.imshow('Difference_of_Gaussians', difference)

Then I performed binary threshold on the image above and found contours. I drew the contour having the largest area:

ret, th = cv2.threshold(difference, 127,255, 0)    #---performed binary threshold ---

_, contours, hierarchy = cv2.findContours(th, cv2.RETR_EXTERNAL, 1)    #---Find contours---
cnts = contours
max = 0    #----Variable to keep track of the largest area----
c = 0      #----Variable to store the contour having largest area---
for i in range(len(contours)):
    if (cv2.contourArea(cnts[i]) > max):
        max = cv2.contourArea(cnts[i])
        c = i

rep = cv2.drawContours(img1, contours[c], -1, (0,255,0), 3)    #----Draw the contour having the largest area on the image---
cv2.imshow('Final_Image.jpg', rep)

And voila!!! There you go.

Now you can obtain bounding rectangles for the contours you found and fed those coordinates as regions to the OCR to extract the text present


问:
AngularJS: create single controller but use it in different parts of the page with different data
I need to write piece of code with AngularJS which will build some table with logic. The information for the table should be obtained from the server. Under the table on the page there should be a button, which will create one more table, but (possibly) with different data from the server, and so on. So, I should use the same controller (because all logic remains the same in every next table), but data, some supporting variables and objects should be different for EVERY table. Previously loaded tables should also remain on the page and support all user functions binded to them. How I can do this? As far as I know, services are singleton objects, so this way is not acceptable.</p>

答:
This is actually what directives are for.

If that seems too complicated, ng-repeat will create a scope for each repeated item that you can then use in ng-controller.


问:
Perl regular expression: How to ignore '..' and 'Rollback' sub-directory
I would like to ignore '..' and 'Rollback' sub-directory but following code is not working. Please suggest.

```<code>if(-d $input) {
    opendir (my $dh, $input) or die "Cannot opendir $input: $!";
    while (my $dir = readdir($dh)) {
        my $path_dir = File::Spec->catfile($input, $dir);
        next unless (-d $path_dir && $dir =~ m/^(?![\.{2}|Rollback])/);
        print "dir=$dir\n";
    }
}
</code>```

Output shows only one sub-directory but the desired output should be a sub-directory plus '.'

答:
Most likely you want to use "non-capturing identifier" ?:
Please try the following code. </p>

```<code>if(-d $input) {
    opendir (my $dh, $input) or die "Cannot opendir $input: $!";
    while (my $dir = readdir($dh)) {
        my $path_dir = File::Spec->catfile($input, $dir);
        next unless (-d $path_dir && $dir =~ m/^(?:([\.]{2}|Rollback))/);
        print "dir=$dir\n";
    }
}
</code>```

Body:
I would like to ignore '..' and 'Rollback' sub-directory but following code is not working. Please suggest.

if(-d $input) {
    opendir (my $dh, $input) or die "Cannot opendir $input: $!";
    while (my $dir = readdir($dh)) {
        my $path_dir = File::Spec->catfile($input, $dir);
        next unless (-d $path_dir && $dir =~ m/^(?![\.{2}|Rollback])/);
        print "dir=$dir\n";
    }
}

Output shows only one sub-directory but the desired output should be a sub-directory plus '.'

Body:
Most likely you want to use "non-capturing identifier" ?:
Please try the following code.

if(-d $input) {
    opendir (my $dh, $input) or die "Cannot opendir $input: $!";
    while (my $dir = readdir($dh)) {
        my $path_dir = File::Spec->catfile($input, $dir);
        next unless (-d $path_dir && $dir =~ m/^(?:([\.]{2}|Rollback))/);
        print "dir=$dir\n";
    }
}


问:
GemfireTemplate workaround for Gemfire 9.0.1
Is there currently a workaround for making use of GemfireTemplate class when upgrading to Gemfire 9.0.1?

One of the upgrade requirements is changing all referencing from:

com.gemstone.gemfire
to
org.apache.geode

However GemfireTemplate dosen't appear to have a corresponding apache geode subclass: http://docs.spring.io/autorepo/docs/spring-data-gemfire/1.7.0.APACHE-GEODE-EA-SNAPSHOT/api/org/springframework/data/gemfire/GemfireTemplate.html

Would it be possible to create a wrapper class to perform the same functionality?

答:
Well...

There is a version of GemfireTemplate (i.e. this) in Spring Data GemFire 2.0.x (Spring Data Release Train Kay), having a current Milestone 1 release (i.e. org.springframework.data:spring-data-gemfire:2.0.0.M1 in the Spring Repos; NOTE: Milestones and Release Candidates are not published to Maven Central), which is based on Pivotal GemFire 9.0.0-beta.1.

We are about to release (see April 3rd, if the date sticks) Spring Data Release Train Kay Milestone 2, which will include Spring Data GemFire 2.0.0.M2, which was upgraded to Pivotal GemFire 9.0.2.

As for Apache Geode, there is Spring Data Geode 1.0.0.INCUBATING-RELEASE (here), which is based on Apache Geode 1.0.0-incubating, which has the same GemfireTemplate (this) for Geode.

I am about to release Spring Data Geode 1.1.0.RELEASE, which will be based on the relatively new Apache Geode 1.1.0 (GA release, non-incubating).

All of the resources you need to know about are here...

Spring Data GemFire project page: http://projects.spring.io/spring-data-gemfire/

Spring Data GemFire Wiki (Compatibility Matrix): https://github.com/spring-projects/spring-data-gemfire/wiki/Spring-Data-GemFire-to-GemFire-Version-Compatibility

Spring Data Commons Wiki (SD Release Trains; see right nav): https://github.com/spring-projects/spring-data-commons/wiki

Maven Central (SD Geode): http://search.maven.org/#search%7Cga%7C1%7Cspring-data-geode

-j


问:
onAnimationEnd and accessing UI elements within it
I have looked through the the documentation of ValueAnimator but didn't notice specific guideline on accessing UI elements in onAnimatorEnd method. However in the application I have in google play, I see many crashlytics reports originating in  onAnimationEnd. All of those crashes are mitigated by adding following code at the beginning of onAnimationEnd

        if(getActivity() != null && !getActivity.isFinishing() ) {
        ...
        }

Does anyone know for sure if activity can be destroyed before animation ends? Also if activity is really destroyed why is onAnimationEnd getting called at all? I can certainly add above code to all my onAnimationEnd but want to make sure its not a incorrect solution.

答:
Does anyone know for sure if activity can be destroyed before animation ends?

Sure it can. Assume you have 10000ms long animation and you press back button. What will happen? Activity will be finished regardless animation has finished or no.

Also if activity is really destroyed why is onAnimationEnd getting called at all?

It shouldn't. Instead, onAnimationCancel() will be called.


答:
I would highly recommend not to use a regex for that. Use the stdlib urlparse.parse_qs() function. It will also take care of URL-encoding and such for you:

```<code>>>> import urlparse
>>> urlparse.parse_qs('X-gmsv=9879480&X-subtype=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&X-X-subscription=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&X-gcm.topic=%2Ftopics%2Fphenotype_com.google.android.gms.icing%25servingVersion&X-X-subtype=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&X-app_ver=9879480&X-kid=%7CID%7C7%7C&X-osv=25')
{'X-subtype': ['cIIP-1V_bTg:APA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW'], 'X-osv': ['25'], 'X-X-subscription': ['cIIP-1V_bTg:APA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW'], 'X-kid': ['|ID|7|'], 'X-app_ver': ['9879480'], 'X-gmsv': ['9879480'], 'X-X-subtype': ['cIIP-1V_bTg:APA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW'], 'X-gcm.topic': ['/topics/phenotype_com.google.android.gms.icing%servingVersion']}
</code>```

Note: In Python 3 this is urllib.parse.parse_qs()

Body:
I have the following http request payload.

X-gmsv=9879480&X-subtype=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&X-X-subscription=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&X-gcm.topic=%2Ftopics%2Fphenotype_com.google.android.gms.icing%25servingVersion&X-X-subtype=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&X-app_ver=9879480&X-kid=%7CID%7C7%7C&X-osv=25&X-sig=vWteecmhHl5q2AsrHaGcOOgaF956SpVk6KAdjijNyeX1uADvPgpgvMkNH-Nu-N8IHc-1Z1ujTytjkQDPZot4zjf_FLSjR0ucPIkFXkZhrRi5RU6uFq-ZlQCEBSPpYuHsx27lC5H3xv-TNe_zC0PaX8h8bTqrImtArVSZjMY6-RFG9TUEj2VkCvs1ixAK21vHxE4ladiXALZO-lhZIvbDIGkY4c-fUMaMBN8EhMr1zH31N41S6cUItkPRe0lTOB4YddkrS2FNRI_LZGfW-cc9h9om-80MskZD0IyJtM4AFsumHxVIQQJwSScASSoFd7e7tANTp5ZPJi2hwr6wQqpveQ&X-cliv=iid-9879000&X-gmsv=9879480&X-pub2=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA9VWXXfudfnoAAl-u_RbBClmI6uvaOH8AFEMvjrtOpL1FuLrUYQzdntRwlMyiL4Nba7WUGeb6CrkEAbwTFcR689QYQ87ytkyY65rD2InSUD3eMLWpiaTciFj-n5sUK6hyci5Je5T8Svgsb-VHSy6vWVKQZ4vGsiGqmkj8sDhCa1UbltWOyhywfG95ENiGKuO_ec55Rmvrew9tFNGIit7FzcNiEAmfSrkEifK6dydjnpahu3lAx4U_MTw5Yo0ou5EGrsByXY2P_tkWg78hq1E_SQORk7q7droAY_wupXHlqSwGCAfbGtRs2gXM-64MSZ1iQX7N7pPojkT4akomcyP2JQIDAQAB&X-X-kid=%7CID%7C7%7C&X-appid=cIIP-1V_bTg&X-scope=%2Ftopics%2Fphenotype_com.google.android.gms.icing%25servingVersion&X-subscription=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&X-app_ver_name=9.8.79+%28480-137224771%29&app=com.google.android.gms&sender=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&device=4374365252386389758&cert=58e1c4133f7441ec3d2c270270a14802da47ba0e&app_ver=9879480&info=AoehgPKryS4XzDpwLBRWN3IuplGtswI&gcm_ver=987948

I want to pull out all the pairs of <key>=<value>.  For example the first key value pair is X-gmsv=9879480.

The best regex I have come up with is .*?\=.*?& but it get's everything but the last key value pair because there is no ampersand at the end of the last variable.  So I tried .*?\=.*?[&|$] which in theory should either match a key value pair ending with an ampersand or the end of the string.

It doesn't get the last string.  I've played around with a couple other regexes and can't figure out what's going on.

Any ideas?

Body:
I would highly recommend not to use a regex for that. Use the stdlib urlparse.parse_qs() function. It will also take care of URL-encoding and such for you:

>>> import urlparse
>>> urlparse.parse_qs('X-gmsv=9879480&X-subtype=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&X-X-subscription=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&X-gcm.topic=%2Ftopics%2Fphenotype_com.google.android.gms.icing%25servingVersion&X-X-subtype=cIIP-1V_bTg%3AAPA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW&X-app_ver=9879480&X-kid=%7CID%7C7%7C&X-osv=25')
{'X-subtype': ['cIIP-1V_bTg:APA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW'], 'X-osv': ['25'], 'X-X-subscription': ['cIIP-1V_bTg:APA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW'], 'X-kid': ['|ID|7|'], 'X-app_ver': ['9879480'], 'X-gmsv': ['9879480'], 'X-X-subtype': ['cIIP-1V_bTg:APA91bG-C3lFgSEzXCnuaLgpa4oJ0mI3NRk8Yv03NBOTfARjfBMWGhwy9J3d2dKUtGZHt6IKFmt7BBWRrQBqbvPoMobfZ2DP1Za0EyDzBqtfTLz9j-EYUHU1PWVjM2kMnOtIuA1s4EHW'], 'X-gcm.topic': ['/topics/phenotype_com.google.android.gms.icing%servingVersion']}

Note: In Python 3 this is urllib.parse.parse_qs()


问:
PHP If Both Variables are 0
Why is it echoing 'both variables 0'

https://3v4l.org/E530h

```<code><?php

  $QuantityOrdered = '1';
  $QuantityShipped = '0';
  echo '<br />' . $QuantityOrdered . ' & ' . $QuantityShipped . '<br />';

  if ($QuantityOrdered != '0' && $QuantityShipped != '0') {
    echo 'at least one variable is not 0';
  }

  else {
    echo 'both variables 0';
  }
</code>```

Trying to get it so that if BOTH $QuantityOrdered and $QuantityShipped are 0, it goes to the else statement.

If $QuantityOrdered and $QuantityShipped are anything other than BOTH 0... for example, 0 and 1 (as in my example).. or 1 and 1, 2 and 2 etc...

anything other than both being 0, it goes to the if statement.

答:
A common way to visualise logical conditions like this is as a truth table:

```<code>  | 0 | 1
--+------
0 |   |
--+---+--
1 |   |
</code>```

Across the top, we have the possible values of $QuantityOrdered; down the side, the values of $QuantityShipped. In the grid, we put the result of the expression; I'll use T for true and F for false.

For your current condition, $QuantityOrdered != '0' && $QuantityShipped != '0', we get this:

```<code>  | 0 | 1
--+------
0 | F | F
--+---+--
1 | F | T
</code>```

We are using 1 to mean "not 0", so the only combination that's true in our table is where both variables are 1.

But what you actually wanted was this:

```<code>  | 0 | 1
--+------
0 | F | T
--+---+--
1 | T | T
</code>```

You wanted the condition to be true in all cases except for one, the case where both variables are 0.

One way to write this would be to start with the opposite. For $QuantityOrdered == '0' && $QuantityShipped == '0' we get this:

```<code>  | 0 | 1
--+------
0 | T | F
--+---+--
1 | F | F
</code>```

So we could write ! ( $QuantityOrdered == '0' && $QuantityShipped == '0' ).

It turns out this is equivalent to $QuantityOrdered != '0' || $QuantityShipped != '0'. Fill in the table, and you'll see.

This equivalence, where "NOT (a AND b)" is equivalent to "(NOT a) OR (NOT b)", is called ''De Morgan's Law''.

Title: PHP If Both Variables are 0

Body:
Why is it echoing 'both variables 0'

https://3v4l.org/E530h

<?php

  $QuantityOrdered = '1';
  $QuantityShipped = '0';
  echo '
' . $QuantityOrdered . ' & ' . $QuantityShipped . '
';

  if ($QuantityOrdered != '0' && $QuantityShipped != '0') {
    echo 'at least one variable is not 0';
  }

  else {
    echo 'both variables 0';
  }

Trying to get it so that if BOTH $QuantityOrdered and $QuantityShipped are 0, it goes to the else statement.

If $QuantityOrdered and $QuantityShipped are anything other than BOTH 0... for example, 0 and 1 (as in my example).. or 1 and 1, 2 and 2 etc...

anything other than both being 0, it goes to the if statement.

Body:
A common way to visualise logical conditions like this is as a truth table:

  | 0 | 1
--+------
0 |   |
--+---+--
1 |   |

Across the top, we have the possible values of $QuantityOrdered; down the side, the values of $QuantityShipped. In the grid, we put the result of the expression; I'll use T for true and F for false.

For your current condition, $QuantityOrdered != '0' && $QuantityShipped != '0', we get this:

  | 0 | 1
--+------
0 | F | F
--+---+--
1 | F | T

We are using 1 to mean "not 0", so the only combination that's true in our table is where both variables are 1.

But what you actually wanted was this:

  | 0 | 1
--+------
0 | F | T
--+---+--
1 | T | T

You wanted the condition to be true in all cases except for one, the case where both variables are 0.

One way to write this would be to start with the opposite. For $QuantityOrdered == '0' && $QuantityShipped == '0' we get this:

  | 0 | 1
--+------
0 | T | F
--+---+--
1 | F | F

So we could write ! ( $QuantityOrdered == '0' && $QuantityShipped == '0' ).

It turns out this is equivalent to $QuantityOrdered != '0' || $QuantityShipped != '0'. Fill in the table, and you'll see.

This equivalence, where "NOT (a AND b)" is equivalent to "(NOT a) OR (NOT b)", is called ''De Morgan's Law''.


问:
Convert 2D array to Byte array
I have a system that composed of two applications using Winforms in C#. The first application has shopping cart form that contains Gridview which displays product’s information. The aim is to send the content of this Gridview to another Gridview in the second application via wireless. I searched and I found that I need to implement TCP socket programming (Asynchronous) approach and it was implemented successfull. However, the tutorials that I found are related to sending an object, I want to send 2D array which result from the Gridview. I plan to follow the following algorithm;

Retrieve the product information in the Gridview.

Reading the data from Gridview into 2D array "integer type".

Convert 2D array to be Byte[], or using Buffer.BlockCopy Method in order to transmitted over the network.

Receive the Byte array.

Convert it to 2D array and fill the Gridview.

Note; I want to send the ID of the customer in the transmission which was not included in the Gridview, I will take it from Public class.

This is my code

```<code> var select = "SELECT Pro_ID, Price, Category_ID FROM Products where Empl_ID = 1";
            var c = new SqlConnection();
            var dataAdapter = new SqlDataAdapter(select, c);

            var commandBuilder = new SqlCommandBuilder(dataAdapter);
            var ds = new DataSet();
            dataAdapter.Fill(ds);
            dataGridView.DataSource = ds.Tables[0];
            dataGridView.Columns[0].HeaderText = "Items";
            dataGridView.Columns[1].HeaderText = "Price";
            dataGridView.Columns[2].HeaderText = "Quantity";

            // reading data from gridview into 2D array
            string[,] DataValue = new string[dataGridView.Rows.Count, dataGridView.Columns.Count];

            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                foreach (DataGridViewColumn col in dataGridView.Columns)
                {
                    DataValue[row.Index, col.Index] = dataGridView.Rows[row.Index].Cells[col.Index].Value.ToString();
                }

            }
</code>```

I was able to implement the first and second points, but the rest, I need some guidance to implement.

答:
In C#, everything is an object. You can cast your 2D array as an object, send it as such, and then simply cast it back to a byte[,].</p>

```<code>byte[,] localByteArray = new byte[someDimension,someOtherDimension];
object transmission = localByteArray;
//transmit

//reception scope, receives "transmission"
byte[,] decode = (byte[,])transmission;
//use decode as 2D array
</code>```

Title: Convert 2D array to Byte array

Body:
I have a system that composed of two applications using Winforms in C#. The first application has shopping cart form that contains Gridview which displays product’s information. The aim is to send the content of this Gridview to another Gridview in the second application via wireless. I searched and I found that I need to implement TCP socket programming (Asynchronous) approach and it was implemented successfull. However, the tutorials that I found are related to sending an object, I want to send 2D array which result from the Gridview. I plan to follow the following algorithm;

Retrieve the product information in the Gridview.

Reading the data from Gridview into 2D array "integer type".

Convert 2D array to be Byte[], or using Buffer.BlockCopy Method in order to transmitted over the network.

Receive the Byte array.

Convert it to 2D array and fill the Gridview.

Note; I want to send the ID of the customer in the transmission which was not included in the Gridview, I will take it from Public class.

This is my code

 var select = "SELECT Pro_ID, Price, Category_ID FROM Products where Empl_ID = 1";
            var c = new SqlConnection();
            var dataAdapter = new SqlDataAdapter(select, c);

            var commandBuilder = new SqlCommandBuilder(dataAdapter);
            var ds = new DataSet();
            dataAdapter.Fill(ds);
            dataGridView.DataSource = ds.Tables[0];
            dataGridView.Columns[0].HeaderText = "Items";
            dataGridView.Columns[1].HeaderText = "Price";
            dataGridView.Columns[2].HeaderText = "Quantity";

            // reading data from gridview into 2D array
            string[,] DataValue = new string[dataGridView.Rows.Count, dataGridView.Columns.Count];

            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                foreach (DataGridViewColumn col in dataGridView.Columns)
                {
                    DataValue[row.Index, col.Index] = dataGridView.Rows[row.Index].Cells[col.Index].Value.ToString();
                }

            }

I was able to implement the first and second points, but the rest, I need some guidance to implement.

Body:
In C#, everything is an object. You can cast your 2D array as an object, send it as such, and then simply cast it back to a byte[,].

byte[,] localByteArray = new byte[someDimension,someOtherDimension];
object transmission = localByteArray;
//transmit

//reception scope, receives "transmission"
byte[,] decode = (byte[,])transmission;
//use decode as 2D array


问:
How can I change where lazy-loading Angular 2 looks for chunks?
I have set up lazy loading in my Angular 2 project using the loadChildren syntax. The problem I have is that after chunks are created, the browser doesn't seem to know where to look to find them. It always tries to load chunks from the root directory, e.g. http://localhost:55626/1.chunk.js. This is of course not where they're stored.

I've been able to work around this issue by bundling the chunks using the .NET bundler, but of course this means they're all loaded at start and defeats the purpose of using lazy loading. I'm guessing that this is an issue with webpack defaulting to look in the wrong place for chunks created during ng build but I'm not confident about that, and even if I'm right, I understand that projects built with angular-cli currently do not support a custom webpack.config.js.

Can anyone shed some insight on this problem? Thanks!

I am using Angular 2.4.6.

Edit: To clarify, I build this project using angular-cli, which doesn't support custom webpack.config files, per https://github.com/angular/angular-cli/issues/1656#issuecomment-240171375

答:
Chunks can be found by configuring webpack with angular2-router-loader. to do so:

Install angular2-router loader

npm install --save-dev angular2-router-loader

Add the loader to your webpack

```<code>loaders: [
  {
    test: /\.ts$/,
    loaders: [
      ‘awesome-typescript-loader’,
      ‘angular2-template-loader’,
      ‘angular2-router-loader’]
   },
   ...
]
</code>```

Then, webpack should automatically know how to load and find your chunks.

Body:
Chunks can be found by configuring webpack with angular2-router-loader. to do so:

Install angular2-router loader

npm install --save-dev angular2-router-loader

Add the loader to your webpack

loaders: [
  {
    test: /\.ts$/,
    loaders: [
      ‘awesome-typescript-loader’,
      ‘angular2-template-loader’,
      ‘angular2-router-loader’]
   },
   ...
]

Then, webpack should automatically know how to load and find your chunks.


问:
How to add a variable to a class dynamically with out modifying the original class
I want to add a variable to a class without modifying the original class. The class can not be modified in anyway because it is tie to an api and would cause build errors if modified. Currently the view is displaying all the variables  in the class,  I want to add a variable to this class during runtime to display to the view. </p>

```<code>public class EventSummaryDto
{
    public long Id { get; set; }
    public string DeviceId { get; set; }
    public DateTime EventTime { get; set; }
    public int EventCode { get; set; }
    public string EventName { get; set; }
    public int DigitalPositionMM { get; set; }
    public string ControllerType { get; set; }

}
</code>```

答:
typically, this is what you would use inheritance for</p>

```<code>public class ExpandedEventSummary : EventSummaryDto
{
    public string MyExtraProperty { get; set; }
}
</code>```

Body:
I want to add a variable to a class without modifying the original class. The class can not be modified in anyway because it is tie to an api and would cause build errors if modified. Currently the view is displaying all the variables  in the class,  I want to add a variable to this class during runtime to display to the view.

public class EventSummaryDto
{
    public long Id { get; set; }
    public string DeviceId { get; set; }
    public DateTime EventTime { get; set; }
    public int EventCode { get; set; }
    public string EventName { get; set; }
    public int DigitalPositionMM { get; set; }
    public string ControllerType { get; set; }

}

Body:
typically, this is what you would use inheritance for

public class ExpandedEventSummary : EventSummaryDto
{
    public string MyExtraProperty { get; set; }
}


问:
Remove items of list from another lists with criteria
i have a list of writers.

```<code>public class Writers{
    long WriterID { get;set; }
}
</code>```

Also I have two lists of type Article.

```<code>public class Article{
    long ArticleID { get; set; }
    long WriterID { get; set; }
    //and others
}
</code>```

so the code i have is:

```<code>List<Article> ArticleList = GetList(1);
List<Article> AnotherArticleList = AnotherList(2);
List<Writers> listWriters = GetAllForbiddenWriters();
</code>```

I want to remove those records from ArticleList, AnotherArticleList where WriterID matches from listWriters WriterID. How to do this in LINQ?

答:
If you've actually got a List<T>, I suggest you use List<T>.RemoveAll, after constructing a set of writer IDs:

HashSet<long> writerIds = new HashSet<long>(listWriters.Select(x => x.WriterID));

articleList.RemoveAll(x => writerIds.Contains(x.WriterId));
anotherArticleList.RemoveAll(x => writerIds.Contains(x.WriterId));
```
<p>If you <em>do</em> want to use LINQ, you could use:</p>
<pre class="lang-cs prettyprint-override"><code>articleList = articleList.Where(x => !writerIds.Contains(x.WriterId))
                         .ToList();
anotherArticleList = anotherArticleList
                         .Where(x => !writerIds.Contains(x.WriterId))
                         .ToList();
</code>```

Note that this changes the variable but doesn't modify the existing list - so if there are any other references to the same list, they won't see any changes. (Whereas RemoveAll modifies the existing list.)

Body:
i have a list of writers.

public class Writers{
    long WriterID { get;set; }
}

Also I have two lists of type Article.

public class Article{
    long ArticleID { get; set; }
    long WriterID { get; set; }
    //and others
}

so the code i have is:

List
 ArticleList = GetList(1);
List
 AnotherArticleList = AnotherList(2);
List<Writers> listWriters = GetAllForbiddenWriters();

I want to remove those records from ArticleList, AnotherArticleList where WriterID matches from listWriters WriterID. How to do this in LINQ?

Body:
If you've actually got a List<T>, I suggest you use List<T>.RemoveAll, after constructing a set of writer IDs:

HashSet<long> writerIds = new HashSet<long>(listWriters.Select(x => x.WriterID));

articleList.RemoveAll(x => writerIds.Contains(x.WriterId));
anotherArticleList.RemoveAll(x => writerIds.Contains(x.WriterId));

If you do want to use LINQ, you could use:

articleList = articleList.Where(x => !writerIds.Contains(x.WriterId))
                         .ToList();
anotherArticleList = anotherArticleList
                         .Where(x => !writerIds.Contains(x.WriterId))
                         .ToList();

Note that this changes the variable but doesn't modify the existing list - so if there are any other references to the same list, they won't see any changes. (Whereas RemoveAll modifies the existing list.)

ContentLicense: CC BY-SA 4.0