问:
JSON contains incorrect UTF-8 \u00ce\u00b2 instead of Unicode \u03b2, how to fix in Python?
First note that symbol β (Greek beta) have hex representation in UTF-8: CE B2

I have legacy source code in Python 2.7 that uses json strings:

```<code>u'{"something":"text \\u00ce\\u00b2 text..."}'
</code>```

I then it calls json.loads(string) or json.loads(string, 'utf-8'), but the result is Unicode string with UTF-8 characters:

```<code>u'text \xce\xb2 text'
</code>```

What I want is normal Python Unicode (UTF-16?) string:

```<code>u'text β text'
</code>```

If I call:

```<code>text = text.decode('unicode_escape')
</code>```

before json.loads, then I got correct Unicode β symbol, but it also breaks json by also replacing all new lines - \n

The question is, how to convert only "\\u00ce\\00b2" part without affecting other json special characters?

(I am new to Python, and it is not my source code, so I have no idea how this is supposed to work. I suspect that the code only works with ASCII characters)

答:
Here's a string-fixer that works after loading the JSON.  It handles any length UTF-8-like sequence and ignores escape sequences that don't look like UTF-8 sequences.

Example:

```<code>import json
import re

def fix(bad):
    return re.sub(ur'[\xc2-\xf4][\x80-\xbf]+',lambda m: m.group(0).encode('latin1').decode('utf8'),bad)

# 2- and 3-byte UTF-8-like sequences and onen correct escape code.
json_text = '''\
{
  "something":"text \\u00ce\\u00b2 text \\u00e4\\u00bd\\u00a0\\u597d..."
}
'''

data = json.loads(json_text)
bad_str = data[u'something']
good_str = fix(bad_str)
print bad_str
print good_str
</code>```

Output:

```<code>text Î² text ä½ 好...
text β text 你好...
</code>```

Body:
First note that symbol β (Greek beta) have hex representation in UTF-8: CE B2

I have legacy source code in Python 2.7 that uses json strings:

u'{"something":"text \\u00ce\\u00b2 text..."}'

I then it calls json.loads(string) or json.loads(string, 'utf-8'), but the result is Unicode string with UTF-8 characters:

u'text \xce\xb2 text'

What I want is normal Python Unicode (UTF-16?) string:

u'text β text'

If I call:

text = text.decode('unicode_escape')

before json.loads, then I got correct Unicode β symbol, but it also breaks json by also replacing all new lines - \n

The question is, how to convert only "\\u00ce\\00b2" part without affecting other json special characters?

(I am new to Python, and it is not my source code, so I have no idea how this is supposed to work. I suspect that the code only works with ASCII characters)

Body:
Here's a string-fixer that works after loading the JSON.  It handles any length UTF-8-like sequence and ignores escape sequences that don't look like UTF-8 sequences.

Example:

import json
import re

def fix(bad):
    return re.sub(ur'[\xc2-\xf4][\x80-\xbf]+',lambda m: m.group(0).encode('latin1').decode('utf8'),bad)

# 2- and 3-byte UTF-8-like sequences and onen correct escape code.
json_text = '''\
{
  "something":"text \\u00ce\\u00b2 text \\u00e4\\u00bd\\u00a0\\u597d..."
}
'''

data = json.loads(json_text)
bad_str = data[u'something']
good_str = fix(bad_str)
print bad_str
print good_str

Output:

text Î² text ä½ 好...
text β text 你好...


来源: stackexchange

问:
jQuery change() loops only adding last change() from object?
I have an array that has settings like so:

["1", "open_order", "form", "county", "San Diego", "title_officer", "Peter", "0"]
["2", "open_order", "form", "county", "San Diego", "branch", "MV", "0"]
["3", "open_order", "form", "county", "San Diego", "title_officer", "Tom", "0"]
["4", "open_order", "form", "county", "San Bernardino", "branch", "RV", "0"]```
</div>
</div>
</p>

<p>It creates an array like so:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() {
  var o = [];
  var i = 0;
  var predata = $('#preferences').text();
  var data = JSON.parse(predata);
    for(i = 0; i < data.length; i++) {
        var dataObject = {};
      dataObject['preferenceId'] = data[i][0];
      dataObject['pageName'] = data[i][1];
      dataObject['preferenceType'] = data[i][2];
      dataObject['baseField'] = data[i][3];
      dataObject['baseValue'] = data[i][4];
      dataObject['targetField'] = data[i][5];
      dataObject['targetValue'] = data[i][6];
      dataObject['conditionalId'] = data[i][7];
        o[i] = dataObject;
    }
    $.each(o, function() {
      console.log();
      var baseField = $('#' + o.baseField);
      var baseValue = o.baseValue;
      var targetField = $('#' + o.targetField);
      var targetValue = o.targetValue;

      baseField.change(function() {
        if (baseField.val() == baseValue) {

            targetField.val(targetValue);
        }
      });
    });
});</code>```

Above, I am trying create a change event for every time the baseField.val() matches the baseValue. From here, this will update other select boxes/input fields.

However, the change() only works for the last object in the list.

What am I doing wrong here?

答:
This worked.

$(function() {
  var arr = [];
  var i = 0;
  var predata = $('#preferences').text();
  var data = JSON.parse(predata);
    for(i = 0; i < data.length; i++) {
        var dataArr = {};
      dataArr['preferenceId'] = data[i][0];
      dataArr['pageName'] = data[i][1];
      dataArr['preferenceType'] = data[i][2];
      dataArr['baseField'] = data[i][3];
      dataArr['baseValue'] = data[i][4];
      dataArr['targetField'] = data[i][5];
      dataArr['targetValue'] = data[i][6];
      dataArr['conditionalId'] = data[i][7];
        arr[i] = dataArr;
    }

    $.each(arr, function(key, value) {
      var baseField = $('#' + value.baseField);
      var baseValue = value.baseValue;
      var targetField = $('#' + value.targetField);
      var targetValue = value.targetValue;

      baseField.change(function() {
        if (baseField.val() == baseValue) {

            targetField.val(targetValue);
        }
      });
    });
});```

ContentLicense: CC BY-SA 3.0

Body:
I have an array that has settings like so:

["1", "open_order", "form", "county", "San Diego", "title_officer", "Peter", "0"]
["2", "open_order", "form", "county", "San Diego", "branch", "MV", "0"]
["3", "open_order", "form", "county", "San Diego", "title_officer", "Tom", "0"]
["4", "open_order", "form", "county", "San Bernardino", "branch", "RV", "0"]

It creates an array like so:

$(function() {
  var o = [];
  var i = 0;
  var predata = $('#preferences').text();
  var data = JSON.parse(predata);
    for(i = 0; i < data.length; i++) {
        var dataObject = {};
      dataObject['preferenceId'] = data[i][0];
      dataObject['pageName'] = data[i][1];
      dataObject['preferenceType'] = data[i][2];
      dataObject['baseField'] = data[i][3];
      dataObject['baseValue'] = data[i][4];
      dataObject['targetField'] = data[i][5];
      dataObject['targetValue'] = data[i][6];
      dataObject['conditionalId'] = data[i][7];
        o[i] = dataObject;
    }
    $.each(o, function() {
      console.log();
      var baseField = $('#' + o.baseField);
      var baseValue = o.baseValue;
      var targetField = $('#' + o.targetField);
      var targetValue = o.targetValue;

      baseField.change(function() {
        if (baseField.val() == baseValue) {

            targetField.val(targetValue);
        }
      });
    });
});

Above, I am trying create a change event for every time the baseField.val() matches the baseValue. From here, this will update other select boxes/input fields.

However, the change() only works for the last object in the list.

What am I doing wrong here?


问:
Applying different textures on a THREE.js OBJLoader loaded object
I have a square shape .obj model and 2 textures. How do I apply one texture on it's top face and another on rest of faces?

答:
There are a ton of ways to do what you're asking all with varying complexity depending on your needs. It looks like you want to apply two materials to your object and not two textures.

It looks this way because it seems you want the textures to be interchangeable so there's no way you're going to combine the images and keep resolution and OBJ & THREE.Material only support one set of uv attributes so you can't use a single material and multiple textures. So multiple materials it is...

Multiple materials

If you have two materials (2 THREE.Materials which correlate to 2 WebGL programs) then each face needs to know what material it's assigned to.

While the THREE.js multi material API has been in flux for quite a while and there are differences between THREE.Geometry and THREE.BufferGeometry, fortunately for you THREE.OBJLoader supports material groups out of the box. To get this into THREE.js, you want to apply multiple materials in your 3D editor to your object and then export the OBJ to get everything. Doing it by hand is a little harder and requires calling addGroup as shown in the docs/the link above.

In THREE.js you simply pass in all the materials as an array to your object demonstrated in this answer. I also updated your fiddle to do the same thing. Relevant code shown below

```<code>var loadingManager = new THREE.LoadingManager();
var ObjLoader = new THREE.OBJLoader(loadingManager);
var textureLoader =  new THREE.TextureLoader(loadingManager);
//Material 1 with first texture
var material = new THREE.MeshLambertMaterial({map: textureLoader.load('https://dl.dropboxusercontent.com/s/nvnacip8fhlrvm4/BoxUV.png?dl=0')});
//Material 2 with second texture
var material2 = new THREE.MeshLambertMaterial({map:
textureLoader.load('https://i.imgur.com/311w7oZ.png')});
ObjLoader.load(
    'https://dl.dropboxusercontent.com/s/hiazgei0rxeirr4/cabinet30.obj?dl=0',
    function ( object ) {
        var geo = object.children[0].geometry;
        var mats = [material, material2];
        //These are just some random groups to demonstrate multi material, you need to set these up so they actually work for your object, either in code or in your 3D editor
        geo.addGroup(0,geo.getAttribute("position").count/2,0);
        geo.addGroup(geo.getAttribute("position").count/2,
        geo.getAttribute("position").count/2,1);
        //Mesh with multiple materials for material parameter
        obj = new THREE.Mesh(geo, mats);
        obj.position.y = 3;
    });
