问:
Extra Outputs when using _
I have the following code:

```<code>pick_even([], []).
pick_even([_, H | T], [H | R]) :-
    pick_even(T, R).
pick_even([_, H , _ | T], [H | R]) :-
    pick_even(T, R).
</code>```

When running the query, ?- pick_even(L,[4,7])., I want to receive the output:

```<code>L = [_7650, 4, _7662, 7] ;
L = [_7650, 4, _7662, 7, _7674] ;
</code>```

Instead I am receiving some extra outputs that I do not want:

```<code>L = [_7650, 4, _7662, 7] ;
L = [_7650, 4, _7662, 7, _7674] ;
L = [_7650, 4, _7662, _7668, 7] ;
L = [_7650, 4, _7662, _7668, 7, _7680].
</code>```

How can I eliminate these extra outputs without modifying the query?

I'm brand new to prolog, so I expect this to be a very easy syntax fix.

答:
```<code>list_evens([], []).
list_evens([_|Es], Fs) :-
   list_evens2(Es, Fs).

list_evens2([], []).
list_evens2([E|Es], [E|Fs]) :-
   list_evens(Es, Fs).
</code>```

That is, you forgot in particular the case of a one-element list.

And, for testing, the best way is to take the most general query:

```<code>?- list_even(Xs, Ys).
   Xs = [], Ys = []
;  Xs = [_A], Ys = []
;  Xs = [_A,_B], Ys = [_B]
;  Xs = [_A,_B,_C], Ys = [_B]
;  Xs = [_A,_B,_C,_D], Ys = [_B,_D]
;  Xs = [_A,_B,_C,_D,_E], Ys = [_B,_D]
;  Xs = [_A,_B,_C,_D,_E,_F], Ys = [_B,_D,_F]
;  ... .
</code>```

In this manner you say:

Oh Prolog, why should I figure out what cases are of interest? Please do this for me!

And, diligently, Prolog will fill out the blanks.  So you only need to ensure that all the answers you expect are here.

Title: Extra Outputs when using _

Body:
I have the following code:

pick_even([], []).
pick_even([_, H | T], [H | R]) :-
    pick_even(T, R).
pick_even([_, H , _ | T], [H | R]) :-
    pick_even(T, R).

When running the query, ?- pick_even(L,[4,7])., I want to receive the output:

L = [_7650, 4, _7662, 7] ;
L = [_7650, 4, _7662, 7, _7674] ;

Instead I am receiving some extra outputs that I do not want:

L = [_7650, 4, _7662, 7] ;
L = [_7650, 4, _7662, 7, _7674] ;
L = [_7650, 4, _7662, _7668, 7] ;
L = [_7650, 4, _7662, _7668, 7, _7680].

How can I eliminate these extra outputs without modifying the query?

I'm brand new to prolog, so I expect this to be a very easy syntax fix.

Body:
list_evens([], []).
list_evens([_|Es], Fs) :-
   list_evens2(Es, Fs).

list_evens2([], []).
list_evens2([E|Es], [E|Fs]) :-
   list_evens(Es, Fs).

That is, you forgot in particular the case of a one-element list.

And, for testing, the best way is to take the most general query:

?- list_even(Xs, Ys).
   Xs = [], Ys = []
;  Xs = [_A], Ys = []
;  Xs = [_A,_B], Ys = [_B]
;  Xs = [_A,_B,_C], Ys = [_B]
;  Xs = [_A,_B,_C,_D], Ys = [_B,_D]
;  Xs = [_A,_B,_C,_D,_E], Ys = [_B,_D]
;  Xs = [_A,_B,_C,_D,_E,_F], Ys = [_B,_D,_F]
;  ... .

In this manner you say:

Oh Prolog, why should I figure out what cases are of interest? Please do this for me!

And, diligently, Prolog will fill out the blanks.  So you only need to ensure that all the answers you expect are here.


来源: stackexchange

问:
promise returns undefined while calling from two different mysql queries
I Have two mysql queries that runs with promise.

The first one is updates information on a mysql table and then resolves the issue and calls the next mysql query. The problem is that, when it calls the next mysql query the promise returns UNDEFINED and I am not sure why. When I console.log it out in my node js server post request, it gives undefined. I documented on the code which areas are problems.

```<code>UpdateUserPath = (data) => new Promise((resolve,reject)=>{
    data.UPDATE_DT = getDateTime();
    db.query('UPDATE path  UPDATE_DT = ?  where Owner = ?',
        [data.UPDATE_DT, data.Owner], function(err,results,fields){
        if(err){
            reject('Could not update user path');
        }else{
            if(results.affectedRows > 0){
                data.ID = null;
                data.UPDATE_DT = null;
                // The problem is here, when this gets resolved it calls the other function SaveUserPath
                resolve(saveUserPath(data));
            }else{
                reject('Could not update user path');
            }
        }
    });
});

saveUserPath = (data) => new Promise((resolve, reject) => {
    db.query('INSERT INTO path SET ?', data, function (error, results, fields) {
        if (error) {
            reject('Could not insert path');
        }else{
            var Id = results.insertId;

            db.query('UPDATE path SET ORIG_ID = ? where ID = ?',[Id, Id], function(err,results,fields){
                if(err){
                    reject('Could not insert row to path  table - saveuserpath');
                }else{
                    if(results.affectedRows > 0){
                       // THIS INFORMATION HERE IS UNDEFINED
                        return resolve(results[0]);
                    }else{
                        reject('Could not update path');
                    }
                }
            });
        }
    });
});
</code>```

In the server it gets called like this.

```<code>getUserPath(req.session.userid).then((path_data)=>{
                path_data.status = 1;
                UpdateUserPath(path_data).then((result)=>{
                    console.log(result); // THIS IS UNDEFINED
                });
            });
</code>```

I am wondering if resolve(saveUserPath(data)); is the right way to call another promise which is not outside in the server.
I was thinking of just doing it this way.

```<code>UpdateUserPath(path_data).then((result)=>{
   saveUserPath(result).then((result_save) => {
     console.log(result_save); // THIS MIGHT WORK
   });
});
</code>```

But why is the normal way wrong.

答:
I have several guesses why it isn't working, but there are a number of things wrong such that it's better to just clean up the code to a much better design.

When combining multiple asynchronous callback-driven operations in an otherwise promise-based interface, you really want to promisify the underlying functions at their lowest level and then you can implement all your control flow and error handling using the benefits of promises.  I think that will also make your problem go away and probably fix a couple other bugs too.

```<code>// promisify db.query()
// if a promisified interface is built into your database, use that one instead
db.queryP = function(q, d) {
    return new Promise((resolve, reject) {
        db.query(q, d, (err, results, fields) => {
            if (err) {
                reject(err);
            } else {
                resolve(results);
            }
        });
    });
}

UpdateUserPath = function(data) {
    data.UPDATE_DT = getDateTime();
    let q = 'UPDATE path  UPDATE_DT = ?  where Owner = ?';
    return db.queryP(q, [data.UPDATE_DT, data.Owner]).then(results => {
        if (results.affectedRows > 0) {
            data.ID = null;
            data.UPDATE_DT = null;
            return saveUserPath(data);
        } else {
            throw new Error('Could not update user path');
        }
    });
}

saveUserPath = function(data) {
    let q = 'INSERT INTO path SET ?'
    return db.queryP(q, data).then(results => {
        let q2 = 'UPDATE path SET ORIG_ID = ? where ID = ?';
        var Id = results.insertId;
        return db.queryP(q2, [Id, Id]).then(results2 => {
            if (results2.affectedRows > 0) {
                return results2[0];
            } else {
                throw new Error('Could not update path');
            }
        });
    });
}

getUserPath(req.session.userid).then(path_data => {
    path_data.status = 1;
    return UpdateUserPath(path_data);
}).then(result => {
    // process result here
}).catch(err => {
    // process error here
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I Have two mysql queries that runs with promise.

The first one is updates information on a mysql table and then resolves the issue and calls the next mysql query. The problem is that, when it calls the next mysql query the promise returns UNDEFINED and I am not sure why. When I console.log it out in my node js server post request, it gives undefined. I documented on the code which areas are problems.

UpdateUserPath = (data) => new Promise((resolve,reject)=>{
    data.UPDATE_DT = getDateTime();
    db.query('UPDATE path  UPDATE_DT = ?  where Owner = ?',
        [data.UPDATE_DT, data.Owner], function(err,results,fields){
        if(err){
            reject('Could not update user path');
        }else{
            if(results.affectedRows > 0){
                data.ID = null;
                data.UPDATE_DT = null;
                // The problem is here, when this gets resolved it calls the other function SaveUserPath
                resolve(saveUserPath(data));
            }else{
                reject('Could not update user path');
            }
        }
    });
});

saveUserPath = (data) => new Promise((resolve, reject) => {
    db.query('INSERT INTO path SET ?', data, function (error, results, fields) {
        if (error) {
            reject('Could not insert path');
        }else{
            var Id = results.insertId;

            db.query('UPDATE path SET ORIG_ID = ? where ID = ?',[Id, Id], function(err,results,fields){
                if(err){
                    reject('Could not insert row to path  table - saveuserpath');
                }else{
                    if(results.affectedRows > 0){
                       // THIS INFORMATION HERE IS UNDEFINED
                        return resolve(results[0]);
                    }else{
                        reject('Could not update path');
                    }
                }
            });
        }
    });
});

In the server it gets called like this.

getUserPath(req.session.userid).then((path_data)=>{
                path_data.status = 1;
                UpdateUserPath(path_data).then((result)=>{
                    console.log(result); // THIS IS UNDEFINED
                });
            });

I am wondering if resolve(saveUserPath(data)); is the right way to call another promise which is not outside in the server.
I was thinking of just doing it this way.

UpdateUserPath(path_data).then((result)=>{
   saveUserPath(result).then((result_save) => {
     console.log(result_save); // THIS MIGHT WORK
   });
});

But why is the normal way wrong.

Body:
I have several guesses why it isn't working, but there are a number of things wrong such that it's better to just clean up the code to a much better design.

When combining multiple asynchronous callback-driven operations in an otherwise promise-based interface, you really want to promisify the underlying functions at their lowest level and then you can implement all your control flow and error handling using the benefits of promises.  I think that will also make your problem go away and probably fix a couple other bugs too.

// promisify db.query()
// if a promisified interface is built into your database, use that one instead
db.queryP = function(q, d) {
    return new Promise((resolve, reject) {
        db.query(q, d, (err, results, fields) => {
            if (err) {
                reject(err);
            } else {
                resolve(results);
            }
        });
    });
}

UpdateUserPath = function(data) {
    data.UPDATE_DT = getDateTime();
    let q = 'UPDATE path  UPDATE_DT = ?  where Owner = ?';
    return db.queryP(q, [data.UPDATE_DT, data.Owner]).then(results => {
        if (results.affectedRows > 0) {
            data.ID = null;
            data.UPDATE_DT = null;
            return saveUserPath(data);
        } else {
            throw new Error('Could not update user path');
        }
    });
}

saveUserPath = function(data) {
    let q = 'INSERT INTO path SET ?'
    return db.queryP(q, data).then(results => {
        let q2 = 'UPDATE path SET ORIG_ID = ? where ID = ?';
        var Id = results.insertId;
        return db.queryP(q2, [Id, Id]).then(results2 => {
            if (results2.affectedRows > 0) {
                return results2[0];
            } else {
                throw new Error('Could not update path');
            }
        });
    });
}

getUserPath(req.session.userid).then(path_data => {
    path_data.status = 1;
    return UpdateUserPath(path_data);
}).then(result => {
    // process result here
}).catch(err => {
    // process error here
});


问:
trying to get rid of a character using strtok in c
So I need to be able to input a string as a phone number like so:
(555)-444-3333.
After that I need to use strtok to remove the parentheses and dashes, and convert the strings area code and the rest of the phone number to just integers and print them out all together
My problem is using strtok to get rid of the  ( , because if I don't the area code will just print 0 when it's converted to an int. Here's what I have:</p>

```<code>int main()
{
phone[14];
int* area_code;
int* digits;
int* i, j;

printf("Enter a phone number: ");
scanf("%s", phone);

strtok( phone, "(" );
area_code = strtok( phone, ")" );
j = atoi(area_code);

printf("%d", j);

while((digits = strtok(NULL, "-")) != NULL )
{
i = atoi(digits);
printf("%d", digits);
}

return 0;
}
</code>```

答:
In your strtok calls, specify the delimiters as "()-".

Best of luck.

Body:
So I need to be able to input a string as a phone number like so:
(555)-444-3333.
After that I need to use strtok to remove the parentheses and dashes, and convert the strings area code and the rest of the phone number to just integers and print them out all together
My problem is using strtok to get rid of the  ( , because if I don't the area code will just print 0 when it's converted to an int. Here's what I have:

int main()
{
phone[14];
int* area_code;
int* digits;
int* i, j;

printf("Enter a phone number: ");
scanf("%s", phone);

strtok( phone, "(" );
area_code = strtok( phone, ")" );
j = atoi(area_code);

printf("%d", j);

while((digits = strtok(NULL, "-")) != NULL )
{
i = atoi(digits);
printf("%d", digits);
}

return 0;
}


问:
PM2 dev and prod environments on same server
I have a dev and prod instance of a microservice running on one machine. My ecosystem file gives them the same name. PM2 will not start the second instance when the first is running due to the name (presumably). Any ideas for a workaround here?</p>

答:
Thanks for the help... I ended up with this:</p>

```<code>require("dotenv").config();

