问:
How to include test classes with init in a Pytest test suite?
I'm trying to create a test suite with pytest and Selenium using Page Object Models for pattern designing. For using my page classes on my tests, I just imported them inside my TestClass __init__ method, since they need to instanced with a driver.

I know that, by default, pytest ignores classes with an __init__ method. I also know, by reading here that it's possible to configure where pytest collects tests. Is it also possible to make it consider class tests with __init__, instead of returning an "Empty Suite" error?

```<code>@pytest.fixture(scope="session")
def driver_init(request):
    from selenium import webdriver
    driver = webdriver.Chrome()
    session = request.node
    page = PageFunctions(driver)
    login_page = LoginPage(driver)
    registration_page = RegistrationPage(driver)

    for item in session.items:
        cls = item.getparent(pytest.Class)
        setattr(cls.obj, "driver", driver)
        setattr(cls.obj, "page", page)
        setattr(cls.obj, "login", login_page)
        setattr(cls.obj, "registration", registration_page)
</code>```

答:
Pytest and Unittest have some different conventions.  Mixing the two in the same test function is usually worth avoiding.

If you're working exclusively with Pytest, you would pass in your fixtures as arguments to your test function, e.g.:

```<code>import pytest
from selenium import webdriver

@pytest.fixture
def driver():
    driver = webdriver.Chrome()
    return driver

def test_func(driver):
    # `driver` is found by pytest in the fixture above and
    # automatically passed in
    request = ... # Instantiate your request (not in your included code)

    session = request.node
    page = PageFunctions(driver)
    login_page = LoginPage(driver)
    registration_page = RegistrationPage(driver)

    # Make some assertions about your data, e.g.:
    assert page is not None
</code>```

You haven't included all of the object definitions/imports so it's hard to see what you're trying to accomplish with the test, but hopefully that gives you an idea of the pytest conventions.

Body:
I'm trying to create a test suite with pytest and Selenium using Page Object Models for pattern designing. For using my page classes on my tests, I just imported them inside my TestClass __init__ method, since they need to instanced with a driver.

I know that, by default, pytest ignores classes with an __init__ method. I also know, by reading here that it's possible to configure where pytest collects tests. Is it also possible to make it consider class tests with __init__, instead of returning an "Empty Suite" error?

@pytest.fixture(scope="session")
def driver_init(request):
    from selenium import webdriver
    driver = webdriver.Chrome()
    session = request.node
    page = PageFunctions(driver)
    login_page = LoginPage(driver)
    registration_page = RegistrationPage(driver)

    for item in session.items:
        cls = item.getparent(pytest.Class)
        setattr(cls.obj, "driver", driver)
        setattr(cls.obj, "page", page)
        setattr(cls.obj, "login", login_page)
        setattr(cls.obj, "registration", registration_page)

Body:
Pytest and Unittest have some different conventions.  Mixing the two in the same test function is usually worth avoiding.

If you're working exclusively with Pytest, you would pass in your fixtures as arguments to your test function, e.g.:

import pytest
from selenium import webdriver

@pytest.fixture
def driver():
    driver = webdriver.Chrome()
    return driver

def test_func(driver):
    # `driver` is found by pytest in the fixture above and
    # automatically passed in
    request = ... # Instantiate your request (not in your included code)

    session = request.node
    page = PageFunctions(driver)
    login_page = LoginPage(driver)
    registration_page = RegistrationPage(driver)

    # Make some assertions about your data, e.g.:
    assert page is not None

You haven't included all of the object definitions/imports so it's hard to see what you're trying to accomplish with the test, but hopefully that gives you an idea of the pytest conventions.


来源: stackexchange

问:
how to update parent state in child component and pass to parent state back?
I am passing object from parent componet to child component and there some input fields in child component which handled in parent component as follow:

```<code>import React, { Component } from "react";
import Child from 'path';

class parent extends Component {
    constuctor(props){
        super(props);
        this.state = {
            obj :{
                //object
            }
        }
        this.handlerInput =  this.handlerInput.bind(this);
    }

    handlerInput(e){
        //logic to update state obj
    }
    render(){
        return(
            <div className="content">
                <Child changeHandle={this.handlerInput}  />
            </div>
        );
    };
}

export default parent;

import React, { Component } from "react";

class Child extends Component {
    render(){
        return(
            <div className="content">
                <input type="text" onChange={ this.props.changeHandle } name="xyz" />
            </div>
        );
    };
}

export default Child;
</code>```

Now lets suppose if i have to use child component at multiple places so every time i have to define changeHandle function in parent component?

Any suggestion to update parent state from child ?

答:
You can try something like that</p>

```<code>import React, { Component } from "react";
import Child from "./Child";
class Parent extends Component {
    constructor(props){
        super(props);
    }
  state = {
      name: 'Parent',
  };

  changeHandle = e => {
    this.setState({ name: e.target.value });
  };

  render() {
    return (
      <div>
        <Child changeHandle={this.changeHandle} name={this.state.name}/>
      </div>
    );
  }
}

export default Parent;

import React, { Component } from "react";
class Child extends Component {
  constructor(props) {
    super(props);
  }
  state = {
    name: "Child"
  };
  render() {
    return (
      <div className="content">
        <input
          type="text"
          onChange={this.props.changeHandle}
          name="xyz"
          value={this.props.name}
        />
      </div>
    );
  }
}

export default Child;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am passing object from parent componet to child component and there some input fields in child component which handled in parent component as follow:

import React, { Component } from "react";
import Child from 'path';

class parent extends Component {
    constuctor(props){
        super(props);
        this.state = {
            obj :{
                //object
            }
        }
        this.handlerInput =  this.handlerInput.bind(this);
    }

    handlerInput(e){
        //logic to update state obj
    }
    render(){
        return(

                <Child changeHandle={this.handlerInput}  />

        );
    };
}

export default parent;

import React, { Component } from "react";

class Child extends Component {
    render(){
        return(

                <input type="text" onChange={ this.props.changeHandle } name="xyz" />

        );
    };
}

export default Child;

Now lets suppose if i have to use child component at multiple places so every time i have to define changeHandle function in parent component?

Any suggestion to update parent state from child ?

Body:
You can try something like that

import React, { Component } from "react";
import Child from "./Child";
class Parent extends Component {
    constructor(props){
        super(props);
    }
  state = {
      name: 'Parent',
  };

  changeHandle = e => {
    this.setState({ name: e.target.value });
  };

  render() {
    return (
      <div>
        <Child changeHandle={this.changeHandle} name={this.state.name}/>
      </div>
    );
  }
}

export default Parent;

import React, { Component } from "react";
class Child extends Component {
  constructor(props) {
    super(props);
  }
  state = {
    name: "Child"
  };
  render() {
    return (
      <div className="content">
        <input
          type="text"
          onChange={this.props.changeHandle}
          name="xyz"
          value={this.props.name}
        />
      </div>
    );
  }
}

export default Child;


问:
how to pass value in api body in protractor while requesting the api
I want to pass the value in API request body.
I tried below code for that

```<code>    var options = { method: 'POST',
        url: 'https://ssgpreprod.serviceurl.in/gonogo-api/atm/tw/cro-approval',
        headers:
            { 'Postman-Token': '9d6a0ad1-c3a1-402f-b845-b6416f49df6b',
                'cache-control': 'no-cache',
                'Content-Type': 'application/json' },
        body:
            { oHeader:
                { sReqType: 'application/json',
                    sAppSource: 'WEB 2.02.01',
                    sSourceID: 'GONOGO_HDBFS',
                    sAppID: 610961419000670,
                    dtSubmit: '',
                    sCroId: 'HDB_TW_CRO@cell.com',
                    sDsaId: 'default',
                    sInstID: 4019,
                    sUserName: 'CHDBTWCRO',
                    sProduct: 'TW',
                    sDealerId: '61096' },
                sRefID:testData.twPreIpa.twReferenceId,
                sAppStat: testData.twCroDetails.twCroDecision,
                aCroJustification: [ { sRemark: testData.twCroDetails.twRemark, sSubTo: testData.twCroDetails.twSubjectTo} ],
                bApprAmtExist: true,
                dApprAmt: testData.twApplyDetails.twLoanAmount,
                dItrRt: testData.twCroDetails.twRoi,
                dLtv: testData.twCroDetails.twLtv,
                aDedupeRefID: [] },
        json: true };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);
        browser.logger.info(JSON.stringify(body));
        browser.logger.info(JSON.stringify(response));
        browser.logger.info('status code is : ' + response.statusCode);
        expect(response.statusCode).toBe(200).then(function () {
            browser.logger.info('case is approved');
            this.logOut(testData);
        })
    });
</code>```

I am passing value from xlsx file i.e testData.twPreIpa.twReferenceId but I am getting 422 status code and below output

[2019-05-28 15:42:10.403] [INFO] : - {"title":"Conversion Failed","status":422,"detail":"The content you've sent is probably malformed."}

Also, when I add - browser.logger.info('approved'); above var options it prints on console..  but when I add -             browser.logger.info(testData.twPreIpa.twReferenceId);

It gives me error .. ouput displayed -

Failed: Cannot read property 'twReferenceId' of undefined
TypeError: Cannot read property 'twReferenceId' of undefined

答:
While this may not directly answer your question it should be helpful to you.
I worked on a similar framework to what (I assume) yours looks like,some api and some UI validations.

I had a separate class for my API calls which returned some value, sometimes the entire response body. I allowed myself the ability to pass in whatever body I needed as a parameter.

This is an example of the approach I took.

```<code>module.exports = class Endpoints {

    addSomethingToUser(bearerToken, userId, JSONbody) {
        //Function will preform a POST request and return the status code if successful
        //Else if will return the body of the response

        let endpoint = 'http://myApp.com:9090/api/users/' + userId;

        return new Promise((resolve, reject) => {
            let options = {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + token,
                },
                body: JSON.stringify(JSONbody),
            };

            request(
                endpoint,
                options ,
                function (error, response, body) {
                    if (!error && (response.statusCode >= 200 && response.statusCode < 300)) {
                        resolve(response.statusCode);
                    } else {
                        console.log('error:', error, response && response.statusCode);
                        reject(JSON.stringify(response, undefined, 2));
                    };
                }
            );
        });
    };
}
</code>```

It is called like

```<code>let apiCallsFile = require('../apiCalls/restCalls');
let apiCalls = new apiCallsFile();

