答:
You need to keep track of the doubling from day to day. Your current code is only printing out twice the starting value each day. Try something like:</p>

```<code>for (day = 1; day <= entries; day++)
{
    cout << day << "\t\t" << pay;
    sum += pay;
    pay *= 2;
}
</code>```

Title: Calculate the penny double after each day of working

Body:
You need to keep track of the doubling from day to day. Your current code is only printing out twice the starting value each day. Try something like:

for (day = 1; day <= entries; day++)
{
    cout << day << "\t\t" << pay;
    sum += pay;
    pay *= 2;
}


来源: stackexchange

问:
Problem in creating two identity columns in a single table
I am having a problem in creating two identity columns in a single table. This is my part of job... They need two identity columns in a single table at  any cost. Is there any way to do this.

Please provide any syntax for creating two identity columns in a single table at a time or later also.

Thanks in Advance,
Shashra

答:
There can be only one identity column in a SQL Server table:

"There can only be one IDENTITY column per table" - Why?

If you gave us more information about what you are trying to achieve (and the expected behavior of the sequences) and why, it might be a little easier.

For instance, you could add a computed or persisted computed column which exposes the identity by another name.

You could make two columns which are foreign keys to two separate tables with individual identity columns and then also add a unique constraint on each of the foreign key columns.

Until we know more about what you are trying to achieve, it's hard to see what benefit you would get from having two identity columns.

ContentLicense: CC BY-SA 2.5


问:
create multiple Azure VMs in single powershell script parallely
I am able to create Azure VM using powershell.

I have to create 4 VM's parallel.

Does any feature in powershell to do create multiple VMs parallel ? Something like background jobs or call the same function for all different VMs using threads kind of ?

