问:
google sheets gives the option of using apikey for javascript but does not work
i am trying to send four points of data to a spread sheet from a website i am developing. name, email, subject, message.

```<code>function loadClient() {
      gapi.client.setApiKey(myapikey);
      return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/sheets/v4/rest")
          .then(function() {
            console.log("GAPI client loaded for API");
          }, function(error) {
            console.error("Error loading GAPI client for API");
          });
    }
    // Make sure the client is loaded before calling this method.
    function execute() {
      return gapi.client.sheets.spreadsheets.values.append({
        "spreadsheetId": mysheetid,
        "range": "a1",
        "includeValuesInResponse": "false",
        "insertDataOption": "INSERT_ROWS",
        "responseDateTimeRenderOption": "SERIAL_NUMBER",
        "responseValueRenderOption": "FORMATTED_VALUE",
        "valueInputOption": "RAW",
        "resource": {
          "values": [
            [
              "test@text.com",
              "jimmy clarke",
              "subject",
              "this is a test email"
            ]
          ]
        }
      })
          .then(function(response) {
            // Handle the results here (response.result has the parsed body).
            console.log("Response", response);
          }, function(error) {
            console.error("Execute error", error);
          });
    }
    gapi.load("client");
  </script>
</code>```

i expected it to send the data to the google sheet without error.

it tells me that this can only be sent using oauth.

i would prefer not to use oauth. my main pain point is that when i look at the (google made) templates it allows for the use of the api key, though when i run the code i recieve and i receive this error