it('simple test', async function(){
    let requiredBody = {
        "NAME": "Test Name",
        "GENDER": "MALE",
    };

    let apiResult = await apiCalls.addSomethingToUser(bearerToken, userId, requiredBody );
    expect(apiResult).toBe('201');
}
</code>```

Your issue seems to be related to the actual values you are using from excel. You should attempt to print out your values before attempting to send the request to ensure they are all present and in the format you expect.

Body:
I want to pass the value in API request body.
I tried below code for that

    var options = { method: 'POST',
        url: 'https://ssgpreprod.serviceurl.in/gonogo-api/atm/tw/cro-approval',
        headers:
            { 'Postman-Token': '9d6a0ad1-c3a1-402f-b845-b6416f49df6b',
                'cache-control': 'no-cache',
                'Content-Type': 'application/json' },
        body:
            { oHeader:
                { sReqType: 'application/json',
                    sAppSource: 'WEB 2.02.01',
                    sSourceID: 'GONOGO_HDBFS',
                    sAppID: 610961419000670,
                    dtSubmit: '',
                    sCroId: 'HDB_TW_CRO@cell.com',
                    sDsaId: 'default',
                    sInstID: 4019,
                    sUserName: 'CHDBTWCRO',
                    sProduct: 'TW',
                    sDealerId: '61096' },
                sRefID:testData.twPreIpa.twReferenceId,
                sAppStat: testData.twCroDetails.twCroDecision,
                aCroJustification: [ { sRemark: testData.twCroDetails.twRemark, sSubTo: testData.twCroDetails.twSubjectTo} ],
                bApprAmtExist: true,
                dApprAmt: testData.twApplyDetails.twLoanAmount,
                dItrRt: testData.twCroDetails.twRoi,
                dLtv: testData.twCroDetails.twLtv,
                aDedupeRefID: [] },
        json: true };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);
        browser.logger.info(JSON.stringify(body));
        browser.logger.info(JSON.stringify(response));
        browser.logger.info('status code is : ' + response.statusCode);
        expect(response.statusCode).toBe(200).then(function () {
            browser.logger.info('case is approved');
            this.logOut(testData);
        })
    });

I am passing value from xlsx file i.e testData.twPreIpa.twReferenceId but I am getting 422 status code and below output

[2019-05-28 15:42:10.403] [INFO] : - {"title":"Conversion Failed","status":422,"detail":"The content you've sent is probably malformed."}

Also, when I add - browser.logger.info('approved'); above var options it prints on console..  but when I add -             browser.logger.info(testData.twPreIpa.twReferenceId);

It gives me error .. ouput displayed -

Failed: Cannot read property 'twReferenceId' of undefined
TypeError: Cannot read property 'twReferenceId' of undefined

Body:
While this may not directly answer your question it should be helpful to you.
I worked on a similar framework to what (I assume) yours looks like,some api and some UI validations.

I had a separate class for my API calls which returned some value, sometimes the entire response body. I allowed myself the ability to pass in whatever body I needed as a parameter.

This is an example of the approach I took.

module.exports = class Endpoints {

    addSomethingToUser(bearerToken, userId, JSONbody) {
        //Function will preform a POST request and return the status code if successful
        //Else if will return the body of the response

        let endpoint = 'http://myApp.com:9090/api/users/' + userId;

        return new Promise((resolve, reject) => {
            let options = {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + token,
                },
                body: JSON.stringify(JSONbody),
            };

            request(
                endpoint,
                options ,
                function (error, response, body) {
                    if (!error && (response.statusCode >= 200 && response.statusCode < 300)) {
                        resolve(response.statusCode);
                    } else {
                        console.log('error:', error, response && response.statusCode);
                        reject(JSON.stringify(response, undefined, 2));
                    };
                }
            );
        });
    };
}

It is called like

let apiCallsFile = require('../apiCalls/restCalls');
let apiCalls = new apiCallsFile();

it('simple test', async function(){
    let requiredBody = {
        "NAME": "Test Name",
        "GENDER": "MALE",
    };

    let apiResult = await apiCalls.addSomethingToUser(bearerToken, userId, requiredBody );
    expect(apiResult).toBe('201');
}

Your issue seems to be related to the actual values you are using from excel. You should attempt to print out your values before attempting to send the request to ensure they are all present and in the format you expect.


问:
How to validate an e-mail if this is not same as other model's e-mail
I have 2 variables "email" and "umail". umail belongs to user-model and email belongs to other model. I want to validate umail, which content shouldn't be same as email. e.g. If umail: "abcd@xxx.com" and email: "abcd@xxx.com", then umail shouldn't be saved and an error message should be shown.

I tried to write devise validation "exclusion" like

```<code>validates :subdomain, exclusion: { in: User.current.email,
   message: "%{value} is not allowed to use }
end
</code>```

But no success, so I tried:

```<code>class Tecdb < ApplicationRecord
validates :umail, presence: true, if: :umail_not_allowed
def umail_not_allowed
  errors.add( umail: "is not allowed to use" ) if :umail == User.current.email
end
</code>```

But also no success (means, even umail and email are same, umail was saved without showing any error message).

Can someone let me know how is the best way to write for this kind of validation?

答:
Try this,</p>

```<code>validate :check_email_and_umail

def check_email_and_umail
  errors.add(:umail, "can't be the same as email") if umail ==  User.current.email
end
</code>```

Body:
I have 2 variables "email" and "umail". umail belongs to user-model and email belongs to other model. I want to validate umail, which content shouldn't be same as email. e.g. If umail: "abcd@xxx.com" and email: "abcd@xxx.com", then umail shouldn't be saved and an error message should be shown.

I tried to write devise validation "exclusion" like

validates :subdomain, exclusion: { in: User.current.email,
   message: "%{value} is not allowed to use }
end

But no success, so I tried:

class Tecdb < ApplicationRecord
validates :umail, presence: true, if: :umail_not_allowed
def umail_not_allowed
  errors.add( umail: "is not allowed to use" ) if :umail == User.current.email
end

But also no success (means, even umail and email are same, umail was saved without showing any error message).

Can someone let me know how is the best way to write for this kind of validation?

Body:
Try this,

validate :check_email_and_umail

def check_email_and_umail
  errors.add(:umail, "can't be the same as email") if umail ==  User.current.email
end


问:
`path must start with the project source root` error in ng serve
I want to use jquery and bootstrap in my Angular-CLI project. The Angular-CLI project is in project/ui directory and the jquery and bootstrap files are in project/public/... path. I am trying to refer to the jquery and bootstrap files as follows in angular.json but on running ng serve in project/ui directory, I am getting error - The ./../public/images/favicon.png asset path must start with the project source root. What am I doing wrong?

The snippet of angular.json is

```<code>"projects": {
    "ui": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets",
              "./../public/images/favicon.png"
            ],
            "styles": [
              "src/styles.css",
              "./../public/stylesheets/common/css-reset.css",
              "./../public/stylesheets/common/common-styles.css",
              "./../public/stylesheets/common/vendor/bootstrap/bootstrap.css"
            ],
            "scripts": [
              "./../public/javascripts/common/vendor/jquery/jquery-3.2.1.js",
              "./../public/javascripts/common/vendor/bootstrap/bootstrap.js"
            ]
          },
</code>```

答:
The ./../public/images/favicon.png asset path must start with the
  project source root

The error states that the path for the favicon.png must start with the project source root.
For a default angular project, this is the src folder.

As stated in the answer above, make sure your path is absolute and starts at src.

Body:
I want to use jquery and bootstrap in my Angular-CLI project. The Angular-CLI project is in project/ui directory and the jquery and bootstrap files are in project/public/... path. I am trying to refer to the jquery and bootstrap files as follows in angular.json but on running ng serve in project/ui directory, I am getting error - The ./../public/images/favicon.png asset path must start with the project source root. What am I doing wrong?

The snippet of angular.json is

"projects": {
    "ui": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets",
              "./../public/images/favicon.png"
            ],
            "styles": [
              "src/styles.css",
              "./../public/stylesheets/common/css-reset.css",
              "./../public/stylesheets/common/common-styles.css",
              "./../public/stylesheets/common/vendor/bootstrap/bootstrap.css"
            ],
            "scripts": [
              "./../public/javascripts/common/vendor/jquery/jquery-3.2.1.js",
              "./../public/javascripts/common/vendor/bootstrap/bootstrap.js"
            ]
          },


问:
UIButton state selected
I've seen a lot of info on changing the button image for selected but being a new I'm having a bit of trouble implementing a simpler version of it.

When the button is pressed it goes dark and I would like it to stay that way once it's been selected. So there are a few questions.

Do I create IBOutlet for the button and then and IBAction to change the state with something like button.state = SELECTED.

Sorry for the complete lack of any code to look at.

Edit: (id)sender is the button object right?

```<code>-(IBAction)journalEntryViewControllerClick: (id)sender
{
    UIButton *button = (id)sender;

    [button setSelected:YES];

}
</code>```

答:
You can set separate image for button's selected state (UIControlStateSelected) and in button action you can toggle its state:</p>

```<code>- (void) btnAction:(UIButton*)button{
    button.selected = !button.selected;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: UIButton state selected

Body:
I've seen a lot of info on changing the button image for selected but being a new I'm having a bit of trouble implementing a simpler version of it.

When the button is pressed it goes dark and I would like it to stay that way once it's been selected. So there are a few questions.

Do I create IBOutlet for the button and then and IBAction to change the state with something like button.state = SELECTED.

Sorry for the complete lack of any code to look at.

Edit: (id)sender is the button object right?

-(IBAction)journalEntryViewControllerClick: (id)sender
{
    UIButton *button = (id)sender;

    [button setSelected:YES];

}

Body:
You can set separate image for button's selected state (UIControlStateSelected) and in button action you can toggle its state:

- (void) btnAction:(UIButton*)button{
    button.selected = !button.selected;
}


问:
JS prevent flickered input border on focus
I'm trying to build a custom input number. The only problem I have is that when I click on the button multiple times (increment), I'm getting a flickered input border.

const input = document.querySelector('input');
document.querySelector('button').addEventListener('click', () => {
 input.focus();
 const value = input.value ? parseFloat(input.value) : 0;
 input.value = value + 1;
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
 margin: 50px;
}

* {
 box-sizing: border-box;
}

input:focus {
 border: 1px solid red;
 outline: none;
}</code>```

<input type="text">

<button>Increment</button>```

There is a way to getting around it?

答:
const input = document.querySelector('input');
document.querySelector('button').addEventListener('click', () => {
 input.focus();
 const value = input.value ? parseFloat(input.value) : 0;
 input.value = value + 1;
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
 margin: 50px;
}

* {
 box-sizing: border-box;
}

input {
  border: 1px solid red;
 outline: none;
}

input:focus {
 border: 1px solid red;
 outline: none;
}</code>```

<input type="text">

<button>Increment</button>```

Body:
I'm trying to build a custom input number. The only problem I have is that when I click on the button multiple times (increment), I'm getting a flickered input border.

const input = document.querySelector('input');
document.querySelector('button').addEventListener('click', () => {
 input.focus();
 const value = input.value ? parseFloat(input.value) : 0;
 input.value = value + 1;
})

body {
 margin: 50px;
}

* {
 box-sizing: border-box;
}

input:focus {
 border: 1px solid red;
 outline: none;
}

<input type="text">

<button>Increment</button>

There is a way to getting around it?

Body:
const input = document.querySelector('input');
document.querySelector('button').addEventListener('click', () => {
 input.focus();
 const value = input.value ? parseFloat(input.value) : 0;
 input.value = value + 1;
})

body {
 margin: 50px;
}

* {
 box-sizing: border-box;
}

input {
  border: 1px solid red;
 outline: none;
}

input:focus {
 border: 1px solid red;
 outline: none;
}

<input type="text">

<button>Increment</button>


问:
How does reduction operations in OpenMP work under the hood?
I am trying to optimize the performance in a parallel-for loop where I have a reduction variable (called delta) and I am wondering how this is handled under the hood by the OpenMP library.

Lets take as an example the following piece of code, where I simply declare the variable as a reduction one, at the beginning of the loop as follows:

```<code>#pragma omp parallel shared(delta, A, B, rows, colms) private(i, j)
.
.
.
    #pragma omp for reduction(+:delta)
            for (i=1; i<=rows; i++){
                for (j=1; j<=colms; j++){
                delta += fabs(A[i][j]- B[i][j]);
                }
    }
.
.
.
//end of parallel region
</code>```

I am wondering whether during the calculation each thread sets a lock when accessing the delta variable and furthermore whether I could increase the performance by replacing delta variable with an array delta[number_of_threads],  where each thread will write in a different position of the array during the calculation and then sum-up all the elements after the parallel region.

答:
Each thread will have its own copy of 'delta' on its stack frame:

```<code>#pragma omp parallel shared(delta, A, B, rows, colms) private(i, j)
{
    double local_delta; // one copy per thread

    __omp_init_schedule(1, rows, &lb, &ub);
    for (i=lb; i<=ub; i++) {
        for (j=1; j<=colms; j++) {
                local_delta += fabs(A[i][j]- B[i][j]);
        }
    }
   __omp_reduce(&delta, local_delta);  // accumulate thread's delta with shared var
   __omp_barrier();                    // do the barrier of the for construct
}
</code>```

Please take the above as pseudo-code.  The actual code pattern will depend on the implementation, inlining, and all sorts of other optimization an OpenMP implementation might do.  If you want to read a bit about how things work please have a look at [1] and [2].

The implementation of __omp_reduce() can either be something tree-based or sequential using either locks or atomic instructions.  OpenMP implementations are usually rather smart and choose the right algorithm for the machine and/or the number of threads being used.

Doing the delta[numthreads] modification will likely reduce performance by more than 100x, as this is the typical example for false-sharing as delta[0] for thread 0 and delta[1] for thread one will be in the same cache line and this cause a lot of traffic on the cache and the memory.  A better appraoch would be to introduce patting delta[numthreads * 8] (assuming that delta is 8 bytes), so that each thread gets its own cache line.  However, then you still need to perform the final aggregation and likely the OpenMP implementation still does a better job.

[1] https://www.dontknow.de/openmp-stuff/the-thing-from-another-world-or-how-do-openmp-compilers-work-part-1/

[2] https://www.dontknow.de/openmp-stuff/thunk-you-very-much-or-how-do-openmp-compilers-work-part-2/

Body:
I am trying to optimize the performance in a parallel-for loop where I have a reduction variable (called delta) and I am wondering how this is handled under the hood by the OpenMP library.

Lets take as an example the following piece of code, where I simply declare the variable as a reduction one, at the beginning of the loop as follows:

#pragma omp parallel shared(delta, A, B, rows, colms) private(i, j)
.
.
.
    #pragma omp for reduction(+:delta)
            for (i=1; i<=rows; i++){
                for (j=1; j<=colms; j++){
                delta += fabs(A[i][j]- B[i][j]);
                }
    }
.
.
.
//end of parallel region

I am wondering whether during the calculation each thread sets a lock when accessing the delta variable and furthermore whether I could increase the performance by replacing delta variable with an array delta[number_of_threads],  where each thread will write in a different position of the array during the calculation and then sum-up all the elements after the parallel region.

Body:
Each thread will have its own copy of 'delta' on its stack frame:

#pragma omp parallel shared(delta, A, B, rows, colms) private(i, j)
{
    double local_delta; // one copy per thread

    __omp_init_schedule(1, rows, &lb, &ub);
    for (i=lb; i<=ub; i++) {
        for (j=1; j<=colms; j++) {
                local_delta += fabs(A[i][j]- B[i][j]);
        }
    }
   __omp_reduce(&delta, local_delta);  // accumulate thread's delta with shared var
   __omp_barrier();                    // do the barrier of the for construct
}

Please take the above as pseudo-code.  The actual code pattern will depend on the implementation, inlining, and all sorts of other optimization an OpenMP implementation might do.  If you want to read a bit about how things work please have a look at [1] and [2].

The implementation of __omp_reduce() can either be something tree-based or sequential using either locks or atomic instructions.  OpenMP implementations are usually rather smart and choose the right algorithm for the machine and/or the number of threads being used.

Doing the delta[numthreads] modification will likely reduce performance by more than 100x, as this is the typical example for false-sharing as delta[0] for thread 0 and delta[1] for thread one will be in the same cache line and this cause a lot of traffic on the cache and the memory.  A better appraoch would be to introduce patting delta[numthreads * 8] (assuming that delta is 8 bytes), so that each thread gets its own cache line.  However, then you still need to perform the final aggregation and likely the OpenMP implementation still does a better job.

[1] https://www.dontknow.de/openmp-stuff/the-thing-from-another-world-or-how-do-openmp-compilers-work-part-1/

[2] https://www.dontknow.de/openmp-stuff/thunk-you-very-much-or-how-do-openmp-compilers-work-part-2/


问:
Understanding output from statsmodels grangercausalitytests
I'm new to Granger Causality and would appreciate any advice on understanding/interpreting the results of the python statsmodels output. I've constructed two data sets (sine functions shifted in time with noise added)

and put them in a "data" matrix with signal 1 as the first column and signal 2 as the second. I then ran the tests using:

```<code>granger_test_result = sm.tsa.stattools.grangercausalitytests(data, maxlag=40, verbose=True)`
</code>```

The results showed that the optimal lag (in terms of the highest F test value) were for a lag of 1.

```<code>Granger Causality
('number of lags (no zero)', 1)
ssr based F test:         F=96.6366 , p=0.0000  , df_denom=995, df_num=1
ssr based chi2 test:   chi2=96.9280 , p=0.0000  , df=1
likelihood ratio test: chi2=92.5052 , p=0.0000  , df=1
parameter F test:         F=96.6366 , p=0.0000  , df_denom=995, df_num=1
</code>```

However, the lag that seems to best describe the optimal overlap of the data is around 25 (in the figure below, signal 1 has been shifted to the right by 25 points):

```<code>Granger Causality
('number of lags (no zero)', 25)
ssr based F test:         F=4.1891  , p=0.0000  , df_denom=923, df_num=25
ssr based chi2 test:   chi2=110.5149, p=0.0000  , df=25
likelihood ratio test: chi2=104.6823, p=0.0000  , df=25
parameter F test:         F=4.1891  , p=0.0000  , df_denom=923, df_num=25
</code>```

I'm clearly misinterpreting something here. Why wouldn't the predicted lag match up with the shift in the data?

Also, can anyone explain to me why the p-values are so small as to be negligible for most lag values? They only begin to show up as non-zero for lags greater than 30.

Thanks for any help you can give.

答:
From the notes of the statsmodels.tsa.stattools.grangercausalitytests function

The Null hypothesis for grangercausalitytests is that the time series in the second column, x2, does NOT Granger cause the time series in the first column, x1. Grange causality means that past values of x2 have a statistically significant effect on the current value of x1, taking past values of x1 into account as regressors. We reject the null hypothesis that x2 does not Granger cause x1 if the pvalues are below a desired size of the test.

The null hypothesis for all four test is that the coefficients corresponding to past values of the second time series are zero.

the test is working exactly as expected.

Let's fix a significance level for your test, say alpha = 5% or 1%. It is important to choose it before performing the test. Then you run your Granger (non-)causality test, whose null hypothesis  is that the second time series doesn't cause the first one, in the sense of Granger, for a fixed lag. As you found, the pvalue for lag = 1 is higher than the threshold alpha that you fixed, meaning that you can reject the null hypothesis (i.e. no causation). For lag > 25 the pvalues drop to zero, meaning that you should reject the null hypothesis, that is non-causation.

This is indeed in agreement with what you provided as time series by construction.

Body:
I'm new to Granger Causality and would appreciate any advice on understanding/interpreting the results of the python statsmodels output. I've constructed two data sets (sine functions shifted in time with noise added)

and put them in a "data" matrix with signal 1 as the first column and signal 2 as the second. I then ran the tests using:

granger_test_result = sm.tsa.stattools.grangercausalitytests(data, maxlag=40, verbose=True)`

The results showed that the optimal lag (in terms of the highest F test value) were for a lag of 1.

Granger Causality
('number of lags (no zero)', 1)
ssr based F test:         F=96.6366 , p=0.0000  , df_denom=995, df_num=1
ssr based chi2 test:   chi2=96.9280 , p=0.0000  , df=1
likelihood ratio test: chi2=92.5052 , p=0.0000  , df=1
parameter F test:         F=96.6366 , p=0.0000  , df_denom=995, df_num=1

However, the lag that seems to best describe the optimal overlap of the data is around 25 (in the figure below, signal 1 has been shifted to the right by 25 points):

Granger Causality
('number of lags (no zero)', 25)
ssr based F test:         F=4.1891  , p=0.0000  , df_denom=923, df_num=25
ssr based chi2 test:   chi2=110.5149, p=0.0000  , df=25
likelihood ratio test: chi2=104.6823, p=0.0000  , df=25
parameter F test:         F=4.1891  , p=0.0000  , df_denom=923, df_num=25

I'm clearly misinterpreting something here. Why wouldn't the predicted lag match up with the shift in the data?

Also, can anyone explain to me why the p-values are so small as to be negligible for most lag values? They only begin to show up as non-zero for lags greater than 30.

Thanks for any help you can give.


问:
WKWebView loadFileURL works only once
I need to load a local file in a WKWebView. I'm using the new ios9 method

- (nullable WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL

It works perfectly for the first load (navigation delegation is properly called), but if I try to load a new and different file, it does nothing.

The URL for the currentItem in the wkwebview instance is modified. But if I force a reload the delegate method didFinishNavigation is called with the previous set URL. I also tried to navigate forward but the file that was supposed to be loaded is the current one, it's not on the backForwardList.

The code I'm using to start the WKWebView and load the file:

```<code>self.wk_webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
self.wk_webview.scrollView.delegate = self;
self.wk_webview.navigationDelegate = self;
[self.view addSubview:self.wk_webview];

NSURL *url = [NSURL fileURLWithPath:local_path];
[self.wk_webview loadFileURL:url allowingReadAccessToURL:[url URLByDeletingLastPathComponent]];
</code>```

Am I missing something? I couldn't find anything related to this.

Any help is appreciated, thanks.

答:
I also encountered this problem.  What worked for me is to simply to refresh the UIView container holding the webView:

```<code>[webView loadFileURL:url allowingReadAccessToURL:[url URLByDeletingLastPathComponent]];
[webViewContainer setNeedsDisplay];
[webViewContainer setNeedsLayout];
</code>```

Hope this helps.

Title: WKWebView loadFileURL works only once

Body:
I need to load a local file in a WKWebView. I'm using the new ios9 method

- (nullable WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL

It works perfectly for the first load (navigation delegation is properly called), but if I try to load a new and different file, it does nothing.

The URL for the currentItem in the wkwebview instance is modified. But if I force a reload the delegate method didFinishNavigation is called with the previous set URL. I also tried to navigate forward but the file that was supposed to be loaded is the current one, it's not on the backForwardList.

The code I'm using to start the WKWebView and load the file:

self.wk_webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
self.wk_webview.scrollView.delegate = self;
self.wk_webview.navigationDelegate = self;
[self.view addSubview:self.wk_webview];

NSURL *url = [NSURL fileURLWithPath:local_path];
[self.wk_webview loadFileURL:url allowingReadAccessToURL:[url URLByDeletingLastPathComponent]];

Am I missing something? I couldn't find anything related to this.

Any help is appreciated, thanks.

Body:
I also encountered this problem.  What worked for me is to simply to refresh the UIView container holding the webView:

[webView loadFileURL:url allowingReadAccessToURL:[url URLByDeletingLastPathComponent]];
[webViewContainer setNeedsDisplay];
[webViewContainer setNeedsLayout];

Hope this helps.


问:
Xdebug ignores breakpoints in Netbeans for Php project created inside Docker container
When I debug project which is not created inside Docker container, then there is no problem with Xdebug.

But when I debug project created inside Docker container, then Xdebug does not stop on breakpoints - although it is running and it stops on xdebug_break().

My Docker host is Ubuntu 14.04. It is installed as VirtualBox. It uses PHP 5.5.9-1ubuntu4.16 with Xdebug v2.2.3. I have a mounted volume (between Docker host and Docker container) where projects created inside Docker container are stored.

My Docker container inside Ubuntu 14.0.4 is based on CentOS release 6.7 (Final). It uses PHP 5.3.29 with Xdebug v2.1.4 and it has Xdebug configured as follows (inside /etc/php.d/xdebug.ini):

```<code>zend_extension=/usr/lib64/php/modules/xdebug.so
;xdebug.remote_autostart = 0
xdebug.remote_autostart = 1
xdebug.remote_connect_back = 1
xdebug.remote_enable = 1
;xdebug.remote_host = 127.0.0.1
;xdebug.remote_host = localhost
;xdebug.remote_host = 172.17.42.1
;xdebug.remote_host = 10.0.2.15
;xdebug.remote_host = 10.0.2.2
;xdebug.remote_port = 9001
xdebug.remote_port = 9000
xdebug.remote_handler = dbgp
xdebug.profiler_enable_trigger = 1
xdebug.profiler_output_dir = /home/devteam/xdebug/profiler
xdebug.remote_log=/home/devteam/xdebug/xdebug.log
xdebug.profiler_output_name = cachegrind.out.%c
xdebug.show_exception_trace = 1
xdebug.idekey = netbeans-xdebug
</code>```

I have checked through all, currently displayed as commented out, values for xdebug.remote_port setting. I have tried different ports (9001, 9002) for xdebug.remote_port setting (of course with the same port set inside Netbeans). I also tried changing xdebug.remote_connect_back and xdebug.remote_autostart settings. I have noticed that with these two ones set to zero, xdebug was actually hanging and waiting for connection.

But still I am not able to make Xdebug stopping on breakpoints while debugging projects previously deployed inside Docker container.

I am not sure if I miss anything regarding Netbeans settings or Xdebug settings. I spent many hours trying to find the solution. I was trying to find some relevant information inside xdebug.log - but it does not seem to contain anything significant to me:

```<code>...
<- breakpoint_set -i 1567 -t line -s enabled -f file:///var/www/html/test/index.php -n 3
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="breakpoint_set" transaction_id="1567" state="enabled" id="11710015"></response>

<- breakpoint_set -i 1568 -t line -s enabled -f file:///home/pkowalski/clients/deployments/demon-prep/application/bootstrap_http.php -n 7
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="breakpoint_set" transaction_id="1568" state="enabled" id="11710016"></response>

<- run -i 1569
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="run" transaction_id="1569" status="stopping" reason="ok"></response>

Log closed at 2016-05-20 23:38:11

Log opened at 2016-05-20 23:40:23
-> <init xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" fileuri="file:///mnt/deployments/demon-prep/application/bootstrap_http.php" language="PHP" protocol_version="1.0" appid="1172" idekey="netbeans-xdebug"><engine version="2.1.4"><![CDATA[Xdebug]]></engine><author><![CDATA[Derick Rethans]]></author><url><![CDATA[http://xdebug.org]]></url><copyright><![CDATA[Copyright (c) 2002-2012 by Derick Rethans]]></copyright></init>

<- feature_set -i 1570 -n show_hidden -v 1
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="1570" feature="show_hidden" success="1"></response>
...
</code>```

It seems like it successfully manages to set breakpoints, but I am not sure if the filepath is correct inside xdebug.log. Maybe I need to use manual path mapping inside Netbeans, but I am not sure how to do it and what path should be a server path.

Right now if I start debugging, the page loads. But some time before, there was an error inside the browser saying that connection was reset.
Apart from that, a couple of times an error popup was showing up. Some time a popup was saying that there was a communication problem between Netbeans and Xdebug. Other time different message was displayed - that there was a socket connection error. I am not sure why now I do not see these popups.

Any idea what could be the solution for Xdebug ignoring breakpoints in Netbeans for projects created inside Docker container?

答:
My friend, my machine went through a similar problem. My machine already had a conventional installation, and the docker modules were installed. So what I did was unseal the php-xdebug package, it solved for me.

command: sudo apt purge php-xdebug

Body:
When I debug project which is not created inside Docker container, then there is no problem with Xdebug.

But when I debug project created inside Docker container, then Xdebug does not stop on breakpoints - although it is running and it stops on xdebug_break().

My Docker host is Ubuntu 14.04. It is installed as VirtualBox. It uses PHP 5.5.9-1ubuntu4.16 with Xdebug v2.2.3. I have a mounted volume (between Docker host and Docker container) where projects created inside Docker container are stored.

My Docker container inside Ubuntu 14.0.4 is based on CentOS release 6.7 (Final). It uses PHP 5.3.29 with Xdebug v2.1.4 and it has Xdebug configured as follows (inside /etc/php.d/xdebug.ini):

zend_extension=/usr/lib64/php/modules/xdebug.so
;xdebug.remote_autostart = 0
xdebug.remote_autostart = 1
xdebug.remote_connect_back = 1
xdebug.remote_enable = 1
;xdebug.remote_host = 127.0.0.1
;xdebug.remote_host = localhost
;xdebug.remote_host = 172.17.42.1
;xdebug.remote_host = 10.0.2.15
;xdebug.remote_host = 10.0.2.2
;xdebug.remote_port = 9001
xdebug.remote_port = 9000
xdebug.remote_handler = dbgp
xdebug.profiler_enable_trigger = 1
xdebug.profiler_output_dir = /home/devteam/xdebug/profiler
xdebug.remote_log=/home/devteam/xdebug/xdebug.log
xdebug.profiler_output_name = cachegrind.out.%c
xdebug.show_exception_trace = 1
xdebug.idekey = netbeans-xdebug

I have checked through all, currently displayed as commented out, values for xdebug.remote_port setting. I have tried different ports (9001, 9002) for xdebug.remote_port setting (of course with the same port set inside Netbeans). I also tried changing xdebug.remote_connect_back and xdebug.remote_autostart settings. I have noticed that with these two ones set to zero, xdebug was actually hanging and waiting for connection.

But still I am not able to make Xdebug stopping on breakpoints while debugging projects previously deployed inside Docker container.

I am not sure if I miss anything regarding Netbeans settings or Xdebug settings. I spent many hours trying to find the solution. I was trying to find some relevant information inside xdebug.log - but it does not seem to contain anything significant to me:

...
<- breakpoint_set -i 1567 -t line -s enabled -f file:///var/www/html/test/index.php -n 3
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="breakpoint_set" transaction_id="1567" state="enabled" id="11710015"></response>

<- breakpoint_set -i 1568 -t line -s enabled -f file:///home/pkowalski/clients/deployments/demon-prep/application/bootstrap_http.php -n 7
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="breakpoint_set" transaction_id="1568" state="enabled" id="11710016"></response>

<- run -i 1569
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="run" transaction_id="1569" status="stopping" reason="ok"></response>

Log closed at 2016-05-20 23:38:11

Log opened at 2016-05-20 23:40:23
-> <init xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" fileuri="file:///mnt/deployments/demon-prep/application/bootstrap_http.php" language="PHP" protocol_version="1.0" appid="1172" idekey="netbeans-xdebug"><engine version="2.1.4"><![CDATA[Xdebug]]></engine><author><![CDATA[Derick Rethans]]></author><url><![CDATA[http://xdebug.org]]></url><copyright><![CDATA[Copyright (c) 2002-2012 by Derick Rethans]]></copyright></init>

<- feature_set -i 1570 -n show_hidden -v 1
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="1570" feature="show_hidden" success="1"></response>
...

It seems like it successfully manages to set breakpoints, but I am not sure if the filepath is correct inside xdebug.log. Maybe I need to use manual path mapping inside Netbeans, but I am not sure how to do it and what path should be a server path.

Right now if I start debugging, the page loads. But some time before, there was an error inside the browser saying that connection was reset.
Apart from that, a couple of times an error popup was showing up. Some time a popup was saying that there was a communication problem between Netbeans and Xdebug. Other time different message was displayed - that there was a socket connection error. I am not sure why now I do not see these popups.

Any idea what could be the solution for Xdebug ignoring breakpoints in Netbeans for projects created inside Docker container?


问:
select all method for checkboxes , should not select disabled checbox in vue.js
i have a list with checkboxes in the table , when i click select all function , it selects all checkbox including disabled ones, i neeed to exclude the disabled checkbox . </p>

```<code>      <li><a @click.prevent="selectAll" id="cardSelectAllAId">
        SelectAll</a></li>

      <single-checkbox class="checkbox "
                 inputId="card.data.id"
                     v-if="card.data.id"
             @change="change(card.data)"
             :value="card.data.selected"
        :disabled="!card.data.licenseEnabled">

      selectAll() {
       for (let i = 0; i < this.cards.length; i += 1) {
        if (this.cards[i].selected !== undefined) {
         this.cards[i].selected = true;
        }
      },
</code>```

答:
You can try something like this in your function- </p>

```<code>  // Reset all selected first
  this.cards.map((x) => x.selected = false);
  // Filter and then set selected to true
  this.cards
    .filter((x) => x.data.licenseEnabled)
    .map((x) => x.selected = true);
</code>```

Body:
i have a list with checkboxes in the table , when i click select all function , it selects all checkbox including disabled ones, i neeed to exclude the disabled checkbox .

        SelectAll

      <single-checkbox class="checkbox "
                 inputId="card.data.id"
                     v-if="card.data.id"
             @change="change(card.data)"
             :value="card.data.selected"
        :disabled="!card.data.licenseEnabled">

      selectAll() {
       for (let i = 0; i < this.cards.length; i += 1) {
        if (this.cards[i].selected !== undefined) {
         this.cards[i].selected = true;
        }
      },

Body:
You can try something like this in your function-

  // Reset all selected first
  this.cards.map((x) => x.selected = false);
  // Filter and then set selected to true
  this.cards
    .filter((x) => x.data.licenseEnabled)
    .map((x) => x.selected = true);


问:
request.remote_ip returns wrong ip
I have logging on my website, and i see logs for different people (with different UserAgent strings).

I'm sure, that they have different ip, but all the log records having the same ip.

I use request.remote_ip to store it in DB.

I don't have Apache as front-end. I just have Mongrel.

The question is - Why they are the same ?

答: If both users are behind the same proxy server or use the same internet provider, they may appear to have the same IP address. The IP that is seen at the web server is not the IP address of the individual PC, it's the address of the connection being used.</p>

Title: request.remote_ip returns wrong ip


问:
How do I add a Google Font to a VueJS Component?
I've been trying for an hour to find a way to import a Google Font into a VueJS Component, but I cannot seem to find a solution, nothing worked yet, not even the stuff from previous StackOverflow questions. All the answers I've found are 1.5 to 2 years old now. I would appreciate it greatly if someone could suggest an up to date solution.

I am using VueJS2 + Webpack + Vue-cli

答:
I am currently doing it like the following:

Install the typeface of the font via npm (eg: npm install --save typeface-source-sans-pro)

Import the typeface in the component (import 'typeface-titillium-web';)

Use the font-face in the component (font-family: 'Titillium Web', sans-serif;)

Keep in mind that with this the font gets self-hosted. So you don't have the support of the cached fonts on a cdn any more.


问:
Aws Appsync Resolver : How to create a resolver to update item in list map (DynaMoDB)
I am creating multiple object in one table, I have here sample DynamoDB table named "User" with fields (firstname, lastname, email, companies), can someone know how can I create a resolver to add a new item in histories? Thanks.

```<code>{
  "id": "d7913a57-f458-4b81-8d6e-10f81e2b1dc2",
  "firstName": "John",
  "lastName": "Doe",
  "email": "johndoe@gmail.com",
  "companies" : [
      {
        "companyId": "6059be51-1e66-4f3a-9c8f-ced3bc89d562",
        "createdAt": 321321,
        "histories": [
          {
           "companyHistoryId": "dc9d1a57-fb82-4c25-a6cf-d27dfe114f8f",
           "content": "Company A was created.",
           "createdAt": 321321,
           "createdBy": "d7913a57-f458-4b81-8d6e-10f81e2b1dc2"
          }
        ],
     },
  ]
}
</code>```

This is the resolver I used to add new company

```<code>{
    "version" : "2017-02-28",
    "operation" : "UpdateItem",
    "key" : {
        "id": { "S": "${context.arguments.id}" },
    },
    "update" : {
        "expression" : "SET companies = list_append(if_not_exists(companies, :emptyList), :newCompany)",
        "expressionValues" : {
            ":emptyList": { "L" : [] },
            ":newCompany" : { "L" : [
                { "M": {
                    "name": { "S" : "${context.arguments.name}" },
                    "createdAt": { "N" : "${context.arguments.createdAt}" },
                    "companyId": { "S": "$util.autoId()" },
                    "isActive": { "BOOL" : true },
                    "histories": { "L": [
                        { "M": {
                            "companyHistoryId": { "S": "$util.autoId()" },
                            "content" : { "S" : "${context.arguments.name} was created." },
                            "createdAt": { "N" : "${context.arguments.createdAt}" },
                            "createdBy": { "S": "${context.arguments.id}" }
                        }}
                    ] }
                }}
            ] },
        }
    }
}
</code>```

答:
Try this:

```<code>{
  "version" : "2017-02-28",
  "operation" : "UpdateItem",
  "key" : {
      "id": { "S": "${context.arguments.id}" },
  },
  "update" : {
      "expression" : "SET companies[$ctx.args.index].histories = list_append(if_not_exists(companies[$ctx.args.index].histories, :emptyList), :history)",
      "expressionValues" : {
          ":emptyList": { "L" : [] },
          ":history" : { "L": [
              { "M": {
                  "companyHistoryId": { "S": "$util.autoId()" },
                  "content" : { "S" : "${context.arguments.name} was created." },
                  "createdAt": { "N" : "${context.arguments.createdAt}" },
                  "createdBy": { "S": "${context.arguments.id}" }
              }}
          ] }
      }
  }
}
</code>```

Remember to pass $ctx.args.index which is the index of companies item whose histories will be updated.

Body:
I am creating multiple object in one table, I have here sample DynamoDB table named "User" with fields (firstname, lastname, email, companies), can someone know how can I create a resolver to add a new item in histories? Thanks.

{
  "id": "d7913a57-f458-4b81-8d6e-10f81e2b1dc2",
  "firstName": "John",
  "lastName": "Doe",
  "email": "johndoe@gmail.com",
  "companies" : [
      {
        "companyId": "6059be51-1e66-4f3a-9c8f-ced3bc89d562",
        "createdAt": 321321,
        "histories": [
          {
           "companyHistoryId": "dc9d1a57-fb82-4c25-a6cf-d27dfe114f8f",
           "content": "Company A was created.",
           "createdAt": 321321,
           "createdBy": "d7913a57-f458-4b81-8d6e-10f81e2b1dc2"
          }
        ],
     },
  ]
}

This is the resolver I used to add new company

{
    "version" : "2017-02-28",
    "operation" : "UpdateItem",
    "key" : {
        "id": { "S": "${context.arguments.id}" },
    },
    "update" : {
        "expression" : "SET companies = list_append(if_not_exists(companies, :emptyList), :newCompany)",
        "expressionValues" : {
            ":emptyList": { "L" : [] },
            ":newCompany" : { "L" : [
                { "M": {
                    "name": { "S" : "${context.arguments.name}" },
                    "createdAt": { "N" : "${context.arguments.createdAt}" },
                    "companyId": { "S": "$util.autoId()" },
                    "isActive": { "BOOL" : true },
                    "histories": { "L": [
                        { "M": {
                            "companyHistoryId": { "S": "$util.autoId()" },
                            "content" : { "S" : "${context.arguments.name} was created." },
                            "createdAt": { "N" : "${context.arguments.createdAt}" },
                            "createdBy": { "S": "${context.arguments.id}" }
                        }}
                    ] }
                }}
            ] },
        }
    }
}

Body:
Try this:

{
  "version" : "2017-02-28",
  "operation" : "UpdateItem",
  "key" : {
      "id": { "S": "${context.arguments.id}" },
  },
  "update" : {
      "expression" : "SET companies[$ctx.args.index].histories = list_append(if_not_exists(companies[$ctx.args.index].histories, :emptyList), :history)",
      "expressionValues" : {
          ":emptyList": { "L" : [] },
          ":history" : { "L": [
              { "M": {
                  "companyHistoryId": { "S": "$util.autoId()" },
                  "content" : { "S" : "${context.arguments.name} was created." },
                  "createdAt": { "N" : "${context.arguments.createdAt}" },
                  "createdBy": { "S": "${context.arguments.id}" }
              }}
          ] }
      }
  }
}

Remember to pass $ctx.args.index which is the index of companies item whose histories will be updated.


问:
React Fabric UI remove the Pivot Item
I am using Pivot component in Office Fabric UI, I need to remove PivotItem for some views. Is there any possible way?

etc. I need to remove 'Insert' Pivot with using isComposeMode() in below

```<code>import * as React from "react";
import { Label } from "office-ui-fabric-react/lib/Label";
import { Pivot, PivotItem } from "office-ui-fabric-react/lib/Pivot";
import InsertView from "./InsertView";

export interface PivotProps {}

export interface PivotState {}

class MainNav extends React.Component<PivotProps, PivotState> {
  render() {
    return (
      <div>
        <Pivot>
          <PivotItem headerText="Insert">
            <InsertView />
          </PivotItem>
          <PivotItem headerText="Review">
            <Label>Review</Label>
          </PivotItem>
          <PivotItem headerText="Settings">
            <Label>Settings</Label>
          </PivotItem>
        </Pivot>
      </div>
    );
  }

  isComposeMode = (): boolean => {
    if (Office.context.mailbox.item.displayReplyForm != undefined) {
      return false;
    } else {
      return true;
    }
  };
}

export default MainNav;
</code>```

答:
You can push the required items to an array based on your condition. Hope this can help you.</p>

```<code>render(){
  let pivotItems=[
    <PivotItem headerText="Insert">
            <InsertView />
    </PivotItem>,
    <PivotItem headerText="Review">
            <Label>Review</Label>
    </PivotItem>,
];

if(addLastPivot){
   pivotItems.push(
      <PivotItem headerText="Settings">
            <Label>Settings</Label>
      </PivotItem>
   );
}

return (
      <div>
        <Pivot>
          {pivotItems}
        </Pivot>
      </div>
    );
  }
</code>```

Title: React Fabric UI remove the Pivot Item

Body:
I am using Pivot component in Office Fabric UI, I need to remove PivotItem for some views. Is there any possible way?

etc. I need to remove 'Insert' Pivot with using isComposeMode() in below

import * as React from "react";
import { Label } from "office-ui-fabric-react/lib/Label";
import { Pivot, PivotItem } from "office-ui-fabric-react/lib/Pivot";
import InsertView from "./InsertView";

export interface PivotProps {}

export interface PivotState {}

class MainNav extends React.Component<PivotProps, PivotState> {
  render() {
    return (

        <Pivot>
          <PivotItem headerText="Insert">
            <InsertView />
          </PivotItem>
          <PivotItem headerText="Review">
            Review
          </PivotItem>
          <PivotItem headerText="Settings">
            Settings
          </PivotItem>
        </Pivot>

    );
  }

  isComposeMode = (): boolean => {
    if (Office.context.mailbox.item.displayReplyForm != undefined) {
      return false;
    } else {
      return true;
    }
  };
}

export default MainNav;

Body:
You can push the required items to an array based on your condition. Hope this can help you.

render(){
  let pivotItems=[
    <PivotItem headerText="Insert">
            <InsertView />
    </PivotItem>,
    <PivotItem headerText="Review">
            <Label>Review</Label>
    </PivotItem>,
];

if(addLastPivot){
   pivotItems.push(
      <PivotItem headerText="Settings">
            <Label>Settings</Label>
      </PivotItem>
   );
}

return (
      <div>
        <Pivot>
          {pivotItems}
        </Pivot>
      </div>
    );
  }


问:
How to break out of an IF statement
I have code like this:

```<code>public void Method()
{
    if(something)
    {
        // Some code
        if(something2)
        {
            // Now I should break from ifs and go to the code outside ifs
        }
        return;
    }
    // The code I want to go if the second if is true
}
</code>```

Is there a possibility to go to that code after ifs without using any go to statement or extracting rest of the code to the other method?

Yes, I know Else ;)

But this code is farly long and should be run IF the first IF is false and when the first IF is true and the second is false.
So extracting a method I think is the best idea.

答:
You can also use a lambda

```<code>if (new Func<bool>(() =>
{
    if (something1)
    {
        // Some code that calculates "something2"
        if (something2)
        {
            // Now I should break from ifs and go to the code outside ifs
            return true;
        }
    }
    return false;
})())
{
    // The code I want to go if the second if is true
}
</code>```

P.S. I think I know why people would want this. "Run stuff if all conditions are true, otherwise run other stuff". And the conditions are too complicated to put into one if or they depend one on another.

Title: How to break out of an IF statement

Body:
I have code like this:

public void Method()
{
    if(something)
    {
        // Some code
        if(something2)
        {
            // Now I should break from ifs and go to the code outside ifs
        }
        return;
    }
    // The code I want to go if the second if is true
}

Is there a possibility to go to that code after ifs without using any go to statement or extracting rest of the code to the other method?

Yes, I know Else ;)

But this code is farly long and should be run IF the first IF is false and when the first IF is true and the second is false.
So extracting a method I think is the best idea.

Body:
You can also use a lambda

if (new Func<bool>(() =>
{
    if (something1)
    {
        // Some code that calculates "something2"
        if (something2)
        {
            // Now I should break from ifs and go to the code outside ifs
            return true;
        }
    }
    return false;
})())
{
    // The code I want to go if the second if is true
}

P.S. I think I know why people would want this. "Run stuff if all conditions are true, otherwise run other stuff". And the conditions are too complicated to put into one if or they depend one on another.


问:
Using fit_generator with multiple inputs gives error at output dense layer
In my case I am using a set of sequential features and also non sequential features to train the model. Following is the architecture of my model

```<code>Sequential features -> LSTM -> Dense(1) --->>
                                             \
                                              \
                                               -- Dense -> Dense -> Dense(1) ->output
                                              /
                   Non-sequential features---/
</code>```

I am using data generator to generate batches for sequential data. Here the batch size is varying for each batch. For one batch I am keeping the non-sequential feature fixed. Following is my data generator.

```<code>def training_data_generator(raw_data):
    while True:
        for index, row in raw_data.iterrows():
            x_train, y_train = list(), list()
            feature1 = row['xxx']
            x_current_batch = []
            y_current_batch = []
            for j in range(yyy):
                x_current_batch.append(row['zz1'])
                y_current_batch.append(row['zz2'])
            x_train.append(x_current_batch)
            y_train.append(y_current_batch)
            x_train = array(x_train)
            y_train = array(y_train)

            yield [x_train, np.reshape(feature1,1)], y_train
</code>```

Note: x_train y_train sizes are varying.

Following is my model implementation.

```<code>seq_input = Input(shape=(None, 3))
lstm_layer = LSTM(50)(seq_input)
dense_layer1 = Dense(1)(lstm_layer)

non_seq_input = Input(shape=(1,))

hybrid_model = concatenate([dense_layer1, non_seq_input])

hidden1 = Dense(10, activation = 'relu')(hybrid_model)
hidden2 = Dense(10, activation='relu')(hidden1)

final_output = Dense(1, activation='sigmoid')(hidden2)

model = Model(inputs = [seq_input, non_seq_input], outputs = final_output)

model.compile(loss='mse',optimizer='adam')

model.fit_generator(training_data_generator(flatten), steps_per_epoch= 5017,
                              epochs = const.NUMBER_OF_EPOCHS, verbose=1)
</code>```

I am getting error at the output dense layer

```<code>ValueError: Error when checking target:
expected dense_4 to have shape (1,) but got array with shape (4,)
</code>```

I think the last layer is getting whole output of the generator but not as one by one.

What is the reason for this issue. Appreciate your insights on this issue.

答:
The output gives a Dense layer with a size of 4. Since you've declared your output as a Dense layer with a size of 1, it crashes.

What you can do is change your output dense Layer to 4. And then manually convert this to one value.

Hopefully this answers your question.

Body:
In my case I am using a set of sequential features and also non sequential features to train the model. Following is the architecture of my model

Sequential features -> LSTM -> Dense(1) --->>
                                             \
                                              \
                                               -- Dense -> Dense -> Dense(1) ->output
                                              /
                   Non-sequential features---/

I am using data generator to generate batches for sequential data. Here the batch size is varying for each batch. For one batch I am keeping the non-sequential feature fixed. Following is my data generator.

def training_data_generator(raw_data):
    while True:
        for index, row in raw_data.iterrows():
            x_train, y_train = list(), list()
            feature1 = row['xxx']
            x_current_batch = []
            y_current_batch = []
            for j in range(yyy):
                x_current_batch.append(row['zz1'])
                y_current_batch.append(row['zz2'])
            x_train.append(x_current_batch)
            y_train.append(y_current_batch)
            x_train = array(x_train)
            y_train = array(y_train)

            yield [x_train, np.reshape(feature1,1)], y_train

Note: x_train y_train sizes are varying.

Following is my model implementation.

seq_input = Input(shape=(None, 3))
lstm_layer = LSTM(50)(seq_input)
dense_layer1 = Dense(1)(lstm_layer)

non_seq_input = Input(shape=(1,))

hybrid_model = concatenate([dense_layer1, non_seq_input])

hidden1 = Dense(10, activation = 'relu')(hybrid_model)
hidden2 = Dense(10, activation='relu')(hidden1)

final_output = Dense(1, activation='sigmoid')(hidden2)

model = Model(inputs = [seq_input, non_seq_input], outputs = final_output)

model.compile(loss='mse',optimizer='adam')

model.fit_generator(training_data_generator(flatten), steps_per_epoch= 5017,
                              epochs = const.NUMBER_OF_EPOCHS, verbose=1)

I am getting error at the output dense layer

ValueError: Error when checking target:
expected dense_4 to have shape (1,) but got array with shape (4,)

I think the last layer is getting whole output of the generator but not as one by one.

What is the reason for this issue. Appreciate your insights on this issue.


问:
How to sort a regex match in PowerShell by a value of the groups array
I have an array of strings and each string includes a number which represents the sprint (scrum) number. Now, I want to sort the array by the sprint number using regular expressions in Powershell.

Example of the array

a.sprint-100

a.sprint-99

a.sprint-49

a.sprint-98

```<code># define the array
$a = @("a.sprint-100","a.sprint-99","a.sprint-49","a.sprint-98")

# escape hard defined string in regex
$escapedString = [regex]::escape(".sprint-")

# create regex which matches <AnyCharacter>.sprint-<SprintNumber>
[regex]$regex = "(.+)$escapedString([0-9]{2,3})"

# process the regex on all strings and print out the sprint number
$a | %{[System.Text.RegularExpressions.Regex]::Match($_, $regex)} | %{$_.Groups[2].value}

# output: 100 99 49 98

# but my sort logic doesn't work
 $a | %{[System.Text.RegularExpressions.Regex]::Match($_, $regex)} | Sort-Object -Property {$_.Groups[2].value} -Descending | %{$_.Groups[2].value}

# output: 99 98 49 100
</code>```

I am sorting on a string. So, this could be the main problem.
Have anyone an idea to parse the match value to an int?

If I try to do it, then I'm getting 'value' is a ReadOnly property.".
Or is there a better way to get to my desired sorting result?

For simplification, I used here a string array. But in the real scenario, it is an array including custom objects with a bunch of data. This array should be sorted after my regex pipe.

Thanks in advance!

答:
```<code>$a | %{
  [System.Text.RegularExpressions.Regex]::Match($_, $regex)} | %{
    [PSCustomObject]@{
      sprint=[convert]::ToInt32($_.Groups[2].value,10)
      name=$_.Groups[0].value
    }
  } | Sort-Object -Property {$_.sprint} | Select -ExpandProperty name

# Output a.sprint-49 a.sprint-98 a.sprint-99 a.sprint-100
</code>```

Maybe a little bit to complicated, but it works for string.

Body:
I have an array of strings and each string includes a number which represents the sprint (scrum) number. Now, I want to sort the array by the sprint number using regular expressions in Powershell.

Example of the array

a.sprint-100

a.sprint-99

a.sprint-49

a.sprint-98

# define the array
$a = @("a.sprint-100","a.sprint-99","a.sprint-49","a.sprint-98")

# escape hard defined string in regex
$escapedString = [regex]::escape(".sprint-")

# create regex which matches <AnyCharacter>.sprint-<SprintNumber>
[regex]$regex = "(.+)$escapedString([0-9]{2,3})"

# process the regex on all strings and print out the sprint number
$a | %{[System.Text.RegularExpressions.Regex]::Match($_, $regex)} | %{$_.Groups[2].value}

# output: 100 99 49 98

# but my sort logic doesn't work
 $a | %{[System.Text.RegularExpressions.Regex]::Match($_, $regex)} | Sort-Object -Property {$_.Groups[2].value} -Descending | %{$_.Groups[2].value}

# output: 99 98 49 100

I am sorting on a string. So, this could be the main problem.
Have anyone an idea to parse the match value to an int?

If I try to do it, then I'm getting 'value' is a ReadOnly property.".
Or is there a better way to get to my desired sorting result?

For simplification, I used here a string array. But in the real scenario, it is an array including custom objects with a bunch of data. This array should be sorted after my regex pipe.

Thanks in advance!

Body:
$a | %{
  [System.Text.RegularExpressions.Regex]::Match($_, $regex)} | %{
    [PSCustomObject]@{
      sprint=[convert]::ToInt32($_.Groups[2].value,10)
      name=$_.Groups[0].value
    }
  } | Sort-Object -Property {$_.sprint} | Select -ExpandProperty name

# Output a.sprint-49 a.sprint-98 a.sprint-99 a.sprint-100

Maybe a little bit to complicated, but it works for string.


问:
How to map json object to string while using <-map["xx"]
I need to transform a json object to string while mapping but the fromJSON is always nil.

I am providing a piece of code in which i think that I should not be getting nil in value. I supposed that I should get the json that is under "a.b"

   func mapping(map: Map) {
        b <- (map["a.b"], TransformOf<String, String>(fromJSON: { value in print("json \(value)"); return String(value) }, toJSON: { $0.map { String($0) } }))
    }
```

<p>the json from which I am trying to map looks something like this</p>

<pre class="lang-swift prettyprint-override"><code>{
"a" : {
       "b" : { ..... } <- this is the piece I need as string
      }
}
</code>```

答:
You might want to look at

Using JSON with custom types

which contains a working playground for converting JSON using Swift Codable

Body:
I need to transform a json object to string while mapping but the fromJSON is always nil.

I am providing a piece of code in which i think that I should not be getting nil in value. I supposed that I should get the json that is under "a.b"

   func mapping(map: Map) {
        b <- (map["a.b"], TransformOf<String, String>(fromJSON: { value in print("json \(value)"); return String(value) }, toJSON: { $0.map { String($0) } }))
    }

the json from which I am trying to map looks something like this

{
"a" : {
       "b" : { ..... } <- this is the piece I need as string
      }
}


答:
If you want the mean per vehicle, just group by vehicle:

```<code> df.groupby(['Vehicle ID','V_Class'])['V_Vel'].agg([np.mean, np.std])
</code>```

it should give (with your sample data):

```<code>                     mean       std
Vehicle ID V_Class
3033       2        28.99  0.834955
</code>```

Title: How to apply unique function and mean function after grouping the dataframe?

Body:
I am working on GPS trajectories.

I am trying to find the mean of velocity of vehicles that belong to three different classes.
Mean of each vehicle is needed.

"Vehicle ID","Frame ID","Total Frames","Global Time","Local X","Local Y","Global X","Global Y","V_Len","V_Width","V_Class","V_Vel","V_Acc","Lane_ID","Pre_Veh","Fol_Veh","Spacing","Headway"
3033,9064,633,1118847885300,42.016,377.256,6451360.093,1873080.530,19.5,8.5,2,27.90,4.29,4,3022,0,93.16,3.34
3033,9065,633,1118847885400,42.060,380.052,6451362.114,1873078.608,19.5,8.5,2,28.43,6.63,4,3022,0,93.87,3.30
3033,9066,633,1118847885500,42.122,382.924,6451364.187,1873076.613,19.5,8.5,2,29.07,6.89,4,3022,0,94.49,3.25
3033,9067,633,1118847885600,42.200,385.882,6451366.307,1873074.553,19.5,8.5,2,29.62,4.41,4,3022,0,95.04,3.21
3033,9068,633,1118847885700,42.265,388.885,6451368.490,1873072.453,19.5,8.5,2,29.93,1.57,4,3022,0,95.57,3.19

df.sort_values(by=["Global Time"])
df["US Time"]=pd.to_datetime(df["Global Time"], unit='ms').dt.tz_localize('UTC' ).dt.tz_convert('America/Los_Angeles')

#Converting gps millisecond TS to US Local Time date format

#sorting

grouped=df.groupby('V_Class')

#find mean of all vehicles in each class
print( grouped['V_Vel'].agg([np.mean,np.std]))

for index, row in df.iterrows():
    print (row["Vehicle ID"], row["V_Class"])

Actual output

V_Class     mean        std
1        40.487673  14.647576
2        37.376317  14.940034
3        40.953483  11.214995

Expected output

Vehicle ID V_Class     mean        std
3033           2           32.4       12.4
125            1           41.3       9.2
.
likewise

Body:
If you want the mean per vehicle, just group by vehicle:

 df.groupby(['Vehicle ID','V_Class'])['V_Vel'].agg([np.mean, np.std])

it should give (with your sample data):

                     mean       std
Vehicle ID V_Class
3033       2        28.99  0.834955


问:
String is immutable?
Just have a problem with this, how do we rewrite the above code so that only a single String object is created?

String is immutable, isnt studentDetails already one single String object

```<code>public void displayString(Student[] students)
{
   String studentDetails = "";
   for (Student stu : students)
   {
       studentDetails += stu.getFirstName();
       studentDetails += " ";
       studentDetails += stu.getLastName();
       studentDetails += " ";
       studentDetails += stu.getAge();
       studentDetails += "\n";
   }
   System.out.println("Student Details are: ");
   System.out.println(studentDetails);
}
</code>```

答:
Use StringBuilder:

```<code>public void displayString(Student[] students)
{
   StringBuilder studentDetails = new StringBuilder();
   for (Student stu : students)
   {
       studentDetails.append(stu.getFirstName());
       studentDetails.append(' ');
       studentDetails.append(stu.getLastName());
       studentDetails.append(' ');
       studentDetails.append(stu.getAge());
       studentDetails.append('\n');
   }
   System.out.println("Student Details are: ");
   System.out.println(studentDetails.toString());
}
</code>```

String is immutable, isnt studentDetails already one single String object

No, since each time you append two Strings with +=, a new String is created.

Title: String is immutable?

Body:
Just have a problem with this, how do we rewrite the above code so that only a single String object is created?

String is immutable, isnt studentDetails already one single String object

public void displayString(Student[] students)
{
   String studentDetails = "";
   for (Student stu : students)
   {
       studentDetails += stu.getFirstName();
       studentDetails += " ";
       studentDetails += stu.getLastName();
       studentDetails += " ";
       studentDetails += stu.getAge();
       studentDetails += "\n";
   }
   System.out.println("Student Details are: ");
   System.out.println(studentDetails);
}

Body:
Use StringBuilder:

public void displayString(Student[] students)
{
   StringBuilder studentDetails = new StringBuilder();
   for (Student stu : students)
   {
       studentDetails.append(stu.getFirstName());
       studentDetails.append(' ');
       studentDetails.append(stu.getLastName());
       studentDetails.append(' ');
       studentDetails.append(stu.getAge());
       studentDetails.append('\n');
   }
   System.out.println("Student Details are: ");
   System.out.println(studentDetails.toString());
}

String is immutable, isnt studentDetails already one single String object

No, since each time you append two Strings with +=, a new String is created.


问:
How to give only 'n'(say 3) colors randomly to scatterplot points in python?
Generated random numbers x,y,z, then put them in scatter 3d plot but am unable to plot the points, randomly with 3 specific colors (say red,black,yellow).

In documentation of matplotlib.pyplot.scatter, I am unable to understand the other 3 ways of specifying colors except the 1st one.

Code:

```<code>import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D

x, y, z = np.random.rand(3,50)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x,y,z,marker='.',color='b')

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()
</code>```

答:
If you just want to randomly assign color to each point from set of n colors, you can do it like this:</p>

```<code>import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D

x, y, z = np.random.rand(3,50)
n=3
colors = np.random.randint(n, size=x.shape[0])

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x,y,z,marker='.',c=colors)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()
</code>```

Body:
Generated random numbers x,y,z, then put them in scatter 3d plot but am unable to plot the points, randomly with 3 specific colors (say red,black,yellow).

In documentation of matplotlib.pyplot.scatter, I am unable to understand the other 3 ways of specifying colors except the 1st one.

Code:

import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D

x, y, z = np.random.rand(3,50)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x,y,z,marker='.',color='b')

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

Body:
If you just want to randomly assign color to each point from set of n colors, you can do it like this:

import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D

x, y, z = np.random.rand(3,50)
n=3
colors = np.random.randint(n, size=x.shape[0])

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x,y,z,marker='.',c=colors)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()


答:
String object is immutable, while the variable studentDetails is not.

When you call  studentDetails += stu.getFirstName(), you created a new String object and assign it to variable studentDetails

Title: String is immutable?


问:
Plot one value per group instead of summing values up using ggplot's bar_plot()
I'm sure this is covered somewhere by a post, but I couldn't find it. The problem is that I want to plot a single variable's values for each group in my dataset.

This is my data:

```<code>my.data <- data.frame(
  a=c("aa","aa","bb","bb","cc","cc"),
  b=c(1,1,4,4,9,9)
)
</code>```

Using {ggplot2}, I tried this:

```<code>ggplot(my.data, aes(x=a, y=b)) + geom_bar(stat="identity")
</code>```

However, judging from the resulting plot, I only get the sum of the values per group instead of the value itself. So what this yields is 2 (for "aa"), 8 (for "bb") and 18 (for "cc").

I also tinkered around with group- and mean() commands, but it didn't work. Does anyone know a quick fix?

答:
Two options that come to my mind:

1) call unique on my.data

```<code>ggplot(unique(my.data), aes(x=a, y=b)) +
  geom_bar(stat="identity")
</code>```

2) use stat_summary which "operates on unique x"

```<code>ggplot(my.data, aes(x=a, y=b)) +
  stat_summary(geom = "bar", fun.y = 'identity')
</code>```

Result

Body:
I'm sure this is covered somewhere by a post, but I couldn't find it. The problem is that I want to plot a single variable's values for each group in my dataset.

This is my data:

my.data <- data.frame(
  a=c("aa","aa","bb","bb","cc","cc"),
  b=c(1,1,4,4,9,9)
)

Using {ggplot2}, I tried this:

ggplot(my.data, aes(x=a, y=b)) + geom_bar(stat="identity")

However, judging from the resulting plot, I only get the sum of the values per group instead of the value itself. So what this yields is 2 (for "aa"), 8 (for "bb") and 18 (for "cc").

I also tinkered around with group- and mean() commands, but it didn't work. Does anyone know a quick fix?

Body:
Two options that come to my mind:

1) call unique on my.data

