问:
Fetch post api from React Client to express server causes error
I'm trying to send user id and password in React frontend (running on localhost:8080) to express backend server(running on localhost:5000) using post method, but when I click button for submit it says cannot Post /login

Below is my code

```<code>import React, { Component } from 'react';
//import'whatwg-fetch';

function postSend(url, data) {
  return fetch(url, {
    credentials: 'same-origin',
    mode: 'cors',
    method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
    body: JSON.stringify(data), // Coordinate the body type with 'Content-Type'
    headers: new Headers({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }),
  }).then((res) => res.json())
  .then((result) => console.log(result))
  .catch((error) =>{
    console.error(error, 'postRequest error');
  })
};

class Signup extends Component {
  constructor(props){
    super(props);
    this.state = { id: "", password: ""}
  }
  componentDidMount() {
    const API = 'http://localhost:8080/';
    const DEFAULT_QUERY = 'routes';
    fetch(API + DEFAULT_QUERY, {
  headers : {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
   },
   mode: 'cors'

  }).then(response => response.json())
    .then(data => this.setState({ data }))
    .catch(function(err) {console.log(err)});
}

  handleChange = event => {
    this.setState({ [event.target.name] : event.target.value });
  };
  handleSubmit(event) {
    event.preventDefault();
    postSend('http://localhost:5000/login', this.state);

  }
    render() {
        return ( <div>

            <h1>Welcome to Secret Admirer</h1>
            <form action = "/login" method = "POST"  > <hr/>
                <label>Enter Your Credentials to sign up</label>
                <div className ="form-group">
                <p>user id:
                <input  type="text" value = {this.state.id} onChange={this.handleChange} name="id" placeholder="Enter your ID..."  required />
                </p><br/></div>
                <div className = "form-group">
                <p>Password:
                <input type="text" value = {this.state.password} onChange={this.handleChange} name="password" placeholder="Enter your password" required />
                </p><br/></div>
             <button className = "btn btn-success" type="submit" value="Sign up" onSubmit={this.handleSubmit}> Sign Up</button>
            </form>

            </div>

        )}
}

export default Signup;
</code>```

```<code>const express = require('express');
const bodyParser = require('body-parser');
const user = require('../db/user');

const router = express.Router();
var urlencodedParser = bodyParser.urlencoded({extended: false});

//Sign Up
router.post('/login', function(req,res){
    console.log(req.body);
    var newUser = new user.User(req.body);
    newUser.save().then(item => {
        res.redirect('/signin.html');
    }).catch(err => {
        res.status(400).send(err,"Unable to save to database");
    });
});

//Sign in logic
router.post('/signin', urlencodedParser, async(req,res) => {
    // check is id exist
    let userid = await user.User.findOne({id: req.body.id});
    if (!userid) {
        res.status(400).send('Invalid id please sign up');
    } else {
        let userpass = await user.User.findOne({
            id: req.body.id,
            password: req.body.password
        });
        if (!userpass) {
            return res.status(400).send('Wrong password');
        }
        res.redirect('/login-success.html');
    }
});

module.exports = router;
</code>```

I would like POST call to work instead of getting cannot POST /login

答:
In addition to the CORS requirement which you stated you've done,

Your form is pointing to localhost:8080/login which is in your React application, not express. change the onSubmit method to the form instead of the button.

```<code>render() {
        return (
          <div>
            <h1>Welcome to Secret Admirer</h1>
            <form onSubmit={this.handleSubmit}> <hr/>
                <label>Enter Your Credentials to sign up</label>
                <div className ="form-group">
                <p>user id:
                <input  type="text" value = {this.state.id} onChange={this.handleChange} name="id" placeholder="Enter your ID..."  required />
                </p><br/></div>
                <div className = "form-group">
                <p>Password:
                <input type="text" value = {this.state.password} onChange={this.handleChange} name="password" placeholder="Enter your password" required />
                </p><br/></div>
             <button className = "btn btn-success" type="submit" value="Sign up"> Sign Up</button>
            </form>

            </div>

        )
}
</code>```

your res.redirect() in the express application should also use a full path. If you're redirecting like this res.redirect('/signin.html');, it would redirect to localhost:5000/signinhtml instead of your React application.

Body:
I'm trying to send user id and password in React frontend (running on localhost:8080) to express backend server(running on localhost:5000) using post method, but when I click button for submit it says cannot Post /login

Below is my code

import React, { Component } from 'react';
//import'whatwg-fetch';

function postSend(url, data) {
  return fetch(url, {
    credentials: 'same-origin',
    mode: 'cors',
    method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
    body: JSON.stringify(data), // Coordinate the body type with 'Content-Type'
    headers: new Headers({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }),
  }).then((res) => res.json())
  .then((result) => console.log(result))
  .catch((error) =>{
    console.error(error, 'postRequest error');
  })
};

class Signup extends Component {
  constructor(props){
    super(props);
    this.state = { id: "", password: ""}
  }
  componentDidMount() {
    const API = 'http://localhost:8080/';
    const DEFAULT_QUERY = 'routes';
    fetch(API + DEFAULT_QUERY, {
  headers : {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
   },
   mode: 'cors'

  }).then(response => response.json())
    .then(data => this.setState({ data }))
    .catch(function(err) {console.log(err)});
}

  handleChange = event => {
    this.setState({ [event.target.name] : event.target.value });
  };
  handleSubmit(event) {
    event.preventDefault();
    postSend('http://localhost:5000/login', this.state);

  }
    render() {
        return (

Welcome to Secret Admirer

            <form action = "/login" method = "POST"  >

                Enter Your Credentials to sign up

user id:
                <input  type="text" value = {this.state.id} onChange={this.handleChange} name="id" placeholder="Enter your ID..."  required />

Password:
                <input type="text" value = {this.state.password} onChange={this.handleChange} name="password" placeholder="Enter your password" required />

             <button className = "btn btn-success" type="submit" value="Sign up" onSubmit={this.handleSubmit}> Sign Up</button>
            </form>

        )}
}

export default Signup;

const express = require('express');
const bodyParser = require('body-parser');
const user = require('../db/user');

const router = express.Router();
var urlencodedParser = bodyParser.urlencoded({extended: false});

//Sign Up
router.post('/login', function(req,res){
    console.log(req.body);
    var newUser = new user.User(req.body);
    newUser.save().then(item => {
        res.redirect('/signin.html');
    }).catch(err => {
        res.status(400).send(err,"Unable to save to database");
    });
});

//Sign in logic
router.post('/signin', urlencodedParser, async(req,res) => {
    // check is id exist
    let userid = await user.User.findOne({id: req.body.id});
    if (!userid) {
        res.status(400).send('Invalid id please sign up');
    } else {
        let userpass = await user.User.findOne({
            id: req.body.id,
            password: req.body.password
        });
        if (!userpass) {
            return res.status(400).send('Wrong password');
        }
        res.redirect('/login-success.html');
    }
});

module.exports = router;

I would like POST call to work instead of getting cannot POST /login

Body:
In addition to the CORS requirement which you stated you've done,

Your form is pointing to localhost:8080/login which is in your React application, not express. change the onSubmit method to the form instead of the button.

render() {
        return (
          <div>
            <h1>Welcome to Secret Admirer</h1>
            <form onSubmit={this.handleSubmit}> <hr/>
                <label>Enter Your Credentials to sign up</label>
                <div className ="form-group">
                <p>user id:
                <input  type="text" value = {this.state.id} onChange={this.handleChange} name="id" placeholder="Enter your ID..."  required />
                </p><br/></div>
                <div className = "form-group">
                <p>Password:
                <input type="text" value = {this.state.password} onChange={this.handleChange} name="password" placeholder="Enter your password" required />
                </p><br/></div>
             <button className = "btn btn-success" type="submit" value="Sign up"> Sign Up</button>
            </form>

            </div>

        )
}

your res.redirect() in the express application should also use a full path. If you're redirecting like this res.redirect('/signin.html');, it would redirect to localhost:5000/signinhtml instead of your React application.


来源: stackexchange

问:
How do I recover from a botched ActiveRecord model rename?
I created a Rails model (and controller) with a typo in the name. I renamed all of the files to the correct names, and then I rolled back the migration I used to create the table and changed it to recreate the table with the proper name.

Unfortunately, ActiveRecord still wants to use the old table name, even though it does not appear in any file in my project. I assume it has been cached somewhere but I have no idea where. There are no files in the application's tmp directory that look suspicious.

For the time being, I added a call to "set_table_name" to the model to get around the problem, but I'm really curious about where the old table name is stored and how to get rid of it.

Update: I went ahead and deleted the scaffold using "rails destroy scaffold". When I recreated it (without the typo), it recreated everything with the typo! I know the typo is cached somewhere but I have no idea where.

答:
OK, it turns out that with Rails 3 (and maybe other versions) if you try to generate a model named "Cafe" it will use the name "cave" instead. No idea why.

Here's an example. I duplicated this on different computers, too.

```<code>holloway:whatever rafeco$ rails g scaffold Cafe
  invoke  active_record
  create    db/migrate/20110412190231_create_caves.rb
  create    app/models/cafe.rb
  invoke    test_unit
  create      test/unit/cafe_test.rb
  create      test/fixtures/caves.yml
   route  resources :caves
  invoke  scaffold_controller
  create    app/controllers/caves_controller.rb
  invoke    erb
  create      app/views/caves
  create      app/views/caves/index.html.erb
  create      app/views/caves/edit.html.erb
  create      app/views/caves/show.html.erb
  create      app/views/caves/new.html.erb
  create      app/views/caves/_form.html.erb
  invoke    test_unit
  create      test/functional/caves_controller_test.rb
  invoke    helper
  create      app/helpers/caves_helper.rb
  invoke      test_unit
  create        test/unit/helpers/caves_helper_test.rb
  invoke  stylesheets
  create    public/stylesheets/scaffold.css
</code>```

ContentLicense: CC BY-SA 3.0