Object {
          result: {…},
          body: "{\n  \"error\":
              {\n    \"code\": 401,\n    \"message\": \"Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.\",\n    \"status\": "UNAUTHENTICATED\"\n  }\n}\n", headers: {…}, status: 401, statusText: "Unauthorized" }

Could i have made a mistake in setting it up?

答:
May have found the answer i believe it is due to the fact that i left the
spread sheet as private, which would require the use of the oauth.</p>

Body:
i am trying to send four points of data to a spread sheet from a website i am developing. name, email, subject, message.

function loadClient() {
      gapi.client.setApiKey(myapikey);
      return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/sheets/v4/rest")
          .then(function() {
            console.log("GAPI client loaded for API");
          }, function(error) {
            console.error("Error loading GAPI client for API");
          });
    }
    // Make sure the client is loaded before calling this method.
    function execute() {
      return gapi.client.sheets.spreadsheets.values.append({
        "spreadsheetId": mysheetid,
        "range": "a1",
        "includeValuesInResponse": "false",
        "insertDataOption": "INSERT_ROWS",
        "responseDateTimeRenderOption": "SERIAL_NUMBER",
        "responseValueRenderOption": "FORMATTED_VALUE",
        "valueInputOption": "RAW",
        "resource": {
          "values": [
            [
              "test@text.com",
              "jimmy clarke",
              "subject",
              "this is a test email"
            ]
          ]
        }
      })
          .then(function(response) {
            // Handle the results here (response.result has the parsed body).
            console.log("Response", response);
          }, function(error) {
            console.error("Execute error", error);
          });
    }
    gapi.load("client");
  </script>

i expected it to send the data to the google sheet without error.

it tells me that this can only be sent using oauth.

i would prefer not to use oauth. my main pain point is that when i look at the (google made) templates it allows for the use of the api key, though when i run the code i recieve and i receive this error

Object {
          result: {…},
          body: "{\n  \"error\":
              {\n    \"code\": 401,\n    \"message\": \"Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.\",\n    \"status\": "UNAUTHENTICATED\"\n  }\n}\n", headers: {…}, status: 401, statusText: "Unauthorized" }

Could i have made a mistake in setting it up?


来源: stackexchange

问:
isnan does not work correctly with `-Ofast` flags
Consider the following test program:

```<code># include <gsl/gsl_statistics_double.h>
# include <iostream>

using namespace std;

int main()
{
  double y = 50.2944, yc = 63.2128;
  double pearson_corr = gsl_stats_correlation(&y, 1, &yc, 1, 1);
  cout << "pearson_corr = " << pearson_corr << endl;
  if (isnan(pearson_corr))
    cout << "It is nan" << endl;
  else
    cout << "Not nan" << endl;
}
</code>```

In some way, this code is some absurd, but its purpose is to show a subtle error that I am experiencing.

The call to gsl_stats_correlation() should give an error because the number of samples is 1 and the pearson coefficient has sense for at least two samples.

When I compile thus:

```<code>c++ test-r2.cc -lgsl -lgslcblas
</code>```

the programs prints out -nan as result and the message "It is nan", which I consider correct because as I said it is not possible to compute the coefficient. The call to isnan()detects correctly that the result is nan. However, when I compile thus:

```<code>c++ -Ofast test-r2.cc -lgsl -lgslcblas
</code>```

The program prints out -nan as result but the message "Not nan", which suggests that the call to isnan() was unable to detect the invalidity of pearson_corr variable.

So, my first question es "Why with the -Ofast flag the call to isnan() is not able to detect that the variable is nan. And my second question would be how to solve this problem in a way independent on the optimizations flags given to the compiler?

I am using gnu c++ version 5.4.0 on ubuntu 16.04 and an Intel i5 run at 64 bits mode

Thanks in advance

答:
man gcc says this:

```<code>   -Ofast
       Disregard strict standards compliance.  -Ofast enables all -O3 optimizations.  It also enables optimizations that are not valid for all standard-compliant programs.  It turns on -ffast-math
       and the Fortran-specific -fno-protect-parens and -fstack-arrays.
</code>```

and this:

```<code>   -ffast-math
       Sets -fno-math-errno, -funsafe-math-optimizations, -ffinite-math-only, -fno-rounding-math, -fno-signaling-nans and -fcx-limited-range.

       This option causes the preprocessor macro "__FAST_MATH__" to be defined.

       This option is not turned on by any -O option besides -Ofast since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications
       for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications.
</code>```

You are telling the compiler to ignore NaNs, among other strange species of a the floating-point family.  If you don't want the compiler to do that, tell it -O2 or -O3 instead.

ContentLicense: CC BY-SA 3.0

Body:
Consider the following test program:

# include <gsl/gsl_statistics_double.h>
# include <iostream>

using namespace std;

int main()
{
  double y = 50.2944, yc = 63.2128;
  double pearson_corr = gsl_stats_correlation(&y, 1, &yc, 1, 1);
  cout << "pearson_corr = " << pearson_corr << endl;
  if (isnan(pearson_corr))
    cout << "It is nan" << endl;
  else
    cout << "Not nan" << endl;
}

In some way, this code is some absurd, but its purpose is to show a subtle error that I am experiencing.

The call to gsl_stats_correlation() should give an error because the number of samples is 1 and the pearson coefficient has sense for at least two samples.

When I compile thus:

c++ test-r2.cc -lgsl -lgslcblas

the programs prints out -nan as result and the message "It is nan", which I consider correct because as I said it is not possible to compute the coefficient. The call to isnan()detects correctly that the result is nan. However, when I compile thus:

c++ -Ofast test-r2.cc -lgsl -lgslcblas

The program prints out -nan as result but the message "Not nan", which suggests that the call to isnan() was unable to detect the invalidity of pearson_corr variable.

So, my first question es "Why with the -Ofast flag the call to isnan() is not able to detect that the variable is nan. And my second question would be how to solve this problem in a way independent on the optimizations flags given to the compiler?

I am using gnu c++ version 5.4.0 on ubuntu 16.04 and an Intel i5 run at 64 bits mode

Thanks in advance

Body:
man gcc says this:

   -Ofast
       Disregard strict standards compliance.  -Ofast enables all -O3 optimizations.  It also enables optimizations that are not valid for all standard-compliant programs.  It turns on -ffast-math
       and the Fortran-specific -fno-protect-parens and -fstack-arrays.

and this:

   -ffast-math
       Sets -fno-math-errno, -funsafe-math-optimizations, -ffinite-math-only, -fno-rounding-math, -fno-signaling-nans and -fcx-limited-range.

       This option causes the preprocessor macro "__FAST_MATH__" to be defined.

       This option is not turned on by any -O option besides -Ofast since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications
       for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications.

You are telling the compiler to ignore NaNs, among other strange species of a the floating-point family.  If you don't want the compiler to do that, tell it -O2 or -O3 instead.


答:
-Ofast, among other things, activates GCC's -ffast-math mode, and -ffast-math, among other things, causes the compiler to generate code that assumes that NaN (and Inf) never occur.

Therefore, if you need to use NaN or Inf, you must not use -Ofast.  There is no workaround.

Nearly all programs are better served by -O2 -march=native anyway; -Ofast turns on extremely aggressive inlining and loop unrolling that, in my experience, almost always blow the I-cache and make the program slower.

Title: isnan does not work correctly with `-Ofast` flags


答:
You told GCC to assume no NaNs, so it's assuming no NaNs. Any code that depends on NaNs is obviously not going to be reliable if you do that.

From the docs:

-Ofast

Disregard strict standards compliance. -Ofast enables all -O3 optimizations. It also enables optimizations that are not valid for all standard-compliant programs. It turns on -ffast-math and the Fortran-specific -fstack-arrays, unless -fmax-stack-var-size is specified, and -fno-protect-parens.

-ffast-math

Sets the options -fno-math-errno, -funsafe-math-optimizations, -ffinite-math-only, -fno-rounding-math, -fno-signaling-nans, -fcx-limited-range and -fexcess-precision=fast. ...

-ffinite-math-only

Allow optimizations for floating-point arithmetic that assume that arguments and results are not NaNs or +-Infs.


问:
Next argmax values in python
I have a function that returns the argmax from a large 2d array

```<code>getMax = np.argmax(dist, axis=1)
</code>```

However I want to get the next biggest values, is there a way of removing the getMax values from the original array and then performing argmax again?

答:
If speed is important to you, using argpartition rather than argsort could be useful.

For example, to return the n largest elements from a list:

```<code>import numpy as np

l = np.random.random_integer(0, 100, 1e6)

top_n_1 = l[np.argsort(-l)[0:n]]
top_n_2 = l[np.argpartition(l, -n)[-n:]]
</code>```

The %timeit function in ipython reports
10 loops, best of 3: 56.9 ms per loop for top_n_1 and 100 loops, best of 3: 8.06 ms per loop for top_n_2.

I hope this is useful.

Title: Next argmax values in python

Body:
I have a function that returns the argmax from a large 2d array

getMax = np.argmax(dist, axis=1)

However I want to get the next biggest values, is there a way of removing the getMax values from the original array and then performing argmax again?

Body:
If speed is important to you, using argpartition rather than argsort could be useful.

For example, to return the n largest elements from a list:

import numpy as np

l = np.random.random_integer(0, 100, 1e6)

top_n_1 = l[np.argsort(-l)[0:n]]
top_n_2 = l[np.argpartition(l, -n)[-n:]]

The %timeit function in ipython reports
10 loops, best of 3: 56.9 ms per loop for top_n_1 and 100 loops, best of 3: 8.06 ms per loop for top_n_2.

I hope this is useful.

ContentLicense: CC BY-SA 4.0


问:
Google api redirect uri issue while reading google sheet from java
I am using oauth2 google drive API to read data from a google sheet in Java.
I have an working sample on my local machine. But when I deploy it on the remote server, at the time of authentication the API returns a URL which is to be opened in browser.
The URL is like below :

```<code>https://accounts.google.com/o/oauth2/auth?access_type=online&approval_prompt=auto&client_id=my.client.id&redirect_uri=http://**localhost:58305**/Callback&response_type=code&scope=https://www.googleapis.com/auth/drive
</code>```

Obviously this URL will not open on remote server as there is no localhost.

My google developers console configuration while generating oauth client id:

Application type : Web Application or Other

Authorized JavaScript origins : My remote server origin

Authorized redirect URIs : My remote server page

The authentication gets successfully done on my local machine when the Application type is Other.
The same when deployed on remote server fails to authenticate because of the localhost string inside the authentication URL.

On the other hand when the application type is Web Application it gives me an error page on both localhost and remote server which has error like below even when I have added proper origins in the above options:

```<code>Error: redirect_uri_mismatch

The redirect URI in the request, http://localhost:59363/Callback, does not match the ones authorized for the OAuth client. Visit https://console.developers.google.com/apis/credentials/oauthclient/my.client.id?project=my.project.id to update the authorized redirect URIs.
</code>```

I tried multiple options with the redirect URIs. But it gives same error.

Is there any setting in the authentication where we can change the
fix the localhost:59363 part ?

Is application type : web application correct when I have to
deploy this on production server as application type : other is
for installed apps ?

答:
You are using the wrong API credential type.

For your project go to: https://console.cloud.google.com/apis/credentials and choose an OAUTH2 credential (client ID of type: OTHER).

Body:
I am using oauth2 google drive API to read data from a google sheet in Java.
I have an working sample on my local machine. But when I deploy it on the remote server, at the time of authentication the API returns a URL which is to be opened in browser.
The URL is like below :

https://accounts.google.com/o/oauth2/auth?access_type=online&approval_prompt=auto&client_id=my.client.id&redirect_uri=http://**localhost:58305**/Callback&response_type=code&scope=https://www.googleapis.com/auth/drive

Obviously this URL will not open on remote server as there is no localhost.

My google developers console configuration while generating oauth client id:

Application type : Web Application or Other

Authorized JavaScript origins : My remote server origin

Authorized redirect URIs : My remote server page

The authentication gets successfully done on my local machine when the Application type is Other.
The same when deployed on remote server fails to authenticate because of the localhost string inside the authentication URL.

On the other hand when the application type is Web Application it gives me an error page on both localhost and remote server which has error like below even when I have added proper origins in the above options:

Error: redirect_uri_mismatch

The redirect URI in the request, http://localhost:59363/Callback, does not match the ones authorized for the OAuth client. Visit https://console.developers.google.com/apis/credentials/oauthclient/my.client.id?project=my.project.id to update the authorized redirect URIs.

I tried multiple options with the redirect URIs. But it gives same error.

Is there any setting in the authentication where we can change the
fix the localhost:59363 part ?

Is application type : web application correct when I have to
deploy this on production server as application type : other is
for installed apps ?


问:
Locking Document Visibility settings in DocuSign for Specific Senders
I've successfully created DocuSign envelopes with a single button click from Salesforce through REST API by auto-populating documents, recipients and Document Visibility settings through this API call.

In order to achieve this, Document Visibility settings has been set to "Must sign to view unless Sender". Hence this section can be edited by any sender. The Document Visibility section in the Draft envelope should be locked/hidden for specific senders.

Is there any feature available to achieve this in New DocuSign Experience? Can this done through Apex REST API?

Any suggestions please?

答: No you cannot disable Document Visibility for the sender of an envelope. Since you are using API integration, you can send an envelope using API credentials and add the requestor of an envelope (logically a sender) as first recipient in the routing order as CC recipient. This way requestor can monitor the envelope but will not do any activity on an envelope including Document Visibility.</p>


问:
React JS editing first item of an array with spread operator
I want to update an item of an array at a given index in my reducer using ES6 spread operator ... Here is what I am doing

```<code>let array = action.payload.items;
return [...array, array[3].id:555]
</code>```

By this way editing works very well, but it also adds an extra item in the array.

Any help???

答:
Please consider this answer over here : https://stackoverflow.com/a/34582848/51428

This is easily applicable to your question,by inserting your new object at the index where yiu are removing the element.

Consider keeping your old element intact, whereby you can also use spreading to create the new element

```<code>const itemToUpdate = {...items[index], id: 1000}
</code>```

Body:
I want to update an item of an array at a given index in my reducer using ES6 spread operator ... Here is what I am doing

let array = action.payload.items;
return [...array, array[3].id:555]

By this way editing works very well, but it also adds an extra item in the array.

Any help???

Body:
Please consider this answer over here : https://stackoverflow.com/a/34582848/51428

This is easily applicable to your question,by inserting your new object at the index where yiu are removing the element.

Consider keeping your old element intact, whereby you can also use spreading to create the new element

const itemToUpdate = {...items[index], id: 1000}


答:
-Ofast

Disregard strict standards compliance. -Ofast enables all -O3 optimizations.
It also enables optimizations that are not valid for all standard-compliant
programs. It turns on -ffast-math

and in that case isnan doesn't work, as explained better here Mingw32 std::isnan with -ffast-math

(one of the answers contains an implementation which will work, but it's also possible to wrap isnan in a c file which isn't compiled with -Ofast)


问:
Electron electron-winstaller Set Installation Path for Msi
I'm using Electron and Angular2 to create a desktop application for Windows, and can successfully generate the .exe and .msi files for installation. I use electron-packager to package my electron app
packaged electron app

After packaging the app I use electron-winstaller to generate an msi from the package

When I run the .msi file though, It automatically installs my project to C:\Users\Username\AppData\Local\ApplicationName . The only thing when double clicking on the msi is this short dialog:
dialog

What I would like though, is for the installer to prompt me to where it should install the application. I want to be able to set the installation path when installing.

I should also mention that I tried using electron-builder, and could also generate the msi file. But here I could also not set the installation path. I found this Electron create MSI installer using electron-builder issue where someone else had the same problem with electron-builder, but there was no answer to his question.

Here is my configuration for electron-winstaller. The winstaller.js file is located at the root of my project:

```<code>var electronInstaller = require('electron-winstaller');
var resultPromise = electronInstaller.createWindowsInstaller(
  {
    appDirectory: '../installer/sda-win32-x64',
    outputDirectory: '../installer',
    authors: 'SORA Desktop Application',
    exe: 'sda.exe',
    setupExe: 'SDASetup.exe',
    setupMsi: 'SDASetup.msi',
    iconUrl: 'file:///d/dev/sda/client/src/app/assets/images/icon.ico',
    setupIcon: 'src/app/assets/images/icon.ico'
  });

resultPromise.then(() => console.log('It worked!'), e => console.log(`No dice: ${e.message}`));
</code>```

Here is my package.json configuration. This is also located at the root of my project

```<code>{
  "name": "sda",
  "description": "SDA 3.0",
  "version": "0.0.1",
  "main": "gulpfile.js",
  "keywords": [
    "Angular",
    "Angular2",
    "Electron",
    "Typescript"
  ],
  "author": "Vic",
  "license": "MIT",
  "scripts": {
    "build": "gulp build",
    "start": "npm run build && electron ./dist/index.js",
    "package": "npm run build && gulp electron:package",
    "postinstall": "concurrently \"bower install\" \"typings install\"",
    "appstart": "electron ./dist/index.js",
    "test": "gulp test",
    "deploy": "rm -rf ../installer && gulp setInDevelopmentFlagToFalse && cp src/app/environment/environment.prod.ts src/app/environment/environment.ts && npm run build && cd dist && electron-packager . --platform=win32 --arch=x64 --overwrite=true --out=../../installer --icon=assets/images/icon.ico && cd ../ && gulp setInDevelopmentFlagToTrue && cp src/app/environment/environment.dev.ts src/app/environment/environment.ts && node winstaller.js"
  },
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "@angular/upgrade": "2.0.0",
    "@ng-bootstrap/ng-bootstrap": "1.0.0-alpha.8",
    "@types/hammerjs": "2.0.33",
    "@types/sjcl": "1.0.27",
    "angular2-jwt": "0.1.23",
    "angular2-moment": "1.0.0-beta.5",
    "angular2localization": "1.0.2",
    "bootstrap": "4.0.0-alpha.4",
    "core-js": "2.4.1",
    "file-saver": "1.3.3",
    "font-awesome": "4.6.3",
    "jquery": "3.1.1",
    "moment": "2.15.2",
    "normalize.css": "5.0.0",
    "reflect-metadata": "0.1.3",
    "rxjs": "5.0.0-beta.12",
    "sjcl": "1.0.6",
    "systemjs": "0.19.27",
    "tether": "1.3.7",
    "zone.js": "0.6.23"
  },
  "devDependencies": {
    "bower": "1.7.9",
    "concurrently": "2.2.0",
    "del": "2.2.0",
    "electron": "1.3.5",
    "electron-connect": "0.6.0",
    "electron-packager": "8.1.0",
    "electron-prebuilt": "1.3.8",
    "electron-winstaller": "2.3.4",
    "eslint": "3.6.0",
    "eslint-config-google": "0.6.0",
    "eslint-plugin-html": "1.5.3",
    "gulp": "3.9.1",
    "gulp-atom-electron": "1.9.0",
    "gulp-concat": "2.6.0",
    "gulp-replace": "^0.5.4",
    "gulp-sass": "2.3.1",
    "gulp-shell": "0.5.2",
    "gulp-symdest": "1.0.0",
    "gulp-typescript": "3.0.2",
    "hammerjs": "2.0.8",
    "jasmine-core": "2.5.2",
    "karma": "1.3.0",
    "karma-chrome-launcher": "2.0.0",
    "karma-cli": "1.0.1",
    "karma-htmlfile-reporter": "0.3.4",
    "karma-jasmine": "1.0.2",
    "karma-jasmine-html-reporter": "0.2.2",
    "karma-sourcemap-loader": "0.3.7",
    "karma-typescript-preprocessor": "0.3.0",
    "run-sequence": "1.1.5",
    "typescript": "2.0.2",
    "typings": "1.3.2"
  }
}
</code>```

Do I maybe need a certificate ?
Is it not a default setting for the windows installer to ask where to install?

答:
electron-winstaller uses squirrel to generate the setup files. According to their documentation, the install path is "effectively immutable" and hard set to \%LocalAppData%\AppName :

Install Location

The Setup.exe, and later the UpdateManager in MyApp must have the
  ability to write files to and execute files from the application
  install location. To ensure permission for all types of users, the
  user's application data directory is selected as the install location
  (i.e., %LocalAppData%\MyApp).

The installation root really only needs to consist of two types of
  folders:

Packages - folder used to download and assemble the update package
  files. App Folders - the "installed" application files for a given
  version of MyApp. \%LocalAppData%\MyApp    \packages
        MyApp-1.0.0.nupkg
        MyApp-1.0.1-delta.nupkg
        MyApp-1.0.1.nupkg       \app-1.0.0
        MyApp.exe    \app-1.0.1
        MyApp.exe The packages directory is effectively immutable, it simply consists of the packages we've downloaded. Using the user's
  local application data directory means that we the needed write-access
  to the install directory on a per-user basis.

Tip: See Machine-wide Installs for more information on ensuring your
  application pushed to all users in an enterprise environment.

The method for installing machine wide is to use the MSI which only triggers installation on the next user login:

Machine-wide Installs

Squirrel's Releasify command generates an MSI file suitable for
  installation via Group Policy. This MSI isn't a general-purpose
  installer, this means that once you run the MSI, users from now on
  will get the app installed, on next Login.

So, most normal users should continue to run the Setup.exe's generated
  by Releasify, but if you want to have an IT Admin Friendly version,
  you can hand off the MSI

Most users of Squirrel won't have to do anything new to enable this
  behavior, though certain NuGet package IDs / names might cause
  problems with MSI.

Body:
I'm using Electron and Angular2 to create a desktop application for Windows, and can successfully generate the .exe and .msi files for installation. I use electron-packager to package my electron app
packaged electron app

After packaging the app I use electron-winstaller to generate an msi from the package

When I run the .msi file though, It automatically installs my project to C:\Users\Username\AppData\Local\ApplicationName . The only thing when double clicking on the msi is this short dialog:
dialog

What I would like though, is for the installer to prompt me to where it should install the application. I want to be able to set the installation path when installing.

I should also mention that I tried using electron-builder, and could also generate the msi file. But here I could also not set the installation path. I found this Electron create MSI installer using electron-builder issue where someone else had the same problem with electron-builder, but there was no answer to his question.

Here is my configuration for electron-winstaller. The winstaller.js file is located at the root of my project:

var electronInstaller = require('electron-winstaller');
var resultPromise = electronInstaller.createWindowsInstaller(
  {
    appDirectory: '../installer/sda-win32-x64',
    outputDirectory: '../installer',
    authors: 'SORA Desktop Application',
    exe: 'sda.exe',
    setupExe: 'SDASetup.exe',
    setupMsi: 'SDASetup.msi',
    iconUrl: 'file:///d/dev/sda/client/src/app/assets/images/icon.ico',
    setupIcon: 'src/app/assets/images/icon.ico'
  });

resultPromise.then(() => console.log('It worked!'), e => console.log(`No dice: ${e.message}`));

Here is my package.json configuration. This is also located at the root of my project

{
  "name": "sda",
  "description": "SDA 3.0",
  "version": "0.0.1",
  "main": "gulpfile.js",
  "keywords": [
    "Angular",
    "Angular2",
    "Electron",
    "Typescript"
  ],
  "author": "Vic",
  "license": "MIT",
  "scripts": {
    "build": "gulp build",
    "start": "npm run build && electron ./dist/index.js",
    "package": "npm run build && gulp electron:package",
    "postinstall": "concurrently \"bower install\" \"typings install\"",
    "appstart": "electron ./dist/index.js",
    "test": "gulp test",
    "deploy": "rm -rf ../installer && gulp setInDevelopmentFlagToFalse && cp src/app/environment/environment.prod.ts src/app/environment/environment.ts && npm run build && cd dist && electron-packager . --platform=win32 --arch=x64 --overwrite=true --out=../../installer --icon=assets/images/icon.ico && cd ../ && gulp setInDevelopmentFlagToTrue && cp src/app/environment/environment.dev.ts src/app/environment/environment.ts && node winstaller.js"
  },
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "@angular/upgrade": "2.0.0",
    "@ng-bootstrap/ng-bootstrap": "1.0.0-alpha.8",
    "@types/hammerjs": "2.0.33",
    "@types/sjcl": "1.0.27",
    "angular2-jwt": "0.1.23",
    "angular2-moment": "1.0.0-beta.5",
    "angular2localization": "1.0.2",
    "bootstrap": "4.0.0-alpha.4",
    "core-js": "2.4.1",
    "file-saver": "1.3.3",
    "font-awesome": "4.6.3",
    "jquery": "3.1.1",
    "moment": "2.15.2",
    "normalize.css": "5.0.0",
    "reflect-metadata": "0.1.3",
    "rxjs": "5.0.0-beta.12",
    "sjcl": "1.0.6",
    "systemjs": "0.19.27",
    "tether": "1.3.7",
    "zone.js": "0.6.23"
  },
  "devDependencies": {
    "bower": "1.7.9",
    "concurrently": "2.2.0",
    "del": "2.2.0",
    "electron": "1.3.5",
    "electron-connect": "0.6.0",
    "electron-packager": "8.1.0",
    "electron-prebuilt": "1.3.8",
    "electron-winstaller": "2.3.4",
    "eslint": "3.6.0",
    "eslint-config-google": "0.6.0",
    "eslint-plugin-html": "1.5.3",
    "gulp": "3.9.1",
    "gulp-atom-electron": "1.9.0",
    "gulp-concat": "2.6.0",
    "gulp-replace": "^0.5.4",
    "gulp-sass": "2.3.1",
    "gulp-shell": "0.5.2",
    "gulp-symdest": "1.0.0",
    "gulp-typescript": "3.0.2",
    "hammerjs": "2.0.8",
    "jasmine-core": "2.5.2",
    "karma": "1.3.0",
    "karma-chrome-launcher": "2.0.0",
    "karma-cli": "1.0.1",
    "karma-htmlfile-reporter": "0.3.4",
    "karma-jasmine": "1.0.2",
    "karma-jasmine-html-reporter": "0.2.2",
    "karma-sourcemap-loader": "0.3.7",
    "karma-typescript-preprocessor": "0.3.0",
    "run-sequence": "1.1.5",
    "typescript": "2.0.2",
    "typings": "1.3.2"
  }
}

Do I maybe need a certificate ?
Is it not a default setting for the windows installer to ask where to install?


问:
Must Java be installed to run a Java application?
when you write an app in java, people need to have this java installed to use it right?

Sorry if this is a dumb question.

答:
Yes, you need the Java Runtime to run a java program:

http://java.com/en/download/

ContentLicense: CC BY-SA 2.5


问:
Writing List to Loaded Excel Workbook using dataframes or other
I am having some trouble finding the best way to write a list to a loaded excel sheet and then saving the result as an xlsx. What I want my code to do is to take the lists that I have created and put them in specific columns of the loaded workbook. I think there is probably an easier way to do this using dataframes, but I do not know how. Ideally, I would like to save the formatting of the loaded workbook. My code does not work as it stands. I am using Spyder from Anaconda.

```<code>col_test = [1L, 2L, 3L, 4L, 5L]
</code>```

My code is this

```<code>import xlrt
from xlrd import open_workbook
rb = open_workbook("Excel FDT Master_01_update.xlsx")
s = rb.sheet_by_name('INPUT')
r = 5
for test in col_test:
    s.cell(row = r, column = 1).value = test
    r += 1
rb.save('didthiswork.xlsx')
</code>```

答:
I'd use pandas

```<code>import pandas as pd

col_test = [1L, 2L, 3L, 4L, 5L]
data = pd.read_excel('workbook.xlsx', 'INPUT')

# Write to specific column name
start_row = 5
for i, val in enumerate(col_test):
    data.iloc[start_row + i, 'COL_NAME'] = val

writer = pd.ExcelWriter('output.xlsx')
data.to_excel(writer, 'NewSheet')
</code>```

Assigning values to particular cell

read_excel

to_excel

Body:
I am having some trouble finding the best way to write a list to a loaded excel sheet and then saving the result as an xlsx. What I want my code to do is to take the lists that I have created and put them in specific columns of the loaded workbook. I think there is probably an easier way to do this using dataframes, but I do not know how. Ideally, I would like to save the formatting of the loaded workbook. My code does not work as it stands. I am using Spyder from Anaconda.

col_test = [1L, 2L, 3L, 4L, 5L]

My code is this

import xlrt
from xlrd import open_workbook
rb = open_workbook("Excel FDT Master_01_update.xlsx")
s = rb.sheet_by_name('INPUT')
r = 5
for test in col_test:
    s.cell(row = r, column = 1).value = test
    r += 1
rb.save('didthiswork.xlsx')

Body:
I'd use pandas

import pandas as pd

col_test = [1L, 2L, 3L, 4L, 5L]
data = pd.read_excel('workbook.xlsx', 'INPUT')

# Write to specific column name
start_row = 5
for i, val in enumerate(col_test):
    data.iloc[start_row + i, 'COL_NAME'] = val

writer = pd.ExcelWriter('output.xlsx')
data.to_excel(writer, 'NewSheet')

Assigning values to particular cell

read_excel

to_excel


问:
Trying to join three tables to get a specific result
I am trying to write an SQL query to return the name of the person who adopted the cat 'seashell'

I have a adopters table with people who will or have adopted an animal.

```<code>pets=# SELECT * FROM adopters;
 id | first_name | last_name |       address        | phone_number
----+------------+-----------+----------------------+--------------
  1 | jack       | smith     | 1 ave                | 123-123-1234
  2 | james      | dude      | 2 ave                | 221-234-4444
  3 | Forrest    | Stone     | 3 lane               | 234-667-6543
  4 | craig      | list      | 44 bulvard           | 555-444-3243
  5 | kap        | seven     | no team              | 999-000-0909
  6 | Miles      | Garrett   | First energy stadium | 123-555-2424
(6 rows)
</code>```

A cats table with the cats on file

```<code>pets=# SELECT * FROM cats;
 id |   name   | gender | age |     intake_date     |    adoption_date
----+----------+--------+-----+---------------------+---------------------
  1 | Mushi    | M      |   1 | 2016-01-09 00:00:00 | 2016-03-22 00:00:00
  2 | Seashell | F      |   7 | 2016-01-09 00:00:00 |
  3 | Azul     | M      |   3 | 2016-01-11 00:00:00 | 2016-04-17 00:00:00
  4 | Victoire | M      |   7 | 2016-01-11 00:00:00 | 2016-09-01 00:00:00
  5 | Nala     | F      |   1 | 2016-01-12 00:00:00 |
(5 rows)
</code>```

And an adoptions table with a record of all the adoptions that have taken place.

```<code>pets=# SELECT * FROM adoptions;
 id | adopters | cat |  dog  |  fee  |    date
----+----------+-----+-------+-------+------------
  1 |        1 |     | 10001 | 10.50 | 2017-11-22
  2 |        2 |     | 10007 | 10.50 | 2017-11-22
  3 |        3 |   5 |       | 10.50 | 2017-11-22
  4 |        5 |   2 |       | 10.50 | 2016-11-22
(4 rows)
</code>```

I am having trouble with the concept of joining three tables and even if you don't have a direct answer to the problem I would greatly appreciate being pointed in the direction of a resource that would help.

答:
Try this</p>

```<code>SELECT adopters.first_name, adopters.last_name
FROM adopters
INNER JOIN adoptions on adopters.id = adoptions.adopters
INNER JOIN cats on cats.id = adoptions.cats
WHERE cats.id = 2
</code>```

Body:
I am trying to write an SQL query to return the name of the person who adopted the cat 'seashell'

I have a adopters table with people who will or have adopted an animal.

pets=# SELECT * FROM adopters;
 id | first_name | last_name |       address        | phone_number
----+------------+-----------+----------------------+--------------
  1 | jack       | smith     | 1 ave                | 123-123-1234
  2 | james      | dude      | 2 ave                | 221-234-4444
  3 | Forrest    | Stone     | 3 lane               | 234-667-6543
  4 | craig      | list      | 44 bulvard           | 555-444-3243
  5 | kap        | seven     | no team              | 999-000-0909
  6 | Miles      | Garrett   | First energy stadium | 123-555-2424
(6 rows)

A cats table with the cats on file

pets=# SELECT * FROM cats;
 id |   name   | gender | age |     intake_date     |    adoption_date
----+----------+--------+-----+---------------------+---------------------
  1 | Mushi    | M      |   1 | 2016-01-09 00:00:00 | 2016-03-22 00:00:00
  2 | Seashell | F      |   7 | 2016-01-09 00:00:00 |
  3 | Azul     | M      |   3 | 2016-01-11 00:00:00 | 2016-04-17 00:00:00
  4 | Victoire | M      |   7 | 2016-01-11 00:00:00 | 2016-09-01 00:00:00
  5 | Nala     | F      |   1 | 2016-01-12 00:00:00 |
(5 rows)

And an adoptions table with a record of all the adoptions that have taken place.

pets=# SELECT * FROM adoptions;
 id | adopters | cat |  dog  |  fee  |    date
----+----------+-----+-------+-------+------------
  1 |        1 |     | 10001 | 10.50 | 2017-11-22
  2 |        2 |     | 10007 | 10.50 | 2017-11-22
  3 |        3 |   5 |       | 10.50 | 2017-11-22
  4 |        5 |   2 |       | 10.50 | 2016-11-22
(4 rows)

I am having trouble with the concept of joining three tables and even if you don't have a direct answer to the problem I would greatly appreciate being pointed in the direction of a resource that would help.

Body:
Try this

SELECT adopters.first_name, adopters.last_name
FROM adopters
INNER JOIN adoptions on adopters.id = adoptions.adopters
INNER JOIN cats on cats.id = adoptions.cats
WHERE cats.id = 2


答:
TRY:</p>

```<code>SELECT
  pers.first_name,
  pers.last_name
FROM
    cats ct
JOIN
    adoptions adop ON (ct.id = adop.id)
JOIN
    adopters pers ON (adop.adopters = pers.id)
WHERE
  ct.name = "Seashell ";
</code>```

Title: Trying to join three tables to get a specific result

Body:
TRY:

SELECT
  pers.first_name,
  pers.last_name
FROM
    cats ct
JOIN
    adoptions adop ON (ct.id = adop.id)
JOIN
    adopters pers ON (adop.adopters = pers.id)
WHERE
  ct.name = "Seashell ";


问:
I2C Master-slave address
I am working on a project where I'm trying to implement I2C master-slave communication so as to read some data from a magnetic sensor. That's all OK and I have written the code. However, I am not quite sure about the slave address needed for the communication to actually happen. The board I'm using can hold STM32 ARM® Cortex™-M3 and Cortex™-M4 MCU's. I don't know if it matters, but the MCU I'm using is STM32F107VCT6.

The part of the code where I need to enter the address is in the following function marked as "SLAVE_ADDRESS_GOES_HERE":

```<code>uint8_t Magnet_readReg(const uint8_t regAdd)
  {
    uint8_t pom[1] = {0};
    pom[0] = regAdd;
    I2C1_Start();
    I2C1_Write(SLAVE_ADDRESS_GOES_HERE, pom, 1, END_MODE_RESTART);
    I2C1_Read(SLAVE_ADDRESS_GOES_HERE, pom, 1, END_MODE_STOP);

    return pom[0];
  }
</code>```

The results should be some numbers which tell me how strong the magnetic field is. It has three different values as an output because it calculates a value for each of the three axes (yes, it's the correct plural of the word axis), so it can could be used as a compass for example.

Now the trick is that I don't get any results because I don't know the actual address of the sensor. Therefore, I will share the datasheet of the sensor I'm using. I am not sure if i'm reading it correctly.

Here is the datasheet:

https://www.memsic.com/userfiles/files/Datasheets/Magnetic-Sensors-Datasheets/MMC3416xPJ_Rev_C_2013_10_30.pdf

Solved.

As it turns out, there was something wrong with the board itself. Therefore, a connection couldn't be established. And the address is 60H for writing and 61H for reading. 30H is the address, but when you add a zero or a one in the LSB position you get 60H or 61H.

答:
The I2C address of your sensor is described on page 4 of the datasheet you provided. You must read the marking on your device package, then use the table from "Number" to "Part number" in the datasheet to determine your exact part. Finally, use the table under the "Ordering Guide" to find the factory-programmed I2C slave address of your device.

Given that you later specified that your 7-bit I2C slave address is 0x30, then you must have part number MMC34160PJ, which should be marked:

0 •

XX

Title: I2C Master-slave address

Body:
I am working on a project where I'm trying to implement I2C master-slave communication so as to read some data from a magnetic sensor. That's all OK and I have written the code. However, I am not quite sure about the slave address needed for the communication to actually happen. The board I'm using can hold STM32 ARM® Cortex™-M3 and Cortex™-M4 MCU's. I don't know if it matters, but the MCU I'm using is STM32F107VCT6.

The part of the code where I need to enter the address is in the following function marked as "SLAVE_ADDRESS_GOES_HERE":

uint8_t Magnet_readReg(const uint8_t regAdd)
  {
    uint8_t pom[1] = {0};
    pom[0] = regAdd;
    I2C1_Start();
    I2C1_Write(SLAVE_ADDRESS_GOES_HERE, pom, 1, END_MODE_RESTART);
    I2C1_Read(SLAVE_ADDRESS_GOES_HERE, pom, 1, END_MODE_STOP);

    return pom[0];
  }

The results should be some numbers which tell me how strong the magnetic field is. It has three different values as an output because it calculates a value for each of the three axes (yes, it's the correct plural of the word axis), so it can could be used as a compass for example.

Now the trick is that I don't get any results because I don't know the actual address of the sensor. Therefore, I will share the datasheet of the sensor I'm using. I am not sure if i'm reading it correctly.

Here is the datasheet:

https://www.memsic.com/userfiles/files/Datasheets/Magnetic-Sensors-Datasheets/MMC3416xPJ_Rev_C_2013_10_30.pdf

Solved.

As it turns out, there was something wrong with the board itself. Therefore, a connection couldn't be established. And the address is 60H for writing and 61H for reading. 30H is the address, but when you add a zero or a one in the LSB position you get 60H or 61H.


问:
How can I extract the value from ipairs?
When I write the command the result is below one.

```<code>No   ID         Sub-Id             Sig    Mode
22   DarrenIm   00:00:00:1a:00     60     13n/d
32   DarrenYou  00:00:00:1b:01     80     13n/d
</code>```

I want to extract the Sig value(and from comparing the sig values, I want to get highest Sig value and want to get ID in same column). I tried it but I have an problem.
Here is my code.

```<code>f = assert(io.popen("Here is my command"))

local val = {}

for line in f:lines() do
    print(line)
    for v in line:gmatch'[%d]%d' do
            table.insert(val, v)
    end

    for i, v in ipairs(val) do
            m = math.max(i)
            n = m-1
            sig = v
            print(sig)
    end

print(n)

end

f:close()
</code>```

However, when I used sig[n] there is an error, so I can't extract the value.
And from comparing that values, I want to get the highest signal and to get Id in same column.
How can I do for solving this problem?

答:
Let's take a look at your code. First you get a file handle

```<code>f = assert(io.popen("Here is my command"))
</code>```

then you create a table

```<code>local val = {}
</code>```

You read the file line by line, print it

```<code>for line in f:lines() do
    print(line)
</code>```

You insert every match for '[%d]%d' in each line into your table val

```<code>    for v in line:gmatch'[%d]%d' do
            table.insert(val, v)
    end
</code>```

Now you do something that would only make sense after having parsed all lines of your file into val. But this is done for each line as you are still inside the line-loop.

```<code>    for i, v in ipairs(val) do
</code>```

i is a number, what is the maximum of a single number? so this line is nonsense.

```<code>            m = math.max(i)
            n = m-1
</code>```

sig is a global variable. in your case it's a string. so sig[n] will of course give you an error because you can only index table values.

```<code>            sig = v
            print(sig)
    end

print(n)

end

f:close()
</code>```

The string pattern '[%d]' doesn't make too much sense. [] creates a class of characters. And %d stands for any number. Putting that into a class alone makes no difference to just using %d.

Your code shows that you lack very basic knowledge in Lua. Please do some beginners tutorial befor attempting to parse files.

The structure of your code indicates that you did not really think about the order of operations. Get pen and paper and think befor you start programming.

Body:
When I write the command the result is below one.

No   ID         Sub-Id             Sig    Mode
22   DarrenIm   00:00:00:1a:00     60     13n/d
32   DarrenYou  00:00:00:1b:01     80     13n/d

I want to extract the Sig value(and from comparing the sig values, I want to get highest Sig value and want to get ID in same column). I tried it but I have an problem.
Here is my code.

f = assert(io.popen("Here is my command"))

local val = {}

for line in f:lines() do
    print(line)
    for v in line:gmatch'[%d]%d' do
            table.insert(val, v)
    end

    for i, v in ipairs(val) do
            m = math.max(i)
            n = m-1
            sig = v
            print(sig)
    end

print(n)

end

f:close()

However, when I used sig[n] there is an error, so I can't extract the value.
And from comparing that values, I want to get the highest signal and to get Id in same column.
How can I do for solving this problem?

Body:
Let's take a look at your code. First you get a file handle

f = assert(io.popen("Here is my command"))

then you create a table

local val = {}

You read the file line by line, print it

for line in f:lines() do
    print(line)

You insert every match for '[%d]%d' in each line into your table val

    for v in line:gmatch'[%d]%d' do
            table.insert(val, v)
    end

Now you do something that would only make sense after having parsed all lines of your file into val. But this is done for each line as you are still inside the line-loop.

    for i, v in ipairs(val) do

i is a number, what is the maximum of a single number? so this line is nonsense.

            m = math.max(i)
            n = m-1

sig is a global variable. in your case it's a string. so sig[n] will of course give you an error because you can only index table values.

            sig = v
            print(sig)
    end

print(n)

end

f:close()

The string pattern '[%d]' doesn't make too much sense. [] creates a class of characters. And %d stands for any number. Putting that into a class alone makes no difference to just using %d.

Your code shows that you lack very basic knowledge in Lua. Please do some beginners tutorial befor attempting to parse files.

The structure of your code indicates that you did not really think about the order of operations. Get pen and paper and think befor you start programming.


问:
Strategies for the caller to decide data connection
Consider an existing data access and business logic layer that is used by multiple different applications and that, until now, only needed a single data connection for the lifetime of any given application that consumed it - so the connection info could simply be pulled by the data layer from the application's config file.  Moving forward, however, the data and logic classes need to provide the flexibility for the applications to determine the data connection on a per call basis.  What's more, the classes are now called by multiple applications simoultaneously through services.

The callers don't want to manage connection strings specifically, but rather connection names in the form of an enum that can be resolved to connection strings in and by the data layer.

Currently, all data and logic classes are static with the data being scoped internal and the logic being scoped public.

What are some good strategies to get a key from the caller all the way down to the methods in the data classes considering things like API useability, performance, thread safety / caller isolation, etc.

Two obvious options are:

Add the connection key as a parameter to all methods. Yuck - isn't going to happen but including for completeness.

Change the logic and data classes to instance classes and pass the key in the constructors for any member method to use.  There would be no method signature changes but a substantially breaking change to how the API is called.

What other options are there?

答:
Unfortunately, you hit the two best options for how to deal with this type of issue. #2 is made a bit more complicated by having services involved, because different service requests are either going to need a way to remember which client is which (like sessions) or going to have to pass the connection information through the service on each call.

I think if you create a client side wrapper class to access the service, you can limit how many client side changes you're going to need. For the service itself, I think you're really going to be stuck passing the connection as a parameter each time simply because the alternatives there are pretty complicated.


问:
IBMWatson - How to run with cURL?
IBM Watson suggests some example on it's guide. But I can't work even a basic request.

```<code>curl -u "xxx@gmail.com":"password" "https://gateway.watsonplatform.net/language-translator/api/v2"
</code>```

I can't understand why the request can't be authorized.

Error is here :

{ "code" : 401 , "error" : "Not Authorized" , "description" : "2017-11-24T17:52:58-05:00, Error ERCDPLTFRM-INVLDCHR occurred when accessing https://gateway.watsonplatform.net/language-translator/api/v2, Tran-Id: gateway-dp01-1410026512 - " }

答:
Here you are using your account credentials, but cURL expects the service authorization credentials, to access these credentials
Log into your IBM Cloud -> Dashboard -> Select Service (In your case language translator) -> Go to Credentials -> if you have one use the username and password from here else create credentials and use those credentials.

FYI they are not your email id and password

Title: IBMWatson - How to run with cURL?

Body:
IBM Watson suggests some example on it's guide. But I can't work even a basic request.

curl -u "xxx@gmail.com":"password" "https://gateway.watsonplatform.net/language-translator/api/v2"

I can't understand why the request can't be authorized.

Error is here :

{ "code" : 401 , "error" : "Not Authorized" , "description" : "2017-11-24T17:52:58-05:00, Error ERCDPLTFRM-INVLDCHR occurred when accessing https://gateway.watsonplatform.net/language-translator/api/v2, Tran-Id: gateway-dp01-1410026512 - " }


问:
fmap applied to types other than the type variable
I have a datatype which keeps track of a 'block' of numbers (kinda like a matrix).

```<code>newtype Block a = Block [[a]]
</code>```

I would like to make it an instance of Functor. However, I am trying to do it in such a way that fmap can apply to the whole list block, so that fmap has type fmap :: [[a]] -> [[b]] instead of type fmap :: a -> b.

The reason is because I would like to map into my Block functor functions like transpose which apply to the list block [[a]] not to each element a. That is, I would like to be able to define functions like

```<code>transposeBlock :: Block a -> Block a
transposeBlock = (transpose <$>)
</code>```

I tried to declare my functor instance as the following.

```<code>instance Functor (Block [[a]]) where
  fmap f (Block x) = Block (f x)
</code>```

But I ran into the type errors that arise from attempting to compile this.

```<code>error:
• Expecting one fewer argument to ‘Block [[a]]’
  Expected kind ‘* -> *’, but ‘Block [[a]]’ has kind ‘*’
• In the first argument of ‘Functor’, namely ‘Block [[a]]’
  In the instance declaration for ‘Functor (Block [[a]])’
</code>```

What are some ways that I could map functions into the list block [[a]] of my Block type?

答:
Sorry, you can't call that function fmap. But that's okay, there's lots of other good names out there.

```<code>onBlock :: ([[a]] -> [[b]]) -> Block a -> Block b
onBlock f (Block v) = Block (f v)
</code>```

You can even give it a name full of infixy punctuation goodness if you want.

```<code>(<#>) :: ([[a]] -> [[b]]) -> Block a -> Block b
f <#> Block v = Block (f v)
</code>```

Body:
I have a datatype which keeps track of a 'block' of numbers (kinda like a matrix).

newtype Block a = Block [[a]]

I would like to make it an instance of Functor. However, I am trying to do it in such a way that fmap can apply to the whole list block, so that fmap has type fmap :: [[a]] -> [[b]] instead of type fmap :: a -> b.

The reason is because I would like to map into my Block functor functions like transpose which apply to the list block [[a]] not to each element a. That is, I would like to be able to define functions like

transposeBlock :: Block a -> Block a
transposeBlock = (transpose <$>)

I tried to declare my functor instance as the following.

instance Functor (Block [[a]]) where
  fmap f (Block x) = Block (f x)

But I ran into the type errors that arise from attempting to compile this.

error:
• Expecting one fewer argument to ‘Block [[a]]’
  Expected kind ‘* -> *’, but ‘Block [[a]]’ has kind ‘*’
• In the first argument of ‘Functor’, namely ‘Block [[a]]’
  In the instance declaration for ‘Functor (Block [[a]])’

What are some ways that I could map functions into the list block [[a]] of my Block type?

Body:
Sorry, you can't call that function fmap. But that's okay, there's lots of other good names out there.

onBlock :: ([[a]] -> [[b]]) -> Block a -> Block b
onBlock f (Block v) = Block (f v)

You can even give it a name full of infixy punctuation goodness if you want.

(<#>) :: ([[a]] -> [[b]]) -> Block a -> Block b
f <#> Block v = Block (f v)


问:
CreateView - Getting a TypeError when trying to save an image upload
I'm trying to wrap my head around images and Form handling with class-based views. So i'm playing with this simple model. When using CreateView do I have to overwrite it with a custom form using form_class in order to successfully upload/save and image?

I can't figure out why I'm getting this:

```<code>Exception Type:     TypeError
Exception Value:    expected str, bytes or os.PathLike object, not tuple
</code>```

The whole thing is barebones, right out of stock.

models.py

```<code>class Post(models.Model):
    headline = models.CharField(max_length=80, blank=True, null=True)
    cover_image = models.ImageField('hero image', upload_to='images/', blank=True, null=True)
    slug = models.SlugField(max_length=80, blank=True, null=True, unique=True)

    def get_absolute_url(self):
        return reverse('details', args=[str(self.slug)])
</code>```

views.py

```<code>from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import CreateView

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['headline', 'cover_image', 'slug']
</code>```

news/templates/news/post_form.py

```<code><form enctype="multipart/form-data" method="post" action="">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save"/>
  </form>
</code>```

Can anyone help me understand?

As requested

```<code># Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

MEDIA_ROOT = (os.path.join(BASE_DIR, 'media'),)
MEDIA_URL = '/media/'

LOGIN_REDIRECT_URL = 'home'
</code>```

答:
You've set MEDIA_ROOT to a tuple, but it should be a string.</p>

```<code>MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
</code>```

Body:
I'm trying to wrap my head around images and Form handling with class-based views. So i'm playing with this simple model. When using CreateView do I have to overwrite it with a custom form using form_class in order to successfully upload/save and image?

I can't figure out why I'm getting this:

Exception Type:     TypeError
Exception Value:    expected str, bytes or os.PathLike object, not tuple

The whole thing is barebones, right out of stock.

models.py

class Post(models.Model):
    headline = models.CharField(max_length=80, blank=True, null=True)
    cover_image = models.ImageField('hero image', upload_to='images/', blank=True, null=True)
    slug = models.SlugField(max_length=80, blank=True, null=True, unique=True)

    def get_absolute_url(self):
        return reverse('details', args=[str(self.slug)])

views.py

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import CreateView

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['headline', 'cover_image', 'slug']

news/templates/news/post_form.py

<form enctype="multipart/form-data" method="post" action="">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save"/>
  </form>

Can anyone help me understand?

As requested

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

MEDIA_ROOT = (os.path.join(BASE_DIR, 'media'),)
MEDIA_URL = '/media/'

LOGIN_REDIRECT_URL = 'home'

Body:
You've set MEDIA_ROOT to a tuple, but it should be a string.

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')


问:
Powershell accessing embedded properties
I am working in Powershell and the result of some queries return a collection member like this (note that this is shortened from the actual output):

```<code>SmsProviderObjectPath : SMS_SCI_SysResUse.FileType=2,ItemName="[\"Display=\\\\SERVER1.MYDOMAIN.ORG\\\"]MSWNET:[\"SMS_SITE=MBC\"]\\\\SERVER1.MYDOMAIN.ORG\\,SMS Distribution Point",ItemType="System
                        Resource Usage",SiteCode="MBC"
FileType              : 2
ItemName              : ["Display=\\SERVER1.MYDOMAIN.ORG\"]MSWNET:["SMS_SITE=MBC"]\\SERVER1.MYDOMAIN.ORG\,SMS Distribution Point
ItemType              : System Resource Usage
NALPath               : ["Display=\\SERVER1.MYDOMAIN.ORG\"]MSWNET:["SMS_SITE=MBC"]\\SERVER1.MYDOMAIN.ORG\
NALType               : Windows NT Server
NetworkOSPath         : \\SERVER1.MYDOMAIN.ORG
PropLists             : {BindExcept, Protected Boundary, SourceDistributionPoints, SourceDPRanks...}
Props                 : {BITS download, Server Remote Name, PreStagingAllowed, SslState...}
RoleCount             : 2
RoleName              : SMS Distribution Point
SiteCode              : MBC
SslState              : 0
Type                  : 8
PSComputerName        : prim-serv.MYDOMAIN.org
PSShowComputerName    : False
ManagedObject         : \\prim-serv\root\sms\site_MBC:SMS_SCI_SysResUse.FileType=2,ItemName="[\"Display=\\\\SERVER1.MYDOMAIN.ORG\\\"]MSWNET:[\"SMS_SITE=MBC\"]\\\\SERVER1.MYDOMAIN.ORG\\,SMS
                        Distribution Point",ItemType="System Resource Usage",SiteCode="MBC"
OverridingObjectClass : SMS_SCI_SysResUse
RegMultiStringLists   : {}
SecurityVerbs         : -1
ObjectClass           : SMS_SCI_SysResUse
Properties            :
                        instance of SMS_EmbeddedProperty
                        {
                            PropertyName = "IsPXE";
                            Value = 0;
                            Value1 = "";
                            Value2 = "";
                        },
                        instance of SMS_EmbeddedProperty
                        {
                            PropertyName = "IsActive";
                            Value = 0;
                            Value1 = "";
                            Value2 = "";
                        },
                        instance of SMS_EmbeddedProperty
                        {
                            PropertyName = "IsPullDP";
                            Value = 0;
                            Value1 = "";
                            Value2 = "";
                        },
                        instance of SMS_EmbeddedProperty
                        {
                            PropertyName = "IsMulticast";
                            Value = 0;
                            Value1 = "";
                            Value2 = "";
                        },
                        instance of SMS_EmbeddedProperty
                        {
                            PropertyName = "LastIISConfigCheckTime";
                            Value = 1490896883;
                            Value1 = "";
                            Value2 = "";
                        }};
                            RoleCount = 2;
                            RoleName = "SMS Distribution Point";
                            SiteCode = "MBC";
                            SslState = 0;
                            Type = 8;
                        };

PropertyNames         : {FileType, ItemName, ItemType, NALPath...}
MethodNames           :
MethodList            : {}
PropertyList          : {[FileType, 2], [ItemName, ["Display=\\SERVER1.MYDOMAIN.ORG\"]MSWNET:["SMS_SITE=MBC"]\\SERVER1.MYDOMAIN.ORG\,SMS Distribution Point], [ItemType, System Resource Usage],
                        [NALPath, ["Display=\\SERVER1.MYDOMAIN.ORG\"]MSWNET:["SMS_SITE=MBC"]\\SERVER1.MYDOMAIN.ORG\]...}
UniqueIdentifier      : 16242167-3aac-4b79-ad5b-2c8030922ba5
ParentResultObject    :
GlobalDisplayString   :
AutoCommit            : False
AutoRefresh           : False
UserDataObject        :
ConnectionManager     : Microsoft.ConfigurationManagement.PowerShell.Provider.CmdletWqlConnectionManager
TraceProperties       : True
NamedValueDictionary  : {[AllProviderLocations, System.Collections.Generic.List`1[System.Management.ManagementBaseObject]], [ProviderLocation,
                        \\prim-serv\ROOT\sms:SMS_ProviderLocation.Machine="prim-serv.MYDOMAIN.org",SiteCode="MBC"], [ProviderMachineName, prim-serv.MYDOMAIN.org], [Connection,
                        \\prim-serv.MYDOMAIN.org\root\sms\site_MBC]...}
AsyncOperationData    :
RetainObjectLock      : False
</code>```

I can access many of the items listed, such as "NetworkOSPath" and "RoleName" with code like this:

$myDP = $DP.NetworkOSPath

I am at a loss how to reference items listed in the Properties area such as:

IsPXE, IsPullDP and the values associated with them.

I can get a listing of them using the command:  $dp.EmbeddedProperties | format-list *

This produces a listing of Keys and Values:

```<code>Key   : AllowInternetClients
Value :
        instance of SMS_EmbeddedProperty
        {
            PropertyName = "AllowInternetClients";
            Value = 0;
            Value1 = "";
            Value2 = "";
        };

Key   : BITS download
Value :
        instance of SMS_EmbeddedProperty
        {
            PropertyName = "BITS download";
            Value = 1;
            Value1 = "";
            Value2 = "";
        };
</code>```

In an effort to just list a specific key, I've tried the following without success:

```<code>foreach ($DP in $DPList) {$DP.EmbeddedProperties | select-object -expandproperty IsPXE }

foreach ($DP in $DPList) {$DP.EmbeddedProperties | Select-Object where Name = "IsPXE"}

foreach ($DP in $DPList) {$DP.EmbeddedProperties | Select-Object IsPXE}
</code>```

Is there a way to reference the key and their associated values so that I can assign them to variables inside of my script?

答:
You were so close with $dp.EmbeddedProperties. Just keep dotting and you'll get there. Once you get the value you are looking for, you can add it to an object. Here's an example:

```<code>$dp = Get-CMDistributionPoint
$NewObj = @()
ForEach ($d in $dp)
{
    $ServerName = $d.NetworkOSPath
    $IsPXE = $d.embeddedproperties.IsPXE.Value
    $NewObj += [pscustomObject]@{ ServerName = $ServerName; IsPXE = $IsPXE }
}
$NewObj | Out-GridView
</code>```

BE CAREFUL - Once you dot-note passed EmbeddedProperties, you enter the eerie world of Case-Sensitivity! If you don't have it correct, you get NOTHING! I'm not sure why. perhaps it has something to do with the .NET's System.Collections.Generic.Dictionary class and Case-Sensitive String Keys?
IE

```<code>$d.embeddedproperties.IsPXE.Value ##This works.
$d.embeddedproperties.IsPXe.Value ##This does not work.
</code>```

Body:
I am working in Powershell and the result of some queries return a collection member like this (note that this is shortened from the actual output):

SmsProviderObjectPath : SMS_SCI_SysResUse.FileType=2,ItemName="[\"Display=\\\\SERVER1.MYDOMAIN.ORG\\\"]MSWNET:[\"SMS_SITE=MBC\"]\\\\SERVER1.MYDOMAIN.ORG\\,SMS Distribution Point",ItemType="System
                        Resource Usage",SiteCode="MBC"
FileType              : 2
ItemName              : ["Display=\\SERVER1.MYDOMAIN.ORG\"]MSWNET:["SMS_SITE=MBC"]\\SERVER1.MYDOMAIN.ORG\,SMS Distribution Point
ItemType              : System Resource Usage
NALPath               : ["Display=\\SERVER1.MYDOMAIN.ORG\"]MSWNET:["SMS_SITE=MBC"]\\SERVER1.MYDOMAIN.ORG\
NALType               : Windows NT Server
NetworkOSPath         : \\SERVER1.MYDOMAIN.ORG
PropLists             : {BindExcept, Protected Boundary, SourceDistributionPoints, SourceDPRanks...}
Props                 : {BITS download, Server Remote Name, PreStagingAllowed, SslState...}
RoleCount             : 2
RoleName              : SMS Distribution Point
SiteCode              : MBC
SslState              : 0
Type                  : 8
PSComputerName        : prim-serv.MYDOMAIN.org
PSShowComputerName    : False
ManagedObject         : \\prim-serv\root\sms\site_MBC:SMS_SCI_SysResUse.FileType=2,ItemName="[\"Display=\\\\SERVER1.MYDOMAIN.ORG\\\"]MSWNET:[\"SMS_SITE=MBC\"]\\\\SERVER1.MYDOMAIN.ORG\\,SMS
                        Distribution Point",ItemType="System Resource Usage",SiteCode="MBC"
OverridingObjectClass : SMS_SCI_SysResUse
RegMultiStringLists   : {}
SecurityVerbs         : -1
ObjectClass           : SMS_SCI_SysResUse
Properties            :
                        instance of SMS_EmbeddedProperty
                        {
                            PropertyName = "IsPXE";
                            Value = 0;
                            Value1 = "";
                            Value2 = "";
                        },
                        instance of SMS_EmbeddedProperty
                        {
                            PropertyName = "IsActive";
                            Value = 0;
                            Value1 = "";
                            Value2 = "";
                        },
                        instance of SMS_EmbeddedProperty
                        {
                            PropertyName = "IsPullDP";
                            Value = 0;
                            Value1 = "";
                            Value2 = "";
                        },
                        instance of SMS_EmbeddedProperty
                        {
                            PropertyName = "IsMulticast";
                            Value = 0;
                            Value1 = "";
                            Value2 = "";
                        },
                        instance of SMS_EmbeddedProperty
                        {
                            PropertyName = "LastIISConfigCheckTime";
                            Value = 1490896883;
                            Value1 = "";
                            Value2 = "";
                        }};
                            RoleCount = 2;
                            RoleName = "SMS Distribution Point";
                            SiteCode = "MBC";
                            SslState = 0;
                            Type = 8;
                        };

PropertyNames         : {FileType, ItemName, ItemType, NALPath...}
MethodNames           :
MethodList            : {}
PropertyList          : {[FileType, 2], [ItemName, ["Display=\\SERVER1.MYDOMAIN.ORG\"]MSWNET:["SMS_SITE=MBC"]\\SERVER1.MYDOMAIN.ORG\,SMS Distribution Point], [ItemType, System Resource Usage],
                        [NALPath, ["Display=\\SERVER1.MYDOMAIN.ORG\"]MSWNET:["SMS_SITE=MBC"]\\SERVER1.MYDOMAIN.ORG\]...}
UniqueIdentifier      : 16242167-3aac-4b79-ad5b-2c8030922ba5
ParentResultObject    :
GlobalDisplayString   :
AutoCommit            : False
AutoRefresh           : False
UserDataObject        :
ConnectionManager     : Microsoft.ConfigurationManagement.PowerShell.Provider.CmdletWqlConnectionManager
TraceProperties       : True
NamedValueDictionary  : {[AllProviderLocations, System.Collections.Generic.List`1[System.Management.ManagementBaseObject]], [ProviderLocation,
                        \\prim-serv\ROOT\sms:SMS_ProviderLocation.Machine="prim-serv.MYDOMAIN.org",SiteCode="MBC"], [ProviderMachineName, prim-serv.MYDOMAIN.org], [Connection,
                        \\prim-serv.MYDOMAIN.org\root\sms\site_MBC]...}