module.exports = {
  apps: [
    {
      name: "app-" + process.env.environment,
      script: "./app.js",
      max_memory_restart: "150M"
    }
  ]
};
</code>```

Body:
Thanks for the help... I ended up with this:

require("dotenv").config();

module.exports = {
  apps: [
    {
      name: "app-" + process.env.environment,
      script: "./app.js",
      max_memory_restart: "150M"
    }
  ]
};


问:
django rest framework same route, different
i'm using django rest framework to build an api, here is my problem

```<code>url(r'^profiles/(?P<pk>[0-9]*)', ProfileRetrieveView.as_view(), name='profiles-detail'),
url(r'^profiles/(?P<pk>[0-9]*)', ProfileUpdateView.as_view(), name='profiles-update'),
</code>```

```<code>    class ProfileRetrieveView(RetrieveAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

class ProfileUpdateView(UpdateAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = (IsAuthenticated, )
</code>```

When i query the api with the link /profile/2 and the method patch, i receive 405, method not allowed, only the get method is allowed, how can i solve that without haven to transform my two view classes into on class with a GenericView Base class and Retrive + update Mixins.

答:
You should condense this into a single endpoint. You can have a single class handle all the listing, update, get, etc for this. Try...something like this:

```<code>from rest_framework import mixins, viewsets
class ProfileUpdateView(viewset.ModelViewSet,
                        mixins.ListModelMixin,
                        mixins.UpdateModelMixin):

    serializer_class = ProfileSerializer
    permission_classes = (IsAuthenticated, )

    get_queryset(self):
          return Profile.objects.all()
</code>```

If you're using pure models, use the built in model stuff, and check out the mixins. It will save you TONS of generic code writing. It has some magic that knows how to route the request to the matching http method.

http://www.django-rest-framework.org/api-guide/generic-views/#mixins

Body:
i'm using django rest framework to build an api, here is my problem

url(r'^profiles/(?P<pk>[0-9]*)', ProfileRetrieveView.as_view(), name='profiles-detail'),
url(r'^profiles/(?P<pk>[0-9]*)', ProfileUpdateView.as_view(), name='profiles-update'),

    class ProfileRetrieveView(RetrieveAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

class ProfileUpdateView(UpdateAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = (IsAuthenticated, )

When i query the api with the link /profile/2 and the method patch, i receive 405, method not allowed, only the get method is allowed, how can i solve that without haven to transform my two view classes into on class with a GenericView Base class and Retrive + update Mixins.

Body:
You should condense this into a single endpoint. You can have a single class handle all the listing, update, get, etc for this. Try...something like this:

from rest_framework import mixins, viewsets
class ProfileUpdateView(viewset.ModelViewSet,
                        mixins.ListModelMixin,
                        mixins.UpdateModelMixin):

    serializer_class = ProfileSerializer
    permission_classes = (IsAuthenticated, )

    get_queryset(self):
          return Profile.objects.all()

If you're using pure models, use the built in model stuff, and check out the mixins. It will save you TONS of generic code writing. It has some magic that knows how to route the request to the matching http method.

http://www.django-rest-framework.org/api-guide/generic-views/#mixins


问:
Downloding a video after payment has been received
I have a web page that I would like to add a new feature.
customers will pay in order to download some video files.

Video files will be stored in amazon S3 (will be about 150GB per year). When a user pays through paypal for example, then a mail will be sent with an amazon s3 url link for the user to download.

but then he/she could pass this video link to other users who haven't paid but can access amazon s3 since the file is public. If the video was in my server I know how I could check if the user has paid, and server the file.

But now that it will be on an external server how could this be done?

How site delivering paid contact avoid this thing?

thanks

答:
You can make your S3 content private and then create a time-limited pre-signed url to the video - eg the url will no longer work after the expiry time.

Of course the user could still share the link before it has expired, but then the user could also just share the downloaded video anyway.

ContentLicense: CC BY-SA 2.5


问:
Python: adding the same string to the end of each row
I'm modifying a CSV file with two fieldnames and I would like to add a string to the end of each row under an additional fieldname. I've figured out how to add the fieldname, but not how to add things to it. It seems like it should be simple, but I'm stumped.

```<code>import csv

with open('test2l.csv', 'r') as inny:
    reader = csv.DictReader(inny)

    with open('outfile.csv', 'w') as outty:
        fieldnames = ["Genus", "Species", "Source"]
        writer = csv.DictWriter(outty, fieldnames = fieldnames)
        writer.writeheader()

        for record in reader:
             g = record['Genus']
             s = record['Species']
</code>```

Everything I tried has just added the string to the existing string in 'Species' and I haven't been able to create a record for 'Source', I assume because it's empty.

Thanks!

答:
If you haven't already, check out the documentation for csv.Reader, csv.DictReader, and csv.DictWriter.

The documentation indicates that reader objects operate on an on object using the iterator protocol. Iterating once (for row in reader:, for example) to add a "Source" exhausts the underlying iterator. Attempting to then use the same reader with a writer later would not work.

To work around this, you could create a list:

```<code>rows = list(csv.DictReader(inny))
</code>```

While this exhausts the iterator, you now have a list to work with. However, this might not be ideal if the list is very long.

Another solution would be to add the Source and write the row during the same iteration:

```<code>for row in reader:
    row['Source'] = 'same string every time'
    writer.writerow(row)
</code>```

Body:
I'm modifying a CSV file with two fieldnames and I would like to add a string to the end of each row under an additional fieldname. I've figured out how to add the fieldname, but not how to add things to it. It seems like it should be simple, but I'm stumped.

import csv

with open('test2l.csv', 'r') as inny:
    reader = csv.DictReader(inny)

    with open('outfile.csv', 'w') as outty:
        fieldnames = ["Genus", "Species", "Source"]
        writer = csv.DictWriter(outty, fieldnames = fieldnames)
        writer.writeheader()

        for record in reader:
             g = record['Genus']
             s = record['Species']

Everything I tried has just added the string to the existing string in 'Species' and I haven't been able to create a record for 'Source', I assume because it's empty.

Thanks!

Body:
If you haven't already, check out the documentation for csv.Reader, csv.DictReader, and csv.DictWriter.

The documentation indicates that reader objects operate on an on object using the iterator protocol. Iterating once (for row in reader:, for example) to add a "Source" exhausts the underlying iterator. Attempting to then use the same reader with a writer later would not work.

To work around this, you could create a list:

rows = list(csv.DictReader(inny))

While this exhausts the iterator, you now have a list to work with. However, this might not be ideal if the list is very long.

Another solution would be to add the Source and write the row during the same iteration:

for row in reader:
    row['Source'] = 'same string every time'
    writer.writerow(row)


问:
Getting a certain value out of a nested array
I have a json file with two arrays, one of them is nested. I need to get the numbers from the nested array and match them with a value (id) in the unnested array so that I can send the matched values in the unnested array to another function. I have been trying to figure this out for two straight days and haven't been able to figure out what it is I am doing wrong. Any pointers or help would be appreciated.

I have the data to my json here for reference.

```<code>{
  "videos": [
    {
      "id": 1,
      "title": "Lego!",
      "created": 1509804047011,
      "duration": 5,
      "poster": "./videos/small.png",
      "video": "./videos/small.mp4"
    },
    {
      "id": 2,
      "title": "Big Bunny",
      "created": 1507804047011,
      "duration": 62,
      "poster": "./videos/bunny.png",
      "video": "./videos/bunny.mp4"
    },
    {
      "id": 3,
      "title": "Prufu myndband",
      "created": 1505904047011,
      "duration": 3600,
      "poster": "./videos/16-9.png",
      "video": "./videos/bunny.mp4"
    },
    {
      "id": 4,
      "title": "Prufu myndband með löngum texta sem fer í tvær línur",
      "created": 1504904047011,
      "duration": 220,
      "poster": "./videos/16-9.png",
      "video": "./videos/bunny.mp4"
    }
  ],

  "categories": [
    {
      "title": "New videos",
      "videos": [1, 2]
    },
    {
      "title": "Amazing videos",
      "videos": [1, 3, 4]
    },
    {
      "title": "Funny videos",
      "videos": [2, 3, 4]
    }
  ]
}
</code>```

答:
You could simply map over the videos array like this:

```<code>const videoIds = data.videos.map(video => video.id);
console.log(videoIds)
</code>```

This will return an array containing all ids in the videos array.

Body:
I have a json file with two arrays, one of them is nested. I need to get the numbers from the nested array and match them with a value (id) in the unnested array so that I can send the matched values in the unnested array to another function. I have been trying to figure this out for two straight days and haven't been able to figure out what it is I am doing wrong. Any pointers or help would be appreciated.

I have the data to my json here for reference.

{
  "videos": [
    {
      "id": 1,
      "title": "Lego!",
      "created": 1509804047011,
      "duration": 5,
      "poster": "./videos/small.png",
      "video": "./videos/small.mp4"
    },
    {
      "id": 2,
      "title": "Big Bunny",
      "created": 1507804047011,
      "duration": 62,
      "poster": "./videos/bunny.png",
      "video": "./videos/bunny.mp4"
    },
    {
      "id": 3,
      "title": "Prufu myndband",
      "created": 1505904047011,
      "duration": 3600,
      "poster": "./videos/16-9.png",
      "video": "./videos/bunny.mp4"
    },
    {
      "id": 4,
      "title": "Prufu myndband með löngum texta sem fer í tvær línur",
      "created": 1504904047011,
      "duration": 220,
      "poster": "./videos/16-9.png",
      "video": "./videos/bunny.mp4"
    }
  ],

  "categories": [
    {
      "title": "New videos",
      "videos": [1, 2]
    },
    {
      "title": "Amazing videos",
      "videos": [1, 3, 4]
    },
    {
      "title": "Funny videos",
      "videos": [2, 3, 4]
    }
  ]
}

Body:
You could simply map over the videos array like this:

const videoIds = data.videos.map(video => video.id);
console.log(videoIds)

This will return an array containing all ids in the videos array.


问:
Remove Default Checked Option on Radio Button when Another Option is Selected
If i'm using radio buttons in HTML and would like a default option to show as selected, I've used the 'checked' attribute to achieves this.  How do I make it so when I check on another option on the radio buttons this default option is removed.  In the code below, when you check another option, the original option remains and you can't uncheck anything?

In the option below the fish option is the one with the 'checked' attribute added.

https://codepen.io/pen/?editors=1010

HTML

```<code><input type="radio" id="dog"name="dog"value="dog"><label for="dog">Dog</label>
<input type="radio"  id="cat" name="cat" value="cat"><label for="cat">Cat</label>
<input type="radio"  id="fish" name="fish" value="fish" checked><label for="fish">Fish</label>
<input type="submit">
</code>```

答:
Your form radio elements need to have a shared name attribute as they
  are the options for one choice. change name to "foo" or "animal" and
  it will work.

All radio inputs require a shared name attribute, I declared it "choice"

<form style="text-align:center">
<input type="radio" id="dog"name="choice"value="dog">Dog
<input type="radio"  id="cat" name="choice" value="cat" >Cat
<input type="radio"  id="fish" name="choice" value="fish" checked="checked" >Fish
<input type="submit">
</form>```

Body:
If i'm using radio buttons in HTML and would like a default option to show as selected, I've used the 'checked' attribute to achieves this.  How do I make it so when I check on another option on the radio buttons this default option is removed.  In the code below, when you check another option, the original option remains and you can't uncheck anything?

In the option below the fish option is the one with the 'checked' attribute added.

https://codepen.io/pen/?editors=1010

HTML

<input type="radio" id="dog"name="dog"value="dog">Dog
<input type="radio"  id="cat" name="cat" value="cat">Cat
<input type="radio"  id="fish" name="fish" value="fish" checked>Fish
<input type="submit">

Body:
Your form radio elements need to have a shared name attribute as they
  are the options for one choice. change name to "foo" or "animal" and
  it will work.

<div style="margin-bottom:15px;">All radio inputs require a shared name attribute, I declared it "choice"</div>

<form style="text-align:center">
<input type="radio" id="dog"name="choice"value="dog"><label for="dog">Dog</label>
<input type="radio"  id="cat" name="choice" value="cat" ><label for="cat" >Cat</label>
<input type="radio"  id="fish" name="choice" value="fish" checked="checked" ><label for="fish" >Fish</label>
<input type="submit">
</form>


问:
Copy Image from one Sheet to another
I've searched through out Google and on here for a proper answer and I can't seem to find one...

I have an image on "Sheet2" that I want to copy over to "Sheet1", the image's name is static and doesn't change. I've got the below code to delete the already existing image on "Sheet1" and now I need it to be replaced with the image from "Sheet2"

```<code>Sub CheckImageName()

    For Each shape In ActiveSheet.Shapes
        If Not Intersect(shape.TopLeftCell, Range("L77:AM97")) Is Nothing Then
            shape.Delete
        End If
    Next shape

End Sub
</code>```

Every method I saw was using .Select and pasting into the area, however I'm really trying to avoid using the .Select and .Paste methods as I've read all over SO and other sources that it's best to avoid using .Select.

答:
I found a response for Word that could apply for your question.

Copy shape in Word 2010 without .Select?

```<code>Sub createShape()
    Set myshape = ActiveDocument.Shapes.AddShape(msoShapeRectangle, 100, 100, 100, 100)
    Set anothershape = myshape.Duplicate
End Sub
</code>```

Title: Copy Image from one Sheet to another

Body:
I've searched through out Google and on here for a proper answer and I can't seem to find one...

I have an image on "Sheet2" that I want to copy over to "Sheet1", the image's name is static and doesn't change. I've got the below code to delete the already existing image on "Sheet1" and now I need it to be replaced with the image from "Sheet2"

Sub CheckImageName()

    For Each shape In ActiveSheet.Shapes
        If Not Intersect(shape.TopLeftCell, Range("L77:AM97")) Is Nothing Then
            shape.Delete
        End If
    Next shape

End Sub

Every method I saw was using .Select and pasting into the area, however I'm really trying to avoid using the .Select and .Paste methods as I've read all over SO and other sources that it's best to avoid using .Select.

Body:
I found a response for Word that could apply for your question.

Copy shape in Word 2010 without .Select?

Sub createShape()
    Set myshape = ActiveDocument.Shapes.AddShape(msoShapeRectangle, 100, 100, 100, 100)
    Set anothershape = myshape.Duplicate
End Sub


问:
Open PDF in new browser full window
How do I open PDF document in new browser window?

The window should be full and withouth menu.

Just a PDF document in a clean full window with native Javascript or jQuery.

答:
```<code><a href="#" onclick="window.open('MyPDF.pdf', '_blank', 'fullscreen=yes'); return false;">MyPDF</a>
</code>```

The above link will open the PDF in full screen mode, that's the best you can achieve.

Title: Open PDF in new browser full window

Body:
<a href="#" onclick="window.open('MyPDF.pdf', '_blank', 'fullscreen=yes'); return false;">MyPDF</a>

The above link will open the PDF in full screen mode, that's the best you can achieve.


问:
SQL exception which only occurs on one of the three servers
We are having a problem with a prepared statement in Java. The exception seems to be very clear:

Root Exception stack trace:
com.microsoft.sqlserver.jdbc.SQLServerException: The statement must be executed before any results can be obtained.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:170)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getGeneratedKeys(SQLServerStatement.java:1973)
at org.apache.commons.dbcp.DelegatingStatement.getGeneratedKeys(DelegatingStatement.java:315)

It basically states that we are trying to fetch the query results before it has been executed. Sounds plausible. Now, the code which is causing this exception is as follows:

```<code>    ...

    preparedStatement.executeUpdate();

    ResultSet resultSet = preparedStatement.getGeneratedKeys();
    if(resultSet.next()) {
        retval = resultSet.getLong(1);
    }

    ...
</code>```

As you can see, we fetch the query result after we executed the statement.

In this case, we try to get the generated key from the ResultSet of the INSERT query we just succesfully executed.

Problem

We run this code on three different servers (load balanced, in docker containers). Strange enough, this exception only occurs on the third docker server. The other two docker servers have never ran into this exception.

Extra: the failing query is executed approxmately 13000 times per day. (4500 processed by server 3) Most of the times the query works well at server 3 as well. Sometimes, lets say 20 times per day, the query fails. Always the same query, always the same server. Never one of the other servers.

What we've tried

We checked the software versions. But this is all the same because all servers are running with the same docker image.

We updated to the newest Microsoft SQL driver for Java

We checked if all our PreparedStatements were constructed using PreparedStatement.RETURN_GENERATED_KEYS parameter.

It looks like it is some server configuration related problem, since the docker images are all the same. But we can't find the cause. Does anyone have suggestions what the problem can be? Or has anyone ever ran in this problem as well?

答:
As I know, getGeneratedKeys() in case of batch execution is not supported by SQL Server.

Here is feature request which is not satisfied yet: https://github.com/Microsoft/mssql-jdbc/issues/245

My suggestion is that if for some reason on you third server batch insert was executed contitiously, this can cause the exception you mentioned (in case on other two only one item was inserted)

You can try to log the sql statement to check this

Body:
We are having a problem with a prepared statement in Java. The exception seems to be very clear:

Root Exception stack trace:
com.microsoft.sqlserver.jdbc.SQLServerException: The statement must be executed before any results can be obtained.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:170)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getGeneratedKeys(SQLServerStatement.java:1973)
at org.apache.commons.dbcp.DelegatingStatement.getGeneratedKeys(DelegatingStatement.java:315)