ggplot(unique(my.data), aes(x=a, y=b)) +
  geom_bar(stat="identity")

2) use stat_summary which "operates on unique x"

ggplot(my.data, aes(x=a, y=b)) +
  stat_summary(geom = "bar", fun.y = 'identity')

Result


问:
how to fix passing variable from view to html
i have a problem passing variable 'res' from view to index.html, it's return the last result in the html page

view file:

def index(request):

    posts = Layout.objects.all()
    urlpost = SiteUrls.objects.all()[:20]

    field_value = SiteUrls.objects.values_list('site_url', flat=True)

    for site_url in field_value:
        print(site_url)
        res = os.system("ping -n 1 " + site_url )

        if res == 0:
            res = "connected"
        else:
            res = "not connected"

    context = {
        'posts':posts,
        'urlpost':urlpost,
        'res': res
    }

    return render (request, 'posts/index.html', context)
```

<p>html file:</p>

<pre class="lang-html prettyprint-override"><code>      <table>
        <tbody>
            {% for SiteUrls in urlpost %}
          <tr>
            <td>{{SiteUrls.site_title}}</td>
            <td>{{SiteUrls.site_url}}</td>

            <td> {{res}} </td>

            <td>open Site</td>
          </tr>
            {% endfor %}
        </tbody>
      </table>
</code>```