AsyncOperationData    :
RetainObjectLock      : False

I can access many of the items listed, such as "NetworkOSPath" and "RoleName" with code like this:

$myDP = $DP.NetworkOSPath

I am at a loss how to reference items listed in the Properties area such as:

IsPXE, IsPullDP and the values associated with them.

I can get a listing of them using the command:  $dp.EmbeddedProperties | format-list *

This produces a listing of Keys and Values:

Key   : AllowInternetClients
Value :
        instance of SMS_EmbeddedProperty
        {
            PropertyName = "AllowInternetClients";
            Value = 0;
            Value1 = "";
            Value2 = "";
        };

Key   : BITS download
Value :
        instance of SMS_EmbeddedProperty
        {
            PropertyName = "BITS download";
            Value = 1;
            Value1 = "";
            Value2 = "";
        };

In an effort to just list a specific key, I've tried the following without success:

foreach ($DP in $DPList) {$DP.EmbeddedProperties | select-object -expandproperty IsPXE }

foreach ($DP in $DPList) {$DP.EmbeddedProperties | Select-Object where Name = "IsPXE"}

foreach ($DP in $DPList) {$DP.EmbeddedProperties | Select-Object IsPXE}

Is there a way to reference the key and their associated values so that I can assign them to variables inside of my script?