It basically states that we are trying to fetch the query results before it has been executed. Sounds plausible. Now, the code which is causing this exception is as follows:

    ...

    preparedStatement.executeUpdate();

    ResultSet resultSet = preparedStatement.getGeneratedKeys();
    if(resultSet.next()) {
        retval = resultSet.getLong(1);
    }

    ...

As you can see, we fetch the query result after we executed the statement.

In this case, we try to get the generated key from the ResultSet of the INSERT query we just succesfully executed.

Problem

We run this code on three different servers (load balanced, in docker containers). Strange enough, this exception only occurs on the third docker server. The other two docker servers have never ran into this exception.

Extra: the failing query is executed approxmately 13000 times per day. (4500 processed by server 3) Most of the times the query works well at server 3 as well. Sometimes, lets say 20 times per day, the query fails. Always the same query, always the same server. Never one of the other servers.

What we've tried

We checked the software versions. But this is all the same because all servers are running with the same docker image.

We updated to the newest Microsoft SQL driver for Java

We checked if all our PreparedStatements were constructed using PreparedStatement.RETURN_GENERATED_KEYS parameter.

It looks like it is some server configuration related problem, since the docker images are all the same. But we can't find the cause. Does anyone have suggestions what the problem can be? Or has anyone ever ran in this problem as well?