</code>```

Body:
There are a ton of ways to do what you're asking all with varying complexity depending on your needs. It looks like you want to apply two materials to your object and not two textures.

It looks this way because it seems you want the textures to be interchangeable so there's no way you're going to combine the images and keep resolution and OBJ & THREE.Material only support one set of uv attributes so you can't use a single material and multiple textures. So multiple materials it is...

Multiple materials

If you have two materials (2 THREE.Materials which correlate to 2 WebGL programs) then each face needs to know what material it's assigned to.

While the THREE.js multi material API has been in flux for quite a while and there are differences between THREE.Geometry and THREE.BufferGeometry, fortunately for you THREE.OBJLoader supports material groups out of the box. To get this into THREE.js, you want to apply multiple materials in your 3D editor to your object and then export the OBJ to get everything. Doing it by hand is a little harder and requires calling addGroup as shown in the docs/the link above.

In THREE.js you simply pass in all the materials as an array to your object demonstrated in this answer. I also updated your fiddle to do the same thing. Relevant code shown below

var loadingManager = new THREE.LoadingManager();
var ObjLoader = new THREE.OBJLoader(loadingManager);
var textureLoader =  new THREE.TextureLoader(loadingManager);
//Material 1 with first texture
var material = new THREE.MeshLambertMaterial({map: textureLoader.load('https://dl.dropboxusercontent.com/s/nvnacip8fhlrvm4/BoxUV.png?dl=0')});
//Material 2 with second texture
var material2 = new THREE.MeshLambertMaterial({map:
textureLoader.load('https://i.imgur.com/311w7oZ.png')});
ObjLoader.load(
    'https://dl.dropboxusercontent.com/s/hiazgei0rxeirr4/cabinet30.obj?dl=0',
    function ( object ) {
        var geo = object.children[0].geometry;
        var mats = [material, material2];
        //These are just some random groups to demonstrate multi material, you need to set these up so they actually work for your object, either in code or in your 3D editor
        geo.addGroup(0,geo.getAttribute("position").count/2,0);
        geo.addGroup(geo.getAttribute("position").count/2,
        geo.getAttribute("position").count/2,1);
        //Mesh with multiple materials for material parameter
        obj = new THREE.Mesh(geo, mats);
        obj.position.y = 3;
    });


问:
In PhpStorm new file menu, there is no .php or php class option
In PhpStorm, when i want to create a new file, there used to be three options for php at the top of the list. new PHP file, new PHP Class, and something else.

Now there is no option for php. there is just 'file', 'directory', 'new scratch file' and then html/css/etc file types.

答:
Problem solved. for anyone having this question in the future, you should know that PhpStorm has the above behavior when indexing the project, which usually happens every time you open a project.

but in my case, something(I don't know what), had caused to add "." to the list of paths to be indexed, making PhpStorm index the whole home folder, and naturally, it took a lot of time.


问:
Fluid flow, heat transfer and Python
full EDIT:

I will give some more information about the whole problem. The project is in early stage and my question is actually only about a narrow portion of the thing.

the final goal:

I am currently trying to simulate the flow of hot air around a rigid obstacle in Python. I have a steady inflow of air, the flow in the bulk is transient and turbulent. The aim of the whole exercise is to understand how

-the air flow behaves

-the obstacle heats up

-the air cools down and the air-pressure drops

done so far:

Not much, the thing is in early stage. I have a 2d rectangular domain and a circular obstacle. The mesh is getting finer at the boundary between bulk and obstacle, since that is where the interesting stuff is happening. Currently I only consider the airflow, no convection or heat transfer. I use the FEniCS software collection to solve the Navier-Stokes equation. Fenics comes with an example for an N-S solver using the Chorin projection method, I adapted this example to my setting. I model the rigid body as an area with no-slip boundary condition (i.e. I set the velocity of the air flow to zero). The solver still solves the N-S equation in that area, in particular the pressure inside the obstacle changes over time. Probably it is a better idea to avoid this and restrict the N-S solver to the bulk. But at the moment I don't think this affects the speed very much.

problem:

The thing runs quite slow. I do not mind if the final simulations takes a few days, but currently it is only 2d fluid flow around an obstacle and the mesh is not as fine as I want it to be in the end. I hoped this to be faster, as it will become a lot more complicated when the heat comes into play.

my question:

It boils down to one question:

What is a fast algorithm or method to solve the Navier-Stokes equation in Python?

I am perfectly fine with writing a solver from scratch, but this raises the same question. This morning it occured to me that the projection method is maybe not the worst idea, because it decouples the pressure and velocity upgrade, I could try to assign this to different CPU kernels.

答:
Python would actually be a fine choice if you were writing it all from scratch.  But you'll need a LOT of background to do it from scratch.

A coupled solution is a difficult problem.

It's been pointed out to me that you're using a package - FEniCS (thank you, Sven).  My original answer needs some amendment.  I'll start with a few questions about the physics, then turn to the package.

Incompressible Navier Stokes applies to a gas like air if the Mach number for air at that temperature is less than 0.1.  Is that the case for your problem?  It's probably true, but I thought I'd ask.

Navier Stokes does NOT apply to your solid obstacle.  If you model the whole thing with one mesh, how are you describing the solid?  Is it a high viscosity fluid?  This could make the system of equations ill-conditioned and hard to solve.  It would also affect the stable time step size if you're using explicit integration.

Is it a steady flow or a transient? (steady is easier)  Is the flow laminar or turbulent?     (laminar is easier)

It's conduction heat transfer in your solid obstacle and conduction/convection in your fluid.  The fluid will have momentum and thermal boundary layers along the solid obstacle of the surface that your mesh will have to resolve.  That's where the important heat transfer between the solid and fluid is happening.  These will require a fine mesh local to the solid surface to resolve the transition from the boundary condition to the far field velocity and temperature.   Have you taken that into account in your mesh?

It appears to me that FEniCS is using finite elements, but I don't see anything in the docs that tells me how you're supposed to couple the momentum and energy equations together.

You'll have to tell a great deal more to get decent advice here.  Is there a numerical methods in physics Stackoverflow?  You'll need it.

ContentLicense: CC BY-SA 2.5

Title: Fluid flow, heat transfer and Python


问:
OpenCart 3.0 (3.x) + Authorize.net - how to disable ONLY the Authorize.net E-mail?
We currently accept credit cards by phone (entering the order info into the Virtual Terminal) as well as on the website (OpenCart, using the built-in Authorize.net AIM module).

Problem: when order is placed on website, the customer receives 2 E-mails - 1 from our site, 1 from Authorize. The Authorize E-mail, being plaintext, looks ugly AF, and my boss wants to have it disabled.

Attempt # 1: looked in the Authorize.net AIM plugin/module settings. No such option.

Attempt # 2: in the Authorize.net account, under "Settings -> E-mail Receipt", there is a checkbox "Email transaction receipt to customer (if email address is provided)".

Result #2:  unfortunately, this disables ALL transaction E-mails - from website transactions (OK) and from Virtual Terminal phone-order transactions (NOT cool). We have to provide an E-mail receipt to phone customers.

Attempt #3: in the OpenCart system, editing file:

```<code>catalog/controller/extension/payment/authorizenet_aim.php
</code>```

to comment out the line

```<code>$data['x_email'] = $order_info['email'];
</code>```

Result #3: during checkout, even if a valid E-mail is entered, upon trying to submit the order, the "Email address is required" error message appears.

So...
Can't disable it in Authorize plugin/module in OpenCart.
Can't disable it in Authorize Account Settings.
Can't just delete the E-mail from the array of data that OpenCart collects during checkout.

How can I disable the Authorize.net E-mail (and ONLY the Authorize.net E-mail, I still want the website receipt to go out) on a site built on OpenCart 3.0?

答:
In attempt number 3, can you confirm whether OpenCart gives the error about the email being required or if Authorize.Net gives that error? If Authorize.Net provides the error it may be reconciled by adjusting the payment form settings in Authorize.Net:
1. Sign into Authorize.Net
2. Account > Payment Form > Form Fields
3. Make sure the email field isn’t checked as required.
4. Save your changes at the bottom of the page</p>

Body:
We currently accept credit cards by phone (entering the order info into the Virtual Terminal) as well as on the website (OpenCart, using the built-in Authorize.net AIM module).

Problem: when order is placed on website, the customer receives 2 E-mails - 1 from our site, 1 from Authorize. The Authorize E-mail, being plaintext, looks ugly AF, and my boss wants to have it disabled.

Attempt # 1: looked in the Authorize.net AIM plugin/module settings. No such option.

Attempt # 2: in the Authorize.net account, under "Settings -> E-mail Receipt", there is a checkbox "Email transaction receipt to customer (if email address is provided)".

Result #2:  unfortunately, this disables ALL transaction E-mails - from website transactions (OK) and from Virtual Terminal phone-order transactions (NOT cool). We have to provide an E-mail receipt to phone customers.

Attempt #3: in the OpenCart system, editing file:

catalog/controller/extension/payment/authorizenet_aim.php

to comment out the line

$data['x_email'] = $order_info['email'];

Result #3: during checkout, even if a valid E-mail is entered, upon trying to submit the order, the "Email address is required" error message appears.

So...
Can't disable it in Authorize plugin/module in OpenCart.
Can't disable it in Authorize Account Settings.
Can't just delete the E-mail from the array of data that OpenCart collects during checkout.

How can I disable the Authorize.net E-mail (and ONLY the Authorize.net E-mail, I still want the website receipt to go out) on a site built on OpenCart 3.0?


问:
java | Return a reversed array by FOR loop
I am stuck with an exercise which tells me to create a reversed array from the given one.

After some thinking I made such code:

```<code>    public int[] reverse3(int[] nums) {

  int[] nums2 = new int[3];

  for (int i = nums.length - 1; i >= 0; i--) {

     for (int j = 0; j < nums.length; j++) {

          nums2[j] = nums[i];

    }
  }
  return nums2;
}
</code>```

But it is throwing out three exact same numbers.

答:
To reverse an array you only have to swap the elements until the midpoint:

```<code>public int[] reverse(int[] nums) {
    int numsLength = nums.length;
    for (int i = 0; i < numsLength / 2; i++) {
        int temp = nums[i];
        nums[i] = nums[numsLength - i - 1];
        nums[numsLength - i - 1] = temp;
    }
    return nums;
}
</code>```

This way is much more optimized.

Source: How do I reverse an int array in Java?

Body:
I am stuck with an exercise which tells me to create a reversed array from the given one.

After some thinking I made such code:

    public int[] reverse3(int[] nums) {

  int[] nums2 = new int[3];

  for (int i = nums.length - 1; i >= 0; i--) {

     for (int j = 0; j < nums.length; j++) {

          nums2[j] = nums[i];

    }
  }
  return nums2;
}

But it is throwing out three exact same numbers.

Body:
To reverse an array you only have to swap the elements until the midpoint:

public int[] reverse(int[] nums) {
    int numsLength = nums.length;
    for (int i = 0; i < numsLength / 2; i++) {
        int temp = nums[i];
        nums[i] = nums[numsLength - i - 1];
        nums[numsLength - i - 1] = temp;
    }
    return nums;
}

This way is much more optimized.

Source: How do I reverse an int array in Java?


问:
Not able to run Protractor / Jasmine tests with Microsoft Edge
I'm working on a project to begin testing Node/Angular applications using Protractor and Jasmine.  I have a POC working in most browsers but having a lot of trouble with MS Edge.  Here's my environment:

```<code>OS: Windows 10 Pro (Version 1709, OS Build 16299.98)
Edge: 41.16299.15.0
EdgeHTML: 16.16299
MS Web Driver: 10.0.16299.15
Node: 6.12.0
Protractor: 5.2.1
Jasmine: 2.8.0
Selenium: 3.8.1
</code>```

When I run the tests in Chrome, Firefox, and IE (11) the behavior is fine (tests run with expected results).  However, with MS Edge the process fails before the test spec can even run.

Example code/output use the Protractor tutorial but I have the same issue when working with our application.

Working conf.js (for Chrome and Firefox)

```<code>exports.config = {
  framework: 'jasmine',
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['./spec/spec.js'],

  multiCapabilities: [
    { 'browserName': 'chrome' },
    { 'browserName': 'firefox', 'marionette': true, 'firefox_binary': "C:\\Program Files\\Mozilla Firefox\\firefox.exe" }//,
]
}
</code>```

Failing conf.js (for MS Edge)

```<code>exports.config = {
  framework: 'jasmine',
  seleniumAddress: 'http://localhost:17556',
  specs: ['./spec/spec.js'],

  capabilites: { browserName: 'MicrosoftEdge' }
}
</code>```

spec.js

```<code>// spec.js
describe('Protractor Demo App', function() {
  it('should have a title', function() {
    browser.get('http://juliemr.github.io/protractor-demo/');

    expect(browser.getTitle()).toEqual('Super Calculator');
  });
});
</code>```

When I run the test for MS Edge after starting the Microsoft Web Driver the following occurs:

```<code>$ protractor conf.js
[14:14:18] I/launcher - Running 1 instances of WebDriver
[14:14:18] I/hosted - Using the selenium server at http://localhost:17556
[14:14:20] E/launcher - Error code: 135
[14:14:20] E/launcher - Error message: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:17556
[14:14:20] E/launcher - Error: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:17556
    at ClientRequest.<anonymous> (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\http\index.js:238:15)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at Socket.socketErrorListener (_http_client.js:310:9)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at emitErrorNT (net.js:1281:8)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