Body:
You were so close with $dp.EmbeddedProperties. Just keep dotting and you'll get there. Once you get the value you are looking for, you can add it to an object. Here's an example:

$dp = Get-CMDistributionPoint
$NewObj = @()
ForEach ($d in $dp)
{
    $ServerName = $d.NetworkOSPath
    $IsPXE = $d.embeddedproperties.IsPXE.Value
    $NewObj += [pscustomObject]@{ ServerName = $ServerName; IsPXE = $IsPXE }
}
$NewObj | Out-GridView

BE CAREFUL - Once you dot-note passed EmbeddedProperties, you enter the eerie world of Case-Sensitivity! If you don't have it correct, you get NOTHING! I'm not sure why. perhaps it has something to do with the .NET's System.Collections.Generic.Dictionary class and Case-Sensitive String Keys?
IE

$d.embeddedproperties.IsPXE.Value ##This works.
$d.embeddedproperties.IsPXe.Value ##This does not work.


问:
`var` and `let` behaviour in arrow functions
Why i behaves differently in arrow functions? Is it because var x is being reassigned while let x is being created new for each iteration?

//prints 55555
for(var x = 0; x < 5;x++){
    setTimeout(()=>console.log(x),0);
}

//prints 01234
for(let x = 0;x < 5;x++){
    setTimeout(()=>console.log(x),0);
}```

答:
It has nothing to do with arrow functions. let is block level scope, so each time you enter the body of the loop, you get a new variable.

In your case, the timer function prints differently,  because of the closure being created around x.

var provides one variable that all iterations of the loop (and therefore, all timer callbacks) share, hence you get the last value of the variable shared by each timer callback. Remember, the timer callbacks won’t run until your loop is finished and, at that time, x has been incremented to 5.

let gives each timer callback it’s own value because of the block scope. So, even though the timer callbacks don’t run until the loop is finished, each callback has a closure around a differently scoped variable.


问:
what are the possible ways to force mathematica to show -1+a as a-1
I am just getting started with pattern in mathematica. I want to know what the different ways to force mma to show -1+a as a-1. Many thanks!

答: The simplest way is probably -1 + a // TraditionalForm.


问:
H.264 - Identify Access Units of an image
I need to parse a H.264 stream to collect only NAL's needed to form a complete image, of only one frame. I'm reading the H.264 standard, but it's confuse and hard to read. I made some experiments but, did not worked. For example, i extracted an access unit with primary_pic_type == 0 containing only slice_type == 7 (I-Slice), it should give me a frame, but i tried to extract from ffmpeg, it did not work. But, when i append the next access_unit, containing only slice_type == 5 (P-Slice) it worked. Maybe i need to extract POC information, but i think not, because i only need extract one frame, but i'm not sure. Someone have some tip of how get only NAL's i need to form one complete image?</p>

答: Just in case someone has the same problem, i solved it. I go until i find an AUD of primary_pic_type == 0. So i extract the AUD and the next one (when it's a field), send the two AUD to the server, and decode the frame using ffmpeg to generate a JPG image.</p>


问:
Angular 2 optional route parameter
Is it possible to have an optional route parameter in the Angular 2 route? I tried the Angular 1.x syntax in RouteConfig but received below error:

"ORIGINAL EXCEPTION: Path "/user/:id?" contains "?" which is not allowed in a route config."

```<code>@RouteConfig([
{
    path: '/user/:id?',
    component: User,
    as: 'User'
}])
</code>```

答:
Ran into another instance of this problem, and in searching for a solution to it came here. My issue was that I was doing the children, and lazy loading of the components as well to optimize things a bit. In short if you are lazy loading the parent module. Main thing was my using '/:id' in the route, and it's complaints about '/' being a part of it. Not the exact problem here, but it applies.

App-routing from parent

```<code>...
const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'pathOne',
        loadChildren: 'app/views/$MODULE_PATH.module#PathOneModule'
      },
      {
        path: 'pathTwo',
        loadChildren: 'app/views/$MODULE_PATH.module#PathTwoModule'
      },