问:
Javascript accessing inner function from outside
I have the following <s>json</s> object

```<code>{
 ....
 ....
 data: function() {
    var x = 10;
    function isBig() {
        return x>6;
    }
    return x;
 }
}
</code>```

I want the isBig to be a function inside data.

When I call data.isBig I am getting undefined and data.isBig() gives me an error saying isBig is not a function.

答:
First of all, that is not JSON. It is an object.
The way your object is structured currently, isBig is only accessible from inside data. If you want to access it outside data, the simplest way is to make it a property of the outer object:

```<code>{
    data: function()
    {
        var x = 10;
        return x;
    }
    isBig: function(x)
    {
        return x > 6;
    }
}
</code>```

If you don't want to do that, then an alternative would be this:

```<code>{
    data: function()
    {
        var x = 10;
        this.isBig = function(x)
        {
            return x > 6;
        }
        return x;
    }
}
</code>```

Calling data() works normally (returns 10), whereas calling new data() returns an object with a property isBig which corresponds to the function. This allows you to do this:

```<code>new myObj.data().isBig()
</code>```

Body:
I have the following <s>json</s> object

{
 ....
 ....
 data: function() {
    var x = 10;
    function isBig() {
        return x>6;
    }
    return x;
 }
}

I want the isBig to be a function inside data.

When I call data.isBig I am getting undefined and data.isBig() gives me an error saying isBig is not a function.

Body:
First of all, that is not JSON. It is an object.
The way your object is structured currently, isBig is only accessible from inside data. If you want to access it outside data, the simplest way is to make it a property of the outer object:

{
    data: function()
    {
        var x = 10;
        return x;
    }
    isBig: function(x)
    {
        return x > 6;
    }
}

If you don't want to do that, then an alternative would be this:

{
    data: function()
    {
        var x = 10;
        this.isBig = function(x)
        {
            return x > 6;
        }
        return x;
    }
}

Calling data() works normally (returns 10), whereas calling new data() returns an object with a property isBig which corresponds to the function. This allows you to do this:

new myObj.data().isBig()


问:
Reading Data from two PHP pages into the third Page
I'm not able to combine the data from two pages. I'm only able to show data from one page. I tried searching for an explanation of my problem on google but I could not find it.
I get an "Undefined index" error as you can see [![in this screenshot][1]][1].
Could not put just code over here because it keeps telling me that I need to use spacing with ctrl + K and im newbie in all this things so please forgive me..

```<code><!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>

<body>
 <form action = "page2.php" method = "POST">
                            <select list="Country" placeholder="Country" name="country" required class="form-control" style="max-width:250px; margin-top:50px;" id="Country">
                                <option >Bosnia & Herzegovina</option>
                                <option >Croatia</option>
                                <option >Serbia</option>
                                <option >England</option>
                                <option >Germany</option>
                                <option >Austria</option>
                                <option >Belgium</option>
                                <option >Switzerland</option>
                                <option >Italy</option>
                                <option >Romania</option>
                                <option >France</option>
                                <option >Montenegro</option>
                                <option >Slovenia</option>
                            </select>

            <input type="email" name="email" id="email" placeholder="Your email address" required class="form-control" style="max-width:250px;" />

            <input type="password" name="password" id="creapass" placeholder="Create your password" required  class="form-control" style="max-width:250px;" />

            <input type="password" name="password2" id="password" placeholder="Confirm your password" required  class="form-control" style="max-width:250px;" />

            <a href="page2.php"> <input type="button" value="Next" class="btn btn-primary" style="width:150px;"></a>

            </form>

</body>
</html>
</code>```

Second Page

```<code><!DOCTYPE html>
<html>
<head>
<title>test2</title>

</head>

<body>
<form action = "finalpage.php" method = "POST">

    <!-- Values from First Step -->

<input type="hidden" name="country" value="<?php $_POST['country'] ?>">

<input type="hidden" name="email" value="<?php $_POST['email'] ?>">

<input type="hidden" name="password" value="<?php $_POST['password'] ?>">
<input type="hidden" name="password" value="<?php $_POST['password2'] ?>">

<!-- End of Values from First Step -->

<?php
echo "Country:" .$_POST["country"]."</br>";
echo "Email:".$_POST["email"]."</br>";
echo "Password:".$_POST["password"]."</br>";
echo "Password2:".$_POST["password2"]."</br>";
?>

                                <input type="text" name="first" class="form-control" placeholder="First name" required style="max-width:250px;" >

                                <input type="text" name="last" class="form-control" placeholder="Last name" required style="max-width:250px;" />

                                <input type="date" name="date" class="dateb" id="dateOfBirth" required  />

                                        <select list="Country" placeholder="Country" name="country2" required class="form-control" style="max-width:250px; " id="Country">
                                            <option >Bosnian</option>
                                            <option >Croat</option>
                                            <option >Serb</option>
                                            <option >English</option>
                                            <option >German</option>
                                            <option >Austrian</option>
                                            <option >Belgian</option>
                                            <option >Swiss</option>
                                            <option >Italian</option>
                                            <option >Romanian</option>
                                            <option >French</option>
                                            <option >Montenegrin</option>
                                            <option >Slovenian</option>
                                        </select>

                                <input type="text" class="form-control" name="street1" placeholder="Street address 1" required style="max-width:250px;" />

                                <input type="text" class="form-control" name="street2" placeholder="Street address 2 (Optional)" style="max-width:250px;" />

                                <input type="text" class="form-control" name="city" placeholder="City" required style="max-width:250px;" />

                                <input type="text" class="form-control" name="region" placeholder="Province/Region" required style="max-width:250px;" />

                                <input type="text" class="form-control" name="postal" placeholder="Postal code" required style="max-width:250px;" />

                                <input type="tel" class="form-control" name="phone" placeholder="Phone number" required style="max-width:250px;" />

                                <input type="checkbox" name="terms" > I have read and agree to the Terms and WBC's User Agreement.

                                <a href="LinkCard.html"><input type="Submit" name="insert" value="Continue" class="btn btn-primary btn-lg"></a>

            </form>

</body>

</html>
</code>```

Final Step.

```<code><html>
<head>
<title>get data from another page</title>
</head>
<body>
<?php
echo "Country:" .$_POST["country"]."</br>";
echo "Email:".$_POST["email"]."</br>";
echo "Password:".$_POST["password"]."</br>";
echo "Password2:".$_POST["password2"]."</br>";

echo "First name:" .$_POST["first"]."</br>";
echo "Last name:".$_POST["last"]."</br>";
echo "Date:".$_POST["date"]."</br>";
echo "Country2:".$_POST["country2"]."</br>";
echo "Street1:" .$_POST["street1"]."</br>";
echo "Street2:".$_POST["street2"]."</br>";
echo "City:".$_POST["city"]."</br>";
echo "Region:".$_POST["region"]."</br>";
echo "Postal code:" .$_POST["postal"]."</br>";
echo "Phone number:".$_POST["phone"]."</br>";
?>
</body>
</html>
</code>```

答:
You've got a number of problems. First, your option fields don't have values.

What you have: <option>Bosnia</option>

What you need: <option value="bosnia" >Bosnia</option>

You should also have a default as your first option, otherwise your program is going to assume that everyone who doesn't pick something has the first option, and you are going to get a million submissions that are not accurate. Eg:

```<code><option value="false" selected="selected">Please select an option from below</option>
</code>```

Then your backend should be checking like this:

```<code><?php
if (!isset($_POST['country'] || $_POST['country'] === 'false')
{
    //They did not pick a country, and you need to bounce them back to the form with an error message.
    header('Location: /path/to/your/form');
    exit;
}
//country is defined, you can continue,
//but you should pre-validate the other required field here also.
//do not assume things are right, assumptions = bugs.
...
</code>```

The anchor tag you have surrounding your submit button may be redirecting instead of submitting the form, in which case your $_POST will be completely empty. The below tag you have:

```<code><a href="page2.php"> <input type="button" value="Next" class="btn btn-primary" style="width:150px;"></a>
</code>```

Needs to look more like this:

```<code><input type="submit" value="Next" class="btn btn-primary" style="width:150px;">
</code>```

Or alternately:

```<code><button type="submit" class="btn btn-primary" style="width:150px;">Next</button>
</code>```

If you are stumped, put this at the beginning of what you have on your processing code:

```<code>echo '```' . print_r($_POST, 1); exit;
```

<p>This will show you what was submitted, and let you work through from there as needed.</p>

<hr>

<p>In general, your conditionals should check if a key exists before validating it if there is any ambiguity as to whether or not it is set:</p>

```//BAD
if ($_POST['country'] == 'someval') { ... }