From: Task: WebDriver.createSession()
    at Function.createSession (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver.js:769:24)
    at Function.createSession (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\chrome.js:761:15)
    at createDriver (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\index.js:170:33)
    at Builder.build (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\index.js:626:16)
    at Hosted.getNewDriver (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\built\driverProviders\driverProvider.js:53:33)
    at Runner.createBrowser (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\built\runner.js:195:43)
    at q.then.then (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\built\runner.js:339:29)
    at _fulfilled (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:834:54)
    at self.promiseDispatch.done (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:863:30)
    at Promise.promise.promiseDispatch (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:796:13)
[14:14:20] E/launcher - Process exited with error code 135
</code>```

The problem seems to be somewhere around that it says it is using the server on 'localhost' but then makes requests on '127.0.0.1' instead.  In theory, they are the same.  But in operation, only 'localhost' is responsive.  If I try to access 127.0.0.1:17556 it doesn't respond.

```<code>This website could not be found
Error Code: INET_E_RESOURCE_NOT_FOUND
</code>```

I've been looking around a long time (here, SQA, and, the Protactor discussions on GitHub) for info on this but have not found a resolution.  Some discussion on GitHub indicates MS Edge testing with Protractor was working at one point.  Has anyone been able to successfully run Protractor tests with this version of MS Edge and MS Webdriver?

One final bit of info: I have access to another Windows 10 machine that has an older version of Edge (10240).  On that machine I don't have this problem (localhost vs 127.0.0.1), but, it is old enough to still have issues with async and I'm not able to use it for testing with Protractor.

Thanks!

UPDATE

The spec file has not changed but I have updated the config file (conf.js):

```<code>// conf.js
exports.config = {
    directConnect: false,
    framework: 'jasmine',
    specs: ['./spec/spec.js'],
    seleniumAddress: 'http://localhost:4444/wd/hub',

    multiCapabilities: [
        //{ 'browserName': 'chrome' },
        //{ 'browserName': 'firefox', 'marionette': true, 'firefox_binary': "C:\\Program Files\\Mozilla Firefox\\firefox.exe" },
        { 'browserName': 'MicrosoftEdge' }
    ]
};
</code>```

When enabled Chrome and Firefox are able to run the test.

Edge fails with the following (timeout waiting for driver server to start):

```<code>$ protractor conf.js
[13:13:53] I/launcher - Running 1 instances of WebDriver
[13:13:53] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
[13:14:13] E/launcher - Timed out waiting for driver server to start.
Build info: version: '3.8.1', revision: '6e95a6684b', time: '2017-12-01T19:05:32.194Z'
System info: host: 'QA-01', ip: '10.1.1.80', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '9.0.1'
Driver info: driver.version: unknown
[13:14:13] E/launcher - WebDriverError: Timed out waiting for driver server to start.
Build info: version: '3.8.1', revision: '6e95a6684b', time: '2017-12-01T19:05:32.194Z'
System info: host: 'QA-01', ip: '10.1.1.80', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '9.0.1'
Driver info: driver.version: unknown
    at WebDriverError (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:27:5)
    at Object.checkLegacyResponse (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:546:15)
    at parseHttpResponse (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\http.js:509:13)
    at doSend.then.response (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\http.js:441:30)
    at process._tickCallback (internal/process/next_tick.js:109:7)
From: Task: WebDriver.createSession()
    at Function.createSession (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver.js:769:24)
    at createDriver (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\index.js:170:33)
    at Builder.build (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\index.js:635:14)
    at Hosted.getNewDriver (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\built\driverProviders\driverProvider.js:53:33)
    at Runner.createBrowser (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\built\runner.js:195:43)
    at q.then.then (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\built\runner.js:339:29)
    at _fulfilled (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:834:54)
    at self.promiseDispatch.done (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:863:30)
    at Promise.promise.promiseDispatch (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:796:13)
    at C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:556:49
[13:14:13] E/launcher - Process exited with error code 199
</code>```

As before - the same setup on an older version of Windows 10, Edge (10240), and, the Edge Driver do try to run the tests (albeit with the async execution issue).

This setup is probably better than what I used before but the overall outcome is the same.  Protractor tests (on this machine) aren't running in MS Edge (16299).

Any insight or advice is much appreciated.

Thanks!

答:
From what I can gather you need to tell protractor where to find the Edge driver. I found a few blog posts that mention adding seleniumArgs to the config.

```<code>seleniumArgs: ['-Dwebdriver.edge.driver=your/path/to/MicrosoftWebDriver.exe']
</code>```

Body:
I'm working on a project to begin testing Node/Angular applications using Protractor and Jasmine.  I have a POC working in most browsers but having a lot of trouble with MS Edge.  Here's my environment:

OS: Windows 10 Pro (Version 1709, OS Build 16299.98)
Edge: 41.16299.15.0
EdgeHTML: 16.16299
MS Web Driver: 10.0.16299.15
Node: 6.12.0
Protractor: 5.2.1
Jasmine: 2.8.0
Selenium: 3.8.1

When I run the tests in Chrome, Firefox, and IE (11) the behavior is fine (tests run with expected results).  However, with MS Edge the process fails before the test spec can even run.

Example code/output use the Protractor tutorial but I have the same issue when working with our application.

Working conf.js (for Chrome and Firefox)

exports.config = {
  framework: 'jasmine',
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['./spec/spec.js'],

  multiCapabilities: [
    { 'browserName': 'chrome' },
    { 'browserName': 'firefox', 'marionette': true, 'firefox_binary': "C:\\Program Files\\Mozilla Firefox\\firefox.exe" }//,
]
}

Failing conf.js (for MS Edge)

exports.config = {
  framework: 'jasmine',
  seleniumAddress: 'http://localhost:17556',
  specs: ['./spec/spec.js'],

  capabilites: { browserName: 'MicrosoftEdge' }
}

spec.js

// spec.js
describe('Protractor Demo App', function() {
  it('should have a title', function() {
    browser.get('http://juliemr.github.io/protractor-demo/');

    expect(browser.getTitle()).toEqual('Super Calculator');
  });
});

When I run the test for MS Edge after starting the Microsoft Web Driver the following occurs:

$ protractor conf.js
[14:14:18] I/launcher - Running 1 instances of WebDriver
[14:14:18] I/hosted - Using the selenium server at http://localhost:17556
[14:14:20] E/launcher - Error code: 135
[14:14:20] E/launcher - Error message: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:17556
[14:14:20] E/launcher - Error: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:17556
    at ClientRequest.<anonymous> (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\http\index.js:238:15)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at Socket.socketErrorListener (_http_client.js:310:9)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at emitErrorNT (net.js:1281:8)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
From: Task: WebDriver.createSession()
    at Function.createSession (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver.js:769:24)
    at Function.createSession (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\chrome.js:761:15)
    at createDriver (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\index.js:170:33)
    at Builder.build (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\index.js:626:16)
    at Hosted.getNewDriver (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\built\driverProviders\driverProvider.js:53:33)
    at Runner.createBrowser (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\built\runner.js:195:43)
    at q.then.then (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\built\runner.js:339:29)
    at _fulfilled (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:834:54)
    at self.promiseDispatch.done (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:863:30)
    at Promise.promise.promiseDispatch (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:796:13)
[14:14:20] E/launcher - Process exited with error code 135

The problem seems to be somewhere around that it says it is using the server on 'localhost' but then makes requests on '127.0.0.1' instead.  In theory, they are the same.  But in operation, only 'localhost' is responsive.  If I try to access 127.0.0.1:17556 it doesn't respond.

This website could not be found
Error Code: INET_E_RESOURCE_NOT_FOUND

I've been looking around a long time (here, SQA, and, the Protactor discussions on GitHub) for info on this but have not found a resolution.  Some discussion on GitHub indicates MS Edge testing with Protractor was working at one point.  Has anyone been able to successfully run Protractor tests with this version of MS Edge and MS Webdriver?

One final bit of info: I have access to another Windows 10 machine that has an older version of Edge (10240).  On that machine I don't have this problem (localhost vs 127.0.0.1), but, it is old enough to still have issues with async and I'm not able to use it for testing with Protractor.

Thanks!

UPDATE

The spec file has not changed but I have updated the config file (conf.js):

// conf.js
exports.config = {
    directConnect: false,
    framework: 'jasmine',
    specs: ['./spec/spec.js'],
    seleniumAddress: 'http://localhost:4444/wd/hub',

    multiCapabilities: [
        //{ 'browserName': 'chrome' },
        //{ 'browserName': 'firefox', 'marionette': true, 'firefox_binary': "C:\\Program Files\\Mozilla Firefox\\firefox.exe" },
        { 'browserName': 'MicrosoftEdge' }
    ]
};

When enabled Chrome and Firefox are able to run the test.

Edge fails with the following (timeout waiting for driver server to start):

$ protractor conf.js
[13:13:53] I/launcher - Running 1 instances of WebDriver
[13:13:53] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
[13:14:13] E/launcher - Timed out waiting for driver server to start.
Build info: version: '3.8.1', revision: '6e95a6684b', time: '2017-12-01T19:05:32.194Z'
System info: host: 'QA-01', ip: '10.1.1.80', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '9.0.1'
Driver info: driver.version: unknown
[13:14:13] E/launcher - WebDriverError: Timed out waiting for driver server to start.
Build info: version: '3.8.1', revision: '6e95a6684b', time: '2017-12-01T19:05:32.194Z'
System info: host: 'QA-01', ip: '10.1.1.80', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '9.0.1'
Driver info: driver.version: unknown
    at WebDriverError (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:27:5)
    at Object.checkLegacyResponse (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:546:15)
    at parseHttpResponse (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\http.js:509:13)
    at doSend.then.response (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\http.js:441:30)
    at process._tickCallback (internal/process/next_tick.js:109:7)
From: Task: WebDriver.createSession()
    at Function.createSession (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\webdriver.js:769:24)
    at createDriver (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\index.js:170:33)
    at Builder.build (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\index.js:635:14)
    at Hosted.getNewDriver (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\built\driverProviders\driverProvider.js:53:33)
    at Runner.createBrowser (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\built\runner.js:195:43)
    at q.then.then (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\built\runner.js:339:29)
    at _fulfilled (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:834:54)
    at self.promiseDispatch.done (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:863:30)
    at Promise.promise.promiseDispatch (C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:796:13)
    at C:\Users\USER.NAME\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:556:49
[13:14:13] E/launcher - Process exited with error code 199

As before - the same setup on an older version of Windows 10, Edge (10240), and, the Edge Driver do try to run the tests (albeit with the async execution issue).

This setup is probably better than what I used before but the overall outcome is the same.  Protractor tests (on this machine) aren't running in MS Edge (16299).

Any insight or advice is much appreciated.

Thanks!

Body:
From what I can gather you need to tell protractor where to find the Edge driver. I found a few blog posts that mention adding seleniumArgs to the config.

seleniumArgs: ['-Dwebdriver.edge.driver=your/path/to/MicrosoftWebDriver.exe']


问:
PATCH existing OneNote Page by appending binary image content
Using the Microsoft Graph v1.0 api and C#, I am able to update (patch) existing OneNote pages however after writing image data to the multipart/form-data section, the resulting image height and width are correct, but, the image is not rendered on the page -- other than an empty image place-holder.

So the question is, what is the correct image format expected by OneNote for a PATCH command?  The docs state that it must be 'binary image data'. Shouldn't File.ReadAllBytes be sufficient?

Here are the formats attempted so far:

```<code>string file = @"c:\images\file1.jpg";