Body:
OK, it turns out that with Rails 3 (and maybe other versions) if you try to generate a model named "Cafe" it will use the name "cave" instead. No idea why.

Here's an example. I duplicated this on different computers, too.

holloway:whatever rafeco$ rails g scaffold Cafe
  invoke  active_record
  create    db/migrate/20110412190231_create_caves.rb
  create    app/models/cafe.rb
  invoke    test_unit
  create      test/unit/cafe_test.rb
  create      test/fixtures/caves.yml
   route  resources :caves
  invoke  scaffold_controller
  create    app/controllers/caves_controller.rb
  invoke    erb
  create      app/views/caves
  create      app/views/caves/index.html.erb
  create      app/views/caves/edit.html.erb
  create      app/views/caves/show.html.erb
  create      app/views/caves/new.html.erb
  create      app/views/caves/_form.html.erb
  invoke    test_unit
  create      test/functional/caves_controller_test.rb
  invoke    helper
  create      app/helpers/caves_helper.rb
  invoke      test_unit
  create        test/unit/helpers/caves_helper_test.rb
  invoke  stylesheets
  create    public/stylesheets/scaffold.css


问:
Buttons and inputs are not displayed on Modal
Buttons are inputs fields are not getting displayed on modal inside .aspx page but labels are visible

                    <button type="button" class="close" data-dismiss="modal">×Close</button>

Filter

                                            By Number
                                            <input id="txt_filter_number" name="txt_filter_number" type="text" class="form-control" runat="server" />

                            <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
                            <button type="button" class="btn btn-primary">Apply</button>

```

Output (missing buttons and input fields):

答:
It looks like your .modal-footer div is inside the .modal-body div.  The bootstrap documentation has an example that shows the footer div outside of the body div

```<code><div class="modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Modal body text goes here.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary">Save changes</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Buttons are inputs fields are not getting displayed on modal inside .aspx page but labels are visible

                    <button type="button" class="close" data-dismiss="modal">×Close</button>

Filter

                                            By Number
                                            <input id="txt_filter_number" name="txt_filter_number" type="text" class="form-control" runat="server" />

                            <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
                            <button type="button" class="btn btn-primary">Apply</button>

Output (missing buttons and input fields):

Body:
It looks like your .modal-footer div is inside the .modal-body div.  The bootstrap documentation has an example that shows the footer div outside of the body div

<div class="modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Modal body text goes here.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary">Save changes</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>


问:
Which is more performant? Custom SQL or PowerBI joins/manipulation
I'm in the process of starting to build a new dashboarding project, and wanted some guidance with respect to some best processes regarding data ingestion into PowerBI. My company uses MySQL for data.

Most common dashboarding software (Tableau and PowerBI, not sure of others) has features to use a GUI to do the equivalent of SQL commands. They also have the option to just do straight custom SQL to get data as well.

Is there a performance advantage to using custom SQL vs the GUI? Does the GUI take advantage of indexing?

答:
With Tableau, you can write custom SQL yourself, but you get more benefit out of Tableau by modeling the relationships between your tables and views in Tableau, and letting Tableau generate optimized SQL for each specific view. When you use hand-written custom SQL, that removes opportunities for Tableau to generate optimized SQL. For instance, Tableau will only select fields that are used in a visualization. It can cull joins that are unnecessary for the particular visualization, and can fuse similar related queries into a single query.

There are very few cases where you really need to use custom SQL with Tableau, say if you want to call a database specific function, but all the typical things you need to do join, union, filter, select, case, group, aggregate, perform calculations are available without hard coding the SQL. You can think of a Tableau data source as template for many similar queries, and Tableau generates a specific query from that template for just the data needed for the particular visualization.

If you're going to use Tableau, take the time to learn it, rather than just copy your previous SQL in unchanged.


问:
Why won't my normals interpolate between the vertices, thus creating a flat shading effect?
I am having some trouble with my Phong shading algorithm. It seems like the normals are off and I always get a flat shaded surface.

I am implementing deferred rendering, so in my geometry pass I store the vertex' position and normal in textures. In the lighting pass, I output the normals as color to check their "values".

EDIT 1 My Gbuffer uses two textures for storing the positions and normals. Both textures use the GL_RGB16F format.

EDIT 5 As you can see in this image

I do not get an elegant color transition. The head on the left is the result of my engine, on the right you can see the same model in Blender. In Blender, the normals (in blue) look correct (no duplicates, etc) but in my engine, they behave like a face-normal (every 4 showing in the same direction).
I am using Assimp to load the models and I include the aiProcess_GenSmoothNormals flag when importing them.

The geometry-pass vertex shader:

#version 440 core

layout (location = 0) in vec4 positionOS;
layout (location = 1) in vec3 normalOS;
layout (location = 2) in vec2 uv;

out VertexData
{
    vec3 PositionVS;
    vec3 NormalVS;
    vec2 UV;
} vs_out;

uniform mat3 normalViewMatrix;
uniform mat4 modelViewMatrix;

struct Camera
{
    mat4 viewMatrix;
    mat4 projMatrix;
};

layout(std140, binding = 0) uniform CameraBlock
{
    Camera cam;
};

void main()
{
    vec4 positionVS = modelViewMatrix * positionOS;
    vs_out.PositionVS = positionVS.xyz;
    vs_out.NormalVS = normalViewMatrix * normalOS;
    vs_out.UV = uv;

    gl_Position = cam.projMatrix * positionVS;
}
```

<p>The geometry-pass fragment shader:</p>

<pre class="lang-c prettyprint-override"><code>#version 440 core

layout (location = 0) out vec3 PositionVS;
layout (location = 1) out vec3 NormalVS;

in VertexData
{
    vec3 PositionVS;
    vec3 NormalVS;
    vec2 UV;
} vs_in;

void main()
{
    PositionVS = vs_in.PositionVS;
    NormalVS = normalize(vs_in.NormalVS);
}
</code>```

EDIT 4 Reading vertex values from Assimp (aiMesh)

void MeshLoader::prepareMesh(const aiMesh & mesh)
{
    { // vertices

        for (int i = 0; i < mesh.mNumVertices; i++) {
            if (mesh.HasPositions()) {
                glm::vec3 position = glm::vec3(mesh.mVertices[i].x, mesh.mVertices[i].y, mesh.mVertices[i].z);

                positions.emplace_back(position.x, position.y, position.z, 1);
            }

            if (mesh.HasNormals()) {
                normals.emplace_back(mesh.mNormals[i].x, mesh.mNormals[i].y, mesh.mNormals[i].z);
            }

            if (mesh.HasTangentsAndBitangents()) {
                tangents.emplace_back(mesh.mTangents[i].x, mesh.mTangents[i].y, mesh.mTangents[i].z);
                bitangents.emplace_back(mesh.mBitangents[i].x, mesh.mBitangents[i].y, mesh.mBitangents[i].z);
            }

            if (mesh.HasTextureCoords(0)) {
                uvs.emplace_back(mesh.mTextureCoords[0][i].x, mesh.mTextureCoords[0][i].y);
            }

        }
    }

    { // polygons
        numFaces = mesh.mNumFaces;

        for (int i = 0; i < numFaces; i++) {
            indices.push_back(mesh.mFaces[i].mIndices[0]);
            indices.push_back(mesh.mFaces[i].mIndices[1]);
            indices.push_back(mesh.mFaces[i].mIndices[2]);
        }
    }
}
```

I would like to find the solution for this mess. I know that the normals are the issue but I can't figure out why.

EDIT 2 By the look of the sphere, it seems like an interpolation problem, hence the shader code above. If the shaders are correct then maybe the importer class is causing this issue?

EDIT 3 I've also implemented a forward rendering version and display the normals as color, but I get the same result as in the deferred version.

答:
Since you are dealing with deferred rendering, my advice would be to make sure, that the screen-space normal textures actually saves the normal values correctly. First of all, how much space do you allocate for the normal texture? A GL_RGBA16 texture should do the job.

The second thing you have to watch out for is, that in glsl negative color values will be cut when written to a texture buffer, since the texture buffers are unsigned. Try to use some kind of converter method to convert color data to vector data, and vise versa. The methods

```<code>vec4 toCoord(vec4 color) {
    return vec4(2.0 * color.xyz - vec3(1, 1, 1), color.w);
}