答:
Have you considered VM Scale Sets? They automatically deploy VMs in parallel in a highly available configuration and make managing those VMs much easier (overview doc here: https://learn.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-overview). You can of course deploy a scale set or a bunch of VMs from powershell (doc for deploying a scale set via powershell here: https://learn.microsoft.com/en-us/azure/virtual-machines/windows/tutorial-create-vmss), but the Powershell commandlets require you to specify lots of related properties (e.g. virtual network, subnet, load balancer configs, etc.). The Azure CLI 2.0 (which you can use on both Windows and Linux!) gives lots of good defaults. For instance, in Azure CLI 2.0 you can do this single command to create all of your VMs in parallel:

az vmss create --resource-group vmss-test-1 --name MyScaleSet --image UbuntuLTS --authentication-type password --admin-username azureuser --admin-password P@ssw0rd! --instance-count 4

(taken from the documentation here: https://learn.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-create#create-from-azure-cli)

Hope this helps! :)

ContentLicense: CC BY-SA 3.0


问:
ng-click not firing even I registered the function in controller
Hi I am working on an app and get the problem. I checked console but no error messages.

I created a component and I insert it into other template. Template itself is working(button is rendered and I inspected the element ng-click attribute is there) but when I click on the button. the function is not fired.

The project is availiable here: https://github.com/Aozaki-Touko/webApplication-dota2hero/tree/master/app

navbar.component.js:

```<code>"use strict";

angular.module("navbar").component("navbar", {
  templateUrl: "/navbar/navbar.template.html",
  controller: [
    "$location",
    function($location) {
      var self=this;
      self.changeToHeroes = function(){
        alert("Button Pressed!");
        $location.path("/heroes");
      };
    }
  ]
});
</code>```

navbar.template.html:

```<code><button type="button" ng-click="$ctrl.changePathToHeroes()">Heroes</button>
</code>```

navbar.module.js:

```<code>"use strict";

angular.module("navbar",[]);
</code>```

答:
It should be,</p>

```<code><button type="button" ng-click="changePathToHeros()">Heroes</button>
</code>```

Body:
Hi I am working on an app and get the problem. I checked console but no error messages.

I created a component and I insert it into other template. Template itself is working(button is rendered and I inspected the element ng-click attribute is there) but when I click on the button. the function is not fired.

The project is availiable here: https://github.com/Aozaki-Touko/webApplication-dota2hero/tree/master/app

navbar.component.js:

"use strict";

angular.module("navbar").component("navbar", {
  templateUrl: "/navbar/navbar.template.html",
  controller: [
    "$location",
    function($location) {
      var self=this;
      self.changeToHeroes = function(){
        alert("Button Pressed!");
        $location.path("/heroes");
      };
    }
  ]
});

navbar.template.html:

<button type="button" ng-click="$ctrl.changePathToHeroes()">Heroes</button>

navbar.module.js:

"use strict";

angular.module("navbar",[]);

Body:
It should be,

<button type="button" ng-click="changePathToHeros()">Heroes</button>


问:
Spark left outer join memory issue
I have a Spark job which gives me a Java.lang.OutOfMemoryError: Java heap space (or some GC overhead).

It appears in a task whithin a stage where the statics for complete tasks show the 75 percentile memory and disk spill are 0 but for maximum they are respectively 1732.5 MB and 145.5 MB.

I am pretty sure I have a key which represents more than 70% of all lines during a leftOuterJoin.

Is there a way to spread values associates to this key on multiple partition when doing this join?

Thanks

答:
Depending on the size of your data you could try a broadcast join (essentially a map join)

http://henning.kropponline.de/2016/12/11/broadcast-join-with-spark/

Title: Spark left outer join memory issue


问:
Ambiguous Authentication in Netsuite Token Based API call
I am trying to make SOAP calls to the Netsuite API using Token Based Authentication. I have a C# client that is generated from WDSL and it is sending the following request (with the secrets replaced).

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:messages_2016_2.platform.webservices.netsuite.com" xmlns:urn1="urn:core_2016_2.platform.webservices.netsuite.com">
   <soapenv:Header>
      <urn:partnerInfo>
         <urn:partnerId>[MyAccountId]</urn:partnerId>
      </urn:partnerInfo>
      <urn:applicationInfo>
         <urn:applicationId>[MyApplicationId]</urn:applicationId>
      </urn:applicationInfo>
      <urn:tokenPassport>
         <urn1:account>[MyAccountId]</urn1:account>
         <urn1:consumerKey>[MyConsumerKey]</urn1:consumerKey>
         <urn1:token>[MyTokenId]</urn1:token>
         <urn1:nonce>1574515852</urn1:nonce>
         <urn1:timestamp>1499135589</urn1:timestamp>
         <urn1:signature algorithm="HMAC-SHA1">Ll8DbLvTWsBh/G7UtenErR03OrM=</urn1:signature>
      </urn:tokenPassport>
   </soapenv:Header>
   <soapenv:Body>
      <urn:getDataCenterUrls>
         <urn:account>[MyAccountId]</urn:account>
      </urn:getDataCenterUrls>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

I am getting the following response

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>soapenv:Server.userException</faultcode>
         <faultstring>Ambiguous authentication</faultstring>
         <detail>
            <platformFaults:invalidCredentialsFault xmlns:platformFaults="urn:faults_2016_2.platform.webservices.netsuite.com">
               <platformFaults:code>USER_ERROR</platformFaults:code>
               <platformFaults:message>Ambiguous authentication</platformFaults:message>
            </platformFaults:invalidCredentialsFault>
            <ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">partners-java20004.sea.netledger.com</ns1:hostname>
         </detail>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

I have tried lots of different ways of generating the signature, nonce and timestamp. Currently I have the following:

```<code>private string computeNonce()
{
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    byte[] data = new byte[20];
    rng.GetBytes(data);
    int value = Math.Abs(BitConverter.ToInt32(data, 0));
    return value.ToString();
}

private long computeTimestamp()
{
    return ((long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
}

private TokenPassportSignature computeSignature(string accountId, string consumerKey, string consumerSecret, string tokenId, string tokenSecret, string nonce, long timestamp)
{
    string baseString = accountId + "&" + consumerKey + "&" + tokenId + "&" + nonce + "&" + timestamp;
    string key = consumerSecret + "&" + tokenSecret;
    string signature = "";
    var encoding = new System.Text.ASCIIEncoding();
    byte[] keyBytes = encoding.GetBytes(key);
    byte[] baseStringBytes = encoding.GetBytes(baseString);
    using (var hmacSha1 = new HMACSHA1(keyBytes))
    {
        byte[] hashBaseString = hmacSha1.ComputeHash(baseStringBytes);
        signature = Convert.ToBase64String(hashBaseString);
    }
    TokenPassportSignature sign = new TokenPassportSignature();
    sign.algorithm = "HMAC-SHA1";
    sign.Value = signature;
    return sign;
}
</code>```

Does anyone have any ideas? Thanks!

答: The getDataCenter calls don't need the passport. I just had the same issue with the mapSso function. It looks like the 2017.1 release made them stricter on not accepting the passport</p>

Body:
I am trying to make SOAP calls to the Netsuite API using Token Based Authentication. I have a C# client that is generated from WDSL and it is sending the following request (with the secrets replaced).

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:messages_2016_2.platform.webservices.netsuite.com" xmlns:urn1="urn:core_2016_2.platform.webservices.netsuite.com">
   <soapenv:Header>
      <urn:partnerInfo>
         <urn:partnerId>[MyAccountId]</urn:partnerId>
      </urn:partnerInfo>
      <urn:applicationInfo>
         <urn:applicationId>[MyApplicationId]</urn:applicationId>
      </urn:applicationInfo>
      <urn:tokenPassport>
         <urn1:account>[MyAccountId]</urn1:account>
         <urn1:consumerKey>[MyConsumerKey]</urn1:consumerKey>
         <urn1:token>[MyTokenId]</urn1:token>
         <urn1:nonce>1574515852</urn1:nonce>
         <urn1:timestamp>1499135589</urn1:timestamp>
         <urn1:signature algorithm="HMAC-SHA1">Ll8DbLvTWsBh/G7UtenErR03OrM=</urn1:signature>
      </urn:tokenPassport>
   </soapenv:Header>
   <soapenv:Body>
      <urn:getDataCenterUrls>
         <urn:account>[MyAccountId]</urn:account>
      </urn:getDataCenterUrls>
   </soapenv:Body>
</soapenv:Envelope>

I am getting the following response

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <soapenv:Fault>
         <faultcode>soapenv:Server.userException</faultcode>
         <faultstring>Ambiguous authentication</faultstring>
         <detail>
            <platformFaults:invalidCredentialsFault xmlns:platformFaults="urn:faults_2016_2.platform.webservices.netsuite.com">
               <platformFaults:code>USER_ERROR</platformFaults:code>
               <platformFaults:message>Ambiguous authentication</platformFaults:message>
            </platformFaults:invalidCredentialsFault>
            <ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">partners-java20004.sea.netledger.com</ns1:hostname>
         </detail>
      </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>

I have tried lots of different ways of generating the signature, nonce and timestamp. Currently I have the following:

private string computeNonce()
{
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    byte[] data = new byte[20];
    rng.GetBytes(data);
    int value = Math.Abs(BitConverter.ToInt32(data, 0));
    return value.ToString();
}

private long computeTimestamp()
{
    return ((long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
}

private TokenPassportSignature computeSignature(string accountId, string consumerKey, string consumerSecret, string tokenId, string tokenSecret, string nonce, long timestamp)
{
    string baseString = accountId + "&" + consumerKey + "&" + tokenId + "&" + nonce + "&" + timestamp;
    string key = consumerSecret + "&" + tokenSecret;
    string signature = "";
    var encoding = new System.Text.ASCIIEncoding();
    byte[] keyBytes = encoding.GetBytes(key);
    byte[] baseStringBytes = encoding.GetBytes(baseString);
    using (var hmacSha1 = new HMACSHA1(keyBytes))
    {
        byte[] hashBaseString = hmacSha1.ComputeHash(baseStringBytes);
        signature = Convert.ToBase64String(hashBaseString);
    }
    TokenPassportSignature sign = new TokenPassportSignature();
    sign.algorithm = "HMAC-SHA1";
    sign.Value = signature;
    return sign;
}

Does anyone have any ideas? Thanks!


问:
how to use NodeJS pop up a alert window in browser
I'm totally new to Javascript and I'm wondering how to use node js to pop up a alert window in browser, after sever(Nodejs) received post message from front end?
Do I need to use Ajax?</p>

答:
There is a npm module for popups known as popups. You have to install it using the command npm install popups. Then use it in the following way:

```<code>var popup = require('popups');

popup.alert({
    content: 'Hello!'
});
</code>```

You can find more information here

Body:
There is a npm module for popups known as popups. You have to install it using the command npm install popups. Then use it in the following way:

var popup = require('popups');

popup.alert({
    content: 'Hello!'
});

You can find more information here

ContentLicense: CC BY-SA 4.0


问:
Python: Printing out result from conditional for loop
I have a simple question. I have a small dataframe:

```<code>      Column1  Column2  Column3
Row1        0        4        6
Row2        1        3        5
Row3        0        4        2
</code>```

I need to only print out only Column1 and Column2 only if Column1 equals 1:

```<code>      Column1  Column2
Row2        1        3
</code>```

I have this piece of code that I am stuck at:

```<code>col=[col for col in df.columns if col=="Column1" or col=="Column2"]
print(loc[:,col])
</code>```

This is printing out the result such that we are having Column1 and Column2 with all the values.

```<code>      Column1  Column2
Row1        0        4
Row2        1        3
Row3        0        4
</code>```

How can I incorporate the condition such that Column1==1?

Thanks!

答:
You can use a conditional index:

```<code>>>> df[df['Column1'] == 1]
      Column1  Column2  Column3
Row2        1        3        5
</code>```

Then just select the columns you want:

```<code>>>> df[df['Column1'] == 1][['Column1', 'Column2']]
      Column1  Column2
Row2        1        3
</code>```

Body:
I have a simple question. I have a small dataframe:

      Column1  Column2  Column3
Row1        0        4        6
Row2        1        3        5
Row3        0        4        2

I need to only print out only Column1 and Column2 only if Column1 equals 1:

      Column1  Column2
Row2        1        3

I have this piece of code that I am stuck at:

col=[col for col in df.columns if col=="Column1" or col=="Column2"]
print(loc[:,col])

This is printing out the result such that we are having Column1 and Column2 with all the values.

      Column1  Column2
Row1        0        4
Row2        1        3
Row3        0        4

How can I incorporate the condition such that Column1==1?

Thanks!

Body:
You can use a conditional index:

>>> df[df['Column1'] == 1]
      Column1  Column2  Column3
Row2        1        3        5

Then just select the columns you want:

>>> df[df['Column1'] == 1][['Column1', 'Column2']]
      Column1  Column2
Row2        1        3


问:
Asp.net MVC and AngularJS Boilerplate framework
We are looking to upgrade our current product. The current product is built using web forms (asp.net), c# and Sql server. The current product does not follow much of the best practices such as IOC, Unit of work, Repository pattern etc, however it does follow three layered architecture.

We would like to build the new product from scratch using best practices so that product can be scaled up when required. Our product needs to be a multi tennant web application which should be mobile friendly if viewed on a mobile device. We have found aspnet zero boiler plate which follows best practices but it seems a wee bit limited for us. The disappointment for us is the effort it requires to just add one new field as we would need to add it into multiple places and then recompile the product and publish it. Our product also rely on multiple forms and each form can contain hundereds of fields and on top of that each of our customers may not use all fields in the same form so we need a mechanism to hide and display fields based on customer's credentials. The dynamic creation of forms is a must requirement for us. I have listed below the requirements that we need:

Must follow Industry standard best practices (IOC, Unit of work, Repository, logging etc)

Ability to create forms dynamically and to report on these fields.

Should not rely on compiling and publishing the product for adding additonal field.

Custom business rules for each customer

Adhoc web based reporting

Full auditing to record changed and new value for certain or all fields.

Fully scalable

Role/User based permissions

Is there a suitable framework for achieving above or do we need to build it ourselves?

答:
You used the tag "aspnetboilerplate" So why don't use them ?
I have been learning it since 2016 and it really helpful. A lot of things is well documented and its open source and free. Give it a try. </p>


问:
a better way to do random sampling with a probability distribution?
I want to choose random items from an array but with certain probability distributions.
currently I do:
    myarray =[5,5,5,95]
which gets me a 75% chance of getting a 5 and 25% chance of getting a 95.

I have a lot more numbers though and it takes too much time to write out all those numbers, is there a faster/better way to do this?

答:
You can have an array with objects that contain any value, and a weight property that's a number.

// data
const samples = [
  { value: 5, weight: 75 },
  { value: 95, weight: 25 }
];

// requested method
function randomSample (samples) {
  // [0..1) * sum of weight
  let sample =
    Math.random() *
    samples.reduce((sum, { weight }) => sum + weight, 0);

  // first sample n where sum of weight for [0..n] > sample
  const { value } = samples.find(
    ({ weight }) => (sample -= weight) < 0
  );

  return value;
}

// demo
const counts = { 5: 0, 95: 0 };

Array
  // take a million random samples
  .from({ length: 1000000 }, () => randomSample(samples))
  // count each sample
  .forEach(value => { counts[value]++; });

console.log(counts);```

The data does not have to be in any particular order, nor do the weights need to add up to any particular sum.

Body:
You can have an array with objects that contain any value, and a weight property that's a number.

// data
const samples = [
  { value: 5, weight: 75 },
  { value: 95, weight: 25 }
];

// requested method
function randomSample (samples) {
  // [0..1) * sum of weight
  let sample =
    Math.random() *
    samples.reduce((sum, { weight }) => sum + weight, 0);

  // first sample n where sum of weight for [0..n] > sample
  const { value } = samples.find(
    ({ weight }) => (sample -= weight) < 0
  );

  return value;
}

// demo
const counts = { 5: 0, 95: 0 };

Array
  // take a million random samples
  .from({ length: 1000000 }, () => randomSample(samples))
  // count each sample
  .forEach(value => { counts[value]++; });

console.log(counts);

The data does not have to be in any particular order, nor do the weights need to add up to any particular sum.


问:
Angular ui-select2 "Add" button inside dropdown list
How can I insert a button inside the dropdown list in ui-select2? Tried to search but can't find any.

Sample image.

See ui-select2 documentation.
https://github.com/angular-ui/ui-select

答:
You can do this instead</p>

```<code><div class="input-group">
   <--- ui-select here --!>
   <span class="input-group-btn">
        <a class="btn btn-default" href="" target="_blank"><i class="glyphicon glyphicon-plus"></i></a>
   </span>
 </div>
</code>```

Body:
You can do this instead

<div class="input-group">
   <--- ui-select here --!>
   <span class="input-group-btn">
        <a class="btn btn-default" href="" target="_blank"><i class="glyphicon glyphicon-plus"></i></a>
   </span>
 </div>


问:
The "@angular/compiler-cli" package was not properly installed
Upgrading my project to Angular 4.0 (from 2.4) with Angular CLI 1.0 (from beta.31), I get the error below after following the migration guide:

```<code>> ng build --prod

The "@angular/compiler-cli" package was not properly installed.
Error: The "@angular/compiler-cli" package was not properly installed.
    at Object.<anonymous> (/home/jan/src/fm-repos/fm-ui/node_modules/@ngtools/webpack/src/index.js:14:11)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/jan/src/fm-repos/fm-ui/node_modules/@angular/cli/tasks/eject.js:10:19)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
</code>```

My angular dependencies post-migration:

```<code>"@angular/animations": "^4.0.0",
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/compiler-cli": "^4.0.0",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/router": "^4.0.0",
"@angular/cli": "1.0.0",
"@angular/material": "2.0.0-beta.3",
</code>```

Note: this similar question is about Angular 2 project: Angular2 CLI error "@angular/compiler-cli" package was not properly installed

答:
```<code>npm uninstall -g angular-cli
rm -rf ./node_modules
rm package-lock.json
npm install --save-dev @angular/cli@latest
</code>```

if installing the latest version still gives you an error you can run through the process again of uninstalling and manually enter the version of angular-cli after verifying the newest release in the angular-cli repo. My package.json listed ^1.3.0, but there was a beta version just released and when i manually changed it to

```<code>"@angular/cli": "^1.3.0-beta.0"
npm i
</code>```

It installed successfully

Body:
Upgrading my project to Angular 4.0 (from 2.4) with Angular CLI 1.0 (from beta.31), I get the error below after following the migration guide:

> ng build --prod

The "@angular/compiler-cli" package was not properly installed.
Error: The "@angular/compiler-cli" package was not properly installed.
    at Object.<anonymous> (/home/jan/src/fm-repos/fm-ui/node_modules/@ngtools/webpack/src/index.js:14:11)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/jan/src/fm-repos/fm-ui/node_modules/@angular/cli/tasks/eject.js:10:19)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)

My angular dependencies post-migration:

"@angular/animations": "^4.0.0",
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/compiler-cli": "^4.0.0",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/router": "^4.0.0",
"@angular/cli": "1.0.0",
"@angular/material": "2.0.0-beta.3",

Note: this similar question is about Angular 2 project: Angular2 CLI error "@angular/compiler-cli" package was not properly installed

Body:
npm uninstall -g angular-cli
rm -rf ./node_modules
rm package-lock.json
npm install --save-dev @angular/cli@latest

if installing the latest version still gives you an error you can run through the process again of uninstalling and manually enter the version of angular-cli after verifying the newest release in the angular-cli repo. My package.json listed ^1.3.0, but there was a beta version just released and when i manually changed it to

"@angular/cli": "^1.3.0-beta.0"
npm i

It installed successfully


问:
Facebook marketing api audience limit
When using marketing api

About this part...

You can add an unlimited number of records to an audience, but only a
  maximum of 10000 at a time. It may take up to 1 hour before Facebook
  adds users to an audience, and up to 24 hours for deleting users from
  an audience.

Is there limit adding user to audience per hour to 10000?

or

when calling

```<code>$emails = array(
'test1@example.com',
'test2@example.com',
'test3@example.com',
);
$audience>addUsers($emails,CustomAudienceTypes::EMAIL);
</code>```

there is limit of 10000 data in $emails each call?

I can't seem find clear explanation, and already post it through facebook marketing developer community group, but still no answer.

My current understanding there is limit of 10000 data in $emails each call. Not sure though.

答: You are correct that it is for each call. I have uploaded around 75,000 before and had to use multiple calls.</p>

Title: Facebook marketing api audience limit

Body:
When using marketing api

About this part...

You can add an unlimited number of records to an audience, but only a
  maximum of 10000 at a time. It may take up to 1 hour before Facebook
  adds users to an audience, and up to 24 hours for deleting users from
  an audience.

Is there limit adding user to audience per hour to 10000?

or

when calling

$emails = array(
'test1@example.com',
'test2@example.com',
'test3@example.com',
);
$audience>addUsers($emails,CustomAudienceTypes::EMAIL);

there is limit of 10000 data in $emails each call?

I can't seem find clear explanation, and already post it through facebook marketing developer community group, but still no answer.

My current understanding there is limit of 10000 data in $emails each call. Not sure though.


问:
How to Loop Year and display all data in CGI
How to Loop Year and display all data under that year in cgi and .dat file</p>

答:
I've already solved my problem here's the link
http://sandbox.onlinephpfunctions.com/code/e128ebe799cc829bbfab15b8ec007debd5506462

that's a sample for the goal i want.
I do that in php but all i need is the algorithm used in the looping statement. to substitute the data in .DAT file i created a array for data.

Thank you.


问:
How can I parse an xml response?
I want to parse xml response in variable string. no make xml file.

I'm using C++ RestSDK.

```<code>pplx::task<void> Azure::GetTranslateText(utility::string_t ocrText, utility::string_t &transText)
{
    auto client = http_client{ U("https://api.microsofttranslator.com/V2/Http.svc") };
    uri_builder query;
    query.set_path(U("/Translate"));
    query.append_query(U("appid"), appid);
    query.append_query(U("text"), ocrText);
    query.append_query(U("from"), U("en"));
    query.append_query(U("to"), U("ko"));

    auto path_query_fragment = query.to_string();

    return client.request(methods::GET, path_query_fragment).then([&](http_response response)
    {
        auto bodyStream = response.body();
        concurrency::streams::stringstreambuf sbuffer;
        auto& target = sbuffer.collection();

        bodyStream.read_to_end(sbuffer).get();

        transText = utility::conversions::to_string_t(target);
    });
}
</code>```

xml response is in transText.

```<code><string xmlns="http://schemas.microsoft.com/2003/10/Serialization/"/>translated text</string>
</code>```

答:
I found how to parse without xml document.
using tinyxml2.

Thanks everyone :D

```<code>    tinyxml2::XMLDocument doc;
    doc.Parse(target.c_str());

    tinyxml2::XMLElement *elem = doc.FirstChildElement("string");
    transText = utility::conversions::to_string_t(elem->GetText());
</code>```

Title: How can I parse an xml response?

Body:
I want to parse xml response in variable string. no make xml file.

I'm using C++ RestSDK.

pplx::task<void> Azure::GetTranslateText(utility::string_t ocrText, utility::string_t &transText)
{
    auto client = http_client{ U("https://api.microsofttranslator.com/V2/Http.svc") };
    uri_builder query;
    query.set_path(U("/Translate"));
    query.append_query(U("appid"), appid);
    query.append_query(U("text"), ocrText);
    query.append_query(U("from"), U("en"));
    query.append_query(U("to"), U("ko"));

    auto path_query_fragment = query.to_string();

    return client.request(methods::GET, path_query_fragment).then([&](http_response response)
    {
        auto bodyStream = response.body();
        concurrency::streams::stringstreambuf sbuffer;
        auto& target = sbuffer.collection();

        bodyStream.read_to_end(sbuffer).get();

        transText = utility::conversions::to_string_t(target);
    });
}

xml response is in transText.

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/"/>translated text</string>

Body:
I found how to parse without xml document.
using tinyxml2.

Thanks everyone :D

    tinyxml2::XMLDocument doc;
    doc.Parse(target.c_str());

    tinyxml2::XMLElement *elem = doc.FirstChildElement("string");
    transText = utility::conversions::to_string_t(elem->GetText());


问:
Java Delegates?
Does the Java language have delegate features, similar to how C# has support for delegates?</p>

答:
Short story: no.

Introduction

The newest version of the Microsoft Visual J++ development environment
supports a language construct called delegates or bound method
references. This construct, and the new keywords delegate and
multicast introduced to support it, are not a part of the JavaTM
programming language, which is specified by the Java Language
Specification and amended by the Inner Classes Specification included
in the documentation for the JDKTM 1.1 software.

It is unlikely that the Java programming language will ever include
this construct. Sun already carefully considered adopting it in 1996,
to the extent of building and discarding working prototypes. Our
conclusion was that bound method references are unnecessary and
detrimental to the language. This decision was made in consultation
with Borland International, who had previous experience with bound
method references in Delphi Object Pascal.

We believe bound method references are unnecessary because another
design alternative, inner classes, provides equal or superior
functionality. In particular, inner classes fully support the
requirements of user-interface event handling, and have been used to
implement a user-interface API at least as comprehensive as the
Windows Foundation Classes.

We believe bound method references are harmful because they detract
from the simplicity of the Java programming language and the
pervasively object-oriented character of the APIs. Bound method
references also introduce irregularity into the language syntax and
scoping rules. Finally, they dilute the investment in VM technologies
because VMs are required to handle additional and disparate types of
references and method linkage efficiently.

OwnerDisplayName: Mark

Title: Java Delegates?

OwnerDisplayName: Patrick


问:
About Manifest file
Recently, I encountered a very strange issue, this issue only happens in Windows XP SP3 and Vista. Here are my steps:

Create two new folders in desktop (assume folder names are A and B)

Copy Microsoft GraphEdit (graphedt.exe) application to A folder, then create a empty graphedt.exe.manifest file as well. Run graphedt.exe, you will see a error message, the graphedt.exe can’t run due to the wrong manifest.

Copy Microsoft GraphEdit (graphedt.exe) application to B folder, run graphedt.exe and close it, then create a empty graphedt.exe.manifest file, run graphedt.exe again, you will see the manifest file can’t apply to graphedt.exe. But if you change the last modified time of graphed.exe, the manifest will work again.

It seems Windows will remember the status the first time the EXE uses a manifest file, but also Windows will reset the old remembered status if you change the EXE size or last modified date.

答:
[I'm the current SxS maintainer at Microsoft]

Good investigation Yigang. You're describing the behavior on Vista, not on XP SP3.

Probing for the existence of a manifest every time an app is run would be a performance issue, since usually apps either have a manifest or don't, and that state doesn't change much. For this reason, on Vista, the first time an application is run, we cache a bit describing "this application has an associated manifest" or "this application does not have a manifest". When you ran graphedt.exe the first time, Windows cached the absence of a manifest, and will subsequently not look for one. To reset the cache, update the last modified time on the executable.

OwnerDisplayName: Yigang Wu

Title: About Manifest file

LastEditorDisplayName: Nathan W

OwnerDisplayName: Eugene Talagrand


问:
Sending data between sites
What is a good method to send data from site A to site B without passing a new URL parameter?

For instance, on site A I submit apples are red via a form. How can I send that data to site B without modifying site B's URL structure?

example http://siteb.com/?data=apples+are+red

Not sure if trackbacks or pingbacks use a similar method.

答:
you mean like:</p>

```<code>$data = 'http://siteb.com?'.$_SERVER['QUERY_STRING'];
$ch = curl_init($data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
</code>```

Title: Sending data between sites

Body:
you mean like:

$data = 'http://siteb.com?'.$_SERVER['QUERY_STRING'];
$ch = curl_init($data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);


问:
Pass by reference in C
I'm trying to use pass by reference in C so that the function can modify the values of the parameters passed to it.  This is the function signature:

```<code>int locate(char *name, int &s, int &i)
</code>```

However when I try to compile it I get this error that refers specifically to the above line:

error: expected ‘;’, ‘,’ or ‘)’ before
  '&' token

If I remove the '&' the program will compile, but it will not function correctly, obviously.  What's wrong here?  How can I make call by reference work?

答:
The earlier answers given seem to be missing context, and don't address the property that C pointers are overloaded. It's completely fair to claim that C "passes by reference." A pointer is a reference, too. However, more formally, a C "reference" is the mechanism to represent a symbol's memory address.

A pointer is simply a variable in memory whose value is treated as an
address.

A reference is simply the value-literal for a memory address.

The C language allows for passing by reference - but only in the right context!

The separation of context is that of signature definition and signature invocation.

Consider the primitives int a = 0x22e8; and somewhere else we declare int* b = &a; (I'll get to functions in a minute).

We could visualize this in memory (assume endianness doesn't matter for this example):

```<code>...
0x00000200:        22e8        ; this is the variable for int a's literal value:
                               ; a == 0x000022e8
                               ; &a == 0x00000200
0x00000???:        9090        ; ... more code ...
0x00000400:        0200        ; this is pointer b pointing to a's address:
                               ; b == 0x00000200
                               ; *b == 0x000022e8
                               ; &b == 0x00000400
...
</code>```

It's easy to see that we can assign a pointer to any address without any special tricks. A pointer is just a variable, but C allows us to reference the address it's pointing to; we can "dereference" the pointer from its value-address to instead treat the pointer as its pointee's underlying value during an invocation context: while ( *b == a ) .... We could easily invoke b == &a.

When applying this to function calls, you have to separate the context of function (signature) definition vs invocation in order to differentiate pass by reference.

```<code>int* foo(int* blah, int nah) { .. }     // signature definition context:
                                        // These are parameters
... vs ...

b = foo( &a, 4);                        // invocation context:
                                        // These are arguments
</code>```

In defining a function signature, we are not telling the compiler which address an argument is accessed from — the runtime doesn't even know yet! It's just nonsense to define void bar(int &blah) {...}. Instead we use the dereferenced pointer syntax — "whatever argument is passed in will be loaded at the address pointed to" — to reference the desired argument value when runtime occurs. Thus C can pass arguments by reference.

The contexts of both function signature definitions and function calls change how the compiler looks at pointer overloading vs reference, and how the runtime can actually address them.

Title: Pass by reference in C

Body:
I'm trying to use pass by reference in C so that the function can modify the values of the parameters passed to it.  This is the function signature:

int locate(char *name, int &s, int &i)

However when I try to compile it I get this error that refers specifically to the above line:

error: expected ‘;’, ‘,’ or ‘)’ before
  '&' token

If I remove the '&' the program will compile, but it will not function correctly, obviously.  What's wrong here?  How can I make call by reference work?

Body:
The earlier answers given seem to be missing context, and don't address the property that C pointers are overloaded. It's completely fair to claim that C "passes by reference." A pointer is a reference, too. However, more formally, a C "reference" is the mechanism to represent a symbol's memory address.

A pointer is simply a variable in memory whose value is treated as an
address.

A reference is simply the value-literal for a memory address.

The C language allows for passing by reference - but only in the right context!

The separation of context is that of signature definition and signature invocation.

Consider the primitives int a = 0x22e8; and somewhere else we declare int* b = &a; (I'll get to functions in a minute).

We could visualize this in memory (assume endianness doesn't matter for this example):

...
0x00000200:        22e8        ; this is the variable for int a's literal value:
                               ; a == 0x000022e8
                               ; &a == 0x00000200
0x00000???:        9090        ; ... more code ...
0x00000400:        0200        ; this is pointer b pointing to a's address:
                               ; b == 0x00000200
                               ; *b == 0x000022e8
                               ; &b == 0x00000400
...

It's easy to see that we can assign a pointer to any address without any special tricks. A pointer is just a variable, but C allows us to reference the address it's pointing to; we can "dereference" the pointer from its value-address to instead treat the pointer as its pointee's underlying value during an invocation context: while ( *b == a ) .... We could easily invoke b == &a.

When applying this to function calls, you have to separate the context of function (signature) definition vs invocation in order to differentiate pass by reference.

int* foo(int* blah, int nah) { .. }     // signature definition context:
                                        // These are parameters
... vs ...

b = foo( &a, 4);                        // invocation context:
                                        // These are arguments

In defining a function signature, we are not telling the compiler which address an argument is accessed from — the runtime doesn't even know yet! It's just nonsense to define void bar(int &blah) {...}. Instead we use the dereferenced pointer syntax — "whatever argument is passed in will be loaded at the address pointed to" — to reference the desired argument value when runtime occurs. Thus C can pass arguments by reference.

The contexts of both function signature definitions and function calls change how the compiler looks at pointer overloading vs reference, and how the runtime can actually address them.


问:
How to have two buttons in JQuery Steps
I really need some help here. So I am using one Jquery Steps PlugIn. Now in this PlugIn when we go to the last tab it has a button name as "Finish" when clicked calls "onFinishing" Method.

```<code>onFinishing: function () {
            var loadedPrefix = MyNamespace.loadedPrefix;
            var inputBoxPrefix = $('#SitePrefix').val();
            $.ajax({
                type: 'POST',
                url: '/Settings/IsPrefixExists',
                data: { newPrefix: inputBoxPrefix, prefixLoadedFromDB: loadedPrefix },
                success: function (data) {
                      // do some stuff here
                    }
                },
                error: function () {
                    DisplayError('Failed to load the data.');
                }
            });
        }
</code>```

Now above works perfectly fine. But my manager wants  me to have two button there. One as "Save" and another as "Submit". And clicking on each of them will perform a different action. But this plugin has only one "Finish" button. And it is getting generated via PlugIn's Javascript code. Can I somehow use JQuery/Javascript to have one more button there, and write some code against it.

JS FIDDLE SAMPLE: JS FIDDLE SAMPLE

Image 1:

I want something like below
Image 2:

SAMPLE Example:
 JS FIDDLE

答:
Using the onStepChanged event found in the Steps plugin documentation...

You could do this:

```<code>$( window ).load(function() {
  $("#example-basic").steps({
    headerTag: "h3",
    bodyTag: "section",
    transitionEffect: "slideLeft",
    autoFocus: true,
    onFinishing: function () {
      alert("Hello");
    },
    onStepChanged:function (event, currentIndex, newIndex) {
      console.log("Step changed to: " + currentIndex);

      if(currentIndex == 2){
        console.log("ok");
        var saveA = $("<a>").attr("href","#").addClass("saveBtn").text("Save");
        var saveBtn = $("<li>").attr("aria-disabled",false).append(saveA);

        $(document).find(".actions ul").prepend(saveBtn)
      }else{
        $(".actions").find(".saveBtn").remove();
      }
      return true;
    },

  });

  // on Save button click
  $(".actions").on("click",".saveBtn",function(){
    alert("Saving!");
  });
});
</code>```

Updated JSFiddle

Title: How to have two buttons in JQuery Steps

Body:
I really need some help here. So I am using one Jquery Steps PlugIn. Now in this PlugIn when we go to the last tab it has a button name as "Finish" when clicked calls "onFinishing" Method.

onFinishing: function () {
            var loadedPrefix = MyNamespace.loadedPrefix;
            var inputBoxPrefix = $('#SitePrefix').val();
            $.ajax({
                type: 'POST',
                url: '/Settings/IsPrefixExists',
                data: { newPrefix: inputBoxPrefix, prefixLoadedFromDB: loadedPrefix },
                success: function (data) {
                      // do some stuff here
                    }
                },
                error: function () {
                    DisplayError('Failed to load the data.');
                }
            });
        }

Now above works perfectly fine. But my manager wants  me to have two button there. One as "Save" and another as "Submit". And clicking on each of them will perform a different action. But this plugin has only one "Finish" button. And it is getting generated via PlugIn's Javascript code. Can I somehow use JQuery/Javascript to have one more button there, and write some code against it.

JS FIDDLE SAMPLE: JS FIDDLE SAMPLE

Image 1:

I want something like below
Image 2:

SAMPLE Example:
 JS FIDDLE

Body:
Using the onStepChanged event found in the Steps plugin documentation...

You could do this:

$( window ).load(function() {
  $("#example-basic").steps({
    headerTag: "h3",
    bodyTag: "section",
    transitionEffect: "slideLeft",
    autoFocus: true,
    onFinishing: function () {
      alert("Hello");
    },
    onStepChanged:function (event, currentIndex, newIndex) {
      console.log("Step changed to: " + currentIndex);

      if(currentIndex == 2){
        console.log("ok");
        var saveA = $("<a>").attr("href","#").addClass("saveBtn").text("Save");
        var saveBtn = $("<li>").attr("aria-disabled",false).append(saveA);

        $(document).find(".actions ul").prepend(saveBtn)
      }else{
        $(".actions").find(".saveBtn").remove();
      }
      return true;
    },

  });

  // on Save button click
  $(".actions").on("click",".saveBtn",function(){
    alert("Saving!");
  });
});

Updated JSFiddle


问:
Map values from a dataframe
I have a dataframe with the correspondence between two values:

A another list with only one of the variables:

```<code>l = ['a','b','c']
</code>```

I want to make the mapping like:

```<code>df[l[0]]
</code>```

and get 1

```<code>df[l[1]]
</code>```

and get 2

As if it was a dictionary, how can I do that?

答:
Are you looking for something like this?

```<code>df.loc[df['key']==l[0], 'value']
</code>```

returns

```<code>0    1
1    1
</code>```

Another way would be to set_index of the df to key.

```<code>df.set_index('key', inplace = True)
df.loc[l[0]].values[0]
</code>```

Title: Map values from a dataframe

Body:
I have a dataframe with the correspondence between two values:

A another list with only one of the variables:

l = ['a','b','c']

I want to make the mapping like:

df[l[0]]

and get 1

df[l[1]]

and get 2

As if it was a dictionary, how can I do that?

Body:
Are you looking for something like this?

df.loc[df['key']==l[0], 'value']

returns

0    1
1    1

Another way would be to set_index of the df to key.

df.set_index('key', inplace = True)
df.loc[l[0]].values[0]


问:
Slack Slash Command - Getting user icon URL with username (PHP)
I am new at programming Slash commands in Slack. For one of my commands, I have a username and need to retrieve the user icon URL. I am using PHP to code them.

I was planning on using users.profile.get, since the tutorial here shows that one of the fields returned is the user icon URL.

However, I am trying to find examples on how to make a call to this method and have not found any. Could anybody give me a quick example of the call, including how to send the parameters?

This is how far I got:

```<code>$slack_profile_url = "https://slack.com/api/users.profile.get";
$fields = urlencode($data);
$slack_call = curl_init($slack_profile_url);
curl_setopt($slack_call, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($slack_call, CURLOPT_POSTFIELDS, $fields);
curl_setopt($slack_call, CURLOPT_CRLF, true);
curl_setopt($slack_call, CURLOPT_RETURNTRANSFER, true);
curl_setopt($slack_call, CURLOPT_HTTPHEADER, array(
    "Content-Type: application/x-www-form-urlencoded",
    "Content-Length: " . strlen($fields))
);

$profile = curl_exec($slack_call);
curl_close($slack_call);
</code>```

I basically have $token and $user_name and need to get the profile picture URL. How do I format $token and $username as $data? Is the call correct?

If anybody recommends doing this a different way, I would appreciate any advice as well.

Thank you so much!

答:
To get data into the right format to post to Slack is pretty straight forward. There's two options (POST body or application/x-www-form-urlencoded).

The query string for application/x-www-form-urlencoded is formatted like a get URL string.

```<code>https://slack.com/api/users.profile.get?token={token}&user={user}
// Optionally you can add pretty=1 to make it more readable
https://slack.com/api/users.profile.get?token={token}&user={user}&pretty=1
</code>```

Just request that URL and you will retrieve the data.

The POST body format will use a similar code to what you have above.

```<code>$loc = "https://slack.com/api/users.profile.get";
$POST['token'] = "{token}";
$POST['user'] = "{user}";

$ch = curl_init($loc);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $POST);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
    if ($error = curl_errno($ch)) { echo $error; }

    //close connection
    curl_close($ch);

echo $result;
</code>```

Body:
I am new at programming Slash commands in Slack. For one of my commands, I have a username and need to retrieve the user icon URL. I am using PHP to code them.

I was planning on using users.profile.get, since the tutorial here shows that one of the fields returned is the user icon URL.

However, I am trying to find examples on how to make a call to this method and have not found any. Could anybody give me a quick example of the call, including how to send the parameters?

This is how far I got:

$slack_profile_url = "https://slack.com/api/users.profile.get";
$fields = urlencode($data);
$slack_call = curl_init($slack_profile_url);
curl_setopt($slack_call, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($slack_call, CURLOPT_POSTFIELDS, $fields);
curl_setopt($slack_call, CURLOPT_CRLF, true);
curl_setopt($slack_call, CURLOPT_RETURNTRANSFER, true);
curl_setopt($slack_call, CURLOPT_HTTPHEADER, array(
    "Content-Type: application/x-www-form-urlencoded",
    "Content-Length: " . strlen($fields))
);

$profile = curl_exec($slack_call);
curl_close($slack_call);

I basically have $token and $user_name and need to get the profile picture URL. How do I format $token and $username as $data? Is the call correct?

If anybody recommends doing this a different way, I would appreciate any advice as well.

Thank you so much!

Body:
To get data into the right format to post to Slack is pretty straight forward. There's two options (POST body or application/x-www-form-urlencoded).

The query string for application/x-www-form-urlencoded is formatted like a get URL string.

https://slack.com/api/users.profile.get?token={token}&user={user}
// Optionally you can add pretty=1 to make it more readable
https://slack.com/api/users.profile.get?token={token}&user={user}&pretty=1

Just request that URL and you will retrieve the data.

The POST body format will use a similar code to what you have above.

$loc = "https://slack.com/api/users.profile.get";
$POST['token'] = "{token}";
$POST['user'] = "{user}";

$ch = curl_init($loc);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $POST);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
    if ($error = curl_errno($ch)) { echo $error; }

    //close connection
    curl_close($ch);

echo $result;


答:
function weightedChoice(array, weights) {
  let s = weights.reduce((a, e) => a + e);
  let r = Math.random() * s;
  return array.find((e, i) => (r -= weights[i]) < 0);
}

let randomArray =
    Array.apply(null, Array(32)).
    map(() => weightedChoice([5, 95], [75, 25]));
console.log(JSON.stringify(randomArray));```
</div>
</div>
</p>

<p>EDIT: Patrick was a bit faster than me, so I'll endorse his answer, and I'll just add that you don't absolutely need the sum to be 1, you can normalise the weight by finding out the sum by yourself.</p>

<p>EDIT EDIT: If you are really worried about performance in the case of needing many random values with the same weights, this would do better (by precalculating as much as possible):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class WeightedSampler {
  constructor(elements, weights) {
    this.total = 0;
    this.elements = Array.from(elements);
    this.cweights = weights.map(weight => this.total += weight);
  }
  get() {
    let random = Math.random() * this.total;
    return this.elements.find((element, index) => random < this.cweights[index]);
  }
}

const sampler = new WeightedSampler(["M", "I", " "], [3, 9, 1]);
let randomArray = Array.apply(null, Array(32)).map(() => sampler.get());
console.log(randomArray.join(""));</code>```

Title: a better way to do random sampling with a probability distribution?

Body:
I want to choose random items from an array but with certain probability distributions.
currently I do:
    myarray =[5,5,5,95]
which gets me a 75% chance of getting a 5 and 25% chance of getting a 95.

I have a lot more numbers though and it takes too much time to write out all those numbers, is there a faster/better way to do this?

Body:
function weightedChoice(array, weights) {
  let s = weights.reduce((a, e) => a + e);
  let r = Math.random() * s;
  return array.find((e, i) => (r -= weights[i]) < 0);
}

let randomArray =
    Array.apply(null, Array(32)).
    map(() => weightedChoice([5, 95], [75, 25]));
console.log(JSON.stringify(randomArray));

EDIT: Patrick was a bit faster than me, so I'll endorse his answer, and I'll just add that you don't absolutely need the sum to be 1, you can normalise the weight by finding out the sum by yourself.

EDIT EDIT: If you are really worried about performance in the case of needing many random values with the same weights, this would do better (by precalculating as much as possible):

class WeightedSampler {
  constructor(elements, weights) {
    this.total = 0;
    this.elements = Array.from(elements);
    this.cweights = weights.map(weight => this.total += weight);
  }
  get() {
    let random = Math.random() * this.total;
    return this.elements.find((element, index) => random < this.cweights[index]);
  }
}

const sampler = new WeightedSampler(["M", "I", " "], [3, 9, 1]);
let randomArray = Array.apply(null, Array(32)).map(() => sampler.get());
console.log(randomArray.join(""));


问:
Unreachable statement in custom ArrayAdapter
There is a bug in my custom ArrayAdapter. Android Studio keeps underlining View listItemView = convertView;, and showing unreachable statement.

```<code>package com.example.android.miwok;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class WordAdapter extends ArrayAdapter<Word> {

    public WordAdapter(Activity context, ArrayList<Word> words) {
        // Here, we initialize the ArrayAdapter's internal storage for the context and the list.
        // the second argument is used when the ArrayAdapter is populating a single TextView.
        // Because this is a custom adapter for two TextViews and an ImageView, the adapter is not
        // going to use this second argument, so it can be any value. Here, we used 0.
        super(context, 0, words);
    }

        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            return super.getView(position, convertView, parent);

            // Check if the existing view is being reused, otherwise inflate the view
            View listItemView = convertView;

            if (listItemView == null) {
                listItemView = LayoutInflater.from(getContext()).inflate(
                        R.layout.list_item, parent, false);
            }

            // Get the {@link AndroidFlavor} object located at this position in the list
            Word currentWord = getItem(position);

            // Find the TextView in the list_item.xml layout with the ID version_name
            TextView defaultTextView = (TextView) listItemView.findViewById(R.id.default_text_view);
            // Get the version name from the current AndroidFlavor object and
            // set this text on the name TextView
            defaultTextView.setText(currentWord.getDefaultTranslation());

            // Find the TextView in the list_item.xml layout with the ID version_number
            TextView miwokTextView = (TextView) listItemView.findViewById(R.id.miwok_text_view);
            // Get the version number from the current AndroidFlavor object and
            // set this text on the number TextView
            miwokTextView.setText(currentWord.getMiwokTranslation());

            // Return the whole list item layout (containing 2 TextViews and an ImageView)
            // so that it can be shown in the ListView
            return listItemView;
        }

}
</code>```

It uses a newly created object of my Word class:

```<code>package com.example.android.miwok;

public class Word {

    /** Default translation for the word */
    private String mDefaultTranslation;

    /** Miwok translation for the word */
    private String mMiwokTranslation;

    /**
     * Create a new Word object.
     *
     * @param defaultTranslation is the word in a language that the user is already familiar with
     *                           (such as English)
     * @param miwokTranslation is the word in the Miwok language
     */
    public Word(String defaultTranslation, String miwokTranslation) {
        mDefaultTranslation = defaultTranslation;
        mMiwokTranslation = miwokTranslation;
    }

    /**
     * Get the default translation of the word.
     */
    public String getDefaultTranslation() {
        return mDefaultTranslation;
    }

    /**
     * Get the Miwok translation of the word.
     */
    public String getMiwokTranslation() {
        return mMiwokTranslation;
    }

}
</code>```

And is called from this Activity:

```<code>package com.example.android.miwok;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

import java.util.ArrayList;

public class NumbersActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_numbers);

        // Create a list of words
        ArrayList<Word> words = new ArrayList<Word>();
        words.add(new Word("one", "lutti"));
        words.add(new Word("two", "otiiko"));
        words.add(new Word("three", "tolookosu"));
        words.add(new Word("four", "oyyisa"));
        words.add(new Word("five", "massokka"));
        words.add(new Word("six", "temmokka"));
        words.add(new Word("seven", "kenekaku"));
        words.add(new Word("eight", "kawinta"));
        words.add(new Word("nine", "wo’e"));
        words.add(new Word("ten", "na’aacha"));

        // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
        // adapter knows how to create list items for each item in the list.
        WordAdapter adapter = new WordAdapter(this, words);

        // Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
        // There should be a {@link ListView} with the view ID called list, which is declared in the
        // activity_numbers.xml layout file.
        ListView listView = (ListView) findViewById(R.id.list);

        // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
        // {@link ListView} will display list items for each {@link Word} in the list.
        listView.setAdapter(adapter);
    }
}
</code>```

答:
You have a return statement directly after the method declaration, nothing can happen after a return.

```<code>@Override
public View getView(int position, View convertView, ViewGroup parent){
    //You might want to put your code here
    return super.getView(position, convertView, parent);
    // Nothing can happen beyond this point

    // Check if the existing view is being reused, otherwise inflate the view
    View listItemView = convertView;
</code>```

Nothing in that method is getting executed, you probably didn't mean to put in the first return.

Body:
There is a bug in my custom ArrayAdapter. Android Studio keeps underlining View listItemView = convertView;, and showing unreachable statement.

package com.example.android.miwok;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class WordAdapter extends ArrayAdapter<Word> {

    public WordAdapter(Activity context, ArrayList<Word> words) {
        // Here, we initialize the ArrayAdapter's internal storage for the context and the list.
        // the second argument is used when the ArrayAdapter is populating a single TextView.
        // Because this is a custom adapter for two TextViews and an ImageView, the adapter is not
        // going to use this second argument, so it can be any value. Here, we used 0.
        super(context, 0, words);
    }

        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            return super.getView(position, convertView, parent);

            // Check if the existing view is being reused, otherwise inflate the view
            View listItemView = convertView;

            if (listItemView == null) {
                listItemView = LayoutInflater.from(getContext()).inflate(
                        R.layout.list_item, parent, false);
            }

            // Get the {@link AndroidFlavor} object located at this position in the list
            Word currentWord = getItem(position);

            // Find the TextView in the list_item.xml layout with the ID version_name
            TextView defaultTextView = (TextView) listItemView.findViewById(R.id.default_text_view);
            // Get the version name from the current AndroidFlavor object and
            // set this text on the name TextView
            defaultTextView.setText(currentWord.getDefaultTranslation());

            // Find the TextView in the list_item.xml layout with the ID version_number
            TextView miwokTextView = (TextView) listItemView.findViewById(R.id.miwok_text_view);
            // Get the version number from the current AndroidFlavor object and
            // set this text on the number TextView
            miwokTextView.setText(currentWord.getMiwokTranslation());

            // Return the whole list item layout (containing 2 TextViews and an ImageView)
            // so that it can be shown in the ListView
            return listItemView;
        }

}

It uses a newly created object of my Word class:

package com.example.android.miwok;

public class Word {

    /** Default translation for the word */
    private String mDefaultTranslation;

    /** Miwok translation for the word */
    private String mMiwokTranslation;

    /**
     * Create a new Word object.
     *
     * @param defaultTranslation is the word in a language that the user is already familiar with
     *                           (such as English)
     * @param miwokTranslation is the word in the Miwok language
     */
    public Word(String defaultTranslation, String miwokTranslation) {
        mDefaultTranslation = defaultTranslation;
        mMiwokTranslation = miwokTranslation;
    }

    /**
     * Get the default translation of the word.
     */
    public String getDefaultTranslation() {
        return mDefaultTranslation;
    }

    /**
     * Get the Miwok translation of the word.
     */
    public String getMiwokTranslation() {
        return mMiwokTranslation;
    }

}

And is called from this Activity:

package com.example.android.miwok;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

import java.util.ArrayList;

public class NumbersActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_numbers);

        // Create a list of words
        ArrayList<Word> words = new ArrayList<Word>();
        words.add(new Word("one", "lutti"));
        words.add(new Word("two", "otiiko"));
        words.add(new Word("three", "tolookosu"));
        words.add(new Word("four", "oyyisa"));
        words.add(new Word("five", "massokka"));
        words.add(new Word("six", "temmokka"));
        words.add(new Word("seven", "kenekaku"));
        words.add(new Word("eight", "kawinta"));
        words.add(new Word("nine", "wo’e"));
        words.add(new Word("ten", "na’aacha"));

        // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
        // adapter knows how to create list items for each item in the list.
        WordAdapter adapter = new WordAdapter(this, words);

        // Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
        // There should be a {@link ListView} with the view ID called list, which is declared in the
        // activity_numbers.xml layout file.
        ListView listView = (ListView) findViewById(R.id.list);

        // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
        // {@link ListView} will display list items for each {@link Word} in the list.
        listView.setAdapter(adapter);
    }
}

Body:
You have a return statement directly after the method declaration, nothing can happen after a return.

@Override
public View getView(int position, View convertView, ViewGroup parent){
    //You might want to put your code here
    return super.getView(position, convertView, parent);
    // Nothing can happen beyond this point

    // Check if the existing view is being reused, otherwise inflate the view
    View listItemView = convertView;

Nothing in that method is getting executed, you probably didn't mean to put in the first return.


问:
Sphinx: How to generate documentation using Sphinx
When we enter the command sphinx-quickstart, we have to enter values for so many times.

For example:

```<code>> Root path for the documentation [.]:
> Separate source and build directories (y/n) [n]:
> Name prefix for templates and static dir [_]:
> Project name:
> Author name(s):
> Project version []:
> Project release []:
> Project language [en]:
> Source file suffix [.rst]:
> Name of your master document (without suffix) [index]:
> Do you want to use the epub builder (y/n) [n]:
> autodoc: automatically insert docstrings from modules (y/n) [n]:
> doctest: automatically test code snippets in doctest blocks (y/n) [n]:
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]:
> todo: write "todo" entries that can be shown or hidden on build (y/n) [n]:
> coverage: checks for documentation coverage (y/n) [n]:
> imgmath: include math, rendered as PNG or SVG images (y/n) [n]:
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]:
> ifconfig: conditional inclusion of content based on config values (y/n) [n]:
> viewcode: include links to the source code of documented Python objects (y/n) [n]:
> githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]:
> Create Makefile? (y/n) [y]:
> Create Windows command file? (y/n) [y]:
</code>```

Is there any way around that we don't have to this tiresome job?

For example any bash script or python script ?

The relevant arguments are:

```<code>> Project name: My Project
> Author name(s): My Name
> Project version []: 1
> autodoc: automatically insert docstrings from modules (y/n) [n]: y
> doctest: automatically test code snippets in doctest blocks (y/n) [n]: y
> viewcode: include links to the source code of documented Python objects (y/n) [n]: y
</code>```

All the rest are just empty strings.

My attempts

```<code>printf '\n\n\nMyProject\nBhishan Poudel\n1\n\n\n\n\n\ny\ny\n\n\n\n\n\n\ny\n\n\n\n' | sphinx-quickstart
</code>```

Attempt 2

```<code># run_sphinx_quickstart.py
#!/usr/bin/env python3
import subprocess