i would like to get back the specific result for each line

答:
Maybe you can pass it as a temporary attribute:

```<code>def index(request):

    posts = Layout.objects.all()
    urlpost = SiteUrls.objects.all()[:20]
    field_value = SiteUrls.objects.values_list('site_url', flat=True)

    for site_url in field_value:
        print(site_url)
        res = os.system("ping -n 1 " + site_url )

        if res == 0:
            site_url.res = "connected"
        else:
            site_url.res = "not connected"

        context = {
            'posts':posts,
            'urlpost':urlpost,
            }

    return render (request, 'posts/index.html', context)
</code>```

and you can access in your loop in the template like:

```<code>{{SiteUrls.res}}
</code>```

Body:
i have a problem passing variable 'res' from view to index.html, it's return the last result in the html page

view file:

def index(request):

    posts = Layout.objects.all()
    urlpost = SiteUrls.objects.all()[:20]

    field_value = SiteUrls.objects.values_list('site_url', flat=True)

    for site_url in field_value:
        print(site_url)
        res = os.system("ping -n 1 " + site_url )

        if res == 0:
            res = "connected"
        else:
            res = "not connected"

    context = {
        'posts':posts,
        'urlpost':urlpost,
        'res': res
    }

    return render (request, 'posts/index.html', context)

