问:
If a GET request's response changes, is idempotency respected?
I am reading a lot about rest API and I always stumble upon terms idempotency. Basically GET, HEAD, PUT, DELETE and OPTIONS are all idempotent, and POST is not.

This statement on http://www.restapitutorial.com/lessons/idempotency.html made me doubt my understanding of idempotency.

From a RESTful service standpoint, for an operation (or service call)
  to be idempotent, clients can make that same call repeatedly while
  producing the same result. In other words, making multiple identical
  requests has the same effect as making a single request. Note that
  while idempotent operations produce the same result on the server (no
  side effects), the response itself may not be the same (e.g. a
  resource's state may change between requests).

So does idempotency actually has something to do with server-work or a response?

What confuses me if I have

```<code>GET /users/5
</code>```

returning

```<code>{
"first_name" : "John",
"last_name" : "Doe",
"minutes_active": 10
}
</code>```

and then do the same request after one minute I would get

```<code>GET /users/5
{
"first_name" : "John",
"last_name" : "Doe",
"minutes_active": 11
}
</code>```

How is this idempotent?

Furthermore if response contains some kind of UUID which is unique for each response, would that break idempotency?

And finally, is idempotency same server-work over and over again, or same results over and over again for the same/single request?

答:
For understanding idempotency in REST, your best starting point is probably going to be the definition include in RFC 7231

A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request.

For "effect", think side effect.  When the server is advertising that a particular action is idempotent, it is telling you that the (semantically significant) side effects will happen at most once.

```<code>// the guarantee of an idempotent operation
oldState.andThen(PUT(newState)) === oldState.andThen(PUT(newState)).andThen(PUT(newState))
</code>```

Safe methods are inherently idempotent, because they have no effect on the server.

```<code>// the guarantee of a safe operation
oldState === oldState.andThen(GET)
</code>```

// therefore, the guarantee of an idempotent operation follows trivially
oldState.andThen(GET) == oldState.andThen(GET).andThen(GET)

So does idempotency actually has something to do with server-work or a response?

Server work.  More generally, its a constraint on the receiver of a command to change state.

Roy Fielding shared this observation in 2002:

HTTP does not attempt to require the results of a GET to be safe.  What it does is require that the semantics of the operation be safe, and therefore it is a fault of the implementation, not the interface or the user of that interface, if anything happens as a result that causes loss of property (money, BTW, is considered property for the sake of this definition).

If you substitute PUT/DELETE for GET, and idempotent for safe, I think you get a good picture -- if a loss of property occurs because the server received two copies of an idempotent request, the fault is that the server handled the request improperly, not that the client broadcast the request more than once.

This is important because it allows for at least once delivery over an unreliable network.  From RFC 7231

Idempotent methods are distinguished because the request can be repeated automatically if a communication failure occurs before the client is able to read the server's response.

Contrast this with POST; which does not promise idempotent handling.  Submitting a web form twice may produce two side effects on the server, so the client implementations (and intermediary components, like proxies) cannot assume it is safe to repeat a lost request.

Back in the day, dialogs like this were common

for precisely this reason

And finally, is idempotency same server-work over and over again, or same results over and over again for the same/single request?

Work on the server.  An idempotent change is analogous to SET, or REPLACE (aka, compare and swap).

The responses may, of course, be different.  A conditional PUT, for example, will include meta data "indicating a precondition to be tested before applying the method semantics to the target resource."

So the server might change state in response to the receiving the first copy of a put, sending back 200 OK to indicate to the client that the request was successful; but upon receiving the second request, the server will find that the now-changed state of the resource no longer matches the provided meta data, and will respond with 412 Precondition Failed.

I noticed you mentioned may produce in "Contrast this with POST; which does not promise idempotent handling. Submitting a web form twice may produce two side effects on the server....." basically rest standards declare POST as non-idempotent, but one could actually make POST an idempotent, but it would be opposite to rest standards...

No, that's not quite right.  The HTTP specification does not require that POST support idempotent semantics -- which means that clients and intermediaries are not permitted to assume that it does.  The server controls its own implementation; it may provide idempotent handling of the POST request.

But the server has no way to advertise this capability to the clients (or intermediaries), so that they can take advantage of it.

Body:
I am reading a lot about rest API and I always stumble upon terms idempotency. Basically GET, HEAD, PUT, DELETE and OPTIONS are all idempotent, and POST is not.

This statement on http://www.restapitutorial.com/lessons/idempotency.html made me doubt my understanding of idempotency.

From a RESTful service standpoint, for an operation (or service call)
  to be idempotent, clients can make that same call repeatedly while
  producing the same result. In other words, making multiple identical
  requests has the same effect as making a single request. Note that
  while idempotent operations produce the same result on the server (no
  side effects), the response itself may not be the same (e.g. a
  resource's state may change between requests).

So does idempotency actually has something to do with server-work or a response?

What confuses me if I have

GET /users/5

returning

{
"first_name" : "John",
"last_name" : "Doe",
"minutes_active": 10
}

and then do the same request after one minute I would get

GET /users/5
{
"first_name" : "John",
"last_name" : "Doe",
"minutes_active": 11
}

How is this idempotent?

Furthermore if response contains some kind of UUID which is unique for each response, would that break idempotency?

And finally, is idempotency same server-work over and over again, or same results over and over again for the same/single request?

Body:
For understanding idempotency in REST, your best starting point is probably going to be the definition include in RFC 7231

A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request.

For "effect", think side effect.  When the server is advertising that a particular action is idempotent, it is telling you that the (semantically significant) side effects will happen at most once.

// the guarantee of an idempotent operation
oldState.andThen(PUT(newState)) === oldState.andThen(PUT(newState)).andThen(PUT(newState))

Safe methods are inherently idempotent, because they have no effect on the server.

// the guarantee of a safe operation
oldState === oldState.andThen(GET)

// therefore, the guarantee of an idempotent operation follows trivially
oldState.andThen(GET) == oldState.andThen(GET).andThen(GET)

So does idempotency actually has something to do with server-work or a response?

Server work.  More generally, its a constraint on the receiver of a command to change state.

Roy Fielding shared this observation in 2002:

HTTP does not attempt to require the results of a GET to be safe.  What it does is require that the semantics of the operation be safe, and therefore it is a fault of the implementation, not the interface or the user of that interface, if anything happens as a result that causes loss of property (money, BTW, is considered property for the sake of this definition).

If you substitute PUT/DELETE for GET, and idempotent for safe, I think you get a good picture -- if a loss of property occurs because the server received two copies of an idempotent request, the fault is that the server handled the request improperly, not that the client broadcast the request more than once.

This is important because it allows for at least once delivery over an unreliable network.  From RFC 7231

Idempotent methods are distinguished because the request can be repeated automatically if a communication failure occurs before the client is able to read the server's response.

Contrast this with POST; which does not promise idempotent handling.  Submitting a web form twice may produce two side effects on the server, so the client implementations (and intermediary components, like proxies) cannot assume it is safe to repeat a lost request.

Back in the day, dialogs like this were common

for precisely this reason

And finally, is idempotency same server-work over and over again, or same results over and over again for the same/single request?

Work on the server.  An idempotent change is analogous to SET, or REPLACE (aka, compare and swap).

The responses may, of course, be different.  A conditional PUT, for example, will include meta data "indicating a precondition to be tested before applying the method semantics to the target resource."

So the server might change state in response to the receiving the first copy of a put, sending back 200 OK to indicate to the client that the request was successful; but upon receiving the second request, the server will find that the now-changed state of the resource no longer matches the provided meta data, and will respond with 412 Precondition Failed.

I noticed you mentioned may produce in "Contrast this with POST; which does not promise idempotent handling. Submitting a web form twice may produce two side effects on the server....." basically rest standards declare POST as non-idempotent, but one could actually make POST an idempotent, but it would be opposite to rest standards...

No, that's not quite right.  The HTTP specification does not require that POST support idempotent semantics -- which means that clients and intermediaries are not permitted to assume that it does.  The server controls its own implementation; it may provide idempotent handling of the POST request.

But the server has no way to advertise this capability to the clients (or intermediaries), so that they can take advantage of it.


来源: stackexchange

问:
OpenGL float precision makes unexpected differece
I have a function which rotates the camera around the player by yaw and pitch angles.

```<code>void Camera::updateVectors() {
    GLfloat radius = glm::length(center - position);
    position.x = cos(glm::radians(this->yaw)) * cos(glm::radians(this->pitch));
    position.y = sin(glm::radians(this->pitch));
    position.z = sin(glm::radians(this->yaw)) * cos(glm::radians(this->pitch));
    position *= radius;
    this->front = glm::normalize(center - position);
    this->right = glm::normalize(glm::cross(this->front, this->worldUp));
    this->up = glm::normalize(glm::cross(this->right, this->front));
    lookAt = glm::lookAt(this->position, this->position + this->front, this->up);
}
</code>```

When I move the player the camera should moves with it by adding a translation vector to both the center and position of the camera:

```<code>void Camera::Transform(glm::vec3& t) {
    this->position += t;
    this->center += t;
}
</code>```

Vefore moving the player the camera rotation works fine and the player movement also works fine but once I try to rotate the camera after player moving it start to change position unexpected.

After making some debugging I noticed that the radius which Is calculated at first line which is the distance between center and position of the camera like 49.888889 or 50.000079 and due to the initialized values it should be 50.0, this very small difference makes the result unexpected at all.
so how could I treat this float precision or is there a bug in my code or calculations.

Edit:
 position the player depends on its yaw and pitch and update the center of the camera

```<code>GLfloat velocity = this->movementSpeed * deltaTime;
if (direction == FORWARD) {
    glm::vec3 t = glm::vec3(sin(glm::radians(yaw)), sin(glm::radians(pitch)), cos(glm::radians(yaw))) * velocity;
    matrix = glm::translate(matrix, t);
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
    glm::vec3 f(matrix[2][0], matrix[2][1], matrix[2][2]);
    f *= velocity;
    scene->getDefCamera()->Transform(f);
}
if (direction == BACKWARD) {
    glm::vec3 t = glm::vec3(sin(glm::radians(yaw)), 0.0, cos(glm::radians(yaw))) * velocity;
    matrix = glm::translate(matrix, -t);
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
    glm::vec3 f(matrix[2][0], matrix[2][1], matrix[2][2]);
    f *= velocity;
    f = -f;
    scene->getDefCamera()->Transform(f);
}
</code>```

答:
The main problem here is that you're rotating based on a position that is moving. But rotations are based on the origin of the coordinate system. So when you move the position, the rotation is still being done relative to the origin.

Instead of having Transform offset the position, it should only offset the center. Indeed, storing position makes no sense; you compute the camera's position based on its current center point, the radius, and the angles of rotation. The radius is a property that should be stored, not computed.

ContentLicense: CC BY-SA 3.0

Body:
I have a function which rotates the camera around the player by yaw and pitch angles.

void Camera::updateVectors() {
    GLfloat radius = glm::length(center - position);
    position.x = cos(glm::radians(this->yaw)) * cos(glm::radians(this->pitch));
    position.y = sin(glm::radians(this->pitch));
    position.z = sin(glm::radians(this->yaw)) * cos(glm::radians(this->pitch));
    position *= radius;
    this->front = glm::normalize(center - position);
    this->right = glm::normalize(glm::cross(this->front, this->worldUp));
    this->up = glm::normalize(glm::cross(this->right, this->front));
    lookAt = glm::lookAt(this->position, this->position + this->front, this->up);
}

When I move the player the camera should moves with it by adding a translation vector to both the center and position of the camera:

void Camera::Transform(glm::vec3& t) {
    this->position += t;
    this->center += t;
}

Vefore moving the player the camera rotation works fine and the player movement also works fine but once I try to rotate the camera after player moving it start to change position unexpected.

After making some debugging I noticed that the radius which Is calculated at first line which is the distance between center and position of the camera like 49.888889 or 50.000079 and due to the initialized values it should be 50.0, this very small difference makes the result unexpected at all.
so how could I treat this float precision or is there a bug in my code or calculations.

Edit:
 position the player depends on its yaw and pitch and update the center of the camera

GLfloat velocity = this->movementSpeed * deltaTime;
if (direction == FORWARD) {
    glm::vec3 t = glm::vec3(sin(glm::radians(yaw)), sin(glm::radians(pitch)), cos(glm::radians(yaw))) * velocity;
    matrix = glm::translate(matrix, t);
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
    glm::vec3 f(matrix[2][0], matrix[2][1], matrix[2][2]);
    f *= velocity;
    scene->getDefCamera()->Transform(f);
}
if (direction == BACKWARD) {
    glm::vec3 t = glm::vec3(sin(glm::radians(yaw)), 0.0, cos(glm::radians(yaw))) * velocity;
    matrix = glm::translate(matrix, -t);
    for (GLuint i = 0; i < this->m_Entries.size(); i++) {
        this->m_Entries[i].setModelMatrix(matrix);
    }
    glm::vec3 f(matrix[2][0], matrix[2][1], matrix[2][2]);
    f *= velocity;
    f = -f;
    scene->getDefCamera()->Transform(f);
}


问:
SSH Key - Still asking for password and passphrase
I've been somewhat 'putting up' with Github always asking for my username and password when I clone a repository.  I want to bypass this step because it is an annoyance within my workflow.

I tried setting up an SSH key (which I successfully did) using this guide. https://help.github.com/articles/generating-ssh-keys and I was successful.

My problem is that I am still asked for my github password and passphrase when cloning a repository (using SSH).  My understanding was that after I set up this SSH key, I would no longer have to do that.

I am a little unsure what to ask, so I will just state my goal.

I want to be able to clone repositories without having to put in my Github information all the time.

What am I missing with my SSH key? If anyone can provide some guidance or resources I would appreciate it, because I've always felt a little lost when it came to SSH authentication in GitHub.

From my knowledge, this is a command that tests if things are working properly, here are the output from my console:

```<code>~ $ ssh -T git@github.com
Saving password to keychain failed
Enter passphrase for key '/Users/MYNAME/.ssh/id_rsa':
Hi MYNAME! You've successfully authenticated, but GitHub does not provide shell access.
</code>```

When I input my password, should that fail first? Then, when I enter my passphrase, it passes.

答: Use ssh remote url provided by Github not https.

Body:
I've been somewhat 'putting up' with Github always asking for my username and password when I clone a repository.  I want to bypass this step because it is an annoyance within my workflow.

I tried setting up an SSH key (which I successfully did) using this guide. https://help.github.com/articles/generating-ssh-keys and I was successful.

My problem is that I am still asked for my github password and passphrase when cloning a repository (using SSH).  My understanding was that after I set up this SSH key, I would no longer have to do that.

I am a little unsure what to ask, so I will just state my goal.

I want to be able to clone repositories without having to put in my Github information all the time.

What am I missing with my SSH key? If anyone can provide some guidance or resources I would appreciate it, because I've always felt a little lost when it came to SSH authentication in GitHub.

From my knowledge, this is a command that tests if things are working properly, here are the output from my console:

~ $ ssh -T git@github.com
Saving password to keychain failed
Enter passphrase for key '/Users/MYNAME/.ssh/id_rsa':
Hi MYNAME! You've successfully authenticated, but GitHub does not provide shell access.

When I input my password, should that fail first? Then, when I enter my passphrase, it passes.


问:
superagent post vs put in react
```<code>var request = require('superagent');
var url = 'api/server';
request.put(url)
    .set('Content-Type', 'application/json')
    .send('{"name":"tj","pet":"tobi"}')
    .end(function(err, res){
        if (err) throw err;
        console.log(res.text);
    });
</code>```

above is the code that i use for upload data. If I change put into post, it's not working. I don't know why is that, can anyone help?

Also, actually I want to upload a file. But I cannot use put with .attach('theFile', file) . I've search a lot of example but none of them work for me.

答:
The server handling your request reads both the route (api/server) and the method to determine what response to return. If it's not configured to accept POST requests for that particular route, the request will fail.

Also, superagent does not allow you to use attach and send in the same request. Instead of send use field:

```<code>.field('name', 'tj')
.field('pet', 'tobi')
</code>```

Read the docs for more details.

Title: superagent post vs put in react

Body:
var request = require('superagent');
var url = 'api/server';
request.put(url)
    .set('Content-Type', 'application/json')
    .send('{"name":"tj","pet":"tobi"}')
    .end(function(err, res){
        if (err) throw err;
        console.log(res.text);
    });

above is the code that i use for upload data. If I change put into post, it's not working. I don't know why is that, can anyone help?

Also, actually I want to upload a file. But I cannot use put with .attach('theFile', file) . I've search a lot of example but none of them work for me.

Body:
The server handling your request reads both the route (api/server) and the method to determine what response to return. If it's not configured to accept POST requests for that particular route, the request will fail.

Also, superagent does not allow you to use attach and send in the same request. Instead of send use field:

.field('name', 'tj')
.field('pet', 'tobi')

Read the docs for more details.


问:
How to define an array with conditional elements?
How can I define conditional array elements?
I want to do something like this:

```<code>const cond = true;
const myArr = ["foo", cond && "bar"];
</code>```

This works as expected and results in ["foo", "bar"] but if I set cond to false, I get the following result: ["foo", false]

How can I define an array with a conditional element?

答:
Alternative approach: Pre-Filter populate instead of post filtering:

```<code>const populate = function(...values) {
    return values.filter(function(el) {
        return el !== false
    });
};

console.log(populate("foo", true && "bar", false && "baz"))
</code>```

Returns

```<code>(2) ["foo", "bar"]
</code>```

I know that does not solve the shorthand notation (since it won't work no matter what you try) but it comes close to that.

ContentLicense: CC BY-SA 4.0

Body:
How can I define conditional array elements?
I want to do something like this:

const cond = true;
const myArr = ["foo", cond && "bar"];

This works as expected and results in ["foo", "bar"] but if I set cond to false, I get the following result: ["foo", false]

How can I define an array with a conditional element?

Body:
Alternative approach: Pre-Filter populate instead of post filtering:

const populate = function(...values) {
    return values.filter(function(el) {
        return el !== false
    });
};

console.log(populate("foo", true && "bar", false && "baz"))

Returns

(2) ["foo", "bar"]

I know that does not solve the shorthand notation (since it won't work no matter what you try) but it comes close to that.


问:
Alamofire module not compiling with Swift 3.0.1
I have an Xcode project in Swift 3.0.1, and am getting this error upon trying to build:

Module compiled with Swift 3.0 cannot be imported in Swift 3.0.1: <path_to_project>/Alamofire.framework/Modules/Alamofire.swiftmodule/x86_64.swiftmodule

I've referenced this question: Module compiled with swift 3.0 cannot be imported in Swift 3.0.1, but the selected answer did not work.

The contents of my Cartfile is simply:
github "Alamofire/Alamofire"

Thanks in advance for your help.

答:
You may have multiple Xcode.

check your xcode path

```<code>xcode-select --print-path
</code>```

check your swift version

```<code>xcrun swift --version
</code>```

carthage will build based on the swift version that printed in terminal by above command.

Solution

```<code>sudo xcode-select --switch <your new Xcode path>

carthage update --no-use-binaries --platform iOS
</code>```

Body:
You may have multiple Xcode.

check your xcode path

xcode-select --print-path

check your swift version

xcrun swift --version

carthage will build based on the swift version that printed in terminal by above command.

Solution

sudo xcode-select --switch <your new Xcode path>

carthage update --no-use-binaries --platform iOS


问:
Redux: Updating state with a list
I am fetching a list of objects from a database and curious how I should map over them to update state using Redux.

I've mostly followed the egghead tutorial, but that dealt with updating state with one object at a time.

Assuming I'm starting with an empty list [] and and I make a fetch() call to a server that returns a list of objects [Object1, Object2, Object3].

I'm struggling to understand the data flow and theoretically how should I do this.

I realized the code below doesn't work, but I'm trying to suggest how I'm trying to make this work in hopes someone can help me finish it..

How do I write the reducer that will map over the results of fetchServerData() and call todo and add everything to the state object?

```<code>const candidate = (state, action) => {
    switch (action.type) {
        case 'ADD_CANDIDATE':
            return {
                id: action.id,
                first: action.first,
                last: action.last,
                title: action.title,
                company: action.company,
                sent_inmail_date: action.sent_inmail_date,
                response: action.response
            }

        default:
            return state
    }
}

const mapOverObject = (listObject, action) => {
    ??
}

const store = createStore(mapOverObject)

const fetchServerData = () => {
    const URL  = 'http://localhost:5000/get_db'
    return fetch(URL)
        .then((response) => response.json())
        .then((responseJson) => {
            return responseJson
        });
}

const TodoApp = (props) => {
    return (
        <div>
            <button onClick = {() => fetchServerData() }> Get Server Data </button>

        </div>
    )
}

ReactDOM.render(
    <Provider store={store} >
        <TodoApp />
    </Provider>,
    document.getElementById('root')
)
</code>```

答:
You don't need the map over the array.
When you get the responseJson,  you dispatch an action with the data ( you can send directly the whole array ). Then your reducer can update directly the store with it.

You would need to map over the array, if for example you'd want to get rid of some fields inside the objects. But again you can do that in your reducer.

Title: Redux: Updating state with a list

Body:
I am fetching a list of objects from a database and curious how I should map over them to update state using Redux.

I've mostly followed the egghead tutorial, but that dealt with updating state with one object at a time.

Assuming I'm starting with an empty list [] and and I make a fetch() call to a server that returns a list of objects [Object1, Object2, Object3].

I'm struggling to understand the data flow and theoretically how should I do this.

I realized the code below doesn't work, but I'm trying to suggest how I'm trying to make this work in hopes someone can help me finish it..

How do I write the reducer that will map over the results of fetchServerData() and call todo and add everything to the state object?

const candidate = (state, action) => {
    switch (action.type) {
        case 'ADD_CANDIDATE':
            return {
                id: action.id,
                first: action.first,
                last: action.last,
                title: action.title,
                company: action.company,
                sent_inmail_date: action.sent_inmail_date,
                response: action.response
            }

        default:
            return state
    }
}

const mapOverObject = (listObject, action) => {
    ??
}

const store = createStore(mapOverObject)

const fetchServerData = () => {
    const URL  = 'http://localhost:5000/get_db'
    return fetch(URL)
        .then((response) => response.json())
        .then((responseJson) => {
            return responseJson
        });
}

const TodoApp = (props) => {
    return (

            <button onClick = {() => fetchServerData() }> Get Server Data </button>

    )
}

ReactDOM.render(
    <Provider store={store} >
        <TodoApp />
    </Provider>,
    document.getElementById('root')
)


问:
Redis: weird protocol/network errors
I'm running Redis and connecting from Ruby using ezmobius's Redis gem[1].

Periodically (about once a day) I get a series of exceptions in my Rails app caused by Redis returning strange results.

They are often triggered by an exception such at this:

```<code>Redis::ProtocolError: Protocol error, got '3' as initial reply byte
</code>```

or

```<code>Redis::ProtocolError: Protocol error, got '9' as initial reply byte
</code>```

or sometimes

```<code>Errno::EAGAIN: Resource temporarily unavailable - Timeout reading from the socket
</code>```

It usually requires a restart of my Rails servers to clear up the connection problem. I'm running Fedora Core 8, Rails 2.3.8, Redis gem 2.0.3. I've got the system_timer gem installed. Anybody got any ideas how I can stop these errors?

[1]Redis gem

答:
When initializing the connection, make sure to pass the :thread_safe option:

```<code>Redis.connect(:thread_safe => true)
</code>```

ContentLicense: CC BY-SA 2.5

Title: Redis: weird protocol/network errors

Body:
I'm running Redis and connecting from Ruby using ezmobius's Redis gem[1].

Periodically (about once a day) I get a series of exceptions in my Rails app caused by Redis returning strange results.

They are often triggered by an exception such at this:

Redis::ProtocolError: Protocol error, got '3' as initial reply byte

or

Redis::ProtocolError: Protocol error, got '9' as initial reply byte

or sometimes

Errno::EAGAIN: Resource temporarily unavailable - Timeout reading from the socket

It usually requires a restart of my Rails servers to clear up the connection problem. I'm running Fedora Core 8, Rails 2.3.8, Redis gem 2.0.3. I've got the system_timer gem installed. Anybody got any ideas how I can stop these errors?

[1]Redis gem

Body:
When initializing the connection, make sure to pass the :thread_safe option:

Redis.connect(:thread_safe => true)


问:
pandas equals mysterious behavior
I'm writing some unit tests, but it keeps failing when the dataframes are equal in every regard. After some investigating, I found that

```<code>a.equals( a[ a.columns ] )
</code>```

is false, where a is the dataframe I've manually created. What reason could there be for that?

edit:
I figured out that the issue is related to creating the df with a mixed type list:

```<code>a = pd.DataFrame( [['a',1],['b',2]] )
</code>```

Even though the list is mixed, the dtypes for the columns are correct.

答:
The DataFrame column types are not the same.

```<code>a = pd.DataFrame( [['a',1],['b',2]] )
print type(a[ a.columns ].columns)
print type(a.columns)

<class 'pandas.indexes.numeric.Int64Index'>
<class 'pandas.indexes.range.RangeIndex'>
</code>```

Moreover

```<code>print type(a[ a.columns ].columns[0])
print type(a.columns[0])

<type 'numpy.int64'>
<type 'int'>
</code>```

It is better to make sure the column types are the same.

Title: pandas equals mysterious behavior

Body:
I'm writing some unit tests, but it keeps failing when the dataframes are equal in every regard. After some investigating, I found that

a.equals( a[ a.columns ] )

is false, where a is the dataframe I've manually created. What reason could there be for that?

edit:
I figured out that the issue is related to creating the df with a mixed type list:

a = pd.DataFrame( [['a',1],['b',2]] )

Even though the list is mixed, the dtypes for the columns are correct.

Body:
The DataFrame column types are not the same.

a = pd.DataFrame( [['a',1],['b',2]] )
print type(a[ a.columns ].columns)
print type(a.columns)

<class 'pandas.indexes.numeric.Int64Index'>
<class 'pandas.indexes.range.RangeIndex'>

Moreover

print type(a[ a.columns ].columns[0])
print type(a.columns[0])

<type 'numpy.int64'>
<type 'int'>

It is better to make sure the column types are the same.


问:
How to share a value between all docker containers spun op by the same "docker-compose up" call?

Context

We are migrating an older application to docker and as a first step we're working against some constraints. The database can not yet be put in a container, and moreover, it is shared between all developers in our team. So this question is to find a fix for a temporary problem.

To not clash with other developers using the same database, there is a system in place where each developer machine starts the application with a value that is unique to his machine. Each container should use this same value.

Question

We are using docker-compose to start the containers. Is there a way to provide a (environment) variable to it that gets propagated to all containers?

How I'm trying to do it:

My docker-compose.yml looks kind of like this:

```<code>my_service:
    image: my_service:latest
    command: ./my_service.sh
    extends:
        file: base.yml
        service: base
    environment:
        - batch.id=${BATCH_ID}
</code>```

then I thought running BATCH_ID=$somevalue docker-compose up my_service would fill in the ${BATCH_ID}, but it doesn't seem to work that way.

Is there another way? A better way?

Optional: Ideally everything should be contained so that a developer can just call docker-compose up my_service leading to compose itself calculating a value to pass to all the containers. But from what I see online, I think this is not possible.

答:
I don't know what I changed, but suddenly it works as described.

BATCH_ID is the name of the environment variable on the host.

batch.id will be the name of the environment variable inside the container.

```<code>my_service:

    environment:
        - batch.id=${BATCH_ID}
</code>```

Body:
Context

We are migrating an older application to docker and as a first step we're working against some constraints. The database can not yet be put in a container, and moreover, it is shared between all developers in our team. So this question is to find a fix for a temporary problem.

To not clash with other developers using the same database, there is a system in place where each developer machine starts the application with a value that is unique to his machine. Each container should use this same value.

Question

We are using docker-compose to start the containers. Is there a way to provide a (environment) variable to it that gets propagated to all containers?

How I'm trying to do it:

My docker-compose.yml looks kind of like this:

my_service:
    image: my_service:latest
    command: ./my_service.sh
    extends:
        file: base.yml
        service: base
    environment:
        - batch.id=${BATCH_ID}

then I thought running BATCH_ID=$somevalue docker-compose up my_service would fill in the ${BATCH_ID}, but it doesn't seem to work that way.

Is there another way? A better way?

Optional: Ideally everything should be contained so that a developer can just call docker-compose up my_service leading to compose itself calculating a value to pass to all the containers. But from what I see online, I think this is not possible.

Body:
I don't know what I changed, but suddenly it works as described.

BATCH_ID is the name of the environment variable on the host.

batch.id will be the name of the environment variable inside the container.

my_service:

    environment:
        - batch.id=${BATCH_ID}


问:
Java 9 - Can I add the MainClass attribute to module-info.class in the archive?
In Java 9, you can create a JAR file with

```<code>jar --create --file=mlib/com.greetings.jar --main-class=com.greetings.Main -C mods/com.greetings .
</code>```

Which has the side effect of adding the MainClass attribute to the module-info.class file in the .jar file.

Do any of the plugins support this yet, or do I need to invoke the Java 9 'jar' command directly?

Is this the right forum to be asking these questions, or is there a better place?

Cheers, Eric

答: The 'module main class' is actually an attribute of the module-info.class file. It's called ModuleMainClass and set by the Java 9's jar command. The current version (3.0.2) of maven-jar-plugin only writes the file when you specify the manifest.mainClass

Body:
In Java 9, you can create a JAR file with

jar --create --file=mlib/com.greetings.jar --main-class=com.greetings.Main -C mods/com.greetings .

Which has the side effect of adding the MainClass attribute to the module-info.class file in the .jar file.

Do any of the plugins support this yet, or do I need to invoke the Java 9 'jar' command directly?

Is this the right forum to be asking these questions, or is there a better place?

Cheers, Eric


问:
Kendo grid drag and drop not working with less number of records
I have integrated kendo grid in my project with drag and drop functionality. I have issue that when there are no records in one grid then the drop functionality is not working as expected. I have to drop the record to one of the record available to work. I have created a sample for the functionality:
Kendo grid sample

Also, here is the screen shot for the issue:

答:
This is because you are specifying that the kendoDropTarget is on the grid table attribute (which would be specifically the content of the grid).

```<code>grid1.table.kendoDropTarget({...
</code>```

Change this to use the grid wrapper attribute, which encapsulates the entire grid control.

```<code>grid1.wrapper.kendoDropTarget({
</code>```

Here is a Dojo example to demonstrate the above.

Body:
This is because you are specifying that the kendoDropTarget is on the grid table attribute (which would be specifically the content of the grid).

grid1.table.kendoDropTarget({...

Change this to use the grid wrapper attribute, which encapsulates the entire grid control.

grid1.wrapper.kendoDropTarget({

Here is a Dojo example to demonstrate the above.


问:
How to insert value into foreign key in SQL server? (Avoid the duplicate key.)
I create two table. They connected by primary key and foreign key. When I insert new values, it said cannot insert duplicate key in object. Here are my tables

```<code>create table person (
sinNum int primary key not null,
gender varchar(6) not null check (gender in ('male','female')) default 'female',
age int not null check (age>=18 and age<=100),
emailAddr varchar (50) not null,
phoneNum int not null,
)

create table employee (
empId int identity (1,1) unique,
lastName varchar (30) not null,
firstName varchar (30) not null,
sinNum int unique foreign key references person (sinNum),
departmentId int foreign key references department (departmentId),
position varchar (20) not null check (position in ('clerk','assistant','supervisor','manager','director','president')) default'clerk',
baseSalary float not null
)
</code>```

Here are my insert statements

```<code>insert into person (sinNum,gender,age,emailAddr, phoneNum) values (333,
'female', 24, 'dds', 2121)

insert into employee(lastName,firstName, sinNum, departmentId,
position,baseSalary) values ('Snow','John',333,20,'clerk',4000)
</code>```

Here are the error messages

Violation of PRIMARY KEY constraint 'PK__person__228E26BE3A9512B2'.
  Cannot insert duplicate key in object 'dbo.person'. The duplicate key
  value is (333).

Can anyone show me the way please? Many thanks

答:
What's happening here is that your insert on Person table is violating the primary key constraint. So we can use this exception as an antidote.

You can make use of Try-Catch statement and can implement your further logic in the catch block.

```<code>/* You an use @output parameter too */
Declare @output bit=1

BEGIN TRY
    insert into person (sinNum,gender,age,emailAddr, phoneNum) values (333,
    'female', 24, 'dds', 2121)

    insert into employee(lastName,firstName, sinNum, departmentId,
    position,baseSalary) values ('Snow','John',333,20,'clerk',4000)

    print 'Record inserted in both table'

set @output=1
END TRY

BEGIN CATCH
 if error_message() like 'Violation of PRIMARY KEY constraint%'
    Begin

    /* Do whatever you like to do here */
    /* You can delete the existing record if you want */

     print 'Record already exists is Person table' --just the intimation
     set @output=0

    End

 else
    print 'other exception'       --just the intimation

END CATCH
</code>```

You can delete the existing record in catch block or can make new transaction using @output variable.. Hope it works for you.

Body:
I create two table. They connected by primary key and foreign key. When I insert new values, it said cannot insert duplicate key in object. Here are my tables

create table person (
sinNum int primary key not null,
gender varchar(6) not null check (gender in ('male','female')) default 'female',
age int not null check (age>=18 and age<=100),
emailAddr varchar (50) not null,
phoneNum int not null,
)

create table employee (
empId int identity (1,1) unique,
lastName varchar (30) not null,
firstName varchar (30) not null,
sinNum int unique foreign key references person (sinNum),
departmentId int foreign key references department (departmentId),
position varchar (20) not null check (position in ('clerk','assistant','supervisor','manager','director','president')) default'clerk',
baseSalary float not null
)

Here are my insert statements

insert into person (sinNum,gender,age,emailAddr, phoneNum) values (333,
'female', 24, 'dds', 2121)

insert into employee(lastName,firstName, sinNum, departmentId,
position,baseSalary) values ('Snow','John',333,20,'clerk',4000)

Here are the error messages

Violation of PRIMARY KEY constraint 'PK__person__228E26BE3A9512B2'.
  Cannot insert duplicate key in object 'dbo.person'. The duplicate key
  value is (333).

Can anyone show me the way please? Many thanks

Body:
What's happening here is that your insert on Person table is violating the primary key constraint. So we can use this exception as an antidote.

You can make use of Try-Catch statement and can implement your further logic in the catch block.

/* You an use @output parameter too */
Declare @output bit=1

BEGIN TRY
    insert into person (sinNum,gender,age,emailAddr, phoneNum) values (333,
    'female', 24, 'dds', 2121)

    insert into employee(lastName,firstName, sinNum, departmentId,
    position,baseSalary) values ('Snow','John',333,20,'clerk',4000)

    print 'Record inserted in both table'

set @output=1
END TRY

BEGIN CATCH
 if error_message() like 'Violation of PRIMARY KEY constraint%'
    Begin

    /* Do whatever you like to do here */
    /* You can delete the existing record if you want */

     print 'Record already exists is Person table' --just the intimation
     set @output=0

    End

 else
    print 'other exception'       --just the intimation

END CATCH

You can delete the existing record in catch block or can make new transaction using @output variable.. Hope it works for you.


问:
frequent bug in UI (tabbar pushed from navigation)
I have encountered this bug several times. I have a application with a navigation controller (navbar hidden). when a button is "pressed" i want to push another view with a tabbarviewcontroller. When the new view is pushed, it's 20 pixels lower than it should (and part of the tabbar is not visible).

If I enter modal-view controller from the tabbarviewcontroller and then i dismiss it, the tabbarviewcontroller is shown properly.

I put the status bar in every view to be unspecified (thought that was the problem) and i un-checked the autoresize subviews from each view.

答:
thank you for your answers. i did it somehow, playing with the tabbar's frame a bit.

```<code>[self.tabBarController.view setFrame:CGRectMake(0, 0, 320, 460)];
[self.view addSubview:tabBarController.view];
[self.view bringSubviewToFront:tabBarController.view];
</code>```

i remember trying this a while ago and not working. now it did.
also, medling with bounds helped a bit.

Body:
thank you for your answers. i did it somehow, playing with the tabbar's frame a bit.

[self.tabBarController.view setFrame:CGRectMake(0, 0, 320, 460)];
[self.view addSubview:tabBarController.view];
[self.view bringSubviewToFront:tabBarController.view];

i remember trying this a while ago and not working. now it did.
also, medling with bounds helped a bit.


问:
Apply Zoom In Zoom out feature by clicking dropdown list any value
current screen is here. i m showing some locations in the map.locations are basically markers ,you can see markers in this picture.what i want to do is,,,

when i change the dropdownlist value i want to zoom in the chart where i can easily see one of the marker position after clicking some another dropdownlist value like when i click on PG & E the google map will zoom in to the specific marker. i will share my code with you. most importantly i am using kml file to load the map on the screen.

```<code><script>
function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 1,
        mapTypeId: google.maps.MapTypeId.HYBRID
        //   center: {lat: 41.876, lng: -87.624}
    });

    var ctaLayer = new google.maps.KmlLayer({url:'https://sites.google.com/site/kmzmap1/plm/868l_little%20falls-st%20stephens%202%20.kmz?attredirects=0&d=1',
        map: map
    });
}
</code>```

```<code><script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</code>```

and my html code is .....

```<code><div id="map" style="width:100%;height:478px;"></div>
</code>```

答:
You will need to use JQuery to achieve this. I will work through an example.

Define a Select box:

```<code><select>
 <option >Choose...</option>
  <option value="in">zoom in</option>
  <option value="out">zoom out</option>
</select>
</code>```

We then need to ensure that the map is globally defined so we can access anywyere within the

Body:
You will need to use JQuery to achieve this. I will work through an example.

Define a Select box:

<select>
 <option >Choose...</option>
  <option value="in">zoom in</option>
  <option value="out">zoom out</option>
</select>

We then need to ensure that the map is globally defined so we can access anywyere within the <script> aspect of the page

var map;

then assign your map to that variable map = new google...

We then use jquery to listen to the select box and perform some sort of action:

$('select').on('change', function() {
    var optionSelected = $("option:selected", this);
    var valueSelected = this.value;
    if(valueSelected == 'in'){
      map.setZoom(17);
    }
    if(valueSelected == 'out'){
    map.setZoom(4);
    map.panTo(new google.maps.LatLng(33.818038, -117.928492));
    }
})

optionSelected gets the value of this select box (having multiple you probably be best basing this on ID rather than generic select).

valueSelected is the value of this selected item (in my example in or out).

we then call what to do; if in we increase the zoom in, if out we zoom out and pan to a coordinate (this could be a marker).

JSFiddle : http://jsfiddle.net/4mtyu/2741/


问:
import com.firebase.client.Firebase in Android 2.3.3
I am creating an application class to use Firebase in my complete application. However in the import line error occurs highlighting 'firebase' in red.
I have looked everywhere but cannot make out the problem.

Code:

```<code>package com.mobility.mobilityindia;
import android.app.Application;
import com.firebase.client.Firebase;  <--- firebase is red here

public class MobilityIndia2 extends Application{
   @Override
    public void onCreate() {
       super.onCreate();

       Firebase.setAndroidContext(this);  <----  Firebase is red here
   }
</code>```

app level gradle.build

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.0"
    defaultConfig
            {
                applicationId "com.mobility.mobilityindia"
                minSdkVersion 21
                targetSdkVersion 26
                versionCode 1
                versionName "1.0"
                testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
            }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    String googleSupportVersion = '26.+'
    String googlePlayServicesVersion = '11.0.2'
    compile "com.google.firebase:firebase-core:$googlePlayServicesVersion"
    compile "com.google.firebase:firebase-auth:$googlePlayServicesVersion"
    compile "com.android.support:appcompat-v7:$googleSupportVersion"
    compile "com.android.support:support-v4:$googleSupportVersion"
    compile "com.google.android.gms:play-services:$googlePlayServicesVersion"
    compile "com.android.support:design:$googleSupportVersion"
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
}
apply plugin: 'com.google.gms.google-services'
</code>```

top level gradle

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.1.0'

    }
}
</code>```

答:
The code you have is for an old version of the Firebase SDK (1.x or 2.x), while you're importing the latest version.

If you follow the latest documentation or the latest Android codelab, you won't need the Firebase.setAndroidContext() anymore and will get imports that start with com.google.firebase.

Body:
I am creating an application class to use Firebase in my complete application. However in the import line error occurs highlighting 'firebase' in red.
I have looked everywhere but cannot make out the problem.

Code:

package com.mobility.mobilityindia;
import android.app.Application;
import com.firebase.client.Firebase;  <--- firebase is red here

public class MobilityIndia2 extends Application{
   @Override
    public void onCreate() {
       super.onCreate();

       Firebase.setAndroidContext(this);  <----  Firebase is red here
   }

app level gradle.build

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.0"
    defaultConfig
            {
                applicationId "com.mobility.mobilityindia"
                minSdkVersion 21
                targetSdkVersion 26
                versionCode 1
                versionName "1.0"
                testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
            }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    String googleSupportVersion = '26.+'
    String googlePlayServicesVersion = '11.0.2'
    compile "com.google.firebase:firebase-core:$googlePlayServicesVersion"
    compile "com.google.firebase:firebase-auth:$googlePlayServicesVersion"
    compile "com.android.support:appcompat-v7:$googleSupportVersion"
    compile "com.android.support:support-v4:$googleSupportVersion"
    compile "com.google.android.gms:play-services:$googlePlayServicesVersion"
    compile "com.android.support:design:$googleSupportVersion"
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
}
apply plugin: 'com.google.gms.google-services'

top level gradle

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.1.0'

    }
}


问:
How to do Push Notification in Xamarin Forms
I am working on Xamarin forms. I had been searching for Push notification in Xamarin forms, some said there is no such implementation for Xamarin forms but there are Xamarin.iOS and Xamarin.Android. I am a newbie I may miss many development news on this subject.

I would like to know:

1) Is there any latest development for Xamarin forms for Push Notification?

2) Any sample app to learn from , any tutorial for xamarin form?

3) What are requirements to build this kind of app, what SDK or tools required.

Please help

答:
I'm assuming you are talking about Azure push notifications.
If that's the case there is a detailed Xamarin guide to help you for this matter:
https://developer.xamarin.com/guides/xamarin-forms/cloud-services/push-notifications/azure/

Also checkout the sidebar since that also include interesting posts about this service.

Good Luck


问:
Gradle dependencies to add gif library
I am using the  these dependencies:

```<code>  compile 'com.felipecsl:gifimageview:2.1.0'
  compile 'commons-io:commons-io:2.4'
</code>```

But it couldn't resolve the first one. I'm using Android Studio 2.3.2.

答:
Do you know Glide? It's like Picasso, a library to load an image into an ImageView, but it's "recommended by Google". Anyway, this library is similar to Picasso, but the difference is the ability to load a gif :)

Why not giving a try ? You can follow this stackoverflow example given by another member: Displaying GIF in ImageView using Glide

Title: Gradle dependencies to add gif library

Body:
I am using the  these dependencies:

  compile 'com.felipecsl:gifimageview:2.1.0'
  compile 'commons-io:commons-io:2.4'

But it couldn't resolve the first one. I'm using Android Studio 2.3.2.


问:
Error - trustAnchors parameter must be non-empty
I'm trying to configure my e-mail on Jenkins/Hudson, and I constantly receive the error:

```<code>java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be
    non-empty
</code>```

I've seen a good amount of information online about the error, but I have not gotten any to work. I'm using Sun's JDK on Fedora Linux (not OpenJDK).

Here are a few things I've tried. I tried following the advice from this post, but copying the cacerts from Windows over to my Fedora box hosting Jenkins didn't work.  I tried following this guide as I'm trying to configure Gmail as my SMTP server, but it didn't work either. I also tried to download and move those cacert files manually and move them over to my Java folder using a variation of the commands on this guide.

I am open to any suggestions as I'm currently stuck right now. I have gotten it to work from a Windows Hudson server, but I am struggling on Linux.

答:
You may also encounter this error after upgrading to Spring Boot 1.4.1 (or newer) because it brings along Tomcat 8.5.5 as part of its dependencies.

The problem is due to the way that Tomcat deals with the trust store. If you happen to have specified your trust store location as the same as your keystore in the Spring Boot configuration, you'll likely get the trustAnchors parameter must be non-empty message when starting the application.

```<code>server.ssl.key-store=classpath:server.jks
server.ssl.trust-store=classpath:server.jks
</code>```

Simply remove the server.ssl.trust-store configuration unless you know that you need it, in which case consult the links below.

The following issues contain more details about the problem:

HTTPS Tomcat connector fails to start with 1.4.1 #7069

SSL-client-auth with self-signed cert stopped working #7406

Upgrade to Tomcat 8.5.5 #6703

Body:
I'm trying to configure my e-mail on Jenkins/Hudson, and I constantly receive the error:

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be
    non-empty

I've seen a good amount of information online about the error, but I have not gotten any to work. I'm using Sun's JDK on Fedora Linux (not OpenJDK).

Here are a few things I've tried. I tried following the advice from this post, but copying the cacerts from Windows over to my Fedora box hosting Jenkins didn't work.  I tried following this guide as I'm trying to configure Gmail as my SMTP server, but it didn't work either. I also tried to download and move those cacert files manually and move them over to my Java folder using a variation of the commands on this guide.

I am open to any suggestions as I'm currently stuck right now. I have gotten it to work from a Windows Hudson server, but I am struggling on Linux.

Body:
You may also encounter this error after upgrading to Spring Boot 1.4.1 (or newer) because it brings along Tomcat 8.5.5 as part of its dependencies.

The problem is due to the way that Tomcat deals with the trust store. If you happen to have specified your trust store location as the same as your keystore in the Spring Boot configuration, you'll likely get the trustAnchors parameter must be non-empty message when starting the application.

server.ssl.key-store=classpath:server.jks
server.ssl.trust-store=classpath:server.jks

Simply remove the server.ssl.trust-store configuration unless you know that you need it, in which case consult the links below.

The following issues contain more details about the problem:

HTTPS Tomcat connector fails to start with 1.4.1 #7069

SSL-client-auth with self-signed cert stopped working #7406

Upgrade to Tomcat 8.5.5 #6703


问:
Deleting an app in iTunes Connect
Apple has introduced the possibility of deleting an app. Quoting the iTunes Connect guide:

If you have created an app in iTunes
  Connect that you no longer need to see
  or manage, you can delete it from your
  iTunes Connect view. Deleting your app
  will not allow you to re-use your SKU
  or App Name and you will not be able
  to restore your app once deleted.

So far so good. Then it gets slightly confusing:

If you are selling your app to another
  developer for their own distribution
  and need to remove it from your iTunes
  Connect account, we recommend that you
  use App Delete so the App Name will be
  freed up for their use.

Does this mean that I won't be able to reuse the name in my account, but other accounts will? Has anybody tried this?

答:
Please see Removing an App From Sale (page 92) section on iTunes Connect Developer Guide 6.3

Click "Rights and Pricing"

Go to the sale territories section. There is a link near the end

Click on the "Deselect all" button to uncheck all App Store territories.

Click on the "Save Changes" button.

After removing all assigned territory checkboxes from your app in the Rights and Pricing section,, the status
changes to Developer Removed from Sale and your app will not be seen on the App Store within 24 hours.

Title: Deleting an app in iTunes Connect


问:
Google analytics. Different platforms of same app. Same tracking code or different?
I have the same app in different platforms (MyApp for Android and MyApp for iOS). Google suggests using different properties in this case. HERE is the link to google's suggestion.

But I would like to go against google's recommendation and use the same tracking property. Using the same tracking property,  I can view data from multiple platforms together in one place. If I want to view data for one platform, I can create multiple views and view separated data as well.

As I am going against google's recommended approach, I am worried a little. Did anyone do this before? Are there any problems I will face using this setup. Can someone give more information on why google recommends this approach?

答: I will suggest using same tracking id for both platforms. It's easy to see difference between platforms. Example from within the behaviour flow:


问:
XSLT Transform from a Generic Model to a Specific Model
I am trying to convert a XML form that is sent to my backend using a generic model to the internal XML model the system uses using XSLT.

The generic model consists of sections, lines and tables (a table is basically an array/group of elements). The PK's are from the sequence for the tableRow and the maxPK is a count. MaxPK I can probably populate afterwards, not sure if that is possible through XSLT.

Any help would be appreciated!

Generic Model

```<code>    <form>
    <section>
        <name>identification</name>
        <sequence>1</sequence>
        <line>
            <sequence>0</sequence>
            <field>
                <name>firstName</name>
                <value>JOHN</value>
            </field>
        </line>
        <line>
            <sequence>1</sequence>
            <field>
                <name>lastName</name>
                <value>DOE</value>
            </field>
        </line>
    </section>
    <section>
        <name>contactDetails</name>
        <sequence>1</sequence>
        <line>
            <sequence>0</sequence>
            <field>
                <name>primaryPhone</name>
                <value>+44 100 1234</value>
            </field>
        </line>
        <table>
            <name>secondaryPhoneGroup</name>
            <tableRow>
                <sequence>1</sequence>
                <field>
                    <sequence>0</sequence>
                    <name>secondaryPhone</name>
                    <value>+44 100 1235</value>
                </field>
            </tableRow>
            <tableRow>
                <sequence>2</sequence>
                <field>
                    <sequence>0</sequence>
                    <name>secondaryPhone</name>
                    <value>+44 100 1236</value>
                </field>
            </tableRow>
        </table>
    </section>
</form>
</code>```

Internal Model

```<code><form>
    <identification>
        <firstName>
            <asCurrent>JOHN</asCurrent>
        </firstName>
        <lastName>
            <asCurrent>DOE</asCurrent>
        </lastName>
    </identification>
    <contactDetails>
        <primaryPhone>
            <asCurrent>+44 100 1234</asCurrent>
        </primaryPhone>
        <secondaryPhoneGroup>
            <secondaryPhone>
                <pk>1</pk>
                <phone>
                    <asCurrent>+44 100 1235</asCurrent>
                </phone>
            </secondaryPhone>
            <secondaryPhone>
                <pk>2</pk>
                <phone>
                    <asCurrent>+44 100 1236</asCurrent>
                </phone>
            </secondaryPhone>
            <maxPK>2</maxPK>
        </secondaryPhoneGroup>
    </contactDetails>
</form>
</code>```

答:
Try along the following lines:</p>

```<code><xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="line">
        <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="sequence"/>

    <xsl:template match="section | field">
        <xsl:element name="{name}">
            <xsl:apply-templates select="* except name"/>
        </xsl:element>
    </xsl:template>

    <xsl:template match="*[name]/value">
        <asCurrent>
            <xsl:apply-templates/>
        </asCurrent>
    </xsl:template>

    <xsl:template match="table">
        <xsl:element name="{name}">
            <xsl:apply-templates select="* except name"/>
            <maxPK>
                <xsl:value-of select="count(tableRow)"/>
            </maxPK>
        </xsl:element>
    </xsl:template>

    <xsl:template match="tableRow">
        <xsl:element name="{field/name}">
            <xsl:apply-templates select="* except name"/>
        </xsl:element>
    </xsl:template>

    <xsl:template match="tableRow/sequence">
        <pk>
            <xsl:apply-templates/>
        </pk>
    </xsl:template>

    <xsl:template match="tableRow/field[name = 'secondaryPhone']">
        <phone>
            <xsl:apply-templates select="value"/>
        </phone>
    </xsl:template>

</xsl:transform>
</code>```

Body:
I am trying to convert a XML form that is sent to my backend using a generic model to the internal XML model the system uses using XSLT.

The generic model consists of sections, lines and tables (a table is basically an array/group of elements). The PK's are from the sequence for the tableRow and the maxPK is a count. MaxPK I can probably populate afterwards, not sure if that is possible through XSLT.

Any help would be appreciated!

Generic Model

    <form>

        <name>identification</name>
        <sequence>1</sequence>
        <line>
            <sequence>0</sequence>
            <field>
                <name>firstName</name>
                <value>JOHN</value>
            </field>
        </line>
        <line>
            <sequence>1</sequence>
            <field>
                <name>lastName</name>
                <value>DOE</value>
            </field>
        </line>

        <name>contactDetails</name>
        <sequence>1</sequence>
        <line>
            <sequence>0</sequence>
            <field>
                <name>primaryPhone</name>
                <value>+44 100 1234</value>
            </field>
        </line>

            <name>secondaryPhoneGroup</name>
            <tableRow>
                <sequence>1</sequence>
                <field>
                    <sequence>0</sequence>
                    <name>secondaryPhone</name>
                    <value>+44 100 1235</value>
                </field>
            </tableRow>
            <tableRow>
                <sequence>2</sequence>
                <field>
                    <sequence>0</sequence>
                    <name>secondaryPhone</name>
                    <value>+44 100 1236</value>
                </field>
            </tableRow>

</form>

Internal Model

<form>
    <identification>
        <firstName>
            <asCurrent>JOHN</asCurrent>
        </firstName>
        <lastName>
            <asCurrent>DOE</asCurrent>
        </lastName>
    </identification>
    <contactDetails>
        <primaryPhone>
            <asCurrent>+44 100 1234</asCurrent>
        </primaryPhone>
        <secondaryPhoneGroup>
            <secondaryPhone>
                <pk>1</pk>
                <phone>
                    <asCurrent>+44 100 1235</asCurrent>
                </phone>
            </secondaryPhone>
            <secondaryPhone>
                <pk>2</pk>
                <phone>
                    <asCurrent>+44 100 1236</asCurrent>
                </phone>
            </secondaryPhone>
            <maxPK>2</maxPK>
        </secondaryPhoneGroup>
    </contactDetails>
</form>

Body:
Try along the following lines:

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="line">
        <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="sequence"/>

    <xsl:template match="section | field">
        <xsl:element name="{name}">
            <xsl:apply-templates select="* except name"/>
        </xsl:element>
    </xsl:template>

    <xsl:template match="*[name]/value">
        <asCurrent>
            <xsl:apply-templates/>
        </asCurrent>
    </xsl:template>

    <xsl:template match="table">
        <xsl:element name="{name}">
            <xsl:apply-templates select="* except name"/>
            <maxPK>
                <xsl:value-of select="count(tableRow)"/>
            </maxPK>
        </xsl:element>
    </xsl:template>

    <xsl:template match="tableRow">
        <xsl:element name="{field/name}">
            <xsl:apply-templates select="* except name"/>
        </xsl:element>
    </xsl:template>

    <xsl:template match="tableRow/sequence">
        <pk>
            <xsl:apply-templates/>
        </pk>
    </xsl:template>

    <xsl:template match="tableRow/field[name = 'secondaryPhone']">
        <phone>
            <xsl:apply-templates select="value"/>
        </phone>
    </xsl:template>

</xsl:transform>


问:
Long difference between server response and browser result with includes
I have an action with this kind of code :

```<code>  Timesheet::WorkPeriod.includes(:ship).limit(2000).to_a
  render nothing: true
</code>```

The server answer gives :

```<code>method=GET path=/timesheet_reports/rest_hours format=html controller=Company::Timesheet::ReportsController action=rest_hours status=200 duration=2106.43 view=3.68 db=23.75
</code>```

But, in the browser, the rendering take 6 sec (for a blank) page. There is a difference of 4 seconds and it increase if I change 2000 for an higher value.

It's correct if I remove the includes or the to_a. It's the same if I do :

```<code>Timesheet::WorkPeriod.includes(:ship).limit(2000).each(&:id)
</code>```

Removing the includes is fastest even if there is a n+1 query problem.

I'm using ruby 2.3 and Rails 4.2.

I suppose there is a problem with memory allocation but I don't know how to to solve it. What can I do?

答:
Make sure that you relations are indexed. Moreover, use pluck instead of each.

```<code>Timesheet::WorkPeriod.includes(:ship).limit(2000).pluck(:id)
# Depending which ID you need
Timesheet::WorkPeriod.includes(:ship).limit(2000).pluck('ships.id')
</code>```

If indexes are fine, please double check if all data is necessary for you. If all you need from your relation is just an ID, feel free to use joins and select only the id.

```<code>Timesheet::WorkPeriod.joins(:ship).limit(2000).pluck('ships.id')
# You may also want left join
Timesheet::WorkPeriod
  .joins('LEFT OUTER JOIN ships ON ships.work_period_id = work_periods.ids')
  .limit(2000).pluck('ships.id')
</code>```

Body:
I have an action with this kind of code :

  Timesheet::WorkPeriod.includes(:ship).limit(2000).to_a
  render nothing: true

The server answer gives :

method=GET path=/timesheet_reports/rest_hours format=html controller=Company::Timesheet::ReportsController action=rest_hours status=200 duration=2106.43 view=3.68 db=23.75

But, in the browser, the rendering take 6 sec (for a blank) page. There is a difference of 4 seconds and it increase if I change 2000 for an higher value.

It's correct if I remove the includes or the to_a. It's the same if I do :

Timesheet::WorkPeriod.includes(:ship).limit(2000).each(&:id)

Removing the includes is fastest even if there is a n+1 query problem.

I'm using ruby 2.3 and Rails 4.2.

I suppose there is a problem with memory allocation but I don't know how to to solve it. What can I do?

Body:
Make sure that you relations are indexed. Moreover, use pluck instead of each.

Timesheet::WorkPeriod.includes(:ship).limit(2000).pluck(:id)
# Depending which ID you need
Timesheet::WorkPeriod.includes(:ship).limit(2000).pluck('ships.id')

If indexes are fine, please double check if all data is necessary for you. If all you need from your relation is just an ID, feel free to use joins and select only the id.

Timesheet::WorkPeriod.joins(:ship).limit(2000).pluck('ships.id')
# You may also want left join
Timesheet::WorkPeriod
  .joins('LEFT OUTER JOIN ships ON ships.work_period_id = work_periods.ids')
  .limit(2000).pluck('ships.id')


问:
Postgres plpgsql with PERFORM data-modifying CTE queries
I tried to simulate my problem in the code example below. In the code below, I am doing a delete from test2 in a procedure. This works great:

However, in my case, this delete is part of a rather complex CTE with several updates and inserts (there are no selects so I add a dummy select 1 as main query). Let's simulate this as this:

```<code>with my_cte as(delete from test2) select 1
</code>```

Now, as we know, we have to use the perform keyword to execute this:

```<code>perform (with my_cte as(delete from test2) select 1);
</code>```

I am getting the following error:

```<code>ERROR: WITH clause containing a data-modifying statement must be at the top level
</code>```

Is this a limitation of plpgsql?

(Please note that this is just an example to explain my problem. I know the queries do not really make any sense.)

```<code>create table test
(
    key int primary key
);

create table test2
(
    key int primary key
);

create function test() returns trigger as
$$
begin
    raise notice 'hello there';
    -- this does work
    delete from test2;
    -- this doesn't work
    perform (with my_cte as(delete from test2) select 1);
    return new;
end;
$$
language plpgsql;

create trigger test after insert on test for each row execute procedure test();

insert into test(key) select 1;
</code>```

答:
As you found out, you can neither nest such a WITH clause in a subselect, not can you do

```<code>WITH cte AS (...)
PERFORM 1;
</code>```

One solution would be to use SELECT ... INTO dummy instead of PERFORM and ignore the result.

But I don't see why you cannot code the DELETEs, UPDATEs and INSERTs in your function with several SQL statements rather than bundling them into CTEs.

If you try to protect yourself from concurrent data modification, use a REPEATABLE READ transaction so that all your statements operate on the same snapshot of the database.

Body:
I tried to simulate my problem in the code example below. In the code below, I am doing a delete from test2 in a procedure. This works great:

However, in my case, this delete is part of a rather complex CTE with several updates and inserts (there are no selects so I add a dummy select 1 as main query). Let's simulate this as this:

with my_cte as(delete from test2) select 1

Now, as we know, we have to use the perform keyword to execute this:

perform (with my_cte as(delete from test2) select 1);

I am getting the following error:

ERROR: WITH clause containing a data-modifying statement must be at the top level

Is this a limitation of plpgsql?

(Please note that this is just an example to explain my problem. I know the queries do not really make any sense.)

create table test
(
    key int primary key
);

create table test2
(
    key int primary key
);

create function test() returns trigger as
$$
begin
    raise notice 'hello there';
    -- this does work
    delete from test2;
    -- this doesn't work
    perform (with my_cte as(delete from test2) select 1);
    return new;
end;
$$
language plpgsql;

create trigger test after insert on test for each row execute procedure test();

insert into test(key) select 1;

Body:
As you found out, you can neither nest such a WITH clause in a subselect, not can you do

WITH cte AS (...)
PERFORM 1;

One solution would be to use SELECT ... INTO dummy instead of PERFORM and ignore the result.

But I don't see why you cannot code the DELETEs, UPDATEs and INSERTs in your function with several SQL statements rather than bundling them into CTEs.

If you try to protect yourself from concurrent data modification, use a REPEATABLE READ transaction so that all your statements operate on the same snapshot of the database.


问:
Cannot read property 'location' of undefined in React Router example
Trying to do the most simple example possible with React Router.
Every example I've looked at is very different and many include 20 page tutorials. I just want a simple root path to work:

```<code>...
<script src="https://unpkg.com/react@15.3.2/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15.3.2/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://npmcdn.com/react-router/umd/react-router.min.js"></script>
...

var insert_point = document.querySelector('#container');

var App = React.createClass({
  render: function() {
    return (
      <div>
        <h1>Simple SPA</h1>
        <ul>
          <li>Home</li>
          <li>Stuff</li>
          <li>Contact</li>
        </ul>
        <div>
        </div>
      </div>
    )
  }
});

ReactDOM.render(
  <ReactRouter.Router>
    <ReactRouter.Route path="/" component={App}>
    </ReactRouter.Route>
  </ReactRouter.Router>,
  insert_point
);
</code>```

答:
I suspect the problem is in how are you importing react router. When working with webpack I am using react-router-dom package and BrowserRouter

```<code>import { BrowserRouter as Router , Route, Switch} from 'react-router-dom'
</code>```

Which are correct packages for V4. So at least I think you should use cdn that provides react-router-dom

also Try to use BrowserRouter instead of Router.

Aside from this, you can close your Route component immediately

```<code><ReactRouter.Route path="/" component={App}/>
</code>```

Also I do not understand your intentions with insertion_point as they are in your code.

Body:
Trying to do the most simple example possible with React Router.
Every example I've looked at is very different and many include 20 page tutorials. I just want a simple root path to work:

...

...

var insert_point = document.querySelector('#container');

var App = React.createClass({
  render: function() {
    return (

Simple SPA

Home

Stuff

Contact

    )
  }
});

ReactDOM.render(
  <ReactRouter.Router>
    <ReactRouter.Route path="/" component={App}>
    </ReactRouter.Route>
  </ReactRouter.Router>,
  insert_point
);

Body:
I suspect the problem is in how are you importing react router. When working with webpack I am using react-router-dom package and BrowserRouter

import { BrowserRouter as Router , Route, Switch} from 'react-router-dom'

Which are correct packages for V4. So at least I think you should use cdn that provides react-router-dom

also Try to use BrowserRouter instead of Router.

Aside from this, you can close your Route component immediately

<ReactRouter.Route path="/" component={App}/>

Also I do not understand your intentions with insertion_point as they are in your code.


问:
Call to a member function getClientOriginalExtension() on null
Hello I am new to Laravel, I am developing a create form for posting where users can create a blog post basically with laravel however when I try to crate the post I am getting an error all the time:

```<code>Call to a member function getClientOriginalExtension() on null
</code>```

Here is my form:

```<code>@extends('master')

@section('content')

<h1>Selling your Home?</h1>

<form action="/flyers"  enctype="multpart/form-data" method="post"  >

  @inject('countries','App\Http\Utilities\Country')
  <div class="row">

  <div class="col-md-6 form-signin">
           {{csrf_field()}}
            <div class="form-group">

                <label for="street">Street:</label>

                <input type="text" name="street" id="street" class="form-control" value="{{old('street')}}" required>

            </div>

            <div class="form-group">

                <label for="city">City:</label>

                <input type="text" name="city" id="city" class="form-control" value="{{old('city')}}" required>

            </div>

            <div class="form-group">

                <label for="zip">Zip/ Postal Code:</label>

                <input type="text" name="zip" id="zip" class="form-control" value="{{old('zip')}}" required>

            </div>

            <div class="form-group">

                <label for="country">Country:</label>

                <select id="country" name="country" class="form-control" required>
                    @foreach($countries::all() as $country=>$code)

                    <option value="{{$code}}">{{$country}}</option>

                    @endforeach
                </select>

            </div>

             <div class="form-group">

                <label for="country">State</label>

                <input type="text" name="state" id="state" class="form-control" value="{{old('state')}}" required>

            </div>
  </div>

  <div class="col-md-6">

            <div class="form-group">

                <label for="price">Sale Price:</label>

                <input type="text" name="price" id="price" class="form-control" value="{{old('price')}}">

            </div>

             <div class="form-group">

                <label for="description">Home Description:</label>

                <textarea name="description" id="description" class ="form-control" cols="30" rows="10"  value="{{old('description')}}"></textarea>

            </div>

      </div>

      <div class="col-md-12">
        <hr>
        <div class="form-group">
                <button type="submit" class="btn btn-primary">Create Flyer</button>
            </div>
        </div>
</div>

</form>

@endsection
</code>```

答:
You are missing an 'i' on your code:

should be: enctype="multipart/form-data"

instead of:

```<code>enctype="multpart/form-data"
</code>```

Body:
Hello I am new to Laravel, I am developing a create form for posting where users can create a blog post basically with laravel however when I try to crate the post I am getting an error all the time:

Call to a member function getClientOriginalExtension() on null

Here is my form:

@extends('master')

@section('content')

Selling your Home?

<form action="/flyers"  enctype="multpart/form-data" method="post"  >

  @inject('countries','App\Http\Utilities\Country')

           {{csrf_field()}}

                Street:

                <input type="text" name="street" id="street" class="form-control" value="{{old('street')}}" required>

                City:

                <input type="text" name="city" id="city" class="form-control" value="{{old('city')}}" required>

                Zip/ Postal Code:

                <input type="text" name="zip" id="zip" class="form-control" value="{{old('zip')}}" required>

                Country:

                <select id="country" name="country" class="form-control" required>
                    @foreach($countries::all() as $country=>$code)

                    <option value="{{$code}}">{{$country}}</option>

                    @endforeach
                </select>

                State

                <input type="text" name="state" id="state" class="form-control" value="{{old('state')}}" required>

                Sale Price:

                <input type="text" name="price" id="price" class="form-control" value="{{old('price')}}">

                Home Description:

                <textarea name="description" id="description" class ="form-control" cols="30" rows="10"  value="{{old('description')}}"></textarea>

                <button type="submit" class="btn btn-primary">Create Flyer</button>

</form>

@endsection

Body:
You are missing an 'i' on your code:

should be: enctype="multipart/form-data"

instead of:

enctype="multpart/form-data"


问:
'No Entity Framework provider found' for EF 6 and SQLite 1.0.96.0
I realize there are already several similar questions on this topic, but many of them are from older version of SQLite which did not fully support EF 6 as far as I am aware. I have tried countless suggestions from these threads and am either doing something wrong or something must have changed.

I am using VS 2013, targeting .NET 4.5.1 and have installed the sqlite-netFx451-setup-bundle-x86-2013-1.0.96.0.exe package from the system.data.sqlite.org download page, as well as the System.Data.SQLite EF6 package from the NuGet Manager (which installs EF6).

Below is my current App.config file (it is pretty much untouched except I tried adding the Version, Culture, and Public key variables to the type):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6, Version=1.0.96.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
    </providers>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SQLite.EF6" />
      <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6, Version=1.0.96.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139"
      />
    </DbProviderFactories>
  </system.data>
</configuration>
```

<p>And my packages.config:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="EntityFramework" version="6.1.2" targetFramework="net451" />
  <package id="System.Data.SQLite.EF6" version="1.0.96.0" targetFramework="net451" />
</packages>
</code>```

If I do something such as attempt to Generate a Database from Model I see the following error:

No Entity Framework provider found for the ADO.NET provider with
  invariant name 'System.Data.SQLite.EF6'. Make sure the provider is registered in the 'entityFramework' section...

I've tried messing around the the App.config file and adding other providers and providers as old threads have suggested but to no avail.

How do I fix this problem? Any help is greatly appreciated!

Edit: I managed to get it to work well enough to use a database first approach. Here is the relevant parts of my App.config file:

<providers>
     <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>

<DbProviderFactories>
     <remove invariant="System.Data.SQLite" />
     <remove invariant="System.Data.SQLite.EF6" />
     <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
     <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
</DbProviderFactories>
```

I'm using EF 6.1.2 and System.Data.SQLite 1.0.96.0.

答:
```<code>public class EFConfiguration : DbConfiguration
{
    public EFConfiguration()
    {
        SetDefaultConnectionFactory(new LocalDbConnectionFactory("v.11"));

        //HACK
        var EF6ProviderServicesType = typeof(System.Data.SQLite.EF6.SQLiteProviderFactory).Assembly.DefinedTypes.First(x => x.Name == "SQLiteProviderServices");
        var EF6ProviderServices = (DbProviderServices)Activator.CreateInstance(EF6ProviderServicesType);
        SetProviderServices("System.Data.SQLite.EF6", EF6ProviderServices);
        SetProviderServices("System.Data.SqlClient", System.Data.Entity.SqlServer.SqlProviderServices.Instance);
        SetProviderFactory("System.Data.SQLite.EF6", System.Data.SQLite.EF6.SQLiteProviderFactory.Instance);
        SetProviderFactory("System.Data.SQLite", System.Data.SQLite.SQLiteFactory.Instance);
    }
}
</code>```

Body:
I realize there are already several similar questions on this topic, but many of them are from older version of SQLite which did not fully support EF 6 as far as I am aware. I have tried countless suggestions from these threads and am either doing something wrong or something must have changed.

I am using VS 2013, targeting .NET 4.5.1 and have installed the sqlite-netFx451-setup-bundle-x86-2013-1.0.96.0.exe package from the system.data.sqlite.org download page, as well as the System.Data.SQLite EF6 package from the NuGet Manager (which installs EF6).

Below is my current App.config file (it is pretty much untouched except I tried adding the Version, Culture, and Public key variables to the type):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6, Version=1.0.96.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
    </providers>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SQLite.EF6" />
      <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6, Version=1.0.96.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139"
      />
    </DbProviderFactories>
  </system.data>
</configuration>

And my packages.config:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="EntityFramework" version="6.1.2" targetFramework="net451" />
  <package id="System.Data.SQLite.EF6" version="1.0.96.0" targetFramework="net451" />
</packages>

If I do something such as attempt to Generate a Database from Model I see the following error:

No Entity Framework provider found for the ADO.NET provider with
  invariant name 'System.Data.SQLite.EF6'. Make sure the provider is registered in the 'entityFramework' section...

I've tried messing around the the App.config file and adding other providers and providers as old threads have suggested but to no avail.

How do I fix this problem? Any help is greatly appreciated!

Edit: I managed to get it to work well enough to use a database first approach. Here is the relevant parts of my App.config file:

<providers>
     <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>

<DbProviderFactories>
     <remove invariant="System.Data.SQLite" />
     <remove invariant="System.Data.SQLite.EF6" />
     <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
     <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
</DbProviderFactories>

I'm using EF 6.1.2 and System.Data.SQLite 1.0.96.0.


问:
Selenium (Java) message "Unable to locate element" but element and XPath exist
I am new to Selenium WebDriver, using NetBeans Java and Firebug for Firefox to get XPath.

The problem is even though some elements are visible and clickable in the browser, and Firebug finds the XPath expression, I still get an error "Unable to locate element". The problem is, the element is not in a frame (there aren’t any frames), not in another window, it's visible and clickable and it has a clear XPath expression.

I used Wait and Thread.sleep, but it didn't help.
Also, I tried all solutions I could find on Stack Overflow similar to this matter.

The element is inside of the table which has some "div" elements inside. This is the XPath expression:

```<code>.//*[@id='NavigationRadPanelBar_i2_i0_trvStandardView']/ul/li[3]/div/span[3]
</code>```

It seems that the panel is a problem, because it can not locate the panel too. I tried another element inside the same panel which has a title and text with this:

```<code>driver.findElement(By.xpath("//*[contains(text(),'Technical Attributes')]")).click();
</code>```

But still I got same message. Similar for all elements inside this panel and panel itself. It seems whatever I tried, it's unable to locate. Everything outside of this panel is working fine with drivers.

The page has a left panel where these elements are located. Some of them are nodes that can be expanded, and some are just links, but nothing can be located.

What can be the cause of element that is obviously existing and visible, but still cannot be located by WebDriver?

I tried to locate the main panel:

```<code>    driver.findElement(By.xpath(".//*[@id='NavigationRadPane']")).click();
</code>```

but still the same exception.

This is part of the HTML content (it's very long):

```<code><div id="RAD_SLIDING_PANE_CONTENT_navigatiionRadSlidingPane" class="rspSlideContent" style="overflow: hidden; width: 200px; height: 579px;">
  <div id="NavigationRadPanelBarPanel" style="display: block;">
    <div id="NavigationRadPanelBar" class="RadPanelBar RadPanelBar_Office2007" postback="false" style="background-color:GhostWhite;height:100%;width:100%;">
      <ul class="rpRootGroup">
        <li class="rpItem rpFirst">
          <li class="rpItem">
            <li class="rpItem rpLast">
              <a class="rpLink rpExpandable rpExpanded" href="#">
                <div class="rpSlide" style="display:block;">
                  <ul class="rpGroup rpLevel1 111460" style="display: block; height: 274.731px; width: 100%;">
                    <li class="rpItem rpFirst rpLast">
                      <div class="rpTemplate">
                        <div id="NavigationRadPanelBar_i2_i0_trvStandardView" class="RadTreeView RadTreeView_Office2007">
                          <ul class="rtUL rtLines">
                            <li class="rtLI rtFirst">
                              <li class="rtLI">
                                <li class="rtLI">
                                  <div class="rtMid">
                                    <span class="rtSp" />
                                    <span class="rtPlus rtPlusHover" />
                                    <img class="rtImg" src="..." alt="Technical Attributes" />
                                    <span class="rtIn" title="Technical Attributes">Technical Attributes</span>
                                  </div>
                                  <ul class="rtUL" style="display:none;">
                                </li>
                                <li class="rtLI rtLast">
</code>```

答:
Here is the answer to your question:

The error says it all, Unable to locate element, because the XPath expression seems incorrect to me.

If you want to click on the element with title set to Technical Attributes you can consider to try with the following XPath expressions:

//div[@id='NavigationRadPanelBar_i2_i0_trvStandardView']/ul/li/li/li/div/span[@class='rtIn']
```
<p>or</p>
<pre class="lang-none prettyprint-override"><code>//div[@id='NavigationRadPanelBar_i2_i0_trvStandardView']/ul/li/li/li/div/span[@title='Technical Attributes']
</code>```

Body:
I am new to Selenium WebDriver, using NetBeans Java and Firebug for Firefox to get XPath.

The problem is even though some elements are visible and clickable in the browser, and Firebug finds the XPath expression, I still get an error "Unable to locate element". The problem is, the element is not in a frame (there aren’t any frames), not in another window, it's visible and clickable and it has a clear XPath expression.

I used Wait and Thread.sleep, but it didn't help.
Also, I tried all solutions I could find on Stack Overflow similar to this matter.

The element is inside of the table which has some "div" elements inside. This is the XPath expression:

.//*[@id='NavigationRadPanelBar_i2_i0_trvStandardView']/ul/li[3]/div/span[3]

It seems that the panel is a problem, because it can not locate the panel too. I tried another element inside the same panel which has a title and text with this:

driver.findElement(By.xpath("//*[contains(text(),'Technical Attributes')]")).click();

But still I got same message. Similar for all elements inside this panel and panel itself. It seems whatever I tried, it's unable to locate. Everything outside of this panel is working fine with drivers.

The page has a left panel where these elements are located. Some of them are nodes that can be expanded, and some are just links, but nothing can be located.

What can be the cause of element that is obviously existing and visible, but still cannot be located by WebDriver?

I tried to locate the main panel:

    driver.findElement(By.xpath(".//*[@id='NavigationRadPane']")).click();

but still the same exception.

This is part of the HTML content (it's very long):

                                    Technical Attributes

Body:
Here is the answer to your question:

The error says it all, Unable to locate element, because the XPath expression seems incorrect to me.

If you want to click on the element with title set to Technical Attributes you can consider to try with the following XPath expressions:

//div[@id='NavigationRadPanelBar_i2_i0_trvStandardView']/ul/li/li/li/div/span[@class='rtIn']

or

//div[@id='NavigationRadPanelBar_i2_i0_trvStandardView']/ul/li/li/li/div/span[@title='Technical Attributes']


问:
Create array from PHP string
Let's say I have an string like

```<code>$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|SEM";
</code>```

and i want an array like:

```<code>array( array("title"=>"BKL", "value"=>bkl),
array("title"=>"EXH", "value"=>exh),
array("title"=>"FFV", "value"=>ffv),
array("title"=>"LEC", "value"=>lec),
array("title"=>"AUE", "value"=>aue),
array("title"=>"SEM", "value"=>SEM),
);
</code>```

I have found a solution here: How to create particular array from string in php but this is giving me an array like:

```<code>Array
(
    [BKL] => bkl
    [EXH] => exh
    [FFV] => ffv
    [LEC] => lec
    [AUE] => aue
    [SEM] => sem
)
</code>```

Thanks a lot.

答:
All you need to do is change the way the array is built up...</p>

```<code>$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";

$final = array();

foreach (explode(',', $str) as $pair) {
  list($key, $value) = explode('|', $pair);
  $final[] = ['title'=>$key, 'value'=>$value];
}

print_r($final);
</code>```

Title: Create array from PHP string

Body:
Let's say I have an string like

$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|SEM";

and i want an array like:

array( array("title"=>"BKL", "value"=>bkl),
array("title"=>"EXH", "value"=>exh),
array("title"=>"FFV", "value"=>ffv),
array("title"=>"LEC", "value"=>lec),
array("title"=>"AUE", "value"=>aue),
array("title"=>"SEM", "value"=>SEM),
);

I have found a solution here: How to create particular array from string in php but this is giving me an array like:

Array
(
    [BKL] => bkl
    [EXH] => exh
    [FFV] => ffv
    [LEC] => lec
    [AUE] => aue
    [SEM] => sem
)

Thanks a lot.

Body:
All you need to do is change the way the array is built up...

$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";

$final = array();

foreach (explode(',', $str) as $pair) {
  list($key, $value) = explode('|', $pair);
  $final[] = ['title'=>$key, 'value'=>$value];
}

print_r($final);