sphinx_args = {
'Root_path'        : '',
'Separate_source'  : '',
'Name_prefix'      : '',
'Project_name'     : 'My Project',
'Author_name'      : 'Bhishan Poudel',
'Project_version'  : '1',
'Project_release'  : '',
'Project_language' : 'en',
'Source_file'      : '.rst',
'master_document'  : 'index',
'epub'             : '',
'autodoc'          : 'y',
'doctest'          : 'y',
'intersphinx'      : 'n',
'todo'             : 'n',
'coverage'         : 'n',
'imgmath'          : 'n',
'mathjax'          : 'n',
'ifconfig'         : 'n',
'viewcode'         : 'y',
'githubpages'      : 'n',
'Makefile'         : 'y',
'Windows_Makefile ': 'n' }

for k,v in sphinx_args.items():
    print(k,'\t\t:', v)

subprocess.call('sphink-quickstart', shell=True)

# I don't know how to caputre the outputs of shell commands!!
</code>```

Help will be truly appreciated.

Related links:

答: You can invoke sphinx-quickstart -q with the options you like.

Body:
When we enter the command sphinx-quickstart, we have to enter values for so many times.

For example:

> Root path for the documentation [.]:
> Separate source and build directories (y/n) [n]:
> Name prefix for templates and static dir [_]:
> Project name:
> Author name(s):
> Project version []:
> Project release []:
> Project language [en]:
> Source file suffix [.rst]:
> Name of your master document (without suffix) [index]:
> Do you want to use the epub builder (y/n) [n]:
> autodoc: automatically insert docstrings from modules (y/n) [n]:
> doctest: automatically test code snippets in doctest blocks (y/n) [n]:
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]:
> todo: write "todo" entries that can be shown or hidden on build (y/n) [n]:
> coverage: checks for documentation coverage (y/n) [n]:
> imgmath: include math, rendered as PNG or SVG images (y/n) [n]:
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]:
> ifconfig: conditional inclusion of content based on config values (y/n) [n]:
> viewcode: include links to the source code of documented Python objects (y/n) [n]:
> githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]:
> Create Makefile? (y/n) [y]:
> Create Windows command file? (y/n) [y]:

Is there any way around that we don't have to this tiresome job?

For example any bash script or python script ?

The relevant arguments are:

> Project name: My Project
> Author name(s): My Name
> Project version []: 1
> autodoc: automatically insert docstrings from modules (y/n) [n]: y
> doctest: automatically test code snippets in doctest blocks (y/n) [n]: y
> viewcode: include links to the source code of documented Python objects (y/n) [n]: y

All the rest are just empty strings.

My attempts

printf '\n\n\nMyProject\nBhishan Poudel\n1\n\n\n\n\n\ny\ny\n\n\n\n\n\n\ny\n\n\n\n' | sphinx-quickstart

Attempt 2

# run_sphinx_quickstart.py
#!/usr/bin/env python3
import subprocess

sphinx_args = {
'Root_path'        : '',
'Separate_source'  : '',
'Name_prefix'      : '',
'Project_name'     : 'My Project',
'Author_name'      : 'Bhishan Poudel',
'Project_version'  : '1',
'Project_release'  : '',
'Project_language' : 'en',
'Source_file'      : '.rst',
'master_document'  : 'index',
'epub'             : '',
'autodoc'          : 'y',
'doctest'          : 'y',
'intersphinx'      : 'n',
'todo'             : 'n',
'coverage'         : 'n',
'imgmath'          : 'n',
'mathjax'          : 'n',
'ifconfig'         : 'n',
'viewcode'         : 'y',
'githubpages'      : 'n',
'Makefile'         : 'y',
'Windows_Makefile ': 'n' }

for k,v in sphinx_args.items():
    print(k,'\t\t:', v)

subprocess.call('sphink-quickstart', shell=True)

# I don't know how to caputre the outputs of shell commands!!

Help will be truly appreciated.

Related links:


问:
gulp uglify unclearify error
I'm using gulp uglify, and I'm getting an error.

this is my code:

```<code>var uglify = require('gulp-uglify');
var deleteLines = require('gulp-delete-lines');