html file:

            {% for SiteUrls in urlpost %}

            {{SiteUrls.site_title}}
            {{SiteUrls.site_url}}

             {{res}}

            open Site

            {% endfor %}

i would like to get back the specific result for each line

Body:
Maybe you can pass it as a temporary attribute:

def index(request):

    posts = Layout.objects.all()
    urlpost = SiteUrls.objects.all()[:20]
    field_value = SiteUrls.objects.values_list('site_url', flat=True)

    for site_url in field_value:
        print(site_url)
        res = os.system("ping -n 1 " + site_url )

        if res == 0:
            site_url.res = "connected"
        else:
            site_url.res = "not connected"

        context = {
            'posts':posts,
            'urlpost':urlpost,
            }

    return render (request, 'posts/index.html', context)

and you can access in your loop in the template like:

{{SiteUrls.res}}


问:
How to use requiereJS to import local imput json file?
I want to load a json from local input file to my js script.

The json is imported and I can get the file object, but I can't properly get the JSON and parse it to a JS Object

I tried to use RequiereJS which seems to be the best and quickest solution but I can't make this line to work

```<code>require(['json!someFile.json'], function(data){

})
</code>```

Here is my input in HTML :

<input type="file" class="custom-file-input" onchange="loadFile(this.file) accept="application/json">
```

<p>And here my js file :</p>

```function loadFile(file) {
    var myJson;
    var url = URL.createObjectURL(file);
    require(['json!'+url+''], function(data){
        myJson = data;
    }
}
```

<p>Or this : </p>

```require(['json!'+file+''], function(data){
```

答:
You can use ajax function from jQuery

```<code>$.ajax({
    type: "Get",
    url: "data.json",
    dataType: "json",
    success: function(data) {

    },
    error: function(){
        alert("json not found");
    }
});
</code>```

Note: You need to have the file in server then only it will work.

Body:
I want to load a json from local input file to my js script.

The json is imported and I can get the file object, but I can't properly get the JSON and parse it to a JS Object

I tried to use RequiereJS which seems to be the best and quickest solution but I can't make this line to work

require(['json!someFile.json'], function(data){

})

Here is my input in HTML :

<input type="file" class="custom-file-input" onchange="loadFile(this.file) accept="application/json">

And here my js file :

function loadFile(file) {
    var myJson;
    var url = URL.createObjectURL(file);
    require(['json!'+url+''], function(data){
        myJson = data;
    }
}

Or this :

require(['json!'+file+''], function(data){

Body:
You can use ajax function from jQuery

$.ajax({
    type: "Get",
    url: "data.json",
    dataType: "json",
    success: function(data) {

    },
    error: function(){
        alert("json not found");
    }
});

Note: You need to have the file in server then only it will work.


问:
How to encourage non-anonymous editing on MediaWiki?

Problem

At work we have a department wiki (running Mediawiki). Unfortunately several
persons edit without logging in, and that makes it very difficult to track
down editors to ask questions about the content.

There are two strategies to improve this

encourage logged in editing

discourage anonymous editing.

Encouraging

For this part, any tips are welcome. But of course there is always risks involved
in rewarding behaviours.

Discourage

I know that this must be kept low or else it will discourage any editing.
But something just slightly annoying would be nice to have.

[update]
I know it is possible to just disallow anonymous editing, but that will put a high barrier to any first time contribution (especially for people outside our department!), so I do not think that is an option.
[/update]

[update2]
Using LDAP or Active Directory does not solve the problem since the wiki is also accessible and used by external contractors.
[/update2]

[update3]
I am no longer working for this company. That does not mean that I completely have lost interest in this question, but from my current interest point the most valuable part is the "Did you forget to log in?" part below, and I will accept answers based on this part of the question.
[/update3]

Confirmation

One thought was to have an additional confirmation step for anonymous users -
"Are you really sure you want to submit this anonymously?", although with
such a question there is a risk that people will give up or resist editing. However,
if that question is re-phrased in a more diplomatic way as "Did you forget
to log in?" I think it will appear as much more acceptable. And besides that
will also capture those situations where the author did in fact forget to
log in, but actually would want to have his/her contributions credited
his/her user. This last point is by itself a good enough reason for wanting it.

Is this possible?

Delay

Another thought for something to be slightly annoying is to add an extra
forced delay after "save page" displaying something like "If you had logged
in you would not have to wait x seconds". Selecting a right x is difficult
because if it is to high it will be a barrier and if it too low might not
make any difference. But then I started thinking, what about starting at
zero and then add one second delay for each anonymous edit by a given IP
address in a given time frame? That way there will be no barrier for
starting to use the wiki, and by the time the delay is getting significant
the user has already contributed a lot so I think the outcome is much
more likely to be that the editor eventually creates a user rather than
giving up. This assumes IP addresses are rather static, but that is very
 typically is the case in a business network.

Is this possible?

答:
Well, I doubt that this solution will be valuable for hlovdal, given that this question is now two months old, but maybe somebody else will find it useful:

The optimum solution to this problem is to enable automatic logins.  This requires two steps.  First, you need to add automatic authentication to your web service.  Right now, we're using Apache with the Debian usn-libapache2-authenntlm-perl package on our internal application server*.  (Our network is Active Directory and, obviously, the server runs on Debian Linux.)  Second, you need a MediaWiki extension that makes MediaWiki aware of the web service's authentication.  I've used the Automatic REMOTE_USER Authentication module successfully on an Apache web server that was tied into our network via an NTLM authentication module, but I do recall that it required a bit of massaging the code to make it work:

I had to follow the "horrid hacks" given on the extension's page, changing the setPassword() and addUser() functions to always return true instead of always returning false.

Since Active Directory is case-insensitive and MediaWiki isn't, I replaced both instances of the statement $username = $_SERVER['REMOTE_USER'] with $username = getCanonicalName($_SERVER['REMOTE_USER']).

Since I wanted to only allow certain people within the company to use our wiki, I set autoCreate() to always return false.  It doesn't sound as if you need to worry about this, so you should leave autoCreate() at always returning true, which means that anybody on your company network will be able to access the wiki.

The nifty thing about this solution is that nobody has to log in into the wiki, ever; they simply go to a wiki page and they are logged in under their network ID.

* We just switched to this from a Red Hat server that was using mod_ntlm.  Unfortunately, mod_ntlm hasn't been updated in a while and it's been starting to sporadically fail.  I mention this because I've started to stumble on a performance issue with our current MediaWiki configuration that may require further code massaging....

OwnerDisplayName: hlovdal

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: hlovdal

OwnerDisplayName: DLJessup

LastEditorDisplayName: DLJessup


答:
String is immutable - Use StringBuilder or StringBuffer (thread-safe) instead

```<code>public void displayString(Student[] students)
{
   StringBuilder studentDetails = new StringBuilder();
   for (Student stu : students)
   {
       studentDetails.append(stu.getFirstName());
       studentDetails.append(" ");
       studentDetails.append(stu.getLastName());
       studentDetails.append(" ");
       studentDetails.append(stu.getAge());
       studentDetails.append("\n");
   }
   System.out.println("Student Details are: ");
   System.out.println(studentDetails.toString());
}
</code>```

Title: String is immutable?

Body:
String is immutable - Use StringBuilder or StringBuffer (thread-safe) instead

public void displayString(Student[] students)
{
   StringBuilder studentDetails = new StringBuilder();
   for (Student stu : students)
   {
       studentDetails.append(stu.getFirstName());
       studentDetails.append(" ");
       studentDetails.append(stu.getLastName());
       studentDetails.append(" ");
       studentDetails.append(stu.getAge());
       studentDetails.append("\n");
   }
   System.out.println("Student Details are: ");
   System.out.println(studentDetails.toString());
}