...
</code>```

Child routes lazy loaded

```<code>...
const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: '',
        component: OverviewComponent
      },
      {
        path: ':id',
        component: DetailedComponent
      },
    ]
  }
];
...
</code>```

Title: Angular 2 optional route parameter

Body:
Is it possible to have an optional route parameter in the Angular 2 route? I tried the Angular 1.x syntax in RouteConfig but received below error:

"ORIGINAL EXCEPTION: Path "/user/:id?" contains "?" which is not allowed in a route config."

@RouteConfig([
{
    path: '/user/:id?',
    component: User,
    as: 'User'
}])

Body:
Ran into another instance of this problem, and in searching for a solution to it came here. My issue was that I was doing the children, and lazy loading of the components as well to optimize things a bit. In short if you are lazy loading the parent module. Main thing was my using '/:id' in the route, and it's complaints about '/' being a part of it. Not the exact problem here, but it applies.

App-routing from parent

...
const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'pathOne',
        loadChildren: 'app/views/$MODULE_PATH.module#PathOneModule'
      },
      {
        path: 'pathTwo',
        loadChildren: 'app/views/$MODULE_PATH.module#PathTwoModule'
      },
...

Child routes lazy loaded

...
const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: '',
        component: OverviewComponent
      },
      {
        path: ':id',
        component: DetailedComponent
      },
    ]
  }
];
...


问:
append item to list at a random index os initial list
i have a list of answers to a quiz i a making, i would like to make it multiple choice and in multiple choice quizes the  answer is never at the bottom always or at the same index however this is what my code is

```<code>Answers = ["bogota", "carracas", "brasilia", "santiago", "london"]
Questions = ["colombia", "venezuela", "brasil", "chile", "england"]
q = [Questions[i] for i in sorted(random.sample(range(len(Questions)), 3))]
tryindex = [i for i, x in enumerate(QuestionsT) if x in q]
Ca = [Answers[i] for i in tryindex]
for x in q:
    Pa = [i for i in random.sample(Answers, 3) if i !=q.index(x)]
    Pa.append(Ca[q.index(x)])
    print("what is the capital of:" + x + "?")
    print("\n".join(Pa))
    a = input("\n""Answer")
    for i in range(0,3):
        if a == Ca[i]:
            score +=1