// JS concat, strip debugging and minify
gulp.task('scripts', function() {
  gulp.src(['./layout3/**/*.js','!./layout3/**/*.min.js'])
    .pipe(deleteLines({
      'filters': [/<script\s+type=["']text\/javascript["']\s+src=/i, /<script>/i]
    }))
    .pipe(uglify().on('error', function(e){
            console.log(e);
         }))
    .pipe(gulp.dest('./layout2'));
});
</code>```

I add print screen of the error:

I know that there is a problem in jquery.elevatezoom file, I can't find the problem.

thanks.

答:
i got this error after update the 'gulp-uglify', in my case is the pipe was replaced by pump.

because the pump can show error detail, checkt this why use pump

so, maybe you can try this:

```<code>var pump = require('pump'); //npm install it first

    gulp.task('cssmin', function (cb) {
      pump([
         gulp.src(['./layout3/**/*.js','!./layout3/**/*.min.js']),
         deleteLines({'filters': [/<script\s+type=["']text\/javascript["']\s+src=/i, /<script>/i]}),
         uglify().on('error', function(e){
             console.log(e);
           })
         gulp.dest('./layout2')
           ],
       cb
     );});
</code>```

it works on my project now, hope it can help.

Title: gulp uglify unclearify error

Body:
I'm using gulp uglify, and I'm getting an error.

this is my code:

var uglify = require('gulp-uglify');
var deleteLines = require('gulp-delete-lines');

// JS concat, strip debugging and minify
gulp.task('scripts', function() {
  gulp.src(['./layout3/**/*.js','!./layout3/**/*.min.js'])
    .pipe(deleteLines({
      'filters': [/

Body:
i got this error after update the 'gulp-uglify', in my case is the pipe was replaced by pump.

because the pump can show error detail, checkt this why use pump

so, maybe you can try this:

var pump = require('pump'); //npm install it first

    gulp.task('cssmin', function (cb) {
      pump([
         gulp.src(['./layout3/**/*.js','!./layout3/**/*.min.js']),
         deleteLines({'filters': [/<script\s+type=["']text\/javascript["']\s+src=/i, /<script>/i]}),
         uglify().on('error', function(e){
             console.log(e);
           })
         gulp.dest('./layout2')
           ],
       cb
     );});

it works on my project now, hope it can help.


问:
Graph authentication using validated JWT
We have an app registration within our Azure subscription that requires access to Graph, set up under the "Required permissions" section.

Delegated Permissions image

Our Angular application is kicking off authentication against AAD, receiving the JWT, appending it to all requests in the Header and sending it to our WebApi where it's being validated successfully....great!

```<code>Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjlGWERw...
</code>```

Now, from the WebApi, I also want to make a request to Graph and considering I have the validated token, I'm passing it to a Graph REST API via an Authorization header.

```<code>request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
</code>```

However, I'm getting a 401 (Unauthorized) result. Why? Obviously I'm missing a piece of the puzzle, but I don't know what.

I assumed that by setting up Graph permissions in the Azure app registration that when it sent the token to our Angular app it was valid for both AAD and Graph...but it seems this is not the case.

My JWT looks like the following. Note the "aud" only shows my app registration id and not Graph (if that's the problem, how do I fix it?)

```<code>{
  "aud": "<application id here>",
  "iss": "https://sts.windows.net/<tenant id here>/",
  "iat": 1499121655,
  "nbf": 1499121655,
  "exp": 1499125555,
  "aio": "ASQA2/8DAAAACuKzzzni2uaVoaIb9yJa4j3XuG0O+9cQQQlnqXl8Sr0=",
  "amr": [
    "pwd",
    "mfa"
  ],
  "family_name": "Smith",
  "given_name": "John",
  "name": "John Smith",
  "nonce": "<nonce here>",
  "platf": "3",
  "pwd_exp": "941678",
  "sub": "<sub here>",
  "tid": "<tenant id here>",
  "unique_name": "jsmith@smithy.com",
  "upn": "jsmith@smithy.com",
  "ver": "1.0"
}
</code>```

EDIT

I've now implemented the on-behalf-of code as Nan Yu described, but I am still getting a 401.  The front-end token is being validated in the WebAPI, which is then creating a request to Graph.

```<code>string authString = ConfigurationManager.AppSettings["ida:Authority"];
string clientId = ConfigurationManager.AppSettings["ida:Audience"];
string clientSecret = ConfigurationManager.AppSettings["ida:AppSecret"];
string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
string graphResourceId = ConfigurationManager.AppSettings["ida:GraphResourceId"];

AuthenticationContext authenticationContext = new AuthenticationContext(authString);
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);

var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;
string userName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null ? ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
string userAccessToken = bootstrapContext.Token;
UserAssertion userAssertion = new UserAssertion(bootstrapContext.Token, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName);

string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

AuthenticationResult result = await authenticationContext.AcquireTokenAsync(graphResourceId, clientCred, userAssertion);
</code>```

This works fine because of the token being returned now has the Graph "aud" and "scp" for the user that logged in:

```<code>"aud": "https://graph.windows.net",
"scp": "User.Read User.ReadBasic.All",
"unique_name": "jsmith@smithy.com",
"upn": "jsmith@smithy.com",
</code>```

Why am I still unauthorized when trying call the /me Graph API?

答:
If you want to call microsoft graph api , you need to acquire access token for microsoft graph api , that means the aud(audience) in access token claims should be https://graph.microsoft.com .

In your scenario , if user login in client app , then client app calls your web api , in web api , you want to call microsoft graph api , there are two ways to achieve that :

1.Using OAuth 2.0 On-Behalf-Of flow to delegate the user’s identity and authenticate to the second-tier web API. See code sample here .

2.Using OAuth 2.0 Client Credentials Grant , Azure AD authenticates the web api application and returns a JWT access token that is used to call the Microsoft graph . In this scenario , you should grant permissions for microsft graph in web api application .See code samples here .

Please click here for more details about above scenarios.

Body:
We have an app registration within our Azure subscription that requires access to Graph, set up under the "Required permissions" section.

Delegated Permissions image

Our Angular application is kicking off authentication against AAD, receiving the JWT, appending it to all requests in the Header and sending it to our WebApi where it's being validated successfully....great!

Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjlGWERw...

Now, from the WebApi, I also want to make a request to Graph and considering I have the validated token, I'm passing it to a Graph REST API via an Authorization header.

request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);

However, I'm getting a 401 (Unauthorized) result. Why? Obviously I'm missing a piece of the puzzle, but I don't know what.

I assumed that by setting up Graph permissions in the Azure app registration that when it sent the token to our Angular app it was valid for both AAD and Graph...but it seems this is not the case.

My JWT looks like the following. Note the "aud" only shows my app registration id and not Graph (if that's the problem, how do I fix it?)

{
  "aud": "<application id here>",
  "iss": "https://sts.windows.net/<tenant id here>/",
  "iat": 1499121655,
  "nbf": 1499121655,
  "exp": 1499125555,
  "aio": "ASQA2/8DAAAACuKzzzni2uaVoaIb9yJa4j3XuG0O+9cQQQlnqXl8Sr0=",
  "amr": [
    "pwd",
    "mfa"
  ],
  "family_name": "Smith",
  "given_name": "John",
  "name": "John Smith",
  "nonce": "<nonce here>",
  "platf": "3",
  "pwd_exp": "941678",
  "sub": "",
  "tid": "<tenant id here>",
  "unique_name": "jsmith@smithy.com",
  "upn": "jsmith@smithy.com",
  "ver": "1.0"
}

EDIT

I've now implemented the on-behalf-of code as Nan Yu described, but I am still getting a 401.  The front-end token is being validated in the WebAPI, which is then creating a request to Graph.

string authString = ConfigurationManager.AppSettings["ida:Authority"];
string clientId = ConfigurationManager.AppSettings["ida:Audience"];
string clientSecret = ConfigurationManager.AppSettings["ida:AppSecret"];
string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
string graphResourceId = ConfigurationManager.AppSettings["ida:GraphResourceId"];

AuthenticationContext authenticationContext = new AuthenticationContext(authString);
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);

var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;
string userName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null ? ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
string userAccessToken = bootstrapContext.Token;
UserAssertion userAssertion = new UserAssertion(bootstrapContext.Token, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName);

string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

AuthenticationResult result = await authenticationContext.AcquireTokenAsync(graphResourceId, clientCred, userAssertion);

This works fine because of the token being returned now has the Graph "aud" and "scp" for the user that logged in:

"aud": "https://graph.windows.net",
"scp": "User.Read User.ReadBasic.All",
"unique_name": "jsmith@smithy.com",
"upn": "jsmith@smithy.com",

Why am I still unauthorized when trying call the /me Graph API?


问:
Looping a certain amount of times in Django Templates
I downloaded a free bootstrap template that I want to use to load in "Show" items. This would be fairly simple, however each set of rows are using the
property. For example:

```<code><div class="row">
    <div class="col-md-4">
         //code here
    </div>
</div>

<div class="row">
    <div class="col-md-4">
         //code here
    </div>
</div>
</code>```

I wanted to be able to loop 3 times within a row then after 3 loops, generate another row div tag. How can I achieve this using Django tempaltes?

答:
You can achieve it using the cycle builtin for such a task as you can see here.

You could also use the forloop.counter variable in a list inside a for loop, but maybe is easier to go with the first approach because you already know the number of times you need to cycle.

Body:
I downloaded a free bootstrap template that I want to use to load in "Show" items. This would be fairly simple, however each set of rows are using the
property. For example:

         //code here

         //code here

I wanted to be able to loop 3 times within a row then after 3 loops, generate another row div tag. How can I achieve this using Django tempaltes?


问:
C++ a class to be used only by another class
I'm building a class (class A) which needs to be able to create a number of instances of another class (class B) in the course of its operation, but class B is only used by a few member functions of class A, and never used outside of the class. How should class B best be defined? Is it practical / reasonable to make it a private member of Class A? Is this the intended purpose of nested classes, or am I parting with the spirit of the construct?

Thanks,
Wyatt

EDIT: On further consideration, I'm not really asking about best practice, as this is for a personal project. I want to include class B as a member of class A from an encapsulation standpoint - it just seems reasonable that a class which is wholly subordinate should in fact be a part of its owning class.

What I'm wondering is whether or not this is a reasonable use-case for nested classes? If not, what is the purpose of nested classes?

答:
Yes, a nested class is fine here.

Note that to keep the code organized, I wouldn't place the definition of B inside A.  Instead:

```<code>class A
{
    class B;
};

class A::B
{
};
</code>```

Among other things, this allows the definition of class A::B to be placed inside A's implementation file.

EDIT: Since there seems to be some confusion about whether a nested class gets access to the containing class's private members, I provide a code snippet to prove that it does:

```<code>class A
{
    int x;

    class B
    {
        int func(A* p) { return p->x; }
    };
};
</code>```

GCC 4.3.4: Accepted.

Variant without inline definition of A::B, also accepted:

```<code>class A
{
    int x;

    class B;
};

class A::B
{
    int func(A* p) { return p->x; }
};
</code>```

Comeau: Accepted (both variants)

Your Comeau C/C++ test results are as
  follows:

Comeau C/C++ 4.3.10.1 (Oct  6 2008
  11:28:09) for ONLINE_EVALUATION_BETA2
  Copyright 1988-2008 Comeau Computing.
  All rights reserved. MODE:strict
  errors C++ noC++0x_extensions

In strict mode, with -tused, Compile
  succeeded (but remember, the Comeau
  online compiler does not link).
  Compiled with C++0x extensions
  DISabled.

Body:
Yes, a nested class is fine here.

Note that to keep the code organized, I wouldn't place the definition of B inside A.  Instead:

class A
{
    class B;
};

class A::B
{
};

Among other things, this allows the definition of class A::B to be placed inside A's implementation file.

EDIT: Since there seems to be some confusion about whether a nested class gets access to the containing class's private members, I provide a code snippet to prove that it does:

class A
{
    int x;

    class B
    {
        int func(A* p) { return p->x; }
    };
};

GCC 4.3.4: Accepted.

Variant without inline definition of A::B, also accepted:

class A
{
    int x;

    class B;
};

class A::B
{
    int func(A* p) { return p->x; }
};

Comeau: Accepted (both variants)

Your Comeau C/C++ test results are as
  follows:

Comeau C/C++ 4.3.10.1 (Oct  6 2008
  11:28:09) for ONLINE_EVALUATION_BETA2
  Copyright 1988-2008 Comeau Computing.
  All rights reserved. MODE:strict
  errors C++ noC++0x_extensions

In strict mode, with -tused, Compile
  succeeded (but remember, the Comeau
  online compiler does not link).
  Compiled with C++0x extensions
  DISabled.


问:
How to solve this concurrency issue in Node.js?
I have an article model, and a comment model. Each article can have up to 10 comments.

Whenever I add a comment, this check is done in the controller.

```<code>Article.findOne({ id: 3 }, function(err, record){

    if(record.commentCount < 10){

        Comment.create({ /* parameters */ })

    }

});
</code>```

(the code isn't checked, but the important part is that there are two queries here).

Now, since Node.js is run in several threads on several computers, this will definitely result in race condition. If 100 requests are done simultaneously, it's unavoidable that sometime some of them will get the count first simultaneously, and then add the comment because all of them thought that there are less than 10 comments.

How can I fix this? Is there a way to lock the database, or lock a row? Ruby on Rails allows me to do pessimistic locking and fix this problem perfectly.

答:
if you use Sequelize as ORM; maybe you can use Transcation;

such as:

```<code>sequelize.transcation({
  isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
}, function(t){
  return Article.findOne({ id: 3, lock: t.LOCK.UPDATE }, function(err, record){
    if(record.commentCount < 10){
        Comment.create({ /* parameters */ })
    }
  });
})
</code>```

Sequelize Doc

Body:
I have an article model, and a comment model. Each article can have up to 10 comments.

Whenever I add a comment, this check is done in the controller.

Article.findOne({ id: 3 }, function(err, record){

    if(record.commentCount < 10){

        Comment.create({ /* parameters */ })

    }

});

(the code isn't checked, but the important part is that there are two queries here).

Now, since Node.js is run in several threads on several computers, this will definitely result in race condition. If 100 requests are done simultaneously, it's unavoidable that sometime some of them will get the count first simultaneously, and then add the comment because all of them thought that there are less than 10 comments.

How can I fix this? Is there a way to lock the database, or lock a row? Ruby on Rails allows me to do pessimistic locking and fix this problem perfectly.

Body:
if you use Sequelize as ORM; maybe you can use Transcation;

such as:

sequelize.transcation({
  isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
}, function(t){
  return Article.findOne({ id: 3, lock: t.LOCK.UPDATE }, function(err, record){
    if(record.commentCount < 10){
        Comment.create({ /* parameters */ })
    }
  });
})

Sequelize Doc


问:
How do i display data in front-end in descending order for year born given in a single row of mysql
I am trying to array year in descending order associated with some other data which is fetched from mysql database in php

```<code>My Table
username   familyperson1     yearofbirth1     cityname1     familyperson2     yearofbirth2     cityname2      familyperson3   yearofbirth3   cityname3 ...
ptbarn     John              1985             New York      Smit              2001             San Fransisco  Kate            1966           Houston   ...
</code>```

My mysql fetch query:

```<code>require("connect.php");
$srno = $_SESSION['username'];
$query = "SELECT * FROM my_table_name WHERE username='" . $srno . "'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$username = $row['username'];
$familyperson1 = $row['familyperson1'];
$yearofbirth1 = $row['yearofbirth1'];
$cityname1 = $row['cityname1'];
$familyperson2 = $row['familyperson2'];
$yearofbirth2 = $row['yearofbirth2'];
$cityname2 = $row['cityname2'];
$familyperson3 = $row['familyperson2'];
$yearofbirth3 = $row['yearofbirth2'];
$cityname3 = $row['cityname2'];
...
}
</code>```

I request you to please not comment on mysqli on this, that i intent to change later.

Below is the query i fetch from mysql database

```<code>echo 'Family members of' . $username . ':<br>';
echo $familyperson1 . 'is born in the year' . $yearofbirth1 . 'and stays in the city' . $cityname1 . '<br>';
echo $familyperson2 . 'is born in the year' . $yearofbirth2 . 'and stays in the city' . $cityname2 . '<br>';
echo $familyperson3 . 'is born in the year' . $yearofbirth3 . 'and stays in the city' . $cityname3 . '<br>';
echo $familyperson4 . 'is born in the year' . $yearofbirth4 . 'and stays in the city' . $cityname4 . '<br>';
echo $familyperson5 . 'is born in the year' . $yearofbirth5 . 'and stays in the city' . $cityname5 . '<br>';
</code>```

Now i want that if $yearofbirth4 is youngest it should echo on top and descents and so on and so forth.

Although, the result is:

```<code>Family members of ptbarn:
John is born in the year 1985 and stays in city New York.
Smit is born in the year 2001 and stays in city San Fransisco.
Kate is born in the year 1966 and stays in city Houston.
Papa is born in the year 2005 and stays in city Las Vegas.
Rony is born in the year 2002 and stays in city San Diego.
</code>```

The result i want is:

```<code>Family members of ptbarn:
Papa is born in the year 2005 and stays in city Las Vegas.
Rony is born in the year 2002 and stays in city San Diego.
Smit is born in the year 2001 and stays in city San Fransisco.
John is born in the year 1985 and stays in city New York.
Kate is born in the year 1966 and stays in city Houston.
</code>```

I tried this code (from w3schools):

```<code>echo 'Family members of' . $username . ':<br>';
$numbers = array($yearofbirth1, $yearofbirth2, $yearofbirth3, $yearofbirth4, $yearofbirth5);
rsort($numbers);

$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
    echo $familyperson1 . 'is born in the year' . $numbers[$x] . 'and stays in the city' . $cityname1;
    echo "<br>";
}
</code>```

And the result i got was:

```<code>Family members of ptbarn:
John is born in the year 2005 and stays in city New York.
John is born in the year 2002 and stays in city New York.
John is born in the year 2001 and stays in city New York.
John is born in the year 1985 and stays in city New York.
John is born in the year 1966 and stays in city New York.
</code>```

It's logical that I am doing it wrong above, request help.

Added info: The limit of data is only 5 per user in this in mysql row.

答:
Use arsort instead of rsort which will sort array in reverse order and maintain index association.

```<code>$yearofbirth1=1985;
$yearofbirth2=2001;
$yearofbirth3=1966;
$yearofbirth4=2005;
$yearofbirth5=2002;

$numbers = array($yearofbirth1, $yearofbirth2, $yearofbirth3,
$yearofbirth4, $yearofbirth5);
arsort($numbers);

print_r($numbers);

//Array ( [3] => 2005 [4] => 2002 [1] => 2001 [0] => 1985 [2] => 1966 )

$familyperson1 = "a";
$familyperson2 = "b";
$familyperson3 = "c";
$familyperson4 = "d";
$familyperson5 = "e";

foreach($numbers as $k=>$v) {
    echo ${'familyperson' . ($k+1)} . ' is born in the year' . $numbers[$k] ;
    echo "<br>";
}
</code>```

Output:

```<code>d is born in the year2005
e is born in the year2002
b is born in the year2001
a is born in the year1985
c is born in the year1966
</code>```

Body:
I am trying to array year in descending order associated with some other data which is fetched from mysql database in php

My Table
username   familyperson1     yearofbirth1     cityname1     familyperson2     yearofbirth2     cityname2      familyperson3   yearofbirth3   cityname3 ...
ptbarn     John              1985             New York      Smit              2001             San Fransisco  Kate            1966           Houston   ...

My mysql fetch query:

require("connect.php");
$srno = $_SESSION['username'];
$query = "SELECT * FROM my_table_name WHERE username='" . $srno . "'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$username = $row['username'];
$familyperson1 = $row['familyperson1'];
$yearofbirth1 = $row['yearofbirth1'];
$cityname1 = $row['cityname1'];
$familyperson2 = $row['familyperson2'];
$yearofbirth2 = $row['yearofbirth2'];
$cityname2 = $row['cityname2'];
$familyperson3 = $row['familyperson2'];
$yearofbirth3 = $row['yearofbirth2'];
$cityname3 = $row['cityname2'];
...
}

I request you to please not comment on mysqli on this, that i intent to change later.

Below is the query i fetch from mysql database

echo 'Family members of' . $username . ':
';
echo $familyperson1 . 'is born in the year' . $yearofbirth1 . 'and stays in the city' . $cityname1 . '
';
echo $familyperson2 . 'is born in the year' . $yearofbirth2 . 'and stays in the city' . $cityname2 . '
';
echo $familyperson3 . 'is born in the year' . $yearofbirth3 . 'and stays in the city' . $cityname3 . '
';
echo $familyperson4 . 'is born in the year' . $yearofbirth4 . 'and stays in the city' . $cityname4 . '
';
echo $familyperson5 . 'is born in the year' . $yearofbirth5 . 'and stays in the city' . $cityname5 . '
';

Now i want that if $yearofbirth4 is youngest it should echo on top and descents and so on and so forth.

Although, the result is:

Family members of ptbarn:
John is born in the year 1985 and stays in city New York.
Smit is born in the year 2001 and stays in city San Fransisco.
Kate is born in the year 1966 and stays in city Houston.
Papa is born in the year 2005 and stays in city Las Vegas.
Rony is born in the year 2002 and stays in city San Diego.

The result i want is:

Family members of ptbarn:
Papa is born in the year 2005 and stays in city Las Vegas.
Rony is born in the year 2002 and stays in city San Diego.
Smit is born in the year 2001 and stays in city San Fransisco.
John is born in the year 1985 and stays in city New York.
Kate is born in the year 1966 and stays in city Houston.

I tried this code (from w3schools):

echo 'Family members of' . $username . ':
';
$numbers = array($yearofbirth1, $yearofbirth2, $yearofbirth3, $yearofbirth4, $yearofbirth5);
rsort($numbers);

$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
    echo $familyperson1 . 'is born in the year' . $numbers[$x] . 'and stays in the city' . $cityname1;
    echo "
";
}

And the result i got was:

Family members of ptbarn:
John is born in the year 2005 and stays in city New York.
John is born in the year 2002 and stays in city New York.
John is born in the year 2001 and stays in city New York.
John is born in the year 1985 and stays in city New York.
John is born in the year 1966 and stays in city New York.

It's logical that I am doing it wrong above, request help.

Added info: The limit of data is only 5 per user in this in mysql row.

Body:
Use arsort instead of rsort which will sort array in reverse order and maintain index association.

$yearofbirth1=1985;
$yearofbirth2=2001;
$yearofbirth3=1966;
$yearofbirth4=2005;
$yearofbirth5=2002;

$numbers = array($yearofbirth1, $yearofbirth2, $yearofbirth3,
$yearofbirth4, $yearofbirth5);
arsort($numbers);

print_r($numbers);

//Array ( [3] => 2005 [4] => 2002 [1] => 2001 [0] => 1985 [2] => 1966 )

$familyperson1 = "a";
$familyperson2 = "b";
$familyperson3 = "c";
$familyperson4 = "d";
$familyperson5 = "e";

foreach($numbers as $k=>$v) {
    echo ${'familyperson' . ($k+1)} . ' is born in the year' . $numbers[$k] ;
    echo "<br>";
}

Output:

d is born in the year2005
e is born in the year2002
b is born in the year2001
a is born in the year1985
c is born in the year1966