//GOOD
if (array_key_exists('country', $_POST) && $_POST['country'] == 'someval') { ... }
```

<p>You can also check with <code>isset($_POST['country']);</code> <em>HOWEVER</em>, if <code>null</code> values are valid for whatever you are checking, then this will return <code>false</code>, even if the key is there. So in any case where <code>null</code> is valid, you need to use <code>array_key_exists()</code> instead.</p>

<hr>

<p>Instead of passing variables directly from one page to another, it's a lot easier if you use <code>$_SESSION</code>, so if they derp up and hit back or walk away for a while, the values are not entirely lost. Users hate having to redundantly redo things, and will probably entirely lose interest in your site if they have to do that. Instead, you can set the values if they exist into session memory like this:</p>

```<?php
session_start(); //you have to do this before printing ANY other content.
$_SESSION['country'] = (isset($_POST['country']) ? $_POST['country'] : null);
```

<p>And then you can retrieve this at any time from any page by doing:</p>

```<?php
session_start();
echo $_SESSION['country'];
```

<p>and if you want to clear them, you just do:</p>

```<?php
session_start(); //can't destroy a non-existent session, you have to do this first
session_destroy(); //clears the session
session_start(); //starts a new one
```

<p>Stashing ongoing form values in the session temporarily lets you access them for as long as the <em>session cookie</em> lasts, so they are not lost if the user quits your form, goes to another site, then comes back to finish. Your form will have to put these back in manually though, so an input might look something like this</p>

```<?php
if (!isset($_POST['country'] || $_POST['country'] === 'false')
{
    //They did not pick a country, and you need to bounce them back to the form with an error message.
    header('Location: /path/to/your/form');
    exit;
}
//country is defined, you can continue,
//but you should pre-validate the other required field here also.
//do not assume things are right, assumptions = bugs.
...
```0

I tried to explain the relevant logic you are not applying rather than just the specific use case, because without actually grasping what the underlying lack of logic is, you would otherwise probably just hit the same wall again. Hopefully this saves you from a number of other bugs that you would otherwise likely hit immediately after this specific thing gets fixed for you.

Body:
I'm not able to combine the data from two pages. I'm only able to show data from one page. I tried searching for an explanation of my problem on google but I could not find it.
I get an "Undefined index" error as you can see [![in this screenshot][1]][1].
Could not put just code over here because it keeps telling me that I need to use spacing with ctrl + K and im newbie in all this things so please forgive me..

<!DOCTYPE html>

<title>TEST</title>

 <form action = "page2.php" method = "POST">
                            <select list="Country" placeholder="Country" name="country" required class="form-control" style="max-width:250px; margin-top:50px;" id="Country">
                                <option >Bosnia & Herzegovina</option>
                                <option >Croatia</option>
                                <option >Serbia</option>
                                <option >England</option>
                                <option >Germany</option>
                                <option >Austria</option>
                                <option >Belgium</option>
                                <option >Switzerland</option>
                                <option >Italy</option>
                                <option >Romania</option>
                                <option >France</option>
                                <option >Montenegro</option>
                                <option >Slovenia</option>
                            </select>

            <input type="email" name="email" id="email" placeholder="Your email address" required class="form-control" style="max-width:250px;" />

            <input type="password" name="password" id="creapass" placeholder="Create your password" required  class="form-control" style="max-width:250px;" />

            <input type="password" name="password2" id="password" placeholder="Confirm your password" required  class="form-control" style="max-width:250px;" />

             <input type="button" value="Next" class="btn btn-primary" style="width:150px;">

            </form>

Second Page

<!DOCTYPE html>

<title>test2</title>

<form action = "finalpage.php" method = "POST">

<input type="hidden" name="country" value="<?php $_POST['country'] ?>">

<input type="hidden" name="email" value="<?php $_POST['email'] ?>">

<input type="hidden" name="password" value="<?php $_POST['password'] ?>">
<input type="hidden" name="password" value="<?php $_POST['password2'] ?>">

<?php
echo "Country:" .$_POST["country"]."
";
echo "Email:".$_POST["email"]."
";
echo "Password:".$_POST["password"]."
";
echo "Password2:".$_POST["password2"]."
";
?>

                                <input type="text" name="first" class="form-control" placeholder="First name" required style="max-width:250px;" >

                                <input type="text" name="last" class="form-control" placeholder="Last name" required style="max-width:250px;" />

                                <input type="date" name="date" class="dateb" id="dateOfBirth" required  />

                                        <select list="Country" placeholder="Country" name="country2" required class="form-control" style="max-width:250px; " id="Country">
                                            <option >Bosnian</option>
                                            <option >Croat</option>
                                            <option >Serb</option>
                                            <option >English</option>
                                            <option >German</option>
                                            <option >Austrian</option>
                                            <option >Belgian</option>
                                            <option >Swiss</option>
                                            <option >Italian</option>
                                            <option >Romanian</option>
                                            <option >French</option>
                                            <option >Montenegrin</option>
                                            <option >Slovenian</option>
                                        </select>

                                <input type="text" class="form-control" name="street1" placeholder="Street address 1" required style="max-width:250px;" />

                                <input type="text" class="form-control" name="street2" placeholder="Street address 2 (Optional)" style="max-width:250px;" />

                                <input type="text" class="form-control" name="city" placeholder="City" required style="max-width:250px;" />

                                <input type="text" class="form-control" name="region" placeholder="Province/Region" required style="max-width:250px;" />

                                <input type="text" class="form-control" name="postal" placeholder="Postal code" required style="max-width:250px;" />

                                <input type="tel" class="form-control" name="phone" placeholder="Phone number" required style="max-width:250px;" />

                                <input type="checkbox" name="terms" > I have read and agree to the Terms and WBC's User Agreement.

                                <input type="Submit" name="insert" value="Continue" class="btn btn-primary btn-lg">

            </form>

Final Step.

<title>get data from another page</title>

<?php
echo "Country:" .$_POST["country"]."
";
echo "Email:".$_POST["email"]."
";
echo "Password:".$_POST["password"]."
";
echo "Password2:".$_POST["password2"]."
";

echo "First name:" .$_POST["first"]."
";
echo "Last name:".$_POST["last"]."
";
echo "Date:".$_POST["date"]."
";
echo "Country2:".$_POST["country2"]."
";
echo "Street1:" .$_POST["street1"]."
";
echo "Street2:".$_POST["street2"]."
";
echo "City:".$_POST["city"]."
";
echo "Region:".$_POST["region"]."
";
echo "Postal code:" .$_POST["postal"]."
";
echo "Phone number:".$_POST["phone"]."
";
?>

Body:
You've got a number of problems. First, your option fields don't have values.

What you have: <option>Bosnia</option>

What you need: <option value="bosnia" >Bosnia</option>

You should also have a default as your first option, otherwise your program is going to assume that everyone who doesn't pick something has the first option, and you are going to get a million submissions that are not accurate. Eg:

<option value="false" selected="selected">Please select an option from below</option>

Then your backend should be checking like this:

<?php
if (!isset($_POST['country'] || $_POST['country'] === 'false')
{
    //They did not pick a country, and you need to bounce them back to the form with an error message.
    header('Location: /path/to/your/form');
    exit;
}
//country is defined, you can continue,
//but you should pre-validate the other required field here also.
//do not assume things are right, assumptions = bugs.
...

The anchor tag you have surrounding your submit button may be redirecting instead of submitting the form, in which case your $_POST will be completely empty. The below tag you have:

<a href="page2.php"> <input type="button" value="Next" class="btn btn-primary" style="width:150px;"></a>

Needs to look more like this:

<input type="submit" value="Next" class="btn btn-primary" style="width:150px;">

Or alternately:

<button type="submit" class="btn btn-primary" style="width:150px;">Next</button>

If you are stumped, put this at the beginning of what you have on your processing code:

echo '<pre>' . print_r($_POST, 1); exit;

This will show you what was submitted, and let you work through from there as needed.

In general, your conditionals should check if a key exists before validating it if there is any ambiguity as to whether or not it is set:

//BAD
if ($_POST['country'] == 'someval') { ... }

//GOOD
if (array_key_exists('country', $_POST) && $_POST['country'] == 'someval') { ... }

You can also check with isset($_POST['country']); HOWEVER, if null values are valid for whatever you are checking, then this will return false, even if the key is there. So in any case where null is valid, you need to use array_key_exists() instead.

Instead of passing variables directly from one page to another, it's a lot easier if you use $_SESSION, so if they derp up and hit back or walk away for a while, the values are not entirely lost. Users hate having to redundantly redo things, and will probably entirely lose interest in your site if they have to do that. Instead, you can set the values if they exist into session memory like this:

<?php
session_start(); //you have to do this before printing ANY other content.
$_SESSION['country'] = (isset($_POST['country']) ? $_POST['country'] : null);

And then you can retrieve this at any time from any page by doing:

<?php
session_start();
echo $_SESSION['country'];

and if you want to clear them, you just do:

<?php
session_start(); //can't destroy a non-existent session, you have to do this first
session_destroy(); //clears the session
session_start(); //starts a new one

Stashing ongoing form values in the session temporarily lets you access them for as long as the session cookie lasts, so they are not lost if the user quits your form, goes to another site, then comes back to finish. Your form will have to put these back in manually though, so an input might look something like this

<input type="password" name="password" value="<?= isset($_SESSION) && isset($_SESSION['password'] ? $_SESSION['password'] : null; ?>" />

I tried to explain the relevant logic you are not applying rather than just the specific use case, because without actually grasping what the underlying lack of logic is, you would otherwise probably just hit the same wall again. Hopefully this saves you from a number of other bugs that you would otherwise likely hit immediately after this specific thing gets fixed for you.


答:
The problem is right here:

```<code>strtok( phone, "(" );
area_code = strtok( phone, ")" );
</code>```

Because the second call passes a non-NULL pointer, it doesn't continue processing the first string, it starts over beginning at the pointer passed, which is now a string of length zero.

In any case, overwriting the string you are parsing is bad style.  If you use strtol, a single call will give you BOTH the numeric value of a group of digits AND a pointer following the digits, where you can start processing the next group of digits.

But if you just are going to print the digits back out, you don't need a numeric conversion at all.  Just remove all punctuation.

Despite having 5/6 characters the same, strtok is not part of the str-to-x family of functions.  Those are strtol returning a long integer, and strtod returning a double.

Title: trying to get rid of a character using strtok in c

Body:
So I need to be able to input a string as a phone number like so:
(555)-444-3333.
After that I need to use strtok to remove the parentheses and dashes, and convert the strings area code and the rest of the phone number to just integers and print them out all together
My problem is using strtok to get rid of the  ( , because if I don't the area code will just print 0 when it's converted to an int. Here's what I have:

int main()
{
phone[14];
int* area_code;
int* digits;
int* i, j;

printf("Enter a phone number: ");
scanf("%s", phone);

strtok( phone, "(" );
area_code = strtok( phone, ")" );
j = atoi(area_code);

printf("%d", j);

while((digits = strtok(NULL, "-")) != NULL )
{
i = atoi(digits);
printf("%d", digits);
}

return 0;
}

Body:
The problem is right here:

strtok( phone, "(" );
area_code = strtok( phone, ")" );

Because the second call passes a non-NULL pointer, it doesn't continue processing the first string, it starts over beginning at the pointer passed, which is now a string of length zero.

In any case, overwriting the string you are parsing is bad style.  If you use strtol, a single call will give you BOTH the numeric value of a group of digits AND a pointer following the digits, where you can start processing the next group of digits.

But if you just are going to print the digits back out, you don't need a numeric conversion at all.  Just remove all punctuation.

Despite having 5/6 characters the same, strtok is not part of the str-to-x family of functions.  Those are strtol returning a long integer, and strtod returning a double.


问:
Python: output to multiple redirects
In C++, I can output to cout and cerr; in practice this results in code wherein I can redirect output to two files at once like:

```<code>./some_program > first_file.something 2> second_file.else
</code>```

How would I accomplish this in python?

答:
https://docs.python.org/3/library/sys.html

```<code>sys.stdout
sys.stderr
</code>```

confused about stdin, stdout and stderr?

Title: Python: output to multiple redirects

Body:
In C++, I can output to cout and cerr; in practice this results in code wherein I can redirect output to two files at once like:

./some_program > first_file.something 2> second_file.else

How would I accomplish this in python?

Body:
https://docs.python.org/3/library/sys.html

sys.stdout
sys.stderr

confused about stdin, stdout and stderr?


答:
Django rest framework provides generic view you don't require Mixins.
You can directly use RetrieveUpdateAPIView. Provides request methods get to retrieve data, put update data and patch for partial update.

```<code>from rest_framework.generics import RetrieveUpdateAPIView

class ProfileUpdateView(RetrieveUpdateAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = (IsAuthenticated, )
</code>```

Reference: http://www.django-rest-framework.org/api-guide/generic-views/#retrieveupdateapiview

Title: django rest framework same route, different

Body:
i'm using django rest framework to build an api, here is my problem

url(r'^profiles/(?P<pk>[0-9]*)', ProfileRetrieveView.as_view(), name='profiles-detail'),
url(r'^profiles/(?P<pk>[0-9]*)', ProfileUpdateView.as_view(), name='profiles-update'),

    class ProfileRetrieveView(RetrieveAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

class ProfileUpdateView(UpdateAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = (IsAuthenticated, )

When i query the api with the link /profile/2 and the method patch, i receive 405, method not allowed, only the get method is allowed, how can i solve that without haven to transform my two view classes into on class with a GenericView Base class and Retrive + update Mixins.

Body:
Django rest framework provides generic view you don't require Mixins.
You can directly use RetrieveUpdateAPIView. Provides request methods get to retrieve data, put update data and patch for partial update.

from rest_framework.generics import RetrieveUpdateAPIView

class ProfileUpdateView(RetrieveUpdateAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = (IsAuthenticated, )

Reference: http://www.django-rest-framework.org/api-guide/generic-views/#retrieveupdateapiview


问:
Using Conda develop to add source code modules doesn't resolve conda packages
I have a requirement to import a dependency using it's source directory. (Names are obfuscated because this is for work).

So I used conda develop which adds a conda.pth file in site-packages

```<code>[user@user folder]$ conda develop /path/to/source/
added /path/to/source/
completed operation for: /path/to/source/
</code>```

The new module resolves, when I run the code using python.py, but then it doesn't resolve dependencies in conda itself. ie:

```<code>(dq) [user@user]$ python file.py
Traceback (most recent call last):
  File "file.py", line 10, in <module>
    import utils as utils
*...
Various stack trace with import getting resolved
...*
    import Pyro.errors
ImportError: No module named errors
</code>```

So Pyro is a package installed in the dq conda environment, but for some reason through the source code imported through conda develop, it can't find the import. I'm not sure if this itself is an issue, but the developer of the code also had the ingenious idea of naming the module Pyro.py and then importing Pyro.errors at the top of the module. Is there a way to have conda imports take precedence over the source code? Or be resolved in the first place?

Thanks in advance for the help!

答: Probably you should change the package of Python you work with to another newer or older one from the Conda page shown by Jupyter as shown in this .

Body:
I have a requirement to import a dependency using it's source directory. (Names are obfuscated because this is for work).

So I used conda develop which adds a conda.pth file in site-packages

[user@user folder]$ conda develop /path/to/source/
added /path/to/source/
completed operation for: /path/to/source/

The new module resolves, when I run the code using python.py, but then it doesn't resolve dependencies in conda itself. ie:

(dq) [user@user]$ python file.py
Traceback (most recent call last):
  File "file.py", line 10, in <module>
    import utils as utils
*...
Various stack trace with import getting resolved
...*
    import Pyro.errors
ImportError: No module named errors

So Pyro is a package installed in the dq conda environment, but for some reason through the source code imported through conda develop, it can't find the import. I'm not sure if this itself is an issue, but the developer of the code also had the ingenious idea of naming the module Pyro.py and then importing Pyro.errors at the top of the module. Is there a way to have conda imports take precedence over the source code? Or be resolved in the first place?

Thanks in advance for the help!


答:
If you want to redirect from the command line, it's pretty much the same way you would do in C++:

```<code>python file.py > first_file.txt 2> second_file.txt
</code>```

Programmatically, you can do this with sys.stdout and sys.stderr, by monkey patching those with files of your choice.

Title: Python: output to multiple redirects

Body:
If you want to redirect from the command line, it's pretty much the same way you would do in C++:

python file.py > first_file.txt 2> second_file.txt

Programmatically, you can do this with sys.stdout and sys.stderr, by monkey patching those with files of your choice.


问:
How to rename files in a drectory based on an existing array of names using Python?
I have some video files in a folder (E://Data/Video) with dummy names as

```<code>vid-dummyName.mp4
vid-dummyName (1).mp4
vid-dummyName (2).mp4
vid-dummyName (3).mp4
vid-dummyName (4).mp4
vid-dummyName (5).mp4
</code>```

How can I use Python to rename them based on an exiting array like this:

```<code>import os

path = 'E:/Data/Video'
files = os.listdir(path)
i = 1

names=['Not Dummy Video','Another Not Dummy Video','May be Dummy','Still Thinking','Give it a Name','Tomorrow']

for file in files:
    os.rename(os.path.join(path, file), os.path.join(path, str(i)+'.mp4'))
</code>```

答:
If you need a 1-1 correspondence between 2 or more lists, zip would be the way to do it.

```<code>a = [1, 2, 3]
b = ['a', 'b', 'c']

for i, j in zip(a, b):
 print(i, j)

1 a
2 b
3 c
</code>```

For your example, you'd need to zip files and names together, so thatfiles[i] is renamed to names[i] for any i.

```<code>for i, j in zip(files, names):
    os.rename(os.path.join(path, i), os.path.join(path, '{}.mp4'.format(j)))
</code>```

You could also use enumerate to track the indices of the filenames from os.listdir and provide these indices to the names list while you are iterating:

```<code>for i, name in enumerate(files):
    os.rename(os.path.join(path, name), os.path.join(path, '{}.mp4'.format(names[i])))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have some video files in a folder (E://Data/Video) with dummy names as

vid-dummyName.mp4
vid-dummyName (1).mp4
vid-dummyName (2).mp4
vid-dummyName (3).mp4
vid-dummyName (4).mp4
vid-dummyName (5).mp4

How can I use Python to rename them based on an exiting array like this:

import os

path = 'E:/Data/Video'
files = os.listdir(path)
i = 1

names=['Not Dummy Video','Another Not Dummy Video','May be Dummy','Still Thinking','Give it a Name','Tomorrow']

for file in files:
    os.rename(os.path.join(path, file), os.path.join(path, str(i)+'.mp4'))

Body:
If you need a 1-1 correspondence between 2 or more lists, zip would be the way to do it.

a = [1, 2, 3]
b = ['a', 'b', 'c']

for i, j in zip(a, b):
 print(i, j)

1 a
2 b
3 c

For your example, you'd need to zip files and names together, so thatfiles[i] is renamed to names[i] for any i.

for i, j in zip(files, names):
    os.rename(os.path.join(path, i), os.path.join(path, '{}.mp4'.format(j)))

You could also use enumerate to track the indices of the filenames from os.listdir and provide these indices to the names list while you are iterating:

for i, name in enumerate(files):
    os.rename(os.path.join(path, name), os.path.join(path, '{}.mp4'.format(names[i])))


问:
Biopython: MMTFParser can't find distances between atoms
I'm using biopython to find the distance between the C alpha atoms of two residues and I keep getting an error. Here's my code and the error:

```</p>

```>>> from Bio.PDB.mmtf import MMTFParser
>>> structure = MMTFParser.get_structure_from_url('4mne')
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain A is discontinuous at line 0.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain D is discontinuous at line 0.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain E is discontinuous at line 0.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain F is discontinuous at line 0.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain H is discontinuous at line 0.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain B is discontinuous at line 0.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain C is discontinuous at line 0.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain G is discontinuous at line 0.
  PDBConstructionWarning)
>>> for c in structure.get_chains():
...     if c.get_id() == 'B':
...             chain = c
...
>>> chain
<Chain id=B>
>>> CAatoms = [a for a in chain.get_atoms() if a.id == 'CA']
>>> for a in CAatoms:
...     for b in CAatoms:
...             distance = a-b
...
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "/Library/Python/2.7/site-packages/Bio/PDB/Atom.py", line 124, in __sub__
    diff = self.coord - other.coord
TypeError: unsupported operand type(s) for -: 'list' and 'list'
>>>
```

<p>```

Does this have something to do with the "get_structure_from_url" method of the MMTFParser?
I've tried this with PDBParser().get_structure and it worked fine.

答:
Biopython's atom class has a custom subtraction method.

From the source code:

```<code>def __sub__(self, other):
    """Calculate distance between two atoms.
    :param other: the other atom
    :type other: L{Atom}
    Examples
    --------
    >>> distance = atom1 - atom2
    """
    diff = self.coord - other.coord
    return numpy.sqrt(numpy.dot(diff, diff))
</code>```

For MMTFParser this feature seems to be missing but you can easily do it yourself.

MMTFParser reads the coordinates as a list (init_atom(str(atom_name), [x, y, z] ..., line 53), unlike PDBParser which reads the coordinates as a Numpy array (coord = numpy.array((x, y, z), "f"), line 187).

In order to get the distance you can convert the coordinate lists to a Numpy array and then calculate the distance.

```<code>import numpy as np
distance = np.linalg.norm(np.array(a.coord) - np.array(b.coord))
</code>```

Body:
I'm using biopython to find the distance between the C alpha atoms of two residues and I keep getting an error. Here's my code and the error:

```</p>

<pre><code>>>> from Bio.PDB.mmtf import MMTFParser
>>> structure = MMTFParser.get_structure_from_url('4mne')
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain A is discontinuous at line 0.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain D is discontinuous at line 0.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain E is discontinuous at line 0.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain F is discontinuous at line 0.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain H is discontinuous at line 0.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain B is discontinuous at line 0.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain C is discontinuous at line 0.
  PDBConstructionWarning)
/Library/Python/2.7/site-packages/Bio/PDB/StructureBuilder.py:89: PDBConstructionWarning: WARNING: Chain G is discontinuous at line 0.
  PDBConstructionWarning)
>>> for c in structure.get_chains():
...     if c.get_id() == 'B':
...             chain = c
...
>>> chain
<Chain id=B>
>>> CAatoms = [a for a in chain.get_atoms() if a.id == 'CA']
>>> for a in CAatoms:
...     for b in CAatoms:
...             distance = a-b
...
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "/Library/Python/2.7/site-packages/Bio/PDB/Atom.py", line 124, in __sub__
    diff = self.coord - other.coord
TypeError: unsupported operand type(s) for -: 'list' and 'list'
>>>
</code></pre>

<p>```

Does this have something to do with the "get_structure_from_url" method of the MMTFParser?
I've tried this with PDBParser().get_structure and it worked fine.

Body:
Biopython's atom class has a custom subtraction method.

From the source code:

def __sub__(self, other):
    """Calculate distance between two atoms.
    :param other: the other atom
    :type other: L{Atom}
    Examples
    --------
    >>> distance = atom1 - atom2
    """
    diff = self.coord - other.coord
    return numpy.sqrt(numpy.dot(diff, diff))

For MMTFParser this feature seems to be missing but you can easily do it yourself.

MMTFParser reads the coordinates as a list (init_atom(str(atom_name), [x, y, z] ..., line 53), unlike PDBParser which reads the coordinates as a Numpy array (coord = numpy.array((x, y, z), "f"), line 187).

In order to get the distance you can convert the coordinate lists to a Numpy array and then calculate the distance.

import numpy as np
distance = np.linalg.norm(np.array(a.coord) - np.array(b.coord))


答:
E.g. in Python 3, just import the equivalents of cout and cerr, namely sys.stdout and sys.stderr.

from sys import stdout, stderr

print('to standard output', file=stdout)
print('to standard error', file=stderr)
```

<p>Then you can use your bash redirection as you normally would:</p>

<pre class="lang-sh prettyprint-override"><code>python program.py 1>output 2>errors
</code>```

And if you want, you can even name them whatever you like. E.g.:

from sys import stdout as cout, stderr as cerr

print('to standard output', file=cout)
print('to standard error', file=cerr)
```

It's less "Pythonic," but if it helps you bridge the gap from your C++ experience, it may be a help.

Title: Python: output to multiple redirects

Body:
E.g. in Python 3, just import the equivalents of cout and cerr, namely sys.stdout and sys.stderr.

from sys import stdout, stderr

print('to standard output', file=stdout)
print('to standard error', file=stderr)

Then you can use your bash redirection as you normally would:

python program.py 1>output 2>errors

And if you want, you can even name them whatever you like. E.g.:

from sys import stdout as cout, stderr as cerr

print('to standard output', file=cout)
print('to standard error', file=cerr)

It's less "Pythonic," but if it helps you bridge the gap from your C++ experience, it may be a help.


问:
Passing a cookie using cURL to a website
Some website I need to make a request to, using cURL in PHP, contains a captcha, which can be deactivated via setting a cookie "downloadcaptcha=1". Now how do I pass that cookie to the website on a cURL request? Before, you mark as duplicate, I've already made research and came across to using cookie jar files. I have never done something like that and couldn't find any newbie-friendly documentation.

The JS-equivalent code of setting the cookie, taken from the website's function that disables captchas:

```<code>var exdate=new Date();
var exdays = 1;
var c_name = "downloadcaptcha";
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(1) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value+";path=/";
window.location.reload();
</code>```

I don't want to necessarily make it expire in 1 day.
Help is appreciated.

答:
Here's the output. Not a single mention of the cookie

Request Header is missing the Cookie:

```<code>Host: www.emuparadise.me
Accept: */*
Accept-Encoding: deflate, gzip
Referer: https://m.emuparadise.me/
</code>```

Change the $request to:

```<code>$cookie = '[downloadcaptcha=1'

$request = array();
$request[] = "Host: www.emuparadise.me";
$request[] = "Accept: */*";
$request[] = "Accept-Encoding: deflate, gzip";
$request[] = "Referer: https://m.emuparadise.me/";
$request[] = "Cookie: $cookie";
</code>```

I have tried that already but the website still asks for a captcha.
  Take a look at the JS code I posted. It's taken from the website's
  function to disable captchas

I could help you much better if I had a URL to test with.

If there is a redirect you must use curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

You may have to make the HTTP Request Header look identical to the JS HTTP header.

You need to look at the cURL HTTP request and response and compare it to the JS HTTP request and response.

To see the JS  HTTP request and response:

right click the page

Select Inspect (Chrome) or Insect Element (FireFox)

Select "Network" tab

Go to the page with the JS request or if already there Refresh.

Trouble shooting PHP code:

```<code>$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request);
curl_setopt($ch, CURLOPT_ENCODING,"");

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
curl_setopt($ch, CURLOPT_FAILONERROR,true);
curl_setopt($ch, CURLOPT_ENCODING,"");

curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HEADER, true);

$data = curl_exec($ch);
if (curl_errno($ch)){
    $data .= 'Retreive Base Page Error: ' . curl_error($ch);
}
else {
  $info = rawurldecode(var_export(curl_getinfo($ch),true));

  $skip = intval(curl_getinfo($ch, CURLINFO_HEADER_SIZE));
  $responseHeader= substr($data,0,$skip);
  $response = substr($data,$skip);
   var_export($info);
  echo "----------------------------------\n$responseHeader\n--------------------------\n$response \n------------------------------------\n";

}
</code>```

Original Post

```<code>curl_setopt($ch, CURLOPT_COOKIE, $cookie );
</code>```

Single Cookie

```<code>$cookie = 'CookieName=CookieValue'
</code>```

Multiple Cookies separated by semi-colon.  There is no semi-colon after the last cookie.

```<code>$cookie = 'CookieName=CookieValue; CookieName=CookieValue'

curl_setopt($ch, CURLOPT_COOKIE, $cookie );
</code>```

Cookies can also be set using CURLOPT_HTTPHEADER

See last line of the following example.

```<code>curl_setopt($ch, CURLOPT_HTTPHEADER, $request);

$request = array();
$request[] = "Host: www.example.com";
$request[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
$request[] = "User-Agent: MOT-V9mm/00.62 UP.Browser/6.2.3.4.c.1.123 (GUI) MMP/2.0";
$request[] = "Accept-Language: en-US,en;q=0.5";
$request[] = "Connection: keep-alive";
$request[] = "Cache-Control: no-cache";
$request[] = "Pragma: no-cache";
$request[] = "Cookie: $cookie";
</code>```

Body:
Some website I need to make a request to, using cURL in PHP, contains a captcha, which can be deactivated via setting a cookie "downloadcaptcha=1". Now how do I pass that cookie to the website on a cURL request? Before, you mark as duplicate, I've already made research and came across to using cookie jar files. I have never done something like that and couldn't find any newbie-friendly documentation.

The JS-equivalent code of setting the cookie, taken from the website's function that disables captchas:

var exdate=new Date();
var exdays = 1;
var c_name = "downloadcaptcha";
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(1) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value+";path=/";
window.location.reload();

I don't want to necessarily make it expire in 1 day.
Help is appreciated.

Body:
Here's the output. Not a single mention of the cookie

Request Header is missing the Cookie:

Host: www.emuparadise.me
Accept: */*
Accept-Encoding: deflate, gzip
Referer: https://m.emuparadise.me/

Change the $request to:

$cookie = '[downloadcaptcha=1'

$request = array();
$request[] = "Host: www.emuparadise.me";
$request[] = "Accept: */*";
$request[] = "Accept-Encoding: deflate, gzip";
$request[] = "Referer: https://m.emuparadise.me/";
$request[] = "Cookie: $cookie";

I have tried that already but the website still asks for a captcha.
  Take a look at the JS code I posted. It's taken from the website's
  function to disable captchas

I could help you much better if I had a URL to test with.

If there is a redirect you must use curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

You may have to make the HTTP Request Header look identical to the JS HTTP header.

You need to look at the cURL HTTP request and response and compare it to the JS HTTP request and response.

To see the JS  HTTP request and response:

right click the page

Select Inspect (Chrome) or Insect Element (FireFox)

Select "Network" tab

Go to the page with the JS request or if already there Refresh.

Trouble shooting PHP code:

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request);
curl_setopt($ch, CURLOPT_ENCODING,"");

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
curl_setopt($ch, CURLOPT_FAILONERROR,true);
curl_setopt($ch, CURLOPT_ENCODING,"");

curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HEADER, true);

$data = curl_exec($ch);
if (curl_errno($ch)){
    $data .= 'Retreive Base Page Error: ' . curl_error($ch);
}
else {
  $info = rawurldecode(var_export(curl_getinfo($ch),true));

  $skip = intval(curl_getinfo($ch, CURLINFO_HEADER_SIZE));
  $responseHeader= substr($data,0,$skip);
  $response = substr($data,$skip);
   var_export($info);
  echo "----------------------------------\n$responseHeader\n--------------------------\n$response \n------------------------------------\n";

}

Original Post

curl_setopt($ch, CURLOPT_COOKIE, $cookie );

Single Cookie

$cookie = 'CookieName=CookieValue'

Multiple Cookies separated by semi-colon.  There is no semi-colon after the last cookie.

$cookie = 'CookieName=CookieValue; CookieName=CookieValue'

curl_setopt($ch, CURLOPT_COOKIE, $cookie );

Cookies can also be set using CURLOPT_HTTPHEADER

See last line of the following example.

curl_setopt($ch, CURLOPT_HTTPHEADER, $request);

$request = array();
$request[] = "Host: www.example.com";
$request[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
$request[] = "User-Agent: MOT-V9mm/00.62 UP.Browser/6.2.3.4.c.1.123 (GUI) MMP/2.0";
$request[] = "Accept-Language: en-US,en;q=0.5";
$request[] = "Connection: keep-alive";
$request[] = "Cache-Control: no-cache";
$request[] = "Pragma: no-cache";
$request[] = "Cookie: $cookie";


问:
C++ unwanted destruction
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ?

```<code>#include <iostream>

using namespace std;

class A
{
public:
    int a, b;
};

class B
{
public:
    A* array[10];
    B()
    {
        for(int i = 0 ; i < 10 ; i++)
            array[i] = new A();
    }
    ~B()
    {
        for(int i = 0 ; i < 10 ; i++)
            delete array[i];
    }
};

class C
{
public:
    B b;
    B* d;
    C()
    {
        b = B();
    }
    ~C()
    {
            delete d;
    }
};

int main()
{
    B b = B();
    C c = C();
    cout << "Ashlamish" << endl;
    system("pause");
    return 0;
}
</code>```

答: Because in the constructor of C, you are creating a temporary B object in the line c = B(); and when the assignment is complete, that temporary object is being destroyed.

Title: C++ unwanted destruction

Body:
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ?

#include <iostream>

using namespace std;

class A
{
public:
    int a, b;
};

class B
{
public:
    A* array[10];
    B()
    {
        for(int i = 0 ; i < 10 ; i++)
            array[i] = new A();
    }
    ~B()
    {
        for(int i = 0 ; i < 10 ; i++)
            delete array[i];
    }
};

class C
{
public:
    B b;
    B* d;
    C()
    {
        b = B();
    }
    ~C()
    {
            delete d;
    }
};

int main()
{
    B b = B();
    C c = C();
    cout << "Ashlamish" << endl;
    system("pause");
    return 0;
}


问:
Python BeautifulSoup scraping web page that has protection
I am new to Python. My recent project is to get the odd information from a website.

Here is the URL:

http://bet.hkjc.com/default.aspx?url=football/odds/odds_allodds.aspx&lang=EN&tmatchid=120998

I am using Python and BeautifulSoup to process, i cant see any odd data when get the html by

```<code>soup.prettify()
</code>```

The result from above code i got is only logical code, variable and function. i think the page have some protection to the data

what should i do to get the odd information from the protected web page?

答:
The answer posted by SuperStew is right but the page loads "http://bet.hkjc.com/football/odds/odds_allodds.aspx?lang=EN&tmatchid=120998" using JavaScript it is this page that has the data on odds. You didn't state which odds you wanted but the code below is an example of one way to get some data if you want other data you will have to modify it.

```<code>import bs4
import requests
url = "http://bet.hkjc.com/football/odds/odds_allodds.aspx?lang=EN&tmatchid=120998"
page = requests.get(url)
soup = bs4.BeautifulSoup(page.text,'lxml')
tOdds = soup.findAll('table', {'class':"tOdds"})
for tOdd in tOdds:
    print (tOdd.text)
</code>```

Outputs:

```<code>  Jong PSV Eindhoven(Home) Draw Jong Utrecht(Away)   1.53 4.00 4.60
  Jong PSV Eindhoven(Home) Draw Jong Utrecht(Away)   1.97 2.45 4.70
  Jong PSV Eindhoven[-1](Home) Draw Jong Utrecht[+1](Away)   2.45 3.60 2.26
  Line High Low  [3/3.5]2.021.70
  Line High Low   [1.5]2.191.60
     1.44    18.00    2.65
  0 1 2 3 4 5 6 7+   18.00 6.60 4.10 3.65 4.50 6.70 11.00 14.00
  Odd Even   1.90 1.80
  H H H D D D A A A   H D A H D A H D A   2.30 14.00 34.00 4.70 6.50 10.50 19.00 14.00 7.50
</code>```

Body:
I am new to Python. My recent project is to get the odd information from a website.

Here is the URL:

http://bet.hkjc.com/default.aspx?url=football/odds/odds_allodds.aspx&lang=EN&tmatchid=120998

I am using Python and BeautifulSoup to process, i cant see any odd data when get the html by

soup.prettify()

The result from above code i got is only logical code, variable and function. i think the page have some protection to the data

what should i do to get the odd information from the protected web page?

Body:
The answer posted by SuperStew is right but the page loads "http://bet.hkjc.com/football/odds/odds_allodds.aspx?lang=EN&tmatchid=120998" using JavaScript it is this page that has the data on odds. You didn't state which odds you wanted but the code below is an example of one way to get some data if you want other data you will have to modify it.

import bs4
import requests
url = "http://bet.hkjc.com/football/odds/odds_allodds.aspx?lang=EN&tmatchid=120998"
page = requests.get(url)
soup = bs4.BeautifulSoup(page.text,'lxml')
tOdds = soup.findAll('table', {'class':"tOdds"})
for tOdd in tOdds:
    print (tOdd.text)

Outputs:

  Jong PSV Eindhoven(Home) Draw Jong Utrecht(Away)   1.53 4.00 4.60
  Jong PSV Eindhoven(Home) Draw Jong Utrecht(Away)   1.97 2.45 4.70
  Jong PSV Eindhoven[-1](Home) Draw Jong Utrecht[+1](Away)   2.45 3.60 2.26
  Line High Low  [3/3.5]2.021.70
  Line High Low   [1.5]2.191.60
     1.44    18.00    2.65
  0 1 2 3 4 5 6 7+   18.00 6.60 4.10 3.65 4.50 6.70 11.00 14.00
  Odd Even   1.90 1.80
  H H H D D D A A A   H D A H D A H D A   2.30 14.00 34.00 4.70 6.50 10.50 19.00 14.00 7.50


问:
Laravel mail parameters (sendmail/smtp)
I'm trying to figure out how to set my mail parameters.

I have a domain name production.mydomain.be. I've created a mail address no-reply@mydomain.be. But my question is now, how do I set my mail parameters? Do I chose sendmail or smtp?

The Laravel documentation is not saying much about sendmail / smtp.

答:
You should choose smtp

You need to fill username and password fields in order to login with the smtp server, and also provide the valid information for that connection with the host and the port. Your server manage should give you that information, along with the encryption.

Title: Laravel mail parameters (sendmail/smtp)


问:
Is it possible for Rollup to preserve file and folder structure?
I'm using ES6 imports and transpiling them with Rollup.

The output is a single bundle file.

Can Rollup be configured to generate a file-for-file transpile result?

Here is the current configuration I'm using which obviously spits out one file.

```<code> gulp.task('rollup', function() {
    const rollup = require('rollup');
    const nodeResolve = require('rollup-plugin-node-resolve');

    const JS_INDEX_FILE = 'src/index.js';

    return rollup.rollup({
        input: JS_INDEX_FILE,
        plugins: [
            nodeResolve({
                browser: true
            })
        ]
    }).then(bundle => {
            bundle.write({
                sourcemap: true,
                format: 'cjs',
                strict: true,
                file: 'bundle.js'
            });
        });
});
</code>```

Basically, I'd like individual files with require() instead of import.

答: Rollup is a module bundler. What you want is a compiler, such as Babel.

Body:
I'm using ES6 imports and transpiling them with Rollup.

The output is a single bundle file.

Can Rollup be configured to generate a file-for-file transpile result?

Here is the current configuration I'm using which obviously spits out one file.

 gulp.task('rollup', function() {
    const rollup = require('rollup');
    const nodeResolve = require('rollup-plugin-node-resolve');

    const JS_INDEX_FILE = 'src/index.js';

    return rollup.rollup({
        input: JS_INDEX_FILE,
        plugins: [
            nodeResolve({
                browser: true
            })
        ]
    }).then(bundle => {
            bundle.write({
                sourcemap: true,
                format: 'cjs',
                strict: true,
                file: 'bundle.js'
            });
        });
});

Basically, I'd like individual files with require() instead of import.


问:
input.value is returning undefined
Input:

```<code><input type="radio" name="options" id="onetime" autocomplete="off" value="90" class='planSelect'> One-Time 6 Months
</code>```

jQuery:

```<code>$('.planSelect').value;
</code>```

This is returning "90undefined" and I have no idea why?

答:
$('.planSelect') returns a jQuery selector, use .val to access its value

Use $('.planSelect').val(); instead.

let index = 0;
let randomColors = ["red","green","blue"];

function run(){
     $("#result").text($('.planSelect').val()).css("color",randomColors[index++%3]);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="options" id="onetime" autocomplete="off" value="90" class='planSelect'> One-Time 6 Months
<div> Result: <span id="result"></span></div>
<button onclick="run()">Rerun</button></code>```

Title: input.value is returning undefined

Body:
Input:

<input type="radio" name="options" id="onetime" autocomplete="off" value="90" class='planSelect'> One-Time 6 Months

jQuery:

$('.planSelect').value;

This is returning "90undefined" and I have no idea why?

Body:
$('.planSelect') returns a jQuery selector, use .val to access its value

Use $('.planSelect').val(); instead.

let index = 0;
let randomColors = ["red","green","blue"];

function run(){
     $("#result").text($('.planSelect').val()).css("color",randomColors[index++%3]);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="options" id="onetime" autocomplete="off" value="90" class='planSelect'> One-Time 6 Months
<div> Result: <span id="result"></span></div>
<button onclick="run()">Rerun</button>


问:
Xcode 9 Wireless debugging not working
For some reason the wireless debugging does not work here. Here is what I've done:

Using newest Xcode 9

Using newest iOS 11 on my iPhone 7+

Both devices are in the same network

Connected the iPhone via Lightning, selected "Connect via Network" in the Devices & Simulator menu

Run an app on the iPhone while still connected via Lightning - everything works

But as soon as I unplug the phone, Xcode is no longer able to connect with the phone. I can ping the phone with the Mac, but even the "connect via ip" option in Xcode does not work.

Anybody got tips on how to get this working?

答: I had the same issue, but it was intermittent - i.e. sometimes the globe would not appear next to the phone name in Xcode Devices and Simulators window and when the phone was disconnected from the lighting cable, I could not debug to it from Xcode.  My fix was much simpler, though - I just turned WiFi on and off both on the Mac and on the phone.  After the devices reconnected to the network wireless debugging was available again.  This seems to be an issue with the network communication (regardless whether the device can be pinged or not).</p>

Title: Xcode 9 Wireless debugging not working