vec4 toColor(vec4 coord) {
    return vec4(0.5 * coord.xyz + vec3(0.5, 0.5, 0.5), coord.w);
}
</code>```

should work just fine for that.
If you didn't already do one of these two things, give it a try :)

If it does not work, some inside on the way you write and read normal data in the fragment shaders to and from the texture buffers would be helpfull :)

Body:
I am having some trouble with my Phong shading algorithm. It seems like the normals are off and I always get a flat shaded surface.

I am implementing deferred rendering, so in my geometry pass I store the vertex' position and normal in textures. In the lighting pass, I output the normals as color to check their "values".

EDIT 1 My Gbuffer uses two textures for storing the positions and normals. Both textures use the GL_RGB16F format.

EDIT 5 As you can see in this image

I do not get an elegant color transition. The head on the left is the result of my engine, on the right you can see the same model in Blender. In Blender, the normals (in blue) look correct (no duplicates, etc) but in my engine, they behave like a face-normal (every 4 showing in the same direction).
I am using Assimp to load the models and I include the aiProcess_GenSmoothNormals flag when importing them.

The geometry-pass vertex shader:

#version 440 core

layout (location = 0) in vec4 positionOS;
layout (location = 1) in vec3 normalOS;
layout (location = 2) in vec2 uv;

out VertexData
{
    vec3 PositionVS;
    vec3 NormalVS;
    vec2 UV;
} vs_out;

uniform mat3 normalViewMatrix;
uniform mat4 modelViewMatrix;

struct Camera
{
    mat4 viewMatrix;
    mat4 projMatrix;
};

layout(std140, binding = 0) uniform CameraBlock
{
    Camera cam;
};

void main()
{
    vec4 positionVS = modelViewMatrix * positionOS;
    vs_out.PositionVS = positionVS.xyz;
    vs_out.NormalVS = normalViewMatrix * normalOS;
    vs_out.UV = uv;

    gl_Position = cam.projMatrix * positionVS;
}

The geometry-pass fragment shader:

#version 440 core

layout (location = 0) out vec3 PositionVS;
layout (location = 1) out vec3 NormalVS;

in VertexData
{
    vec3 PositionVS;
    vec3 NormalVS;
    vec2 UV;
} vs_in;

void main()
{
    PositionVS = vs_in.PositionVS;
    NormalVS = normalize(vs_in.NormalVS);
}

EDIT 4 Reading vertex values from Assimp (aiMesh)

void MeshLoader::prepareMesh(const aiMesh & mesh)
{
    { // vertices

        for (int i = 0; i < mesh.mNumVertices; i++) {
            if (mesh.HasPositions()) {
                glm::vec3 position = glm::vec3(mesh.mVertices[i].x, mesh.mVertices[i].y, mesh.mVertices[i].z);

                positions.emplace_back(position.x, position.y, position.z, 1);
            }

            if (mesh.HasNormals()) {
                normals.emplace_back(mesh.mNormals[i].x, mesh.mNormals[i].y, mesh.mNormals[i].z);
            }

            if (mesh.HasTangentsAndBitangents()) {
                tangents.emplace_back(mesh.mTangents[i].x, mesh.mTangents[i].y, mesh.mTangents[i].z);
                bitangents.emplace_back(mesh.mBitangents[i].x, mesh.mBitangents[i].y, mesh.mBitangents[i].z);
            }

            if (mesh.HasTextureCoords(0)) {
                uvs.emplace_back(mesh.mTextureCoords[0][i].x, mesh.mTextureCoords[0][i].y);
            }

        }
    }

    { // polygons
        numFaces = mesh.mNumFaces;

        for (int i = 0; i < numFaces; i++) {
            indices.push_back(mesh.mFaces[i].mIndices[0]);
            indices.push_back(mesh.mFaces[i].mIndices[1]);
            indices.push_back(mesh.mFaces[i].mIndices[2]);
        }
    }
}

I would like to find the solution for this mess. I know that the normals are the issue but I can't figure out why.

EDIT 2 By the look of the sphere, it seems like an interpolation problem, hence the shader code above. If the shaders are correct then maybe the importer class is causing this issue?

EDIT 3 I've also implemented a forward rendering version and display the normals as color, but I get the same result as in the deferred version.

Body:
Since you are dealing with deferred rendering, my advice would be to make sure, that the screen-space normal textures actually saves the normal values correctly. First of all, how much space do you allocate for the normal texture? A GL_RGBA16 texture should do the job.

The second thing you have to watch out for is, that in glsl negative color values will be cut when written to a texture buffer, since the texture buffers are unsigned. Try to use some kind of converter method to convert color data to vector data, and vise versa. The methods

vec4 toCoord(vec4 color) {
    return vec4(2.0 * color.xyz - vec3(1, 1, 1), color.w);
}

vec4 toColor(vec4 coord) {
    return vec4(0.5 * coord.xyz + vec3(0.5, 0.5, 0.5), coord.w);
}

should work just fine for that.
If you didn't already do one of these two things, give it a try :)

If it does not work, some inside on the way you write and read normal data in the fragment shaders to and from the texture buffers would be helpfull :)


问:
Python Split only take the 3 array
Im making some script to separate between two array using | and im testing it using two line of

```<code>email1|password1
email2|password2
</code>```

it only giving me the

```<code>password1
email2|password2
</code>```

i have tried to use one line of it but it giving me IndexError: list index out of range

the spliting script

```<code>import sys

maillist = sys.argv[1]
email = open(maillist, 'r').read().split('|')
print(email[1]+'|'+email[2])
</code>```

答: I think the real problem you have right now is that you may not know Pyhon starts counting at 0 instead of 1. As for a full solution to the problem I will refer you to Jab's answer.</p>

Title: Python Split only take the 3 array

Body:
Im making some script to separate between two array using | and im testing it using two line of

email1|password1
email2|password2

it only giving me the

password1
email2|password2

i have tried to use one line of it but it giving me IndexError: list index out of range

the spliting script

import sys

maillist = sys.argv[1]
email = open(maillist, 'r').read().split('|')
print(email[1]+'|'+email[2])


问:
Is there a heap or heap-like structure that works with pointers, in other words nodes not in an array?
I currently have a double-linked list of objects in descending sorted order.  (The list is intrusive--pointers in the objects.)  I have a very limited set of operations:

add a node with the highest possible key

remove a node with the highest possible key (doesn't matter which one)

remove a node with key 0 (doesn't matter which one)

increment key of a node with highest current key (doesn't matter which one)

decrement key of any given node whose key is above 0

Operations 1-4 will be constant time, but operation 5 is O(n), where n=number of nodes with same key value.  This is because such nodes, when incremented, have to be moved past their siblings with the same key value, and placed after that range.  And finding that re-insert place will be O(n).

I thought of the heap (heapsort heap, not malloc heap) as a solution where worst-case would be O(log n) (where n=number of nodes).  However, based on my recollection and what Google is finding me, it seems invariably implemented in an array, as opposed to a binary tree.  So:

Question: is there an implementation of a heap that uses pointers in the manner of a binary tree, as opposed to an array, that maintains O() of the typical array implementation?

答:
Unfortunately the answer to the written problem isn't an answer to the headline title of the written problem.

Solution 1: amortized O(1) data structure

A solution was found with amortized O(1) implementations of all required operations.

It is simply a double-linked list of double-linked lists.  The "main" double-linked list nodes are called parents, and we have at most one parent per key value.  The parent nodes keep a double-linked list of child nodes with the same key value.  Each child additionally points to its parent.

add a node with the highest possible value: If there is no list head or it's value is not max, add new node to head of main linked list.  Otherwise, add it to tail of the head node's child list.

remove a (any) node with the highest possible value:  In the case of multiple items with highest value, it doesn't matter which we remove.  So, if head parent has children, remove the tail child from the child list.  Otherwise, remove the parent from the main list.

remove a (any) node with value 0:  Same operations.

increment value of a (any) node with the highest current value: In case of multiple nodes with same key value, we can choose any, so choose the head parent's tail child.  Remove it from the child list.  If incrementing its value exceeds max value then you're done.  Otherwise it's a new head node.  If instead there are no children, then increment the head parent in place, and if it exceeds maximum value remove it.

decrement value of any node above 0:  If the node is a child, remove from child list, then either add to parent's successor's child list or as a new node after the parent.  A parent with no children: if the successor in the main list still has a smaller key, you're done.  Otherwise remove it and add as successor's tail child.  A parent with children: same but promote the head child to take its place.  This is O(n), where n=number of nodes of given size, because you must change the parent pointer for all children.  However, if the odds of the node selected for decrement being the parent node of all nodes of given size are 1/n, this amortizes to O(1).

The main downside is that we logically have 7 different pointers for each node.  If it's in the parent role we need previous and next parent, and head and tail child.  If it's in the child role we need previous and next child, and parent.  These can be unionized into two alternate substructures of 4 and 3 pointers, which saves storage, but not CPU time (excepting perhaps the need to zero out unused pointers for cleanliness).  Updating them all won't be fast.

Solution 2: Sloppy is Good Enough

Another approach is simply to be sloppy.  The application benefits from finding nodes with higher scores but it's not critical that they be absolutely in perfect order.  So rather than an O(n) operation to move nodes potentially from one end of the chain to the other, we could accept a solution that does an O(1) albeit at times imperfect job.

This could be the current implementation of a double linked list.  It can support all operations except decrement in O(1).  It can handle decrement of a unique key value in O(1).  Only decrement of a non-unique key value would go O(n), as we need to skip the remaining nodes with the previous key value to find the first with the same or higher key.  in the worst case, we could simply cap that search at say 5 or 10 links.  This too would provide a nominally O(1) solution.  However, some pernicious usage patterns may slowly cause the entire list to become quite unordered.


问:
Is it possible to run a goroutine or go method under a different user?
I am working on a small web server that serves files and provides access to each user's home directory.

If the source was to be in C I had the option of answering each request under different threads and to make sure each thread gets to run with the user of the caller as its users.

Is there any approach to achieve something similar to that in Go?
Ideally, the part of the code that handles the request, the goroutine or the method that gets called should be run under the user account of the caller.

I have done some research and it seems in Go we can stick a single goroutine to the current thread but I can't see how it is possible to create a new thread and then attach a goroutine to that thread.

答:
It is not possible to run a goroutine or method as a different user because they both run within the same context as the parent process. Goroutines are equivalent to green threads and don't even necessarily spawn off proper OS thread per routine.

This answer might also depend on OS, but I don't think this will work on windows either.

if you are spawning another process via the cmd package, then this answer may be useful
Running external commands through os/exec under another user


答:
If your file looks like:

```<code>email1|password1
email2|password2
</code>```

And you split by '|' then you will get 3 values returned, the first email, then the first password and the second email as one item, then the second password. That’s why when you access the second and third items you’re only missing the first email. You either need to .split() then .split('|') to remove that line or loop through each line.

```<code>import sys

maillist = sys.argv[1]
with open(maillist, 'r') as email:
    for line in email:
        email, pass = line.split('|')
        print(email, '|', pass)