</code>```

this returns eg for one iteration:
what is the capital of: colombia?
london
carracas
brasilia
santiago
bogota

notice that bogota is at the bottom due to the .append(Ca[q.insert(x)])

what i would like is that the answer in this case would be inserted into Ca(correct answers) randomly. is there a way to do this?

Answers means the genral list of all the answers possible Questions
means the general list of all questions possible

in both of the above lists each element is reference by its index so

that by finding the index of the element in Questions it is
possible    to find the value held in Answers by the same index

q means questions selected randomly for quiz
Ca means correct answers for questions in q.
Pa means possible answers, randomly obtained from the genral array Answers.

答:
Here is a clean solution, take a look, change what you want, ask for what you don't get.</p>

```<code># -*- coding: utf-8 -*-

# Imports
import random

# Parameters
data = {'Brasil': 'Brasilia',
 'Chile': 'Santiago',
 'Colombia': 'Bogota',
 'England': 'London',
 'Venezuela': 'Carracas'}

nbr_questions = 3
score = 0
former_questions = ['']

# Script
for i in range(nbr_questions):
    # Grab the couple country / capital from the data dictionnary
    capital = ''
    while capital in former_questions:
        country, capital = random.choice(list(data.items()))

    # Create the proposition display list
    proposition_display = list()
    proposition_display.append(capital)
    i = 0
    while i < 2:
        cap = random.choice(list(data.values()))
        if cap not in proposition_display:
            proposition_display.append(cap)
            i += 1

    # Display
    print ('What is the capital of {} ?'.format(country))
    answer = input ('Answer: ')

    if answer.lower().strip(' ') == capital.lower().strip(' '):
        print ('Correct!')
        score += 1
    else:
        print ('Wrong. Answer was {}.'.format(capital))

    print ('-----------------------------')

    # Add this capital to the list former_questions to avoid repetition
    former_questions.append(capital)