var rawData = System.IO.File.ReadAllText(file); //attempt1
byte[] bytes = System.IO.File.ReadAllBytes(file);  //attempt2
var byteArray = BitConverter.ToString(bytes);   //attempt3
var byteString = Encoding.ASCII.GetString(bytes);  //attempt4
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);  //attempt5
string imageDataURL = string.Format("data:image/jpeg;base64,{0}", base64String);  //attempt6
</code>```

...

```<code>/* Construct message content */
StringBuilder sb = new StringBuilder();
sb.Append("--MyPartBoundary198374" + "\r\n");
sb.Append(@"Content-Disposition: form-data; name=""Commands"""  + "\r\n");
sb.Append("Content-Type: application/json" + "\r\n" + "\r\n");

sb.Append(
@"[{
    'target':'body',
    'action':'append',
    'position':'before',
    'content':'<img src=""name:image1"" width=""400"" height=""500""/>'
}]"

+ "\r\n" + "\r\n");

sb.Append("--MyPartBoundary198374" + "\r\n");
sb.Append(@"Content-Disposition: form-data; name=""image1""" + "\r\n");
sb.Append("Content-Type: image/jpeg" +  "\r\n\r\n" );
sb.Append([see formats above] + "\r\n");
sb.Append("--MyPartBoundary198374--" );

string content = sb.ToString();
string contentType = "multipart/form-data; boundary=MyPartBoundary198374";
var result = await OneNoteService.UpdatePageAsync(client, page, contentType, content);
</code>```

...

```<code>internal static async Task <HttpResponseMessage> UpdatePageAsync(GraphServiceClient client, OnenotePage page, string contentType, string content)
{
    HttpResponseMessage response = null;

    try
    {
        string requestUri = client.Users[ME].Onenote.Pages[page.Id].Content.Request().RequestUrl;

        List<OnenotePatchContentCommand> patchCommands = new List<OnenotePatchContentCommand>();

        HttpRequestMessage request = new HttpRequestMessage()
        {
            Method = new HttpMethod("PATCH"),
            RequestUri = new Uri(requestUri),
            Content = new StringContent(content, Encoding.UTF8, "application/json"),
        };

        request.Content.Headers.Remove("Content-Type");
        request.Content.Headers.TryAddWithoutValidation("Content-Type", contentType);

        // Adds the user's access token from the GraphServiceClient to the request.
        await client.AuthenticationProvider.AuthenticateRequestAsync(request);

        response = await client.HttpProvider.SendAsync(request);

        if (!response.IsSuccessStatusCode)
        {
            throw new Microsoft.Graph.ServiceException(
                new Error
                {
                    Code = response.StatusCode.ToString(),
                    Message = await response.Content.ReadAsStringAsync()
                });
        }
    }
    catch (Exception ex)
    {
        //TODO: Error handling
        Console.WriteLine(ex.ToString());
    }
    return response;
}
</code>```

The suggestions listed in this post did not resolve the issue:
Inserting image into existing OneNote page via REST api not working

Been trying to resolve this for more than a day.  Can someone provide the proper image data format expected by the PATCH command.

Thanks,
Roland

答:
Moving previous comment to an answer in case others run into this.

Rather than sending multiple parts, combine attempts 5 & 6 and include the result directly in the src attribute:

```<code>string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);  //attempt5
string imageDataURL = string.Format("data:image/jpeg;base64,{0}", base64String);  //attempt6

/* Construct message content */
StringBuilder sb = new StringBuilder();
sb.Append("--MyPartBoundary198374" + "\r\n");
sb.Append(@"Content-Disposition: form-data; name=""Commands"""  + "\r\n");
sb.Append("Content-Type: application/json" + "\r\n" + "\r\n");

sb.Append(
@"[{
    'target':'body',
    'action':'append',
    'position':'before',
    'content':'<img src=" + imageDataURL  + " width=""400"" height=""500""/>'
}]"

+ "\r\n" + "\r\n");
</code>```

This will include the image directly in the HTML you're inserting.

Body:
Using the Microsoft Graph v1.0 api and C#, I am able to update (patch) existing OneNote pages however after writing image data to the multipart/form-data section, the resulting image height and width are correct, but, the image is not rendered on the page -- other than an empty image place-holder.

So the question is, what is the correct image format expected by OneNote for a PATCH command?  The docs state that it must be 'binary image data'. Shouldn't File.ReadAllBytes be sufficient?

Here are the formats attempted so far:

string file = @"c:\images\file1.jpg";

var rawData = System.IO.File.ReadAllText(file); //attempt1
byte[] bytes = System.IO.File.ReadAllBytes(file);  //attempt2
var byteArray = BitConverter.ToString(bytes);   //attempt3
var byteString = Encoding.ASCII.GetString(bytes);  //attempt4
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);  //attempt5
string imageDataURL = string.Format("data:image/jpeg;base64,{0}", base64String);  //attempt6

...

/* Construct message content */
StringBuilder sb = new StringBuilder();
sb.Append("--MyPartBoundary198374" + "\r\n");
sb.Append(@"Content-Disposition: form-data; name=""Commands"""  + "\r\n");
sb.Append("Content-Type: application/json" + "\r\n" + "\r\n");

sb.Append(
@"[{
    'target':'body',
    'action':'append',
    'position':'before',
    'content':''
}]"

+ "\r\n" + "\r\n");

sb.Append("--MyPartBoundary198374" + "\r\n");
sb.Append(@"Content-Disposition: form-data; name=""image1""" + "\r\n");
sb.Append("Content-Type: image/jpeg" +  "\r\n\r\n" );
sb.Append([see formats above] + "\r\n");
sb.Append("--MyPartBoundary198374--" );

string content = sb.ToString();
string contentType = "multipart/form-data; boundary=MyPartBoundary198374";
var result = await OneNoteService.UpdatePageAsync(client, page, contentType, content);

...

internal static async Task <HttpResponseMessage> UpdatePageAsync(GraphServiceClient client, OnenotePage page, string contentType, string content)
{
    HttpResponseMessage response = null;

    try
    {
        string requestUri = client.Users[ME].Onenote.Pages[page.Id].Content.Request().RequestUrl;

        List<OnenotePatchContentCommand> patchCommands = new List<OnenotePatchContentCommand>();

        HttpRequestMessage request = new HttpRequestMessage()
        {
            Method = new HttpMethod("PATCH"),
            RequestUri = new Uri(requestUri),
            Content = new StringContent(content, Encoding.UTF8, "application/json"),
        };

        request.Content.Headers.Remove("Content-Type");
        request.Content.Headers.TryAddWithoutValidation("Content-Type", contentType);

        // Adds the user's access token from the GraphServiceClient to the request.
        await client.AuthenticationProvider.AuthenticateRequestAsync(request);

        response = await client.HttpProvider.SendAsync(request);

        if (!response.IsSuccessStatusCode)
        {
            throw new Microsoft.Graph.ServiceException(
                new Error
                {
                    Code = response.StatusCode.ToString(),
                    Message = await response.Content.ReadAsStringAsync()
                });
        }
    }
    catch (Exception ex)
    {
        //TODO: Error handling
        Console.WriteLine(ex.ToString());
    }
    return response;
}

The suggestions listed in this post did not resolve the issue:
Inserting image into existing OneNote page via REST api not working

Been trying to resolve this for more than a day.  Can someone provide the proper image data format expected by the PATCH command.

Thanks,
Roland

Body:
Moving previous comment to an answer in case others run into this.

Rather than sending multiple parts, combine attempts 5 & 6 and include the result directly in the src attribute:

string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);  //attempt5
string imageDataURL = string.Format("data:image/jpeg;base64,{0}", base64String);  //attempt6

/* Construct message content */
StringBuilder sb = new StringBuilder();
sb.Append("--MyPartBoundary198374" + "\r\n");
sb.Append(@"Content-Disposition: form-data; name=""Commands"""  + "\r\n");
sb.Append("Content-Type: application/json" + "\r\n" + "\r\n");

sb.Append(
@"[{
    'target':'body',
    'action':'append',
    'position':'before',
    'content':'<img src=" + imageDataURL  + " width=""400"" height=""500""/>'
}]"

+ "\r\n" + "\r\n");

This will include the image directly in the HTML you're inserting.


问:
.vscode folder missing from Angular2+ project
I have an Angular2+ project and I need to create launch.json file inside of .vscode folder that is supposed to be immediately under my Angular project folder. I do not see .vscode folder.

I can create it with the command prompt but I wonder why do I not have one in my project when the instructions I am following assume it should be there already?

答:
Figured out the way to do it.

In VS Code, click on Debug button:

In the Debug toolbar on top, click Configure button:

The popup will appear under VS Code toolbar, asking which debugger you want to use. Select one from the list. Node.js debugger is built into VS Code. I installed Chrome debugger and it shows up in the list.

Selecting one of the debuggers creates .vscode folder (if it did not exist) and saves the file launch.json in it.


问:
Angular 2 error throw "'router-outlet' is not a known element:". if I use submodule.Please guide
I am learning angular 2. I am facing an error 'router-outlet' is not a known element'. I have one folder dashboard including dashboard.component.ts,dashboard.module.ts,dashboard.component.html. And codes of those files are followings.

```<code>    dashboard.module.ts
------------------------------
    import { NgModule }      from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { DashboardComponent }  from './dashboard.component';
    import { AllBookListComponent }  from './allbooklist.component';
    @NgModule({
    imports: [CommonModule],
    declarations: [AllBookListComponent,DashboardComponent],
    exports: [AllBookListComponent,DashboardComponent],
    providers: [],
    })
    export class DashboardModule {
    }

    dashboard.component.ts