</code>```

Title: Python Split only take the 3 array

Body:
If your file looks like:

email1|password1
email2|password2

And you split by '|' then you will get 3 values returned, the first email, then the first password and the second email as one item, then the second password. That’s why when you access the second and third items you’re only missing the first email. You either need to .split() then .split('|') to remove that line or loop through each line.

import sys

maillist = sys.argv[1]
with open(maillist, 'r') as email:
    for line in email:
        email, pass = line.split('|')
        print(email, '|', pass)


问:
combine two pictures(different size) horizontally?
I have 2 pictures, need to combine them horizontally. I know numpy and cv2(opencv) should help me to do this. But don't know how.
I used img1 = cv2.imread(file1), img2 = cv2.imread(file2)
the 2 images' shape are (2048, 1334, 3) and (720, 1200, 3)
How could I do this? when I open These 2 images, they have similar height, different width.
I only know if the 2 pics have the same size, then just use concate, but my 2 pics are different sizes.
For the final output, I want to have them keep their own width, height choose the biggest/smallest...
So I imagine the final output should maybe 2/3 width one picture, 1/3 width the other pic which is totally good. I don't need these 2 are evenly distributed. Just keep their own width. Thanks!</p>

答:
I just solved my question.
Basically use cv2.resize()function to resize the images
Then simply concatenate them horizontally or vertically.
Just change the axis.

```<code>img1 = cv2.imread('xxx.png')
img2 = cv2.imread('yyy.jpg')
</code>```

then compare img1.shape() and img2.shape()
Use resize()function to make them width the same or height the same.

```<code>vis = np.concatenate((img1, img2), axis=1)
cv2.imwrite('out.png', vis)
</code>```

Body:
I just solved my question.
Basically use cv2.resize()function to resize the images
Then simply concatenate them horizontally or vertically.
Just change the axis.

img1 = cv2.imread('xxx.png')
img2 = cv2.imread('yyy.jpg')

then compare img1.shape() and img2.shape()
Use resize()function to make them width the same or height the same.

vis = np.concatenate((img1, img2), axis=1)
cv2.imwrite('out.png', vis)


问:
Issue with some simple exception handling using .hasNextInt() in Java?
I'm creating an array list for a menu of food items which correspond to a number on a menu. Most of that is left out: my main issue is that the error message does not display for the first time the user does not enter an integer value. Nothing will show on the console after I press enter, but if I again enter something that isn't an integer it will work like it should and display the error message.

Edit: something else I should note is that earlier in the code I use the same scanner object so use .next() to clear it of the previous value it had.

```<code>        orderArray = new String[length];
        menuDisplay();
        int item; //the item number that user must enter
        for(int i=1; i<=length;i++)
        {
            System.out.println("Please choose item #"+ i+": ");
            scan.next();
            while(!scan.hasNextInt()) //this while loop checks that an integer value has been entered
            {
                System.out.println("Please enter an integer value from the above menu.");
                scan.next();
            }

        }
</code>```

答:
The hasNextInt check the next token, not the token just received, so always call hasNextXxx() before calling nextXxx().

You'd also want to actually get the integer value and assign it to item.

Rearrange your code like this:

```<code>System.out.println("Please choose item #"+ i+": ");
while (!scan.hasNextInt()) //this while loop checks that an integer value has been entered
{
    System.out.println("Please enter an integer value from the above menu.");
    scan.next(); // skip bad token
}
item = scan.nextInt();
</code>```

Body:
I'm creating an array list for a menu of food items which correspond to a number on a menu. Most of that is left out: my main issue is that the error message does not display for the first time the user does not enter an integer value. Nothing will show on the console after I press enter, but if I again enter something that isn't an integer it will work like it should and display the error message.

Edit: something else I should note is that earlier in the code I use the same scanner object so use .next() to clear it of the previous value it had.

        orderArray = new String[length];
        menuDisplay();
        int item; //the item number that user must enter
        for(int i=1; i<=length;i++)
        {
            System.out.println("Please choose item #"+ i+": ");
            scan.next();
            while(!scan.hasNextInt()) //this while loop checks that an integer value has been entered
            {
                System.out.println("Please enter an integer value from the above menu.");
                scan.next();
            }

        }

Body:
The hasNextInt check the next token, not the token just received, so always call hasNextXxx() before calling nextXxx().

You'd also want to actually get the integer value and assign it to item.

Rearrange your code like this:

System.out.println("Please choose item #"+ i+": ");
while (!scan.hasNextInt()) //this while loop checks that an integer value has been entered
{
    System.out.println("Please enter an integer value from the above menu.");
    scan.next(); // skip bad token
}
item = scan.nextInt();


问:
Windows CE Console output converting strings
I created a C# console application running on a Windows CE device. I have one line of code in the program so far:

Console.WriteLine("Hello World");

Output on Screen: 11

The 11 is the length of the string, so is something converting my string to a character array or something?

I am using the SDK created from the BSP to target my device. In addition, the BSP includes both .NET 2.0 and .NET 3.5 for the OS, and I'm using Visual Studio 2005 for my console application.

Has anyone ever seen this before in a .NET console app? Thanks.

UPDATE: I tried to create a basic Windows Forms app and run that on my device. This time I got an actual error "System.Windows.Forms dll cannot be found", so that indicates to me that .NET is not installed correctly. I have it included in the Platform Builder catalog, so I'm not sure what else might be missing. Any ideas?

答:
I've definitely never seen this, and I've seen a lot of CF behaviors.

First, don't put CF 2.0 and 3.5 in the OS.  Ever.  They don't coexist in an OS image project peacefully due to SYSGEN overlaps, plus it's unnecessary as the 3.5 runtimes can load and run 2.0 binaries.

You're certain that your only code is that one line?  You're certain that you're runnign the app that is the code you're seeing (i.e. it's not running an old or different version by mistake)?  Are you at a breakpoint when this happens?


问:
How to capitalize every word including in the beginning of a quote?
For example, this sentence:

```<code>say "mosquito!"
</code>```

I try to capitalize with the following code:

```<code>'say "mosquito!"'.capitalize()
</code>```

Which returns this:

```<code>'Say "mosquito!"’
</code>```

However, the desired result is:

```<code>'Say "Mosquito!"’
</code>```

答:
You could do it using a lambda in regular expression substitution:</p>

```<code>string = 'say "mosquito\'s house" '

import re
caps   = re.sub("((^| |\")[a-z])",lambda m:m.group(1).upper(),string)

# 'Say "Mosquito\'s House" '
</code>```

Body:
For example, this sentence:

say "mosquito!"

I try to capitalize with the following code:

'say "mosquito!"'.capitalize()

Which returns this:

'Say "mosquito!"’

However, the desired result is:

'Say "Mosquito!"’

Body:
You could do it using a lambda in regular expression substitution:

string = 'say "mosquito\'s house" '

import re
caps   = re.sub("((^| |\")[a-z])",lambda m:m.group(1).upper(),string)

# 'Say "Mosquito\'s House" '


问:
Deserializing from JSON into PHP, with casting?
Suppose I have a User class with 'name' and 'password' properties, and a 'save' method. When serializing an object of this class to JSON via json_encode, the method is properly skipped and I end up with something like {'name': 'testName', 'password': 'testPassword'}.

However, when deserializing via json_decode, I end up with a StdClass object instead of a User object, which makes sense but this means the object lacks the 'save' method. Is there any way to cast the resultant object as a User, or to provide some hint to json_decode as to what type of object I'm expecting?

答:
Old question, new answer.

What about creating your own interface to match JsonSerializable? ;)

/**
 * Interface JsonUnseriablizable
 */
interface JsonUnseriablizable {
    /**
     * @param array $json
     */
    public function jsonUnserialize(array $json);
}
```
<p>example:</p>
<pre class="lang-php prettyprint-override"><code>/**
 * Class Person
 */
class Person implements JsonUnseriablizable {

    public $name;
    public $dateOfBirth;

    /**
     * @param string $json
     */
    public function jsonUnserialize(array $json)
    {
        $this->name = $json['name'] ?? $this->name;
        $this->dateOfBirth = $json['date_of_birth'] ?? $this->dateOfBirth;
    }
}

$json = '{"name":"Bob","date_of_birth":"1970-01-01"}';

$person = new Person();
if($person instanceof JsonUnseriablizable){
    $person->jsonUnserialize(json_decode($json, true, 512, JSON_THROW_ON_ERROR));
}