print ('Your score is: {}'.format(score))
</code>```

Body:
i have a list of answers to a quiz i a making, i would like to make it multiple choice and in multiple choice quizes the  answer is never at the bottom always or at the same index however this is what my code is

Answers = ["bogota", "carracas", "brasilia", "santiago", "london"]
Questions = ["colombia", "venezuela", "brasil", "chile", "england"]
q = [Questions[i] for i in sorted(random.sample(range(len(Questions)), 3))]
tryindex = [i for i, x in enumerate(QuestionsT) if x in q]
Ca = [Answers[i] for i in tryindex]
for x in q:
    Pa = [i for i in random.sample(Answers, 3) if i !=q.index(x)]
    Pa.append(Ca[q.index(x)])
    print("what is the capital of:" + x + "?")
    print("\n".join(Pa))
    a = input("\n""Answer")
    for i in range(0,3):
        if a == Ca[i]:
            score +=1

this returns eg for one iteration:
what is the capital of: colombia?
london
carracas
brasilia
santiago
bogota

notice that bogota is at the bottom due to the .append(Ca[q.insert(x)])

what i would like is that the answer in this case would be inserted into Ca(correct answers) randomly. is there a way to do this?

Answers means the genral list of all the answers possible Questions
means the general list of all questions possible

in both of the above lists each element is reference by its index so

that by finding the index of the element in Questions it is
possible    to find the value held in Answers by the same index

q means questions selected randomly for quiz
Ca means correct answers for questions in q.
Pa means possible answers, randomly obtained from the genral array Answers.

Body:
Here is a clean solution, take a look, change what you want, ask for what you don't get.

# -*- coding: utf-8 -*-

# Imports
import random

# Parameters
data = {'Brasil': 'Brasilia',
 'Chile': 'Santiago',
 'Colombia': 'Bogota',
 'England': 'London',
 'Venezuela': 'Carracas'}

nbr_questions = 3
score = 0
former_questions = ['']

# Script
for i in range(nbr_questions):
    # Grab the couple country / capital from the data dictionnary
    capital = ''
    while capital in former_questions:
        country, capital = random.choice(list(data.items()))

    # Create the proposition display list
    proposition_display = list()
    proposition_display.append(capital)
    i = 0
    while i < 2:
        cap = random.choice(list(data.values()))
        if cap not in proposition_display:
            proposition_display.append(cap)
            i += 1

    # Display
    print ('What is the capital of {} ?'.format(country))
    answer = input ('Answer: ')

    if answer.lower().strip(' ') == capital.lower().strip(' '):
        print ('Correct!')
        score += 1
    else:
        print ('Wrong. Answer was {}.'.format(capital))

    print ('-----------------------------')

    # Add this capital to the list former_questions to avoid repetition
    former_questions.append(capital)

print ('Your score is: {}'.format(score))


问:
How to post the Theta 360 degree photo to facebook in ios
I am using the Theta Camera SDK to take the picture in 360 degrees.

I want to post this photo to Facebook this is 360 photo.

```<code>         UIImage *image = [UIImage imageNamed:@"IMG_0133.JPG"];

         NSString *token = [NSString stringWithFormat:@"%@", [FBSDKAccessToken currentAccessToken].tokenString];
         NSDictionary *param = @{@"message": @"test",
                                 @"access_token": token,
                                  @"photo":image,
                                 @"allow_spherical_photo": [NSNumber numberWithBool:true]

                                 };

         FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                                       initWithGraphPath:@"me/photos"
                                       parameters:param
                                       HTTPMethod:@"post"];

         [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                               id result,
                                               NSError *error)
          {

              if (!error)
              {
                  NSLog(@"post success");

              }
          }];
</code>```

but it was post like normal image not with 360 view

答:
I wrote a framework for this exact purpose:

https://github.com/AppCoders-io/Facebook360

Assuming that you've requested the permission to share, this is what you'd use:

```<code>[[Facebook360Manager sharedInstance] shareImage:[UIImage imageNamed:@"spherical360.jpg"]
                                      userCaption:@"Example caption..."
                                    horizontalFOV:360.0
                                  sharePreference:FacebookShareManagerPreferenceSphericalImage
                                  completionBlock:^(NSError * _Nullable error, NSString * _Nullable postID) {
                                    if (error) {
                                      NSLog(@"Error: %@",error);
                                    }else{
                                      NSLog(@"Shared successfully. Post ID: %@",postID);
                                    }
                                  }];
</code>```

Body:
I am using the Theta Camera SDK to take the picture in 360 degrees.

I want to post this photo to Facebook this is 360 photo.

         UIImage *image = [UIImage imageNamed:@"IMG_0133.JPG"];

         NSString *token = [NSString stringWithFormat:@"%@", [FBSDKAccessToken currentAccessToken].tokenString];
         NSDictionary *param = @{@"message": @"test",
                                 @"access_token": token,
                                  @"photo":image,
                                 @"allow_spherical_photo": [NSNumber numberWithBool:true]

                                 };

         FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                                       initWithGraphPath:@"me/photos"
                                       parameters:param
                                       HTTPMethod:@"post"];

         [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                               id result,
                                               NSError *error)
          {

              if (!error)
              {
                  NSLog(@"post success");

              }
          }];

but it was post like normal image not with 360 view

Body:
I wrote a framework for this exact purpose:

https://github.com/AppCoders-io/Facebook360

Assuming that you've requested the permission to share, this is what you'd use:

[[Facebook360Manager sharedInstance] shareImage:[UIImage imageNamed:@"spherical360.jpg"]
                                      userCaption:@"Example caption..."
                                    horizontalFOV:360.0
                                  sharePreference:FacebookShareManagerPreferenceSphericalImage
                                  completionBlock:^(NSError * _Nullable error, NSString * _Nullable postID) {
                                    if (error) {
                                      NSLog(@"Error: %@",error);
                                    }else{
                                      NSLog(@"Shared successfully. Post ID: %@",postID);
                                    }
                                  }];


问:
Why is basic_fstream<unsigned char> order of magnitude slower than basic_fstream<char> on Windows?
In a program I was working on some one used alias for byte in the following way:

```<code>#include <fstream>
#include <vector>
using Byte = unsigned char;