-----------------------------
    import { Component } from '@angular/core';
    @Component({
    templateUrl: './dashboard.component.html',
    })
    export class DashboardComponent
    {
    }
    dashboard.component.html
------------------------------------
    <a routerLink="aaa" routerLinkActive="active">Home</a>
    <router-outlet ></router-outlet>

    app.module.ts
----------------------------
    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { LoginModule }  from './login/login.module';
    import { DashboardModule }  from './dashboard/dashboard.module';
    import { routing } from './app.routing';
    import { AppComponent }  from './app.component';
    @NgModule({
    imports:[ BrowserModule,routing,LoginModule,DashboardModule],
    declarations: [ AppComponent],
    providers: [],
    bootstrap:    [ AppComponent ]
    })
    export class AppModule { }

    app.routing.ts
-----------------------
    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { LoginComponent }  from './login/login.component';
    import { DashboardComponent }  from './dashboard/dashboard.component';
    import { AllBookListComponent }  from './dashboard
    export const routing = RouterModule.forRoot([
    {path: '', component: LoginComponent},
    { path: 'dashboard', component: DashboardComponent,
    children: [
    { path: 'aaa', component: AllBookListComponent }
    ]
    }
    ]);

app.component.ts
-------------------
import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: `<router-outlet></router-outlet>`,
})
export class AppComponent  { name = 'Angular'; }
</code>```

But if I import the DashboardComponent (import { DashboardComponent }  from './dashboard.component';) in app.module.ts instead of dashboard.module.ts then its working fine. My question is why should I import DashboardComponent in app.module.ts instead of dashboard.module.ts?as at last dashboard.module.ts is imported in app.module.ts.Please help

答:
Import RouterModule in DashBoardMoule

explanation

<router-outlet> is a part of RouterModule and your component is trying to access router-outlet and module that contains DashBoardComponent is not importing RouterModule

Body:
I am learning angular 2. I am facing an error 'router-outlet' is not a known element'. I have one folder dashboard including dashboard.component.ts,dashboard.module.ts,dashboard.component.html. And codes of those files are followings.

    dashboard.module.ts
------------------------------
    import { NgModule }      from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { DashboardComponent }  from './dashboard.component';
    import { AllBookListComponent }  from './allbooklist.component';
    @NgModule({
    imports: [CommonModule],
    declarations: [AllBookListComponent,DashboardComponent],
    exports: [AllBookListComponent,DashboardComponent],
    providers: [],
    })
    export class DashboardModule {
    }

    dashboard.component.ts
-----------------------------
    import { Component } from '@angular/core';
    @Component({
    templateUrl: './dashboard.component.html',
    })
    export class DashboardComponent
    {
    }
    dashboard.component.html
------------------------------------
    Home
    <router-outlet ></router-outlet>

    app.module.ts
----------------------------
    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { LoginModule }  from './login/login.module';
    import { DashboardModule }  from './dashboard/dashboard.module';
    import { routing } from './app.routing';
    import { AppComponent }  from './app.component';
    @NgModule({
    imports:[ BrowserModule,routing,LoginModule,DashboardModule],
    declarations: [ AppComponent],
    providers: [],
    bootstrap:    [ AppComponent ]
    })
    export class AppModule { }

    app.routing.ts
-----------------------
    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { LoginComponent }  from './login/login.component';
    import { DashboardComponent }  from './dashboard/dashboard.component';
    import { AllBookListComponent }  from './dashboard
    export const routing = RouterModule.forRoot([
    {path: '', component: LoginComponent},
    { path: 'dashboard', component: DashboardComponent,
    children: [
    { path: 'aaa', component: AllBookListComponent }
    ]
    }
    ]);

app.component.ts
-------------------
import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: `<router-outlet></router-outlet>`,
})
export class AppComponent  { name = 'Angular'; }

But if I import the DashboardComponent (import { DashboardComponent }  from './dashboard.component';) in app.module.ts instead of dashboard.module.ts then its working fine. My question is why should I import DashboardComponent in app.module.ts instead of dashboard.module.ts?as at last dashboard.module.ts is imported in app.module.ts.Please help


问:
What are the current differences between MyISAM and InnoDB storage engines specifically in MySQL 5.7?
I saw so many questions and answers on this topic MyISAM vs InnoDB on stackoverflow itself.

But, all of the questions and answers are too old and not related to the current stable version of MySQL 5.7.x

By the time so much development must have been done in both MyISAM and InnoDB.

So, I need those differences available presently with version 5.7.x

So, please don't mark my question duplicate and someone please explain the differences these storage engines have currently as well as the differences they have since past.

Also, please explain at what situation which storage engine should be chosen for a table.

Can different tables belonging to the same schema have different storage engines i.e. few tables will have InnoDB and few ones will have MyISAM.

If yes, then how the JOIN queries would get execute between tables with MyISAM and InnoDB?

Is it true that MySQL is going to remove MyISAM storage engine from the future version?

答:
Your assumption that MyISAM has been receiving new development is not correct. MyISAM is not receiving any significant new development. MySQL is clearly moving in the direction of phasing out MyISAM, and using MyISAM is discouraged.

Oracle Corp. has not announced any specific date or version by which they will remove MyISAM. My guess is that MyISAM will never be fully removed, because there are too many sites that wouldn't be able to upgrade, without doing expensive testing to make sure their specific app won't experience any regression issues by converting to InnoDB.

But you might notice that in the MySQL 5.7 manual, the section on MyISAM has been demoted to Alternative Storage Engines, which should be a clue that it's receiving less priority.

In MySQL 5.7, MyISAM is still used for some of the system tables, like mysql.user, mysql.db, etc. But new system tables introduced in 5.6 and 5.7 are InnoDB. All system tables are InnoDB in MySQL 8.0.

MyISAM still does not support any of the properties of ACID. There are no transactions, no consistency features, and no durable writes. See my answer to MyISAM versus InnoDB.

MyISAM still does not support foreign keys, for what it's worth. But I seldom see real production sites using foreign keys even with InnoDB.

MyISAM supports only table-level locking (except for some INSERT appending to the end of a table, as noted in the manual).

MySQL 5.7 supports both fulltext indexes and spatial indexes in both MyISAM and InnoDB. These features are not reasons to continue using MyISAM as they once were.

Both logical backup tools like mysqldump and physical backup tools like Percona XtraBackup can't back up MyISAM tables without acquiring a global lock.

You asked if you could create a variety of tables with different storage engines in the same schema. Yes, you can, and this is the same as it has been for many versions of MySQL.

You asked if you can join tables of different storage engines (by the way, tables don't need to be in the same schema to be joined). Yes, you can join such tables, MySQL takes care of all the details. This is the same as it has been for many versions of MySQL.

But some weird cases can come up when you do this, like what if you update a MyISAM table and an InnoDB table in a transaction, and then roll back? The changes in the InnoDB table are rolled back, but the changes in the MyISAM table are not rolled back, so your data integrity can be broken if you aren't careful. This is also the same as it has been for many versions of MySQL.

Cases where MyISAM has an advantage over InnoDB is a short list, and it's getting shorter.

Some table-scan queries and bulk inserts are faster in MyISAM. InnoDB is better at indexed searches.

MyISAM may use less storage space than the equivalent data stored in an uncompressed InnoDB table. You can further compact MyISAM tables with myisampack, but this makes the MyISAM table read-only.

There are other options these days for compact storage of data in transactional storage engines, for example InnoDB table compression, or MyRocks.

SELECT COUNT(*) FROM MyTable queries (with no WHERE clause) are very fast in MyISAM, because the accurate count of rows is persisted in the MyISAM metadata. InnoDB (or other MVCC implementations) doesn't keep this count persisted, because every transaction viewing the table might "see" a different row count. Only a storage engine that has table-level locking and no transaction isolation like MyISAM, can optimize this case.

Auto-increment that numbers independently for each distinct value in another key column. Again, this requires table-level locking, so it's not supported in InnoDB.

```<code>CREATE TABLE MyTable (
  group_id INT NOT NULL,
  seq_id INT NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (group_id, seq_id)
) ENGINE=MyISAM;
</code>```

It's still easy to move a MyISAM table from server to server, because the .MYD and .MYI files are self-contained. You can kind of do something similar with InnoDB tables, but you have to use the intricate feature of transportable tablespaces. But this easy-to-move-tables quality of MyISAM no longer works in MySQL 8.0, because of their new data dictionary feature.

Under certain load, MyISAM might be a better choice for internal_tmp_disk_storage_engine, which defaults to InnoDB in MySQL 5.7. If you run lots of queries that create temp tables on disk (in-memory temp tables won't benefit), it can put a strain on the InnoDB engine. But you'd have to have a high query rate for this to matter, and if your queries create so many temp tables on disk, you should try to optimize the queries differently.

MyISAM allows you to set multiple key caches, and define caches for specific tables. But the MyISAM key caches are only for index structures, not for data.

References:

https://www.percona.com/blog/2016/10/11/mysql-8-0-end-myisam/

https://www.percona.com/blog/2017/12/04/internal-temporary-tables-mysql-5-7/

http://jfg-mysql.blogspot.com/2017/08/why-we-still-need-myisam.html

Body:
Your assumption that MyISAM has been receiving new development is not correct. MyISAM is not receiving any significant new development. MySQL is clearly moving in the direction of phasing out MyISAM, and using MyISAM is discouraged.

Oracle Corp. has not announced any specific date or version by which they will remove MyISAM. My guess is that MyISAM will never be fully removed, because there are too many sites that wouldn't be able to upgrade, without doing expensive testing to make sure their specific app won't experience any regression issues by converting to InnoDB.

But you might notice that in the MySQL 5.7 manual, the section on MyISAM has been demoted to Alternative Storage Engines, which should be a clue that it's receiving less priority.

In MySQL 5.7, MyISAM is still used for some of the system tables, like mysql.user, mysql.db, etc. But new system tables introduced in 5.6 and 5.7 are InnoDB. All system tables are InnoDB in MySQL 8.0.

MyISAM still does not support any of the properties of ACID. There are no transactions, no consistency features, and no durable writes. See my answer to MyISAM versus InnoDB.

MyISAM still does not support foreign keys, for what it's worth. But I seldom see real production sites using foreign keys even with InnoDB.

MyISAM supports only table-level locking (except for some INSERT appending to the end of a table, as noted in the manual).

MySQL 5.7 supports both fulltext indexes and spatial indexes in both MyISAM and InnoDB. These features are not reasons to continue using MyISAM as they once were.

Both logical backup tools like mysqldump and physical backup tools like Percona XtraBackup can't back up MyISAM tables without acquiring a global lock.

You asked if you could create a variety of tables with different storage engines in the same schema. Yes, you can, and this is the same as it has been for many versions of MySQL.

You asked if you can join tables of different storage engines (by the way, tables don't need to be in the same schema to be joined). Yes, you can join such tables, MySQL takes care of all the details. This is the same as it has been for many versions of MySQL.

But some weird cases can come up when you do this, like what if you update a MyISAM table and an InnoDB table in a transaction, and then roll back? The changes in the InnoDB table are rolled back, but the changes in the MyISAM table are not rolled back, so your data integrity can be broken if you aren't careful. This is also the same as it has been for many versions of MySQL.

Cases where MyISAM has an advantage over InnoDB is a short list, and it's getting shorter.

Some table-scan queries and bulk inserts are faster in MyISAM. InnoDB is better at indexed searches.

MyISAM may use less storage space than the equivalent data stored in an uncompressed InnoDB table. You can further compact MyISAM tables with myisampack, but this makes the MyISAM table read-only.

There are other options these days for compact storage of data in transactional storage engines, for example InnoDB table compression, or MyRocks.

SELECT COUNT(*) FROM MyTable queries (with no WHERE clause) are very fast in MyISAM, because the accurate count of rows is persisted in the MyISAM metadata. InnoDB (or other MVCC implementations) doesn't keep this count persisted, because every transaction viewing the table might "see" a different row count. Only a storage engine that has table-level locking and no transaction isolation like MyISAM, can optimize this case.

Auto-increment that numbers independently for each distinct value in another key column. Again, this requires table-level locking, so it's not supported in InnoDB.

CREATE TABLE MyTable (
  group_id INT NOT NULL,
  seq_id INT NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (group_id, seq_id)
) ENGINE=MyISAM;

It's still easy to move a MyISAM table from server to server, because the .MYD and .MYI files are self-contained. You can kind of do something similar with InnoDB tables, but you have to use the intricate feature of transportable tablespaces. But this easy-to-move-tables quality of MyISAM no longer works in MySQL 8.0, because of their new data dictionary feature.

Under certain load, MyISAM might be a better choice for internal_tmp_disk_storage_engine, which defaults to InnoDB in MySQL 5.7. If you run lots of queries that create temp tables on disk (in-memory temp tables won't benefit), it can put a strain on the InnoDB engine. But you'd have to have a high query rate for this to matter, and if your queries create so many temp tables on disk, you should try to optimize the queries differently.

MyISAM allows you to set multiple key caches, and define caches for specific tables. But the MyISAM key caches are only for index structures, not for data.

References:

https://www.percona.com/blog/2016/10/11/mysql-8-0-end-myisam/

https://www.percona.com/blog/2017/12/04/internal-temporary-tables-mysql-5-7/

http://jfg-mysql.blogspot.com/2017/08/why-we-still-need-myisam.html


问:
How to correctly declare "extern"?
If ‘char a[10];’ is defined in one file and ‘extern char *a;’ is declared in another file then it does not work. Is it correct?
The declaration ‘extern char *a;’ does not declare an array and therefore
does not match the actual definition.</p>

答:
Correct -- all declarations of a global symbol must be compatible with the definition of that symbol, or you get the dreaded Undefined Behavior.  extern char *a; is not compatible with char a[10];.

You could use either extern char a[10]; or extern char a[];, both of which are compatible with char a[10]; instead.

Title: How to correctly declare "extern"?


问:
Use ENTER or RETURN as TAB in form and panels
My form as multiple controls like Textboxes and Panels, and Textboxes in Panels, which cause problem. I try to make keys ENTER and RETURN do the same as TAB, so select next control, but for an unknown reason if I i go from any control to a panel, it doesn't enter the first control in the panel, it skips to the next control which isn't a panel.

My form key preview is already True and my tab index are okay :
First textbox is 10, first panel 11, first textbox of panel 12. For now it skips to 20, next textbox not in a panel.

Code based on this question : Tab Key Functionality Using Enter Key in VB.Net

Here is my code

```<code>Private Sub Values_KeyDown(ByVal sender As Control,
  ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Then
        If TypeOf Me.GetNextControl(Me.ActiveControl, True) Is Panel Then
            Me.SelectNextControl(CType(Me.ActiveControl, Panel).Controls.Item(0), True, True, False, True)
        Else
            Me.SelectNextControl(Me.ActiveControl, True, True, False, True)
        End If
        e.Handled = True
    End If
End Sub
</code>```

Thanks!

答:
With Hans' answer i manage to make it work by simply changing the nested parameter to true and get rid of the part that was suppose to make it work with panels, like this:

```<code>Private Sub Values_KeyDown(ByVal sender As Control, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Then
        Me.SelectNextControl(Me.ActiveControl, True, True, True, True)
        e.Handled = True
    End If
End Sub
</code>```

You'll still need to put the Key Preview parameter on your form to True

I also found an alternative here : How to make Enter on a TextBox act as TAB button

```<code>Private Sub Values_KeyDown(ByVal sender As Control, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Then
        SendKeys.Send("{TAB}")
        e.Handled = True
    End If
End Sub
</code>```

Body:
My form as multiple controls like Textboxes and Panels, and Textboxes in Panels, which cause problem. I try to make keys ENTER and RETURN do the same as TAB, so select next control, but for an unknown reason if I i go from any control to a panel, it doesn't enter the first control in the panel, it skips to the next control which isn't a panel.

My form key preview is already True and my tab index are okay :
First textbox is 10, first panel 11, first textbox of panel 12. For now it skips to 20, next textbox not in a panel.

Code based on this question : Tab Key Functionality Using Enter Key in VB.Net

Here is my code

Private Sub Values_KeyDown(ByVal sender As Control,
  ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Then
        If TypeOf Me.GetNextControl(Me.ActiveControl, True) Is Panel Then
            Me.SelectNextControl(CType(Me.ActiveControl, Panel).Controls.Item(0), True, True, False, True)
        Else
            Me.SelectNextControl(Me.ActiveControl, True, True, False, True)
        End If
        e.Handled = True
    End If
End Sub

Thanks!

Body:
With Hans' answer i manage to make it work by simply changing the nested parameter to true and get rid of the part that was suppose to make it work with panels, like this:

Private Sub Values_KeyDown(ByVal sender As Control, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Then
        Me.SelectNextControl(Me.ActiveControl, True, True, True, True)
        e.Handled = True
    End If
End Sub

You'll still need to put the Key Preview parameter on your form to True

I also found an alternative here : How to make Enter on a TextBox act as TAB button

Private Sub Values_KeyDown(ByVal sender As Control, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Then
        SendKeys.Send("{TAB}")
        e.Handled = True
    End If
End Sub


问:
How do I use JDK 7 on Mac OSX?
I would like to use the WatchService API as mentioned in this link:
http://download.oracle.com/javase/tutorial/essential/io/notification.html

After reading around, I found out that WatchService is part of the NIO class which is scheduled for JDK 7. So, it is in beta form. It's fine.

http://jdk7.java.net/download.html has the JDK which I downloaded and extracted. I got a bunch of folders. I don't know what to do with them.

Then, I read around some more and found that some nice group of people created JDK 7 as a binary so someone like me can install it easily. It is called Open JDK:
http://code.google.com/p/openjdk-osx-build/

So, I downloaded the .dmg file and install it. Then I open "Java Preference" and see that OpenJDK7 is available.

So, now I feel that I can start trying out WatchService API. From the tutorial in the first link, the author gave a .java file to test it out first and make sure that it is running. Here is the link to the file:
http://download.oracle.com/javase/tutorial/essential/io/examples/WatchDir.java

So, I boot up Eclipse (actually I use STS) and create a new Java project and choose JaveSE-1.7 in the "use an execution environment JRE:". Under the src folder, I copy pasted the WatchDir.java file.

And I still see tons of squiggly red lines. All the "import.java.nio.*" are all red and I cannot run it as a Java app.

What do I need to do?

答:
As of December 2017, previously posted links don't work, but JDK 7 can still be downloaded from Oracle Archives (login required):

http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html

ContentLicense: CC BY-SA 4.0

Title: How do I use JDK 7 on Mac OSX?


问:
Do I need to commit the dist folder to git in order to be able to install the package using pip from git?
I want to reuse some code for my internal team at work. My plan is to create a package and then have people install the package using pip straight out of our git repo. i.e. as shown here: https://pip.pypa.io/en/latest/reference/pip_install/#git

My question is, do I commit the dist folder to git? What is pip looking for?

Or is there a better way to share / reuse code internally for a team (across many different projects)?

I used a .gitignore file from here (is that github's default Python .gitignore file?) and it ignores all the dist files:

```<code># Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
</code>```

but it seems wrong to exclude these from the repo when I'm trying to install from the repo.

答: You do not need to commit the dist folder.  pip really just needs the repository to have a setup.py file along with the packages and/or modules you're installing.

Body:
I want to reuse some code for my internal team at work. My plan is to create a package and then have people install the package using pip straight out of our git repo. i.e. as shown here: https://pip.pypa.io/en/latest/reference/pip_install/#git

My question is, do I commit the dist folder to git? What is pip looking for?

Or is there a better way to share / reuse code internally for a team (across many different projects)?

I used a .gitignore file from here (is that github's default Python .gitignore file?) and it ignores all the dist files:

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

but it seems wrong to exclude these from the repo when I'm trying to install from the repo.


问:
Joining two arrays by key name for Angular project
I'm pretty new to angular and typescript and I've run into an issue. I have two arrays that I need merged into one based on their category-id. Both arrays include some values that the other does not have. These arrays will change based on user inputs so I have no way of knowing ahead of time what the length of each array will be. I do know that "category-id" will always be included in each array, however, which is why I would like to merge the 2 arrays based on that. Thanks for any help.

Example:

```<code>arr1 = [
{category-id: car, category-value: mustang},
{category-id: convertible, category-value: softTop}
]
arr2 = [
{category-id: car, category-feature: convertible},
{category-id: truck, category-value: ranger},
{category-id: convertible, category-feature: blue}
]
</code>```

Desired Result:

```<code>arr3 = [
{category-id: car, category-value:mustang, category-feature: convertible},
{category-id: truck, category-value: ranger},
{category-id: convertible, category-value: softTop, category-feature: blue}
]
</code>```

答:
Here you go. It's not the most elegant solution, you could do it in 2 lines using lodash or Typescript LINQ or Immutable.js but it's pure.

```<code>const arr1 = [
    { categoryid: 'car', categoryvalue: 'mustang'},
    { categoryid: 'convertible', categoryvalue: 'softTop'}
]
const arr2 = [
    { categoryid: 'car', categoryfeature: 'convertible'},
    { categoryid: 'truck', categoryvalue: 'ranger'},
    { categoryid: 'convertible', categoryfeature: 'blue'}
]

const arr3 = []
for (let x of arr1)
{
    const found = arr2.filter(y => y.categoryid === x.categoryid).shift();
    if (found)
       arr3.push({ ...x, ...found });
}
arr3.push(... arr2.filter(z=> arr1.map(x=>x.categoryid).indexOf(z.categoryid) === -1 ))
</code>```

So the trick here is to use the spread operator. It will automatically merge two object by their field names.

Body:
I'm pretty new to angular and typescript and I've run into an issue. I have two arrays that I need merged into one based on their category-id. Both arrays include some values that the other does not have. These arrays will change based on user inputs so I have no way of knowing ahead of time what the length of each array will be. I do know that "category-id" will always be included in each array, however, which is why I would like to merge the 2 arrays based on that. Thanks for any help.

Example:

arr1 = [
{category-id: car, category-value: mustang},
{category-id: convertible, category-value: softTop}
]
arr2 = [
{category-id: car, category-feature: convertible},
{category-id: truck, category-value: ranger},
{category-id: convertible, category-feature: blue}
]

Desired Result:

arr3 = [
{category-id: car, category-value:mustang, category-feature: convertible},
{category-id: truck, category-value: ranger},
{category-id: convertible, category-value: softTop, category-feature: blue}
]

Body:
Here you go. It's not the most elegant solution, you could do it in 2 lines using lodash or Typescript LINQ or Immutable.js but it's pure.

const arr1 = [
    { categoryid: 'car', categoryvalue: 'mustang'},
    { categoryid: 'convertible', categoryvalue: 'softTop'}
]
const arr2 = [
    { categoryid: 'car', categoryfeature: 'convertible'},
    { categoryid: 'truck', categoryvalue: 'ranger'},
    { categoryid: 'convertible', categoryfeature: 'blue'}
]

const arr3 = []
for (let x of arr1)
{
    const found = arr2.filter(y => y.categoryid === x.categoryid).shift();
    if (found)
       arr3.push({ ...x, ...found });
}
arr3.push(... arr2.filter(z=> arr1.map(x=>x.categoryid).indexOf(z.categoryid) === -1 ))

So the trick here is to use the spread operator. It will automatically merge two object by their field names.


问:
python - calculate orthographic similarity between words of a list
I need to calculate orthographic similarity (edit/Levenshtein distance) among words in a given corpus.

As Kirill suggested below, I tried to do the following:

```<code>import csv, itertools, Levenshtein
import numpy as np

# import the list of words from csv file
path = '/Users/my path'
file = path + 'file.csv'

with open(file, 'rb') as f:
    reader = csv.reader(f)
    wordlist = list(reader)

wordlist = np.array(wordlist) #make it a np array
wordlist2 = wordlist[:,0] #subset the first column of the imported list

for a, b in itertools.product(wordlist, wordlist):
    if a < b:
        print(a, b, Levenshtein.distance(a, b))
</code>```

However, the following error pops up:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I understand the ambiguity in the code, but can someone help me figure out how to solve this? Thanks!

答:
Levenshtein distance by its definition can be computed only between two strings: it's how you can edit one string to obtain the other. You can compare words pairwise, it requires n*(n-1)/2 comparisons (where n is the number of unique words in your corpus). Here's how you can do it:

```<code>>>> import itertools, Levenshtein
>>> words = sorted(set('little Mary had a little lamb'.split()))
>>> for a, b in itertools.product(words, words):
...     if a < b:
...         print(a, b, Levenshtein.distance(a, b))
...
Mary a 3
Mary had 3
Mary lamb 3
Mary little 6
a had 2
a lamb 3
a little 6
had lamb 3
had little 6
lamb little 5
</code>```

Body:
I need to calculate orthographic similarity (edit/Levenshtein distance) among words in a given corpus.

As Kirill suggested below, I tried to do the following:

import csv, itertools, Levenshtein
import numpy as np

# import the list of words from csv file
path = '/Users/my path'
file = path + 'file.csv'

with open(file, 'rb') as f:
    reader = csv.reader(f)
    wordlist = list(reader)

wordlist = np.array(wordlist) #make it a np array
wordlist2 = wordlist[:,0] #subset the first column of the imported list

for a, b in itertools.product(wordlist, wordlist):
    if a < b:
        print(a, b, Levenshtein.distance(a, b))

However, the following error pops up:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I understand the ambiguity in the code, but can someone help me figure out how to solve this? Thanks!

Body:
Levenshtein distance by its definition can be computed only between two strings: it's how you can edit one string to obtain the other. You can compare words pairwise, it requires n*(n-1)/2 comparisons (where n is the number of unique words in your corpus). Here's how you can do it:

>>> import itertools, Levenshtein
>>> words = sorted(set('little Mary had a little lamb'.split()))
>>> for a, b in itertools.product(words, words):
...     if a < b:
...         print(a, b, Levenshtein.distance(a, b))
...
Mary a 3
Mary had 3
Mary lamb 3
Mary little 6
a had 2
a lamb 3
a little 6
had lamb 3
had little 6
lamb little 5


问:
Problems to create a C# ClassLibrary in MacOS (.Net Core 2.0)
I'm quite confusing trying to create a .net core app in MacOs.

I followed the tutorial found here and everthing worked well, but when I tried to create another ClassLibrary with some other dependencies,  anything works and I can't understand why.

I installed the VisualStudio 2017 with .net core SDK , so I think that my Mac now has all pre-requisites to create my C# Libraries. For information, when I type dotnet --version I get 2.0.0.

So I create a new ClassLibrary, and set the target framework to netStandard 1.4, foloowing the instructions found here, since I want that my library be used in another environments besides MacOs and NetCore.

The problem is that, apparently, net core 2.0 in my mac does not have all necessary assemblies to create the library, because a simple code like below is broken with the message

"Error CS0234: The type or namespace name 'Cryptography' does not
  exist in the namespace 'System.Security' (are you missing an assembly
  reference?) (CS0234)"

```<code>MD5 md5 = new MD5CryptoServiceProvider();
</code>```

Im have the code using System.Security.Cryptography; in the top of my file, so it should work since this module is available since netstandard1.1, right?

I know that I'm doing some type of confusion, but I want to understand where is my mistake.

Can I create a ClassLibrary in my MacOS targeting the netstandanrd1.4 even running the .NET CORE 2.0? If yes, where can I found the missing assemblies for .NET libraries? Should I install anything?

答:
.NET Standard 1.4 is only supported in .NET Core 1.0.  Not 2.0

Reference of Supported Libraries

You can target a previous version of .NET Core by specifying this in your .csproj file by using the following:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

</Project>
</code>```

Body:
I'm quite confusing trying to create a .net core app in MacOs.

I followed the tutorial found here and everthing worked well, but when I tried to create another ClassLibrary with some other dependencies,  anything works and I can't understand why.

I installed the VisualStudio 2017 with .net core SDK , so I think that my Mac now has all pre-requisites to create my C# Libraries. For information, when I type dotnet --version I get 2.0.0.

So I create a new ClassLibrary, and set the target framework to netStandard 1.4, foloowing the instructions found here, since I want that my library be used in another environments besides MacOs and NetCore.

The problem is that, apparently, net core 2.0 in my mac does not have all necessary assemblies to create the library, because a simple code like below is broken with the message

"Error CS0234: The type or namespace name 'Cryptography' does not
  exist in the namespace 'System.Security' (are you missing an assembly
  reference?) (CS0234)"

MD5 md5 = new MD5CryptoServiceProvider();

Im have the code using System.Security.Cryptography; in the top of my file, so it should work since this module is available since netstandard1.1, right?

I know that I'm doing some type of confusion, but I want to understand where is my mistake.

Can I create a ClassLibrary in my MacOS targeting the netstandanrd1.4 even running the .NET CORE 2.0? If yes, where can I found the missing assemblies for .NET libraries? Should I install anything?

Body:
.NET Standard 1.4 is only supported in .NET Core 1.0.  Not 2.0

Reference of Supported Libraries

You can target a previous version of .NET Core by specifying this in your .csproj file by using the following:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

</Project>


问:
Can't call a function from a separate file
I'm trying to run a function that's inside an included file. The file get's included properly but I still get a undefined function error. Tried everything and nothing seems to work. Here's a simplified version of my code...

File functions.php

```<code><?php function myFunction($foo){ echo $foo; } ?>
</code>```

File index.php

```<code><?php include('functions.php'); $string = "Hello, world!"; myFunction($string); ?>
</code>```

I'm getting the following error:

Fatal error: Uncaught Error: Call to undefined function myFunction()
  in /functions.php on line 1

I tried with include, include_once, request, request_once and even creating a class with a public function but nothing works. The file is being properly included because if I added an echo at the beginning of functions.php and it displays properly on index.php. Also, there is no error in my function because if I run it from the functions.php file it works like a charm. The problem is that index.php isn't recognizing myFunction() as a defined function. Could it be a problem with the php.ini file? The include works so that can't be it.

How can I call myFunction($foo) from index.php?

Thanks in advance!

答:
Was able to fix it. In the original file I was calling the include via a complete URL. I wrote it with an absolute URL and it worked. Must be a local server thing.

Thanks for your feedback!

Body:
I'm trying to run a function that's inside an included file. The file get's included properly but I still get a undefined function error. Tried everything and nothing seems to work. Here's a simplified version of my code...

File functions.php

<?php function myFunction($foo){ echo $foo; } ?>

File index.php

<?php include('functions.php'); $string = "Hello, world!"; myFunction($string); ?>

I'm getting the following error:

Fatal error: Uncaught Error: Call to undefined function myFunction()
  in /functions.php on line 1

I tried with include, include_once, request, request_once and even creating a class with a public function but nothing works. The file is being properly included because if I added an echo at the beginning of functions.php and it displays properly on index.php. Also, there is no error in my function because if I run it from the functions.php file it works like a charm. The problem is that index.php isn't recognizing myFunction() as a defined function. Could it be a problem with the php.ini file? The include works so that can't be it.

How can I call myFunction($foo) from index.php?

Thanks in advance!


问:
Reference Json as $arg bash with variables in payload (arg1 arg2 not variable passed)
I have a script that is helping me to POST some data to a system

I have a function

```<code>function curler(){
#curl "https://secure.aha.io/api/v1/features/"$featureID"/requirements?access_token={myAccessToken}" -d "$minReq" -X POST -H "Content-type: Application/json" -H "Accept: application/json"
echo "https://secure.aha.io/api/v1/features/"$1"/requirements?access_token={myAccessToken}" -d "$2" -X POST -H "Content-type: Application/json" -H "Accept: application/json"
echo $1
echo $2
}
</code>```

I then call upon the function passing in $featureID and a minReq variable I have defined with my json payload

```<code>minReq='{"requirement":{"name":"'$elementName' - Min
Length","workflow_status":{"name":"Defined"},"description":"-
Indicates the minimum length of strings or
numbers.","assigned_to_user":{"email":"kelly@someEmail.com"}}}'
</code>```

In the curler function, you can see that I have tried referencing by the actual variable names and by $1 andf $2 based on the arg index

Ultimately I want to use the curl, but for testing I have the echo

I call the curler function with curler $featureID $minReq where featureID is a string MDL-123 and $minReq contains my json payload

the echo outputs the following

```<code>https://secure.aha.io/api/v1/features/mdl-149/requirements?access_token={myAccessToken} -d {"requirement":{"name":"Act-On -X POST -H Content-type: Application/json -H Accept: application/json

mdl-149
{"requirement":{"name":"Act-On
</code>```

elements-mac27:Scripts kellygold$

What I am seeing is that my payload $minReq is cut off after $elementName is inserted when I reference the $minReq argument as $2

in my example above elementName is 'act-on' $elementName is defined and was previously gathered from the user

I also notice, that if I reference the variable as it's native name $minReq then it works as expected

so the following echo
echo "https://secure.aha.io/api/v1/features/"$1"/requirements?access_token={myaccesstoken}" -d "$minReq" -X POST -H "Content-type: Application/json" -H "Accept: application/json"

Outputs expected

```<code>https://secure.aha.io/api/v1/features/mdl-149/requirements?access_token={myAccessToken} -d {"requirement":{"name":"act-on - Min Length","workflow_status":{"name":"Defined"},"description":"- Indicatest the minimum length of strings or numbers.","assigned_to_user":{"email":"kelly@someEmail.com"}}} -X POST -H Content-type: Application/json -H Accept: application/json

mdl-149

{"requirement":{"name":"act-on
elements-mac27:Scripts kellygold$
</code>```

Why is it that when I reference my argument by the variable name passed in the function call $minReq it works as expected, but when I pass $2 it cuts off right after the variable is inserted into my payload? How can I reference the arg number instead of variable name, while maintaining my data?

答:
You need to call your function with the parameters enclosed in double-quotes:

```<code>curler "$featureID" "$minReq"
</code>```

Without the double-quotes,
the shell performs word-splitting,
and instead of passing two parameters,
the function will receive them word-split over multiple parameters.

As a rule of thumb,
you should double-quote variables used in command parameters.

Body:
I have a script that is helping me to POST some data to a system

I have a function

function curler(){
#curl "https://secure.aha.io/api/v1/features/"$featureID"/requirements?access_token={myAccessToken}" -d "$minReq" -X POST -H "Content-type: Application/json" -H "Accept: application/json"
echo "https://secure.aha.io/api/v1/features/"$1"/requirements?access_token={myAccessToken}" -d "$2" -X POST -H "Content-type: Application/json" -H "Accept: application/json"
echo $1
echo $2
}

I then call upon the function passing in $featureID and a minReq variable I have defined with my json payload

minReq='{"requirement":{"name":"'$elementName' - Min
Length","workflow_status":{"name":"Defined"},"description":"-
Indicates the minimum length of strings or
numbers.","assigned_to_user":{"email":"kelly@someEmail.com"}}}'

In the curler function, you can see that I have tried referencing by the actual variable names and by $1 andf $2 based on the arg index

Ultimately I want to use the curl, but for testing I have the echo

I call the curler function with curler $featureID $minReq where featureID is a string MDL-123 and $minReq contains my json payload

the echo outputs the following

https://secure.aha.io/api/v1/features/mdl-149/requirements?access_token={myAccessToken} -d {"requirement":{"name":"Act-On -X POST -H Content-type: Application/json -H Accept: application/json

mdl-149
{"requirement":{"name":"Act-On

elements-mac27:Scripts kellygold$

What I am seeing is that my payload $minReq is cut off after $elementName is inserted when I reference the $minReq argument as $2

in my example above elementName is 'act-on' $elementName is defined and was previously gathered from the user

I also notice, that if I reference the variable as it's native name $minReq then it works as expected

so the following echo
echo "https://secure.aha.io/api/v1/features/"$1"/requirements?access_token={myaccesstoken}" -d "$minReq" -X POST -H "Content-type: Application/json" -H "Accept: application/json"

Outputs expected

https://secure.aha.io/api/v1/features/mdl-149/requirements?access_token={myAccessToken} -d {"requirement":{"name":"act-on - Min Length","workflow_status":{"name":"Defined"},"description":"- Indicatest the minimum length of strings or numbers.","assigned_to_user":{"email":"kelly@someEmail.com"}}} -X POST -H Content-type: Application/json -H Accept: application/json

mdl-149

{"requirement":{"name":"act-on
elements-mac27:Scripts kellygold$

Why is it that when I reference my argument by the variable name passed in the function call $minReq it works as expected, but when I pass $2 it cuts off right after the variable is inserted into my payload? How can I reference the arg number instead of variable name, while maintaining my data?

Body:
You need to call your function with the parameters enclosed in double-quotes:

curler "$featureID" "$minReq"

Without the double-quotes,
the shell performs word-splitting,
and instead of passing two parameters,
the function will receive them word-split over multiple parameters.

As a rule of thumb,
you should double-quote variables used in command parameters.


问:
How to calculate dimensions of a 2d array?
I am looking for the dimensions of a 2d array. Not the fixed values assigned to the array, but the values containing integers. Example:

```<code>int a[][] = new int[4][5];
a[1][1] = 1;
a[1][2] = 2;
a[1][3] = -2;
a[1][4] = 0;
a[2][1] = -3;
a[2][2] = 4;
a[2][3] = 7;
a[2][4] = 2;
a[3][1] = 6;
a[3][2] = 0;
a[3][3] = 3;
a[3][4] = 1;
</code>```

Only 3 variables are used out of 4, and 4 variables used out of 5. How can you tell what is actually there versus what is assigned to be there?

```<code>array.length;
array[0].length;
</code>```

The previous code will only give you the fixed variable assigned to the array. But what if your not using all the variables? In other words I am looking for an output of 3 for columns and 4 for rows.

答:
In your code example, you are using all variables in the array. Just because you haven't assigned anything to them, they are still sitting there.

If you want to determine whether or not you've assigned a value to each element in the array, you need to initialize everything to a default value, and then just compare against the default value.

A variation on that option is to declare them as int?, which is a nullable int. That would allow you to set everything to null, and then you'll know that the elements that are no longer null have had a value assigned to them.

Body:
I am looking for the dimensions of a 2d array. Not the fixed values assigned to the array, but the values containing integers. Example:

int a[][] = new int[4][5];
a[1][1] = 1;
a[1][2] = 2;
a[1][3] = -2;
a[1][4] = 0;
a[2][1] = -3;
a[2][2] = 4;
a[2][3] = 7;
a[2][4] = 2;
a[3][1] = 6;
a[3][2] = 0;
a[3][3] = 3;
a[3][4] = 1;

Only 3 variables are used out of 4, and 4 variables used out of 5. How can you tell what is actually there versus what is assigned to be there?

array.length;
array[0].length;

The previous code will only give you the fixed variable assigned to the array. But what if your not using all the variables? In other words I am looking for an output of 3 for columns and 4 for rows.