var_dump($person->name);
</code>```

OwnerDisplayName: Jeroen van Delft

ContentLicense: CC BY-SA 2.5

Body:
Old question, new answer.

What about creating your own interface to match JsonSerializable? ;)

/**
 * Interface JsonUnseriablizable
 */
interface JsonUnseriablizable {
    /**
     * @param array $json
     */
    public function jsonUnserialize(array $json);
}

example:

/**
 * Class Person
 */
class Person implements JsonUnseriablizable {

    public $name;
    public $dateOfBirth;

    /**
     * @param string $json
     */
    public function jsonUnserialize(array $json)
    {
        $this->name = $json['name'] ?? $this->name;
        $this->dateOfBirth = $json['date_of_birth'] ?? $this->dateOfBirth;
    }
}

$json = '{"name":"Bob","date_of_birth":"1970-01-01"}';

$person = new Person();
if($person instanceof JsonUnseriablizable){
    $person->jsonUnserialize(json_decode($json, true, 512, JSON_THROW_ON_ERROR));
}

var_dump($person->name);


问:
Problem sending mail with javamail
I'm trying to send an email to myself using the javamail api.  I've followed the code correctly that I found online but I can't seem to get it to work.  The error I'm getting is:

```<code>Exception in thread "main" javax.mail.AuthenticationFailedException: No authentication mechansims supported by both server and client
</code>```

Does that mean my computer doesn't support authentication?

```<code>public class Emails
{
    public static void main(String[] args) throws MessagingException
    {
        Emails e = new Emails();
        e.sendMail();
    }

    public void sendMail() throws MessagingException
    {
        boolean debug = false;
        String subject = "Testing";
        String message = "Testing Message";
        String from = "myemail@email.com";
        String[] recipients = {"myemail@email.com"};

        // create some properties and get the default Session
        Session session = getSession();
        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++)
        {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Optional : You can also set your custom headers in the Email if you Want
        msg.addHeader("MyHeaderName", "myHeaderValue");

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
    }

    private Session getSession()
    {
        Authenticator authenticator = new Authenticator();

        Properties properties = new Properties();
        properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
        properties.setProperty("mail.smtp.auth", "true");

        properties.setProperty("mail.smtp.host", "smtp.examplehost.com");
        properties.setProperty("mail.smtp.port", "25");

        return Session.getInstance(properties, authenticator);
    }

    private class Authenticator extends javax.mail.Authenticator
    {
        private PasswordAuthentication authentication;

        public Authenticator()
        {
            String username = "myusername";
            String password = "mypassword";
            authentication = new PasswordAuthentication(username, password);
        }

        protected PasswordAuthentication getPasswordAuthentication()
        {
            return authentication;
        }
    }
}
</code>```

When I send emails from this server, what I have to do is, login via ssh to the server (login.server.com etc.) then I can send emails from the mail server (smtp.server.com etc.).  I need to mimic this in java

RESOLVED:  Use the SMTPSSLTransport class

答: SMTPSSLTransport solved the problem</p>

Title: Problem sending mail with javamail

Body:
I'm trying to send an email to myself using the javamail api.  I've followed the code correctly that I found online but I can't seem to get it to work.  The error I'm getting is:

Exception in thread "main" javax.mail.AuthenticationFailedException: No authentication mechansims supported by both server and client

Does that mean my computer doesn't support authentication?

public class Emails
{
    public static void main(String[] args) throws MessagingException
    {
        Emails e = new Emails();
        e.sendMail();
    }

    public void sendMail() throws MessagingException
    {
        boolean debug = false;
        String subject = "Testing";
        String message = "Testing Message";
        String from = "myemail@email.com";
        String[] recipients = {"myemail@email.com"};

        // create some properties and get the default Session
        Session session = getSession();
        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++)
        {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Optional : You can also set your custom headers in the Email if you Want
        msg.addHeader("MyHeaderName", "myHeaderValue");

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
    }

    private Session getSession()
    {
        Authenticator authenticator = new Authenticator();

        Properties properties = new Properties();
        properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
        properties.setProperty("mail.smtp.auth", "true");

        properties.setProperty("mail.smtp.host", "smtp.examplehost.com");
        properties.setProperty("mail.smtp.port", "25");

        return Session.getInstance(properties, authenticator);
    }

    private class Authenticator extends javax.mail.Authenticator
    {
        private PasswordAuthentication authentication;

        public Authenticator()
        {
            String username = "myusername";
            String password = "mypassword";
            authentication = new PasswordAuthentication(username, password);
        }

        protected PasswordAuthentication getPasswordAuthentication()
        {
            return authentication;
        }
    }
}

When I send emails from this server, what I have to do is, login via ssh to the server (login.server.com etc.) then I can send emails from the mail server (smtp.server.com etc.).  I need to mimic this in java

RESOLVED:  Use the SMTPSSLTransport class

Body: SMTPSSLTransport solved the problem


问:
Is there a way to gitignore a specific word?
I want my git to ignore the vim-foldmarker ({{{,}}}) that I add to a repo.
I know git has the --ignore-whitespace option but,
is there a way to tell git to ignore a specific word or strings?
Of course I want git to track the diffs which is not "{{{" or "}}}"

if the original code cloned is

def foo(bar):
    # do someting
    return "buz"
```

<p>and I edit like</p>

<pre class="lang-python prettyprint-override"><code>def foo(bar): # {{{ <- this tells vim to fold from here
    # do something
    return "baz" # }}} to here
</code>```

I want git diff to be like this

```<code>-    # do someting
+    # do something
-    return "buz"
*    return "baz"
</code>```

not like this

```<code>-def foo(bar):
+def foo(bar): # {{{ <- this tells vim to fold from here
-    return "buz"
*    return "baz" # }}} to here
</code>```

答:
Git doesn't allow you to use a .gitignore file to ignore part of a file. You can either ignore the whole thing, or not ignore it at all.

However, there is a way to do what you want, which is a diff filter. If you edit the .git/info/attributes file (creating it if it doesn't exist), you can enter a line that says *.py diff=vim, which will make all Python files use the "vim" diff filter. You could also write this in .gitattributes, if you're the only person on the project, or in any other valid gitattributes file (see the man page for details).

Once you've done that, you can specify a diff filter in your .git/config file, or in your personal .gitconfig file. that specifies how to modify the file to render diffs. For example, you could write something like this:

```<code>[diff "vim"]
    textconv = "sed -e 's/ # {{{.*$//' -e 's/ # }}}.*$//'"