void write(const Byte* buffer, size_t size) {
    std::basic_fstream<Byte> file("1gb_file", std::ios::in | std::ios::out);
    file.write(buffer, size);
    file.flush(); // To ensure the data is being written, to eliminate caching claims
}

int main(){
    auto GB = 1024u * 1024u * 1024u;
    std::vector<Byte> zeros(GB, 0);
    write(zeros.data(), zeros.size());
    return 0;
}
</code>```

The time this function took to execute on Byte == unsigned char: 52.0245s on my brand new SSD, MSVC-x64 on release mode.

On the other hand, if we change the definition to Byte == char: 1.46725s. That's it.

Why is this difference, and are there any general good practices on using the standard library to avoid such pitfalls?

Note(Edited due to a mistake): On Linux the code actually fails to run when given unsigned char(on gcc and clang), as @SergeyA pointed out. The GCC version on windows also fails to run, contrary to what I have written beforehand.

答:
I am going to bite the bullet here and guess that it has to do with locales. Based on very limited information I have, it looks like in MSVC unsigned char streams to perform locale conversions, while normal char streams do not and instead just do bulk IO. (See Notes on http://en.cppreference.com/w/cpp/io/basic_ostream/write).

Interestingly enough, the same code snippet doesn't work at all on my Linux installation with g++ 5.4 (rather old, I know). Write fails due to some internal member in stream class being nullptr (whoever interested it is _M_codecvt) and stream's badbit is set.

Body:
In a program I was working on some one used alias for byte in the following way:

#include <fstream>
#include <vector>
using Byte = unsigned char;

void write(const Byte* buffer, size_t size) {
    std::basic_fstream<Byte> file("1gb_file", std::ios::in | std::ios::out);
    file.write(buffer, size);
    file.flush(); // To ensure the data is being written, to eliminate caching claims
}

int main(){
    auto GB = 1024u * 1024u * 1024u;
    std::vector<Byte> zeros(GB, 0);
    write(zeros.data(), zeros.size());
    return 0;
}

The time this function took to execute on Byte == unsigned char: 52.0245s on my brand new SSD, MSVC-x64 on release mode.

On the other hand, if we change the definition to Byte == char: 1.46725s. That's it.

Why is this difference, and are there any general good practices on using the standard library to avoid such pitfalls?

Note(Edited due to a mistake): On Linux the code actually fails to run when given unsigned char(on gcc and clang), as @SergeyA pointed out. The GCC version on windows also fails to run, contrary to what I have written beforehand.


答:
let in the loop can re-binds it to each iteration of the loop, making
  sure to re-assign it the value from the end of the previous loop
  iteration, so it can be used to avoid issue with closures.

Read more here: http://www.jstips.co/en/javascript/keyword-var-vs-let/

Title: `var` and `let` behaviour in arrow functions

Body:
Why i behaves differently in arrow functions? Is it because var x is being reassigned while let x is being created new for each iteration?

//prints 55555
for(var x = 0; x < 5;x++){
    setTimeout(()=>console.log(x),0);
}

//prints 01234
for(let x = 0;x < 5;x++){
    setTimeout(()=>console.log(x),0);
}


问:
How to replace IDs of users with their fullNames in the current scenario?
I have two databases with the following schema:

```<code>tbl_users(userID, fullName, emailID, password)
</code>```

userID is the Primary Key

```<code>tbl_savings(savingsID, creditorName, amount, interestRate, interestType, interestCalculationMethod, ownerID, dataEnteredByID)
</code>```

savingsID is the Primary Key.

ownerID is a Foreign Key on userID of tbl_users with a one-to-many relationship.

ownerID specifies the ID of the owner of the saving. Similarly, dataEnteredByID specifies the ID of the person who entered the data.

I have a GridView with the following specification:

```<code><asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false" runat="server" DataKeyNames="savingsID" OnRowCommand="GridViewSavingsTracker_RowCommand" AllowPaging="true" OnSelectedIndexChanged="GridViewSavingsTracker_SelectedIndexChanged" OnPageIndexChanging="GridViewSavingsTracker_PageIndexChanging" PageSize="10">
    <Columns>
        <asp:CommandField ShowSelectButton="true" />
        <asp:BoundField DataField="creditorName" HeaderText="Creditor Name" />
        <asp:BoundField DataField="amount" HeaderText="Principal Amount" />
        <asp:BoundField DataField="interestRate" HeaderText="Interest Rate" />
        <asp:BoundField DataField="interestType" HeaderText="Interest Type" />
        <asp:BoundField DataField="interestCalculationMethod" HeaderText="Interest Calculation Method" />
        <asp:BoundField DataField="insertedDate" HeaderText="Date" />
        <asp:BoundField DataField="ownerID" HeaderText="Owner" />
        <asp:BoundField DataField="dataEnteredByID" HeaderText="Data Entered By" />

    </Columns>
</asp:GridView>
</code>```

What I want to do: Instead of printing the ownerID and dataEnteredByID, I want to print the fullNames of the corresponding IDs. How can I do that?

What I already have: I have the following server side code for GridView. I have a method ShowGridView() that populates the data into the GridView from the database(s).

```<code>protected void ShowGridView()
{
    string connectionString = GetConnString();
    OleDbConnection con = new OleDbConnection(connectionString);
    con.Open();

    string showGridViewQuery = "(SELECT s.creditorName, s.amount, s.interestRate, s.interestType, s.interestCalculationMethod, s.insertedDate, u.fullName FROM tbl_savings s LEFT JOIN tbl_users u ON s.ownerID = u.usersID) UNION (select s.creditorName, s.amount, s.interestRate, s.interestType, s.interestCalculationMethod, s.insertedDate, u.fullName from tbl_savings s LEFT JOIN tbl_users u ON s.dataEnteredByID = u.usersID)";

    OleDbCommand showGridViewCommand = new OleDbCommand(showGridViewQuery, con);
    showGridViewCommand.ExecuteNonQuery();
    DataTable dt = new DataTable();
    OleDbDataAdapter olda = new OleDbDataAdapter(showGridViewCommand);
    olda.Fill(dt);

    GridViewSavingsTracker.DataSource = dt;
    GridViewSavingsTracker.DataBind();

    con.Close();
}
</code>```

答:
You can create a separate code-behind method that gets the full name and call it from the gridview.

Create an ItemTemplate for the field. The Text property calls the method. Replace UserID with your field's name.

```<code><ItemTemplate>
    <asp:Label ID="lblUserNameItem" runat="server"
        Text='<%# GetUserNameByID(Eval("UserID").ToString()) %>'></asp:Label>
</ItemTemplate>
</code>```

Code behind:

```<code>protected string GetUserNameByID(string userID)
{
    // your data-code...
    ... uname = GetUserByID(int.Parse(userID));
    return uname;
}
</code>```

Do the same with the other id, with the same method or another.

Body:
I have two databases with the following schema:

tbl_users(userID, fullName, emailID, password)

userID is the Primary Key

tbl_savings(savingsID, creditorName, amount, interestRate, interestType, interestCalculationMethod, ownerID, dataEnteredByID)

savingsID is the Primary Key.

ownerID is a Foreign Key on userID of tbl_users with a one-to-many relationship.

ownerID specifies the ID of the owner of the saving. Similarly, dataEnteredByID specifies the ID of the person who entered the data.

I have a GridView with the following specification:

<asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false" runat="server" DataKeyNames="savingsID" OnRowCommand="GridViewSavingsTracker_RowCommand" AllowPaging="true" OnSelectedIndexChanged="GridViewSavingsTracker_SelectedIndexChanged" OnPageIndexChanging="GridViewSavingsTracker_PageIndexChanging" PageSize="10">
    <Columns>
        <asp:CommandField ShowSelectButton="true" />
        <asp:BoundField DataField="creditorName" HeaderText="Creditor Name" />
        <asp:BoundField DataField="amount" HeaderText="Principal Amount" />
        <asp:BoundField DataField="interestRate" HeaderText="Interest Rate" />
        <asp:BoundField DataField="interestType" HeaderText="Interest Type" />
        <asp:BoundField DataField="interestCalculationMethod" HeaderText="Interest Calculation Method" />
        <asp:BoundField DataField="insertedDate" HeaderText="Date" />
        <asp:BoundField DataField="ownerID" HeaderText="Owner" />
        <asp:BoundField DataField="dataEnteredByID" HeaderText="Data Entered By" />

    </Columns>
</asp:GridView>

What I want to do: Instead of printing the ownerID and dataEnteredByID, I want to print the fullNames of the corresponding IDs. How can I do that?

What I already have: I have the following server side code for GridView. I have a method ShowGridView() that populates the data into the GridView from the database(s).

protected void ShowGridView()
{
    string connectionString = GetConnString();
    OleDbConnection con = new OleDbConnection(connectionString);
    con.Open();

    string showGridViewQuery = "(SELECT s.creditorName, s.amount, s.interestRate, s.interestType, s.interestCalculationMethod, s.insertedDate, u.fullName FROM tbl_savings s LEFT JOIN tbl_users u ON s.ownerID = u.usersID) UNION (select s.creditorName, s.amount, s.interestRate, s.interestType, s.interestCalculationMethod, s.insertedDate, u.fullName from tbl_savings s LEFT JOIN tbl_users u ON s.dataEnteredByID = u.usersID)";

    OleDbCommand showGridViewCommand = new OleDbCommand(showGridViewQuery, con);
    showGridViewCommand.ExecuteNonQuery();
    DataTable dt = new DataTable();
    OleDbDataAdapter olda = new OleDbDataAdapter(showGridViewCommand);
    olda.Fill(dt);

    GridViewSavingsTracker.DataSource = dt;
    GridViewSavingsTracker.DataBind();

    con.Close();
}

Body:
You can create a separate code-behind method that gets the full name and call it from the gridview.

Create an ItemTemplate for the field. The Text property calls the method. Replace UserID with your field's name.

<ItemTemplate>
    <asp:Label ID="lblUserNameItem" runat="server"
        Text='<%# GetUserNameByID(Eval("UserID").ToString()) %>'></asp:Label>
</ItemTemplate>

Code behind:

protected string GetUserNameByID(string userID)
{
    // your data-code...
    ... uname = GetUserByID(int.Parse(userID));
    return uname;
}

Do the same with the other id, with the same method or another.


问:
wcsncat_s show error assertion string is not null terminated
I want to append char. after succeful compile it show error assertion failure.

L"string is not null terminated. line 124

```<code>    #include <iostream>
    #include <windows.h>
    #include <string>

int main(){
    wchar_t jszProcessName[4096];
    wcsncat_s(jszProcessName, L"iloveyou", 1000);

    wcout << jszProcessName;
return 0;
}
</code>```

答: Set the first character of your target array to 0. wcsncat_s appends to a character string; that means it looks for the terminating null at the end of the string, and copies the new text at that point. If there is no terminating null your program goes off into lala-land.

Body:
I want to append char. after succeful compile it show error assertion failure.

L"string is not null terminated. line 124

    #include <iostream>
    #include <windows.h>
    #include <string>

int main(){
    wchar_t jszProcessName[4096];
    wcsncat_s(jszProcessName, L"iloveyou", 1000);

    wcout << jszProcessName;
return 0;
}