</code>```

That will have sed modify all your diffs to strip out the whitespace, comments, and fold markers. You can perform arbitrary transformations on your files to modify them as you please for diff output.

Body:
I want my git to ignore the vim-foldmarker ({{{,}}}) that I add to a repo.
I know git has the --ignore-whitespace option but,
is there a way to tell git to ignore a specific word or strings?
Of course I want git to track the diffs which is not "{{{" or "}}}"

if the original code cloned is

def foo(bar):
    # do someting
    return "buz"

and I edit like

def foo(bar): # {{{ <- this tells vim to fold from here
    # do something
    return "baz" # }}} to here

I want git diff to be like this

-    # do someting
+    # do something
-    return "buz"
*    return "baz"

not like this

-def foo(bar):
+def foo(bar): # {{{ <- this tells vim to fold from here
-    return "buz"
*    return "baz" # }}} to here

Body:
Git doesn't allow you to use a .gitignore file to ignore part of a file. You can either ignore the whole thing, or not ignore it at all.

However, there is a way to do what you want, which is a diff filter. If you edit the .git/info/attributes file (creating it if it doesn't exist), you can enter a line that says *.py diff=vim, which will make all Python files use the "vim" diff filter. You could also write this in .gitattributes, if you're the only person on the project, or in any other valid gitattributes file (see the man page for details).

Once you've done that, you can specify a diff filter in your .git/config file, or in your personal .gitconfig file. that specifies how to modify the file to render diffs. For example, you could write something like this:

[diff "vim"]
    textconv = "sed -e 's/ # {{{.*$//' -e 's/ # }}}.*$//'"

That will have sed modify all your diffs to strip out the whitespace, comments, and fold markers. You can perform arbitrary transformations on your files to modify them as you please for diff output.


问:
Running postgres 9.5 and django in one container for CI (Bamboo)
I am trying to configure a CI job on Bamboo for a Django app, the tests to be run rely on a database (postgres 9.5). It seems that a prudent way to go about is it run the whole test in a docker container, as I do not control the agent environment so I cannot install Postgres there.

Most guides I found recommend running postgres and django in two separate containers and using docker-compose to easily manage them. In this scenario each docker image runs just one service, started with CMD. In Bamboo I cannot use docker-compose however, I need to use just one image, so I am trying to get Postgres and Django to run nicely together in one container but with little success so far.

My problem is that I see no easy way to start Postgres as a service inside docker but NOT as a docker CMD command, official postgre image uses an entrypoint.sh approach, also described in the official docker docs
But it is not clear to me how to implement that. I would appreciate your help!

答:
Well, basically you would start postgres as a background process in the docker-entrypoint shell script that does otherwise start your django application.

The only trick here is that you need to put a 'trap' command in it so that you can send a shutdown/kill to the background process when your master process stops.

Although I have done that a thousand times, I know that it is a good source for programming errors. In general I do just use my docker-systemctl-replacement which takes care of running multiple applications as services, just as if the container is a virtual machine hosting multiple applications.


问:
Mac can't install Angular-CLI
I'm trying to install Angular-CLI so I can use Ionic framework, however the installation keeps crashing and gives me an error as such.

```<code>npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!  { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules']
npm ERR!   stack:
npm ERR!    'Error: EACCES: permission denied, access \'/usr/local/lib/node_modules\'',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/me/.npm/_logs/2019-05-31T09_00_09_770Z-debug.log
</code>```

I've tried installing it by writing

```<code>sudo npm install -g @angular-cli
</code>```

I've also tried installing it though this method here:
Can't install angular-cli on Mac

I'm sorry, I'm fairly new to this so I'm unsure on what information I should be providing.

I've installed Node JS (10.16.0)

I've also just installed the Ionic Framework and Cordova, however whenever I try opening a project that I create through the terminal, it tells me that I need to install Angular-CLI and once I say yes to the installation, I receive the same errors as above.

My MacOSX is 10.14.5

EDIT:

I've assigned read and write permission to my current user login on my computer but I'm still getting errors. When I run Ionic lab in my terminal to open my project the terminal asks me if I want to install angular and I write Yes. Then I get these errors.

```<code>[ng] Could not find module "@angular-devkit/build-angular" from "/Users/me/project".
[ng] Error: Could not find module "@angular-devkit/build-angular" from "/Users/me/project".
[ng]     at Object.resolve (/Users/me/project/node_modules/@angular-devkit/core/node/resolve.js:141:11)
[ng]     at Observable.rxjs_1.Observable [as _subscribe] (/Users/me/project/node_modules/@angular-devkit/architect/src/architect-legacy.js:153:40)
[ng]     at Observable._trySubscribe (/Users/me/project/node_modules/@angular-devkit/architect/node_modules/rxjs/internal/Observable.js:44:25)
[ng]     at Observable.subscribe (/Users/me/project/node_modules/@angular-devkit/architect/node_modules/rxjs/internal/Observable.js:30:22)
[ng]     at /Users/me/project/node_modules/@angular-devkit/architect/node_modules/rxjs/internal/Observable.js:99:19
[ng]     at new Promise (<anonymous>)
[ng]     at Observable.toPromise (/Users/me/project/node_modules/@angular-devkit/architect/node_modules/rxjs/internal/Observable.js:97:16)
[ng]     at RunCommand.runSingleTarget (/Users/me/project/node_modules/@angular/cli/models/architect-command.js:161:86)
[ng]     at RunCommand.runArchitectTarget (/Users/me/project/node_modules/@angular/cli/models/architect-command.js:201:35)
[ng]     at RunCommand.run (/Users/me/project/node_modules/@angular/cli/commands/run-impl.js:14:25)
[ng]     at RunCommand.validateAndRun (/Users/me/project/node_modules/@angular/cli/models/command.js:124:31)
[ng]     at process._tickCallback (internal/process/next_tick.js:68:7)
[ng]     at Function.Module.runMain (internal/modules/cjs/loader.js:832:11)
[ng]     at startup (internal/bootstrap/node.js:283:19)
[ng]     at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

[ERROR] ng has unexpectedly closed (exit code 1).

        The Ionic CLI will exit. Please check any output above for error
        details.
</code>```

答:
If anybody here is running into the same issue as me, basically what I had done was I ran

sudo chown -R $(whoami) ~/.npm*

in my terminal and then I restarted me computer. Once I did that I essentially just created a new Project and everything was added from there (including Angular CLI)

Title: Mac can't install Angular-CLI

Body:
I'm trying to install Angular-CLI so I can use Ionic framework, however the installation keeps crashing and gives me an error as such.

npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!  { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules']
npm ERR!   stack:
npm ERR!    'Error: EACCES: permission denied, access \'/usr/local/lib/node_modules\'',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/me/.npm/_logs/2019-05-31T09_00_09_770Z-debug.log

I've tried installing it by writing

sudo npm install -g @angular-cli

I've also tried installing it though this method here:
Can't install angular-cli on Mac

I'm sorry, I'm fairly new to this so I'm unsure on what information I should be providing.

I've installed Node JS (10.16.0)

I've also just installed the Ionic Framework and Cordova, however whenever I try opening a project that I create through the terminal, it tells me that I need to install Angular-CLI and once I say yes to the installation, I receive the same errors as above.

My MacOSX is 10.14.5

EDIT:

I've assigned read and write permission to my current user login on my computer but I'm still getting errors. When I run Ionic lab in my terminal to open my project the terminal asks me if I want to install angular and I write Yes. Then I get these errors.

[ng] Could not find module "@angular-devkit/build-angular" from "/Users/me/project".
[ng] Error: Could not find module "@angular-devkit/build-angular" from "/Users/me/project".
[ng]     at Object.resolve (/Users/me/project/node_modules/@angular-devkit/core/node/resolve.js:141:11)
[ng]     at Observable.rxjs_1.Observable [as _subscribe] (/Users/me/project/node_modules/@angular-devkit/architect/src/architect-legacy.js:153:40)
[ng]     at Observable._trySubscribe (/Users/me/project/node_modules/@angular-devkit/architect/node_modules/rxjs/internal/Observable.js:44:25)
[ng]     at Observable.subscribe (/Users/me/project/node_modules/@angular-devkit/architect/node_modules/rxjs/internal/Observable.js:30:22)
[ng]     at /Users/me/project/node_modules/@angular-devkit/architect/node_modules/rxjs/internal/Observable.js:99:19
[ng]     at new Promise (<anonymous>)
[ng]     at Observable.toPromise (/Users/me/project/node_modules/@angular-devkit/architect/node_modules/rxjs/internal/Observable.js:97:16)
[ng]     at RunCommand.runSingleTarget (/Users/me/project/node_modules/@angular/cli/models/architect-command.js:161:86)
[ng]     at RunCommand.runArchitectTarget (/Users/me/project/node_modules/@angular/cli/models/architect-command.js:201:35)
[ng]     at RunCommand.run (/Users/me/project/node_modules/@angular/cli/commands/run-impl.js:14:25)
[ng]     at RunCommand.validateAndRun (/Users/me/project/node_modules/@angular/cli/models/command.js:124:31)
[ng]     at process._tickCallback (internal/process/next_tick.js:68:7)
[ng]     at Function.Module.runMain (internal/modules/cjs/loader.js:832:11)
[ng]     at startup (internal/bootstrap/node.js:283:19)
[ng]     at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

[ERROR] ng has unexpectedly closed (exit code 1).

        The Ionic CLI will exit. Please check any output above for error
        details.


问:
Class Method Not Returning Value When Accessed Via Inheritance
I have a class method that stops returning a value when I try accessing through an inherited subclass.

Have no idea what's causing it to not return the appropriate value.

Here's what I have:

class KNN():
    def __init__(self, neighbors=5, centered=True):
        self.neighbors = neighbors
        self.centered  = centered

    def _get_distance(self, xi):
        return np.sqrt(((xi - self.X_fit)**2).sum(1))

    def fit(self, X, y):
        if self.centered:
            self.X_fit = standardize(X)
        else:
            self.X_fit = X
        self.y_fit     = y

    def predict(self, X, centered=False):
        m, n              = X.shape[0], self.X_fit.shape[0]
        self.dist_matrix  = np.zeros((m, n))
        X_pred            = np.zeros(X.shape)

        if standardize:
           X_pred  = standardize(X)
        else:
           X_pred  = X

        for row in range(m):
            self.dist_matrix[row] = self._get_distance(X_pred[row])

        self.idx_vals      = np.argsort(self.dist_matrix)[:, :self.neighbors]
        self.y_idx         = self.y_fit[self.idx_vals]
        self.preds         = [self.neighbor_calculation(self.y_idx[i]) for i in range(len(self.y_idx))]
        return self.preds
```

<p>If I access the <code>KNN</code> class directly the <code>predict</code> method works as intended, and it returns an array of the predicted values.</p>

<p>However, it stops when I try and create a subclass that inherits from <code>KNN</code>:</p>

```class KNNClassifier(KNN):
    def predict(self, X, centered=False):
        self.neighbor_calculation = majority_vote
        super().predict(X, standardize)
```

<p>When I access the <code>predict</code> method through the <code>KNNClassifier</code> class it doesn't return a value.  </p>

<p>However, <code>self.preds</code> contains the actual predictions.  </p>

<p>But trying something like <code>KNNClassifier.predict(X)[:10]</code> gives the error message:</p>

```'NoneType' object is not subscriptable'
```

I don't know why the returned value is suddenly being interpreted as None.

答:
You are using super to call the parent method from the child, which is right, but you need to use return to return the value:

```<code>return super().predict(X, standardize)
</code>```

Body:
I have a class method that stops returning a value when I try accessing through an inherited subclass.

Have no idea what's causing it to not return the appropriate value.

Here's what I have:

class KNN():
    def __init__(self, neighbors=5, centered=True):
        self.neighbors = neighbors
        self.centered  = centered

    def _get_distance(self, xi):
        return np.sqrt(((xi - self.X_fit)**2).sum(1))

    def fit(self, X, y):
        if self.centered:
            self.X_fit = standardize(X)
        else:
            self.X_fit = X
        self.y_fit     = y

    def predict(self, X, centered=False):
        m, n              = X.shape[0], self.X_fit.shape[0]
        self.dist_matrix  = np.zeros((m, n))
        X_pred            = np.zeros(X.shape)

        if standardize:
           X_pred  = standardize(X)
        else:
           X_pred  = X

        for row in range(m):
            self.dist_matrix[row] = self._get_distance(X_pred[row])

        self.idx_vals      = np.argsort(self.dist_matrix)[:, :self.neighbors]
        self.y_idx         = self.y_fit[self.idx_vals]
        self.preds         = [self.neighbor_calculation(self.y_idx[i]) for i in range(len(self.y_idx))]
        return self.preds

If I access the KNN class directly the predict method works as intended, and it returns an array of the predicted values.

However, it stops when I try and create a subclass that inherits from KNN:

class KNNClassifier(KNN):
    def predict(self, X, centered=False):
        self.neighbor_calculation = majority_vote
        super().predict(X, standardize)

When I access the predict method through the KNNClassifier class it doesn't return a value.

However, self.preds contains the actual predictions.

But trying something like KNNClassifier.predict(X)[:10] gives the error message:

'NoneType' object is not subscriptable'

I don't know why the returned value is suddenly being interpreted as None.

Body:
You are using super to call the parent method from the child, which is right, but you need to use return to return the value:

return super().predict(X, standardize)


问:
Cumulative deposits with fixed rate decay
I'm trying to model the accumulation of biomass from dead wood deposited anually. The wood decays at a rate of 4.6% each year.

My data is formatted:

Cols: Treatment, Year, New.deposit
Treatment (A, B, C...)
Year (0:105)
New.deposit (numeric)

For the past few days, I've tried a combination of functions looking roughly as follows, but ended up with wrong combinations - maybe I'm making things too difficult:

```<code>#OBS! These code attempts are incorrect.
df <- df %>% group_by(Treatment) %>% mutate(Accumulated.deposits = cumsum(lag(New.deposit, n=1, default=0))*(1-0.046))

df <- df %>% group_by(Treatment) %>% mutate(Accumulated.deposits = cumsum((lag(Accumulated.deposits, n=1, default=0)*(1-0.046))) + new.deposit

My goal is to have one variable, Accumulated.biomass.yearY = deposit.year0 *  (1-0.046)^(Y) + deposit.year1 * (1-0.046)^(Y-1) + deposit.year2 * (1-0.046)^(Y-2)..... deposit.yearY * (1-0.046)^(Y-Y).
</code>```

I would love an matrix showing amount of remaining biomass from each years deposit at year X.

答:
Welcome to stackoverflow. Can you try something like this? I like to break out the steps so it's easier to see what's happening. If I didn't understand it fully, leave a comment and I'll update my answer. You can also use this example dataframe in your question and show us the output you would like to see so we can follow along.

library(tidyverse)

df <-
  tibble(
    treatment = rep(LETTERS[1:2], 5),
    years = rep(0:4, each = 2),
    new_deposit = rep(1:5*10, each = 2)
  ) %>%
  arrange(treatment, years, new_deposit)

df %>%
  arrange(treatment, years) %>%
  group_by(treatment) %>%
  mutate(
    prev_deposit = lag(new_deposit, default = 0),
    running_sum = cumsum(prev_deposit),
    accumulated = running_sum * (1-0.046)^(years)
  ) %>%
  ungroup()

#  treatment years new_deposit prev_deposit running_sum accumulated
#  <chr>     <int>       <dbl>        <dbl>       <dbl>       <dbl>
#  A             0          10            0           0        0
#  A             1          20           10          10        9.54
#  A             2          30           20          30       27.3
#  A             3          40           30          60       52.1
#  A             4          50           40         100       82.8
```

Body:
I'm trying to model the accumulation of biomass from dead wood deposited anually. The wood decays at a rate of 4.6% each year.

My data is formatted:

Cols: Treatment, Year, New.deposit
Treatment (A, B, C...)
Year (0:105)
New.deposit (numeric)

For the past few days, I've tried a combination of functions looking roughly as follows, but ended up with wrong combinations - maybe I'm making things too difficult:

#OBS! These code attempts are incorrect.
df <- df %>% group_by(Treatment) %>% mutate(Accumulated.deposits = cumsum(lag(New.deposit, n=1, default=0))*(1-0.046))

df <- df %>% group_by(Treatment) %>% mutate(Accumulated.deposits = cumsum((lag(Accumulated.deposits, n=1, default=0)*(1-0.046))) + new.deposit

My goal is to have one variable, Accumulated.biomass.yearY = deposit.year0 *  (1-0.046)^(Y) + deposit.year1 * (1-0.046)^(Y-1) + deposit.year2 * (1-0.046)^(Y-2)..... deposit.yearY * (1-0.046)^(Y-Y).

I would love an matrix showing amount of remaining biomass from each years deposit at year X.


问:
Error with importing self defined function
When I try to import a function from a file, it doesn't recognize the module that I imported earlier, while when its defined directly then there is no problem. </p>

<p>The module is imported as sr. Should I import it body of the function or is there any other trick. </p>

```<code>    # doesn't work
    import speech_recognition as sr
    r = sr.Recognizer()

    from Chatfunctions import Listner

    Listner()
    ---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-720eb32cc560> in <module>()
      7
      8
----> 9 Listner()
     10

/Users/michalczapski/Bots/BI Bot/Chatfunctions.py in Listner()
     12     print("Botty: ",message)
     13     return None
---> 14
     15 def Listner():
     16     with sr.Microphone() as source:

NameError: name 'sr' is not defined

    # works
    import speech_recognition as sr
    r = sr.Recognizer()

    def Listner():
        with sr.Microphone() as source:
            print("...")
            audio=r.listen(source)

          try:
            print("You: "+r.recognize_google(audio));
            return r.recognize_google(audio)
          except:
            pass;
    Listner()
</code>```

答: All the modules used in the imported functions need to be imported in the file in which functions are defined</p>

Body:
When I try to import a function from a file, it doesn't recognize the module that I imported earlier, while when its defined directly then there is no problem.

The module is imported as sr. Should I import it body of the function or is there any other trick.

    # doesn't work
    import speech_recognition as sr
    r = sr.Recognizer()

    from Chatfunctions import Listner

    Listner()
    ---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-720eb32cc560> in <module>()
      7
      8
----> 9 Listner()
     10

/Users/michalczapski/Bots/BI Bot/Chatfunctions.py in Listner()
     12     print("Botty: ",message)
     13     return None
---> 14
     15 def Listner():
     16     with sr.Microphone() as source:

NameError: name 'sr' is not defined

    # works
    import speech_recognition as sr
    r = sr.Recognizer()

    def Listner():
        with sr.Microphone() as source:
            print("...")
            audio=r.listen(source)

          try:
            print("You: "+r.recognize_google(audio));
            return r.recognize_google(audio)
          except:
            pass;
    Listner()


问:
How to fix C++ error: expected unqualified-id
I'm getting this error on line 6:

```<code>error: expected unqualified-id before '{' token
</code>```

I can't tell what's wrong.

```<code>#include <iostream>

using namespace std;

class WordGame;
{               // <== error is here on line 6
public:

    void setWord( string word )
    {
        theWord = word;
    }
    string getWord()
    {
        return theWord;
    }
    void displayWord()
    {
        cout << "Your word is " << getWord() << endl;
    }
private:
    string theWord;
}

int main()
{
    string aWord;
    WordGame theGame;
    cin >> aWord;
    theGame.setWord(aWord);
    theGame.displaymessage();

}
</code>```

答:
For what it's worth, I had the same problem but it wasn't because of an extra semicolon, it was because I'd forgotten a semicolon on the previous statement.

My situation was something like

```<code>mynamespace::MyObject otherObject

for (const auto& element: otherObject.myVector) {
  // execute arbitrary code on element
  //...
  //...
}
</code>```

From this code, my compiler kept telling me:

error: expected unqualified-id before for (const auto& element: otherObject.myVector) {
etc...

which I'd taken to mean I'd writtten the for loop wrong. Nope! I'd simply forgotten a ; after declaring otherObject.

Body:
I'm getting this error on line 6:

error: expected unqualified-id before '{' token

I can't tell what's wrong.

#include <iostream>

using namespace std;

class WordGame;
{               // <== error is here on line 6
public:

    void setWord( string word )
    {
        theWord = word;
    }
    string getWord()
    {
        return theWord;
    }
    void displayWord()
    {
        cout << "Your word is " << getWord() << endl;
    }
private:
    string theWord;
}

int main()
{
    string aWord;
    WordGame theGame;
    cin >> aWord;
    theGame.setWord(aWord);
    theGame.displaymessage();

}

Body:
For what it's worth, I had the same problem but it wasn't because of an extra semicolon, it was because I'd forgotten a semicolon on the previous statement.

My situation was something like

mynamespace::MyObject otherObject

for (const auto& element: otherObject.myVector) {
  // execute arbitrary code on element
  //...
  //...
}

From this code, my compiler kept telling me:

error: expected unqualified-id before for (const auto& element: otherObject.myVector) {
etc...

which I'd taken to mean I'd writtten the for loop wrong. Nope! I'd simply forgotten a ; after declaring otherObject.


问:
Count Non-Substring Overlapping
Write a program allows user to input a string. End the program is printing out:

a. How many words that repeated itself.
For example: 'This is Jake and Jake is 24 years old'
The console must print out '4' because 'is' and 'Jake' are the word that repeated

b. Remove all the repeated word. Print out the rest: 'This and 24 years old'

c. Print out which repeated words have been removed

So the idea is the user can type whatever they want, 'This is Jake and Jake is 24 years old' is just an example. The hardest part is how can console check all the repeated words without a substring?

答:
Does this work?
Here is what I am doing.

First I grab the user input, then I convert the string to a list splitting on spaces between words. Then I count the occurence of the words, if the wordcount is greater than 1, I add it to a dictionary , where the key is the word and the value is the count of the words that exist in the string.
After printing out the repeated words, I remove the strings that find a mention in the dictionary.

Note - This code can be improved so much but I purposely did it such a manner to make it easier to understand. You should not be using this code if its a production system.

```<code>string = input("Enter your string : ")

items = {}
words = string.split(" ")

for word in words:
    wordCount = words.count(word)
    if(wordCount > 1):
        items[word] = wordCount

print("There are {0} repeated words".format(len(items)))

updateString = ""
for item in items:
    updateString =string.replace(item,"")

print(updateString)
print(items)
</code>```

Updated

```<code>string = input("Enter your string : ")

items = {}
words = string.split(" ")

for word in words:
    wordCount = words.count(word)
    if(wordCount > 1):
        items[word] = wordCount

print("There are {0} repeated words".format(len(items)))

for item in items:
    string = string.replace(" {0} ".format(item)," ")

print(string)
print(items)
</code>```

Title: Count Non-Substring Overlapping

Body:
Does this work?
Here is what I am doing.

First I grab the user input, then I convert the string to a list splitting on spaces between words. Then I count the occurence of the words, if the wordcount is greater than 1, I add it to a dictionary , where the key is the word and the value is the count of the words that exist in the string.
After printing out the repeated words, I remove the strings that find a mention in the dictionary.

Note - This code can be improved so much but I purposely did it such a manner to make it easier to understand. You should not be using this code if its a production system.

string = input("Enter your string : ")

items = {}
words = string.split(" ")

for word in words:
    wordCount = words.count(word)
    if(wordCount > 1):
        items[word] = wordCount

print("There are {0} repeated words".format(len(items)))

updateString = ""
for item in items:
    updateString =string.replace(item,"")

print(updateString)
print(items)

Updated

string = input("Enter your string : ")

items = {}
words = string.split(" ")

for word in words:
    wordCount = words.count(word)
    if(wordCount > 1):
        items[word] = wordCount

print("There are {0} repeated words".format(len(items)))

for item in items:
    string = string.replace(" {0} ".format(item)," ")

print(string)
print(items)


问:
What is causing the first block of code to work but the second to return a syntax error?
I'm practicing Python with problems on a website and the my program is returning a Syntax error on Line 9, yet on the example answer to the problem provided on the website, the same line of code is that is in my program is working without error. Just curious as to what is causing the problem in my program? The point of the problem is to take numbers from 2 lists, find the even numbers from list one and finding the odd from list 2 and creating a 3rd list using the even and odds. I changed it up to find the even and odd from both and make both an even and an odd list pulling from both list one and two but I was thinking it should still work...

Pretty new to Python. Not quite sure what to even try.

Provided code from Website:

```<code>def mergeList(listOne, listTwo):
  thirdList = []
  for num in listOne:
    if(num % 2 != 0):
      thirdList.append(num)
  for num in listTwo:
    if(num % 2 == 0):
      thirdList.append(num)
  return thirdList

print("Merged List is")
listOne = [10, 20, 23, 11, 17]
listTwo = [13, 43, 24, 36, 12]
print(mergeList(listOne, listTwo))
</code>```

My code

```<code>list1 = [81, 71, 61, 34, 55]
list2 = [14, 19, 48, 32, 91]

def mergelist(list1, list2):
    mergedlist = list1 + list2
    even = []
    odd = []
    for num in mergedlist:
        if (num % 2 = 0):
            even.append(num)
            else:
            odd.append(num)
print("even: " + even)
print("odd: " + odd)
</code>```

My program should merge list 1 and 2 into one list, "mergedlist", and then search the list for even numbers and appending them to the even list. The non even numbers, odds, should be appended to the odd list. Then finally print both the even and odd lists. My program is saying that there is a syntax error on line 9.

答:
You have one equals sign, which is assignment, and can't be done in an if statement.

You need two equals signs, as the original had. And you don't need parens:

```<code>if num % 2 == 0:
</code>```

Body:
I'm practicing Python with problems on a website and the my program is returning a Syntax error on Line 9, yet on the example answer to the problem provided on the website, the same line of code is that is in my program is working without error. Just curious as to what is causing the problem in my program? The point of the problem is to take numbers from 2 lists, find the even numbers from list one and finding the odd from list 2 and creating a 3rd list using the even and odds. I changed it up to find the even and odd from both and make both an even and an odd list pulling from both list one and two but I was thinking it should still work...

Pretty new to Python. Not quite sure what to even try.

Provided code from Website:

def mergeList(listOne, listTwo):
  thirdList = []
  for num in listOne:
    if(num % 2 != 0):
      thirdList.append(num)
  for num in listTwo:
    if(num % 2 == 0):
      thirdList.append(num)
  return thirdList

print("Merged List is")
listOne = [10, 20, 23, 11, 17]
listTwo = [13, 43, 24, 36, 12]
print(mergeList(listOne, listTwo))

My code

list1 = [81, 71, 61, 34, 55]
list2 = [14, 19, 48, 32, 91]

def mergelist(list1, list2):
    mergedlist = list1 + list2
    even = []
    odd = []
    for num in mergedlist:
        if (num % 2 = 0):
            even.append(num)
            else:
            odd.append(num)
print("even: " + even)
print("odd: " + odd)

My program should merge list 1 and 2 into one list, "mergedlist", and then search the list for even numbers and appending them to the even list. The non even numbers, odds, should be appended to the odd list. Then finally print both the even and odd lists. My program is saying that there is a syntax error on line 9.

Body:
You have one equals sign, which is assignment, and can't be done in an if statement.

You need two equals signs, as the original had. And you don't need parens:

if num % 2 == 0:


问:
Facebook permissions in IE Causing infinite facebook loop
I am trying to get permissions for a facebook app I am making, but every time I try to run the app in IE8 I cannot get the permissions box to show up. I have tested the app in firefox and it can open fine, and get all the permissions fine (i dont ask for any special ones).

When I run the debugger in IE8 I see that once the program hits FB.getLoginStatus(function (response) { (see code below) it then moves into an infinite loop of code written by facebook.

I think the issue is because of how I am making the permissions call. I have a form that I use for a login that will call the permissions method once the user attempts to login to the site. Here is the form and button in the form I use:

```<code><form id = "membershipInfo" method = "post" action = "Login.aspx">
<input type = "button" id = "submitInfo" class = "MemberInfo" value = "Take Me There!" onclick = "authorize(acceptPermissions, rejectPermissions)"/>
</code>```

And here is the auth method I use:

```<code>function authorize(successCallback, failureCallback) {
FB.getLoginStatus(function (response) {
   //****** DOES NOT MAKE IT PAST HERE *******//
    if (response.session) {
        // logged in and connected user, carry on
        session = response.session;
        //Set access token
        accessToken = response.session.access_token;
        //Call success callback
        successCallback();
    } else {
        // no user session available, Lets ask for perms
        FB.ui(
        {
            method: 'permissions.request',
            perms: permissionString //(equals "" )
        },
        function (response) {
            if (response && response.session != null) {
                //Get session
                session = response.session;
                //Set access token
                accessToken = response.session.access_token;
                //Call success callback
                successCallback();
            } else {
                //Call failure callback
                failureCallback();
            }
        });
    }
});
</code>```

When the user accepts permissions they get moved into a success callback method which is here (never makes it this far):

```<code>function acceptPermissions() {
    //Code done before moving on
    $('#submitInfo').submit();
}
</code>```

Anyone see any issues?

答:
That looks like it should work to me, so probably a good opportunity to file a bug report with Facebook....

That said, I think you could clean up your code using FB.login instead http://developers.facebook.com/docs/reference/javascript/FB.login/

```<code>FB.login(function(response){
    if(response.session){
        // logged in and connected user, carry on
        session = response.session;
        //Set access token
        accessToken = response.session.access_token;
        //Call success callback
        successCallback();
    }
    else{
        failureCallback();
    }
}, {perms: permissionString});
</code>```

Body:
I am trying to get permissions for a facebook app I am making, but every time I try to run the app in IE8 I cannot get the permissions box to show up. I have tested the app in firefox and it can open fine, and get all the permissions fine (i dont ask for any special ones).

When I run the debugger in IE8 I see that once the program hits FB.getLoginStatus(function (response) { (see code below) it then moves into an infinite loop of code written by facebook.

I think the issue is because of how I am making the permissions call. I have a form that I use for a login that will call the permissions method once the user attempts to login to the site. Here is the form and button in the form I use:

<form id = "membershipInfo" method = "post" action = "Login.aspx">
<input type = "button" id = "submitInfo" class = "MemberInfo" value = "Take Me There!" onclick = "authorize(acceptPermissions, rejectPermissions)"/>

And here is the auth method I use:

function authorize(successCallback, failureCallback) {
FB.getLoginStatus(function (response) {
   //****** DOES NOT MAKE IT PAST HERE *******//
    if (response.session) {
        // logged in and connected user, carry on
        session = response.session;
        //Set access token
        accessToken = response.session.access_token;
        //Call success callback
        successCallback();
    } else {
        // no user session available, Lets ask for perms
        FB.ui(
        {
            method: 'permissions.request',
            perms: permissionString //(equals "" )
        },
        function (response) {
            if (response && response.session != null) {
                //Get session
                session = response.session;
                //Set access token
                accessToken = response.session.access_token;
                //Call success callback
                successCallback();
            } else {
                //Call failure callback
                failureCallback();
            }
        });
    }
});

When the user accepts permissions they get moved into a success callback method which is here (never makes it this far):

function acceptPermissions() {
    //Code done before moving on
    $('#submitInfo').submit();
}

Anyone see any issues?

Body:
That looks like it should work to me, so probably a good opportunity to file a bug report with Facebook....

That said, I think you could clean up your code using FB.login instead http://developers.facebook.com/docs/reference/javascript/FB.login/

FB.login(function(response){
    if(response.session){
        // logged in and connected user, carry on
        session = response.session;
        //Set access token
        accessToken = response.session.access_token;
        //Call success callback
        successCallback();
    }
    else{
        failureCallback();
    }
}, {perms: permissionString});


问:
Takes too long to export data from bigquery into Jupyter notebook
In the Jupyter Notebook, I am trying to import data from BigQuery using an sql-like query on the BigQuery server. I then store the data in a dataframe:

```<code>import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="credentials.json"
from google.cloud import bigquery

sql = """
SELECT * FROM dataset.table
"""
client = bigquery.Client()
df_bq = client.query(sql).to_dataframe()
</code>```

The data has the shape (6000000, 8) and uses about 350MB of memory once stored in the dataframe.

The query sql, if executed directly in BQ, takes about 2 seconds.

However, it usually takes about 30-40 minutes to execute the code above, and more often than not the code fails to execute raising the following error:

```<code>ConnectionError: ('Connection aborted.', OSError("(10060, 'WSAETIMEDOUT')",))
</code>```

All in all, there could be three reasons for the error:

It takes the BigQuery server a long time to execute the query

It takes a long time to transfer data (I don't understand why a 350MB file should take 30min to be sent over the network. I tried using a LAN connection to eliminate server cuts and maximize throughput, which didn't help)

It takes a long time to set a dataframe with the data from BigQuery

Would be happy to gain any insight into the problem, thanks in advance!

答:
The WSAETIMEDOUT error means that the connected party did not properly respond after a period of time. You need to review your firewall.

Regarding:

the query takes 2 seconds as you tested

review your firewall

as your data shape is (6000000, 8), this will take time depending on the computing resources you are using

This being said, you might reach the connection time out because the multidimensional array takes too long.

You can separate the query and the dataframe and print the time to have a better view of what is happening.

```<code>    result = client.query(sql)
    print(datetime.datetime.now())
    df_bq = result.to_dataframe()
    print(datetime.datetime.now())
</code>```

Body:
In the Jupyter Notebook, I am trying to import data from BigQuery using an sql-like query on the BigQuery server. I then store the data in a dataframe:

import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="credentials.json"
from google.cloud import bigquery

sql = """
SELECT * FROM dataset.table
"""
client = bigquery.Client()
df_bq = client.query(sql).to_dataframe()

The data has the shape (6000000, 8) and uses about 350MB of memory once stored in the dataframe.

The query sql, if executed directly in BQ, takes about 2 seconds.

However, it usually takes about 30-40 minutes to execute the code above, and more often than not the code fails to execute raising the following error:

ConnectionError: ('Connection aborted.', OSError("(10060, 'WSAETIMEDOUT')",))

All in all, there could be three reasons for the error:

It takes the BigQuery server a long time to execute the query

It takes a long time to transfer data (I don't understand why a 350MB file should take 30min to be sent over the network. I tried using a LAN connection to eliminate server cuts and maximize throughput, which didn't help)

It takes a long time to set a dataframe with the data from BigQuery

Would be happy to gain any insight into the problem, thanks in advance!

Body:
The WSAETIMEDOUT error means that the connected party did not properly respond after a period of time. You need to review your firewall.

Regarding:

the query takes 2 seconds as you tested

review your firewall

as your data shape is (6000000, 8), this will take time depending on the computing resources you are using

This being said, you might reach the connection time out because the multidimensional array takes too long.

You can separate the query and the dataframe and print the time to have a better view of what is happening.

    result = client.query(sql)
    print(datetime.datetime.now())
    df_bq = result.to_dataframe()
    print(datetime.datetime.now())