问:
trying to defuse Binary Bomb phase 5 (phase_5)
This seems like a very popular question but i've been looking at this for a few hours now, and i just cant seem to decode it. I do know I need a lookup table and to somehow create a six digit string that is equivalent 0x34, also each character from my input string is ANDed with 0xf, and the result is used to get the character with the corresponding index from the array. Just cant seem to find 6 suitable characters to defuse the bomb.</p>

```<code>Dump of assembler code for function phase_5:
=> 0x08048dd5 <+0>: push   %ebx
   0x08048dd6 <+1>: sub    $0x14,%esp
   0x08048dd9 <+4>: mov    0x1c(%esp),%ebx
   0x08048ddd <+8>: push   %ebx
   0x08048dde <+9>: call   0x8049043 <string_length>
   0x08048de3 <+14>:    add    $0x10,%esp
   0x08048de6 <+17>:    cmp    $0x6,%eax
   0x08048de9 <+20>:    je     0x8048df0 <phase_5+27>
   0x08048deb <+22>:    call   0x8049159 <explode_bomb>
   0x08048df0 <+27>:    mov    %ebx,%eax
   0x08048df2 <+29>:    add    $0x6,%ebx
   0x08048df5 <+32>:    mov    $0x0,%ecx
   0x08048dfa <+37>:    movzbl (%eax),%edx
   0x08048dfd <+40>:    and    $0xf,%edx
   0x08048e00 <+43>:    add    0x804a100(,%edx,4),%ecx
   0x08048e07 <+50>:    add    $0x1,%eax
   0x08048e0a <+53>:    cmp    %ebx,%eax
   0x08048e0c <+55>:    jne    0x8048dfa <phase_5+37>
   0x08048e0e <+57>:    cmp    $0x34,%ecx
   0x08048e11 <+60>:    je     0x8048e18 <phase_5+67>
   0x08048e13 <+62>:    call   0x8049159 <explode_bomb>
   0x08048e18 <+67>:    add    $0x8,%esp
   0x08048e1b <+70>:    pop    %ebx
   0x08048e1c <+71>:    ret
End of assembler dump.
(gdb)
(gdb) x/16dw 0x804a100
0x804a100 <array.3248>: 2   10  6   1
0x804a110 <array.3248+16>:  12  16  9   3
0x804a120 <array.3248+32>:  4   7   14  5
0x804a130 <array.3248+48>:  11  8   15  13

</code>```

答:
so i needed to create a six character string that is equivalent 0x34 which is 52.
i used abcdef, ghijkl, mnopqr as test strings while using (gdb) info r to observe the changes in register ecx for each different character while the program was looping eg. a ->10, b ->6...
so as to save time i created a breakpoint at  0x08048e07.
then i use 6 characters summing up to 52.
eg. of solutions are:
dmmmmm,
mmmmmd</p>

```<code>a=10 10
b=16 6
c=17 1
d=29 12
e=45 16
f=54 9

g=3  3
h=7  4
i=14 7
j=28 21
k=33 5
l=44 11

m=8   8
n=23  15
o=36  13
p=38  3
q=48  10
r=54  6
</code>```

Body:
This seems like a very popular question but i've been looking at this for a few hours now, and i just cant seem to decode it. I do know I need a lookup table and to somehow create a six digit string that is equivalent 0x34, also each character from my input string is ANDed with 0xf, and the result is used to get the character with the corresponding index from the array. Just cant seem to find 6 suitable characters to defuse the bomb.

Dump of assembler code for function phase_5:
=> 0x08048dd5 <+0>: push   %ebx
   0x08048dd6 <+1>: sub    $0x14,%esp
   0x08048dd9 <+4>: mov    0x1c(%esp),%ebx
   0x08048ddd <+8>: push   %ebx
   0x08048dde <+9>: call   0x8049043 <string_length>
   0x08048de3 <+14>:    add    $0x10,%esp
   0x08048de6 <+17>:    cmp    $0x6,%eax
   0x08048de9 <+20>:    je     0x8048df0 <phase_5+27>
   0x08048deb <+22>:    call   0x8049159 <explode_bomb>
   0x08048df0 <+27>:    mov    %ebx,%eax
   0x08048df2 <+29>:    add    $0x6,%ebx
   0x08048df5 <+32>:    mov    $0x0,%ecx
   0x08048dfa <+37>:    movzbl (%eax),%edx
   0x08048dfd <+40>:    and    $0xf,%edx
   0x08048e00 <+43>:    add    0x804a100(,%edx,4),%ecx
   0x08048e07 <+50>:    add    $0x1,%eax
   0x08048e0a <+53>:    cmp    %ebx,%eax
   0x08048e0c <+55>:    jne    0x8048dfa <phase_5+37>
   0x08048e0e <+57>:    cmp    $0x34,%ecx
   0x08048e11 <+60>:    je     0x8048e18 <phase_5+67>
   0x08048e13 <+62>:    call   0x8049159 <explode_bomb>
   0x08048e18 <+67>:    add    $0x8,%esp
   0x08048e1b <+70>:    pop    %ebx
   0x08048e1c <+71>:    ret
End of assembler dump.
(gdb)
(gdb) x/16dw 0x804a100
0x804a100 <array.3248>: 2   10  6   1
0x804a110 <array.3248+16>:  12  16  9   3
0x804a120 <array.3248+32>:  4   7   14  5
0x804a130 <array.3248+48>:  11  8   15  13

Body:
so i needed to create a six character string that is equivalent 0x34 which is 52.
i used abcdef, ghijkl, mnopqr as test strings while using (gdb) info r to observe the changes in register ecx for each different character while the program was looping eg. a ->10, b ->6...
so as to save time i created a breakpoint at  0x08048e07.
then i use 6 characters summing up to 52.
eg. of solutions are:
dmmmmm,
mmmmmd

a=10 10
b=16 6
c=17 1
d=29 12
e=45 16
f=54 9

g=3  3
h=7  4
i=14 7
j=28 21
k=33 5
l=44 11

m=8   8
n=23  15
o=36  13
p=38  3
q=48  10
r=54  6


来源: stackexchange

问:
Change colour of button highlighted when using tab button
I'm currently trying to make my application more keyboard/visually friendly for a user. I added a few features that will provide a better visual indication for the user but I noticed when using the buttons it's difficult to see when the button is currently highlighted when tabbing down the application.

Example

As shown in the example, we can see that the button on the left is highlighted. However I would like it so either the highlight feature is a different cover or is bigger so the user can see that is the case.

```<code> <button class="btn btn-blue" ng-click="handleCreate()" ng-show="isNew" ng-disabled="detailsForm.$invalid">
        Create
 </button>
</code>```

I would assume I need to modify the css, but I'm not too sure how to achieve that or what tags I would need. Any suggestions?

答:
For that there is :focus selector. (Read more)

button:focus {
  background: #ff0000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>TEST1</button>
<button>TEST2</button>
<button>TEST3</button></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm currently trying to make my application more keyboard/visually friendly for a user. I added a few features that will provide a better visual indication for the user but I noticed when using the buttons it's difficult to see when the button is currently highlighted when tabbing down the application.

Example

As shown in the example, we can see that the button on the left is highlighted. However I would like it so either the highlight feature is a different cover or is bigger so the user can see that is the case.

 <button class="btn btn-blue" ng-click="handleCreate()" ng-show="isNew" ng-disabled="detailsForm.$invalid">
        Create
 </button>

I would assume I need to modify the css, but I'm not too sure how to achieve that or what tags I would need. Any suggestions?

Body:
For that there is :focus selector. (Read more)

button:focus {
  background: #ff0000;
}

<button>TEST1</button>
<button>TEST2</button>
<button>TEST3</button>


问:
Hide LINK in user account Prestashop for a specific USer Group ID
Hi guys according with this screenshot
i want to hide this links tabs for a specific id group user in Prestashop 1.7.6.
is there any way?
thanks!</p>

答:
I guess that wrapping the code in theme/templates/customer/my-account.tpl within a condition

```<code>{if $customer.id_default_group != 'limited_group_id_here'}
   // code goes here
{/if}
</code>```

would be enough

Body:
I guess that wrapping the code in theme/templates/customer/my-account.tpl within a condition

{if $customer.id_default_group != 'limited_group_id_here'}
   // code goes here
{/if}

would be enough


问:
Dynamoose- error while saving custom type using object: Expected xxx to be of type object, instead found type object
I'm trying to migrate my mongoose code/db to dynamoose/dynamodb.

I get the following exception while trying to save custom object:

TypeMismatch: Expected name to be of type object, instead found type object

Here is my sample code on nodejs / typescript:

```<code>import dynamoose from "dynamoose";

export = {
    run: async() => {
        dynamoose.aws.sdk.config.update({
            "accessKeyId": "AKID",
            "secretAccessKey": "SECRET",
            "region": "us-east-1"
        });
        dynamoose.aws.ddb.local();
        const Man = dynamoose.model('Man', {
            id: String,
            name: {
                type: Object,
                schema: {
                    firstname: String,
                    lastname: String
                }
            }});
        Man.create({
            id:"random",
            name: new Name("John", "Martin")
        });
    }
}.run();

class Name {
    firstname: string;
    lastname: string;
    constructor(firstname: string, lastname: string){
        this.firstname = firstname;
        this.lastname = lastname;
    }
}
</code>```

How can I fix this?

答:
I got it working using this as identified in this issue on Github:

Man.create({
    id:"random",
    name: { ...new Name("John", "Martin") }
});
```

Not sure if there is any better way though.

Body:
I'm trying to migrate my mongoose code/db to dynamoose/dynamodb.

I get the following exception while trying to save custom object:

TypeMismatch: Expected name to be of type object, instead found type object

Here is my sample code on nodejs / typescript:

import dynamoose from "dynamoose";

export = {
    run: async() => {
        dynamoose.aws.sdk.config.update({
            "accessKeyId": "AKID",
            "secretAccessKey": "SECRET",
            "region": "us-east-1"
        });
        dynamoose.aws.ddb.local();
        const Man = dynamoose.model('Man', {
            id: String,
            name: {
                type: Object,
                schema: {
                    firstname: String,
                    lastname: String
                }
            }});
        Man.create({
            id:"random",
            name: new Name("John", "Martin")
        });
    }
}.run();

class Name {
    firstname: string;
    lastname: string;
    constructor(firstname: string, lastname: string){
        this.firstname = firstname;
        this.lastname = lastname;
    }
}

How can I fix this?

Body:
I got it working using this as identified in this issue on Github:

Man.create({
    id:"random",
    name: { ...new Name("John", "Martin") }
});

Not sure if there is any better way though.


问:
PHP FPM dies every request in Cloud Run
I'm trying to run an example application in Google Cloud Run (Fully managed). Every time I send a request to the instance, I get a 503 Service unavailable.

The logs tell me, the process is restarted every time on the same PID, so the process is dying with every request.

Since I have a very standard image, i'm not sure if there is a mistake I made or a misunderstanding on how the things are working.

Dockerfile

```<code>FROM php:7.4-fpm-alpine3.11

RUN sed -i 's/9000/${PORT}/' /usr/local/etc/php-fpm.d/zz-docker.conf

RUN mkdir /var/www/public; echo 'This page works' > /var/www/public/index.php
EXPOSE ${PORT}
CMD ["php-fpm", "-F", "-R"]
</code>```

Logs:

答: Currently I am assuming that the error is due to the missing HTTP Server in the fpm container. I followed the tutorial Daniel provided, which works fine for my current use case.</p>

Title: PHP FPM dies every request in Cloud Run

Body:
I'm trying to run an example application in Google Cloud Run (Fully managed). Every time I send a request to the instance, I get a 503 Service unavailable.

The logs tell me, the process is restarted every time on the same PID, so the process is dying with every request.

Since I have a very standard image, i'm not sure if there is a mistake I made or a misunderstanding on how the things are working.

Dockerfile

FROM php:7.4-fpm-alpine3.11

RUN sed -i 's/9000/${PORT}/' /usr/local/etc/php-fpm.d/zz-docker.conf

RUN mkdir /var/www/public; echo 'This page works' > /var/www/public/index.php
EXPOSE ${PORT}
CMD ["php-fpm", "-F", "-R"]

Logs:


问:
jQuery, use the right selector
I have a div, inside which there is a some text and a number of words surrounded by certain span tags. I want to click on those "spanned" words and have the div slide down, showing an "underlying" div with a text related to that certain spanned word. When i click on the div and not on a spanned word, i want the div to slide back up. Thus i bound some actions to the div and to the class of those spans. however, when i click on a span, the div also gets the click action. How should i change the selectors not to receive a clicking action on the div when i click on the span?

Here is the code:

```<code><div class='mainpage'>
    <p class='common'>bla-bla-bla <span class='footnoted' footnote='f1'>foo bar</span></p>
</div>
</code>```

jQuery code:

```<code>$(document).ready(function(){
    $(".mainpage>.common>.footnoted").click(function(){
        alert('a');
    });

    $(".mainpage").not($(".mainpage>.common>.footnoted")).click(function(){
        alert('b');
    });
});
</code>```

In other words, when i click on "foo bar", i get the "a" and "b" alerts, whereas i want to get only "a". How can i do that?

Thank you in advance.
Timofey.

答: Depending on which event is firing first, you could try adding return false; to the end of your click event function. That should stop the second click event from firing and fix your problem.

ContentLicense: CC BY-SA 3.0

Title: jQuery, use the right selector

Body:
I have a div, inside which there is a some text and a number of words surrounded by certain span tags. I want to click on those "spanned" words and have the div slide down, showing an "underlying" div with a text related to that certain spanned word. When i click on the div and not on a spanned word, i want the div to slide back up. Thus i bound some actions to the div and to the class of those spans. however, when i click on a span, the div also gets the click action. How should i change the selectors not to receive a clicking action on the div when i click on the span?

Here is the code:

bla-bla-bla foo bar

jQuery code:

$(document).ready(function(){
    $(".mainpage>.common>.footnoted").click(function(){
        alert('a');
    });

    $(".mainpage").not($(".mainpage>.common>.footnoted")).click(function(){
        alert('b');
    });
});

In other words, when i click on "foo bar", i get the "a" and "b" alerts, whereas i want to get only "a". How can i do that?

Thank you in advance.
Timofey.


问:
Can I add optional attributes to an element in React?
Currently, in my React app I have this,

```<code><input style={{ borderColor: valid ? null : "red", boxShadow: valid ? null : "rgb(2, 0, 0)"}} />
</code>```

If I have more styling to do, it doesn't make sense checking the same condition again and again right? I wish to make the entire style attribute optional; something like this,

```<code><input valid ? null : style={{ borderColor: "red", boxShadow: "rgb(2, 0, 0)"}} />
</code>```

But I know that's not the right syntax. Isn't there a better way to do this?

答:
One option would be to create a variable:

const inputStyle = !valid ? {
  borderColor: "red",
  boxShadow: "rgb(2, 0, 0)"
} : {};

<input style={inputStyle}/>
```

It is the same that you currently have but you can add new properties as you wish into the variable without increasing the amount of comparisons in the input tag.

Body:
Currently, in my React app I have this,

<input style={{ borderColor: valid ? null : "red", boxShadow: valid ? null : "rgb(2, 0, 0)"}} />

If I have more styling to do, it doesn't make sense checking the same condition again and again right? I wish to make the entire style attribute optional; something like this,

<input valid ? null : style={{ borderColor: "red", boxShadow: "rgb(2, 0, 0)"}} />

But I know that's not the right syntax. Isn't there a better way to do this?

Body:
One option would be to create a variable:

const inputStyle = !valid ? {
  borderColor: "red",
  boxShadow: "rgb(2, 0, 0)"
} : {};

<input style={inputStyle}/>

It is the same that you currently have but you can add new properties as you wish into the variable without increasing the amount of comparisons in the input tag.


问:
Restart Services on GCE Instance Using Cloud Build
I have a GCE instance that I push code to using Cloud Build. I need to restart services on that VM once the code has been pushed. Here's what my Cloud Build YAML looks like:

```<code>steps:

- name: 'gcr.io/cloud-builders/gcloud'
  entrypoint: 'bash'
  args:
  - '-c'
  -  |
      for d in *; do
              gcloud compute scp $d user@instance-1:/path/to/directory --zone=asia-south1-a --recurse

      done

- name: 'gcr.io/cloud-builders/gcloud'
  entrypoint: 'bash'
  args:
  - '-c'
  -  |
      gcloud compute ssh user@instance-1 --zone=asia-south1-a --command="service uwsgi restart"

timeout: 1200s
</code>```

While the first step works fine, while trying to restart the service, I receive the following error:

```<code>Already have image (with digest): gcr.io/cloud-builders/gcloud
Sent message type=method_call sender=n/a destination=org.freedesktop.DBus object=/org/freedesktop/DBus interface=org.freedesktop.DBus member=Hello cookie=1 reply_cookie=0 error=n/a
Got message type=method_return sender=org.freedesktop.DBus destination=:1.3477 object=n/a interface=n/a member=n/a cookie=1 reply_cookie=1 error=n/a
Sent message type=method_call sender=n/a destination=org.freedesktop.DBus object=/org/freedesktop/DBus interface=org.freedesktop.DBus member=AddMatch cookie=2 reply_cookie=0 error=n/a
Sent message type=method_call sender=n/a destination=org.freedesktop.DBus object=/org/freedesktop/DBus interface=org.freedesktop.DBus member=AddMatch cookie=3 reply_cookie=0 error=n/a
Calling manager for ReloadUnit on uwsgi.service, replace
Sent message type=method_call sender=n/a destination=org.freedesktop.systemd1 object=/org/freedesktop/systemd1 interface=org.freedesktop.systemd1.Manager member=ReloadUnit cookie=4 reply_cookie=0 error=n/a
Failed to reload uwsgi.service: Interactive authentication required.
See system logs and 'systemctl status uwsgi.service' for details.
Sent message type=method_call sender=n/a destination=org.freedesktop.DBus object=/org/freedesktop/DBus interface=org.freedesktop.DBus member=RemoveMatch cookie=5 reply_cookie=0 error=n/a
Sent message type=method_call sender=n/a destination=org.freedesktop.DBus object=/org/freedesktop/DBus interface=org.freedesktop.DBus member=RemoveMatch cookie=6 reply_cookie=0 error=n/a
Sent message type=method_call sender=n/a destination=org.freedesktop.systemd1 object=/org/freedesktop/systemd1 interface=org.freedesktop.systemd1.Manager member=ReloadUnit cookie=4 reply_cookie=0 error=n/a
Failed to reload uwsgi.service: Interactive authentication required.
See system logs and 'systemctl status uwsgi.service' for details.
</code>```

I've tried disabling the interactive authentication mechanism as mentioned here and here but that hasn't worked. Please help.

答:
After investigating this issue, I suggest a workaround, which is to make a listener run by root, that checks if a file exists. This file is created by the user from Cloud Build when there is a build (with touch, for example). If the file exists, the listener deletes it and restarts the service. The code:

```<code>#!/bin/bash

# Listener to be run by root. When user from
# Cloud Build touches $FILE, root removes it
# and restarts the service from within the VM.

FILE="/home/user/file"

function listen()
{
        if [ -f "$FILE" ]; then
            rm $FILE
            service uwsgi restart
            sleep 60
        else
            sleep 10
        fi
}

while true
do
    listen
done
</code>```

Body:
I have a GCE instance that I push code to using Cloud Build. I need to restart services on that VM once the code has been pushed. Here's what my Cloud Build YAML looks like:

steps:

- name: 'gcr.io/cloud-builders/gcloud'
  entrypoint: 'bash'
  args:
  - '-c'
  -  |
      for d in *; do
              gcloud compute scp $d user@instance-1:/path/to/directory --zone=asia-south1-a --recurse

      done

- name: 'gcr.io/cloud-builders/gcloud'
  entrypoint: 'bash'
  args:
  - '-c'
  -  |
      gcloud compute ssh user@instance-1 --zone=asia-south1-a --command="service uwsgi restart"

timeout: 1200s

While the first step works fine, while trying to restart the service, I receive the following error:

Already have image (with digest): gcr.io/cloud-builders/gcloud
Sent message type=method_call sender=n/a destination=org.freedesktop.DBus object=/org/freedesktop/DBus interface=org.freedesktop.DBus member=Hello cookie=1 reply_cookie=0 error=n/a
Got message type=method_return sender=org.freedesktop.DBus destination=:1.3477 object=n/a interface=n/a member=n/a cookie=1 reply_cookie=1 error=n/a
Sent message type=method_call sender=n/a destination=org.freedesktop.DBus object=/org/freedesktop/DBus interface=org.freedesktop.DBus member=AddMatch cookie=2 reply_cookie=0 error=n/a
Sent message type=method_call sender=n/a destination=org.freedesktop.DBus object=/org/freedesktop/DBus interface=org.freedesktop.DBus member=AddMatch cookie=3 reply_cookie=0 error=n/a
Calling manager for ReloadUnit on uwsgi.service, replace
Sent message type=method_call sender=n/a destination=org.freedesktop.systemd1 object=/org/freedesktop/systemd1 interface=org.freedesktop.systemd1.Manager member=ReloadUnit cookie=4 reply_cookie=0 error=n/a
Failed to reload uwsgi.service: Interactive authentication required.
See system logs and 'systemctl status uwsgi.service' for details.
Sent message type=method_call sender=n/a destination=org.freedesktop.DBus object=/org/freedesktop/DBus interface=org.freedesktop.DBus member=RemoveMatch cookie=5 reply_cookie=0 error=n/a
Sent message type=method_call sender=n/a destination=org.freedesktop.DBus object=/org/freedesktop/DBus interface=org.freedesktop.DBus member=RemoveMatch cookie=6 reply_cookie=0 error=n/a
Sent message type=method_call sender=n/a destination=org.freedesktop.systemd1 object=/org/freedesktop/systemd1 interface=org.freedesktop.systemd1.Manager member=ReloadUnit cookie=4 reply_cookie=0 error=n/a
Failed to reload uwsgi.service: Interactive authentication required.
See system logs and 'systemctl status uwsgi.service' for details.

I've tried disabling the interactive authentication mechanism as mentioned here and here but that hasn't worked. Please help.

Body:
After investigating this issue, I suggest a workaround, which is to make a listener run by root, that checks if a file exists. This file is created by the user from Cloud Build when there is a build (with touch, for example). If the file exists, the listener deletes it and restarts the service. The code:

#!/bin/bash

# Listener to be run by root. When user from
# Cloud Build touches $FILE, root removes it
# and restarts the service from within the VM.

FILE="/home/user/file"

function listen()
{
        if [ -f "$FILE" ]; then
            rm $FILE
            service uwsgi restart
            sleep 60
        else
            sleep 10
        fi
}

while true
do
    listen
done


问:
Formatting logic app expression for DateTime
I  am  generating a file  for export with the file name utcnow in the logic app expression which returns a value like this

utcNow()-  "2020-06-01T15:41:15.5103915Z"
I want to convert  it like "20200601154151" that means I need  to remove  some characters like" -","T"  and millisecondsfollwed by Z,
I tried few combination of string format and I am not getting it right hoping you  guys  to help me.
Thanks,

答:
There are many options for custom date formats. Here is a simple guide:

yyyy = Year (2020)

MM = Month (06)

dd = Day (01)

HH = Hour (15)

mm = Minute (41)

ss = Second (15)

Construct a format string (ex: yyyyMMddHHmmss) based on your requirements and pass it to formatDateTime:

```<code>formatDateTime(utcNow(), 'yyyyMMddHHmmss')
</code>```

The resulting value will be '20200601154115'. There are many additional options at the link above.

Body:
There are many options for custom date formats. Here is a simple guide:

yyyy = Year (2020)

MM = Month (06)

dd = Day (01)

HH = Hour (15)

mm = Minute (41)

ss = Second (15)

Construct a format string (ex: yyyyMMddHHmmss) based on your requirements and pass it to formatDateTime:

formatDateTime(utcNow(), 'yyyyMMddHHmmss')

The resulting value will be '20200601154115'. There are many additional options at the link above.


问:
How can I create an object that contains instances of a class in Python?
I want to create an object that contains some instances of a class. That object should be some kind of list-generalization of the instances. E.g. I have the following class:

```<code>class car:
    def __init__(self, prize, color)
        self.prize = prize
        self.color = color
</code>```

Now I want to have an object cars that contains many instances of the class car but that I can work with like an instance of car, i.e. cars.prize should return a list of the prizes for all the instances I collected in that object cars.

答:
Small error in your code: you need a : at the end of your __init__ method definition line:

def __init__(self, prize, color):

Here's an implementation of cars which does what you desire. The use of the @property decorator allows you to access methods as object properties:

```<code>class car:
    def __init__(self, prize, color):
        self.prize = prize
        self.color = color

class cars:
    def __init__(self, list_of_cars):
        for one_car in list_of_cars:
            assert isinstance(one_car, car) # ensure you are only given cars
        self.my_cars = list_of_cars

    @property
    def prize(self):
        return [one_car.prize for one_car in self.my_cars]

    @property
    def color(self):
        return [one_car.color for one_car in self.my_cars]

>>> a = car('prize1', 'red')
>>> b = car('prize2', 'green')
>>> c = car('prize3', 'azure')
>>> carz = cars([a,b,c])
>>> carz.prize
['prize1', 'prize2', 'prize3']
>>> carz.color
['red', 'green', 'azure']
</code>```

You can add more checking on inputs in each object if desired, but this is the basic framework. Hope it helps, Happy Coding!

Body:
I want to create an object that contains some instances of a class. That object should be some kind of list-generalization of the instances. E.g. I have the following class:

class car:
    def __init__(self, prize, color)
        self.prize = prize
        self.color = color

Now I want to have an object cars that contains many instances of the class car but that I can work with like an instance of car, i.e. cars.prize should return a list of the prizes for all the instances I collected in that object cars.

Body:
Small error in your code: you need a : at the end of your __init__ method definition line:

def __init__(self, prize, color):

Here's an implementation of cars which does what you desire. The use of the @property decorator allows you to access methods as object properties:

class car:
    def __init__(self, prize, color):
        self.prize = prize
        self.color = color

class cars:
    def __init__(self, list_of_cars):
        for one_car in list_of_cars:
            assert isinstance(one_car, car) # ensure you are only given cars
        self.my_cars = list_of_cars

    @property
    def prize(self):
        return [one_car.prize for one_car in self.my_cars]

    @property
    def color(self):
        return [one_car.color for one_car in self.my_cars]

>>> a = car('prize1', 'red')
>>> b = car('prize2', 'green')
>>> c = car('prize3', 'azure')
>>> carz = cars([a,b,c])
>>> carz.prize
['prize1', 'prize2', 'prize3']
>>> carz.color
['red', 'green', 'azure']

You can add more checking on inputs in each object if desired, but this is the basic framework. Hope it helps, Happy Coding!


答:
You can define your styles as an object in the render method, then assign it optionally as prop to the component using ternary and spread operators.</p>

```<code>const styles = {
    borderColor: "red",
    boxShadow: "rgb(2, 0, 0)",
    // etc...
};

return (
    <input { ...(valid ? { styles } : {}) } />
);
</code>```

Title: Can I add optional attributes to an element in React?

Body:
You can define your styles as an object in the render method, then assign it optionally as prop to the component using ternary and spread operators.

const styles = {
    borderColor: "red",
    boxShadow: "rgb(2, 0, 0)",
    // etc...
};

return (
    <input { ...(valid ? { styles } : {}) } />
);


答:
Use :focus rule.

For example:

```<code>.button:focus {
    border: 1px solid red;
}
</code>```

Title: Change colour of button highlighted when using tab button

Body:
Use :focus rule.

For example:

.button:focus {
    border: 1px solid red;
}


问:
Segfault in emitted IR For `printf` call
I would like to use the system printf to be able to print a single integer from the programming language I'm writing a compiler for, as in print(3). I am running into a segfault when executing the compiled IR.

Following this example, my code is

```<code>#include "llvm/ADT/APInt.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
#include <memory>
#include <vector>

using namespace llvm;

static LLVMContext TheContext;
static IRBuilder<> Builder(TheContext);

int main() {
  static std::unique_ptr<Module> TheModule;
  TheModule = std::make_unique<Module>("inputFile", TheContext);
  std::vector<Type *> Nats(1, Type::getInt32Ty(TheContext));
  FunctionType *PNFT =
      FunctionType::get(Type::getInt32Ty(TheContext), Nats, false);
  Function *PNF = Function::Create(PNFT, Function::ExternalLinkage, "printf",
                                   TheModule.get());
  for (auto &Arg : PNF->args()) {
    Arg.setName("x");
  }
  FunctionType *mainType = FunctionType::get(Builder.getInt32Ty(), false);
  Function *main = Function::Create(mainType, Function::ExternalLinkage, "main",
                                    TheModule.get());
  BasicBlock *entry = BasicBlock::Create(TheContext, "entry", main);
  Builder.SetInsertPoint(entry);

  std::vector<Value *> printArgs;
  printArgs.push_back(ConstantInt::get(TheContext, APInt(32, 20)));
  Builder.CreateCall(TheModule->getFunction("printf"), printArgs);
  Builder.CreateRet(ConstantInt::get(TheContext, APInt(32, 0)));

  TheModule->print(llvm::outs(), nullptr);
}
</code>```

I compile this with clang++ `llvm-config --cxxflags --ldflags --system-libs --libs all` test.cpp

This outputs the LLVM IR

```<code>; ModuleID = 'inputFile'
source_filename = "inputFile"

declare i32 @printf(i32)

define i32 @main() {
entry:
  %0 = call i32 @printf(i32 20)
  ret i32 0
}
</code>```

which I  put into a file test.ll and compile as clang test.ll. I threw the segfaulting code into lldb and found that the code segfaults in strchr:

```<code>(lldb) bt
* thread #1, name = 'a.out', stop reason = signal SIGSEGV: invalid address (fault address: 0x14)
  * frame #0: 0x00007ffff7f300fc libc.so.6`__strchrnul_avx2 + 28
    frame #1: 0x00007ffff7e38a53 libc.so.6`__vfprintf_internal + 163
    frame #2: 0x00007ffff7e25a2f libc.so.6`_IO_printf + 175
    frame #3: 0x000055555555514b a.out`main + 11
    frame #4: 0x00007ffff7df5002 libc.so.6`__libc_start_main + 242
    frame #5: 0x000055555555506e a.out`_start + 46
</code>```

I don't think the problem is with compiling the IR, because in my actual code (that is, not the MVE I've shown above) I'm emitting object code directly using a pass (as suggested in part eight of the kaleidescope tutorial) and still experiencing the same issue. What am I doing wrong here?

Thank you.

答:
Thanks to @arnt's comment, I found this resource which lead me to modify my program to the following:

```<code>#include "llvm/ADT/APInt.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
#include <memory>
#include <vector>

using namespace llvm;

static LLVMContext TheContext;
static IRBuilder<> Builder(TheContext);

int main() {
  static std::unique_ptr<Module> TheModule;
  TheModule = std::make_unique<Module>("inputFile", TheContext);

  std::vector<llvm::Type *> args;
  args.push_back(llvm::Type::getInt8PtrTy(TheContext));
  llvm::FunctionType *printfType =
      llvm::FunctionType::get(Builder.getInt32Ty(), args, true);
  llvm::Constant *printfFunc = Function::Create(
      printfType, Function::ExternalLinkage, "printf", TheModule.get());

  /*begin codegen for `main`*/
  FunctionType *mainType = FunctionType::get(Builder.getInt32Ty(), false);
  Function *main = Function::Create(mainType, Function::ExternalLinkage, "main",
                                    TheModule.get());
  BasicBlock *entry = BasicBlock::Create(TheContext, "entry", main);
  Builder.SetInsertPoint(entry);

  std::vector<Value *> printArgs;
  llvm::Value *formatStr = Builder.CreateGlobalStringPtr("%d\n");
  printArgs.push_back(formatStr);
  printArgs.push_back(ConstantInt::get(TheContext, APInt(32, 20)));
  Builder.CreateCall(TheModule->getFunction("printf"), printArgs);
  Builder.CreateRet(ConstantInt::get(TheContext, APInt(32, 0)));

  TheModule->print(llvm::outs(), nullptr);
}
</code>```

This emits the following IR:

```<code>; ModuleID = 'inputFile'
source_filename = "inputFile"

@0 = private unnamed_addr constant [4 x i8] c"%d\0A\00", align 1

declare i32 @printf(i8*, ...)

define i32 @main() {
entry:
  %0 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @0, i32 0, i32 0), i32 20)
  ret i32 0
}
</code>```

which works as expected.

Body:
I would like to use the system printf to be able to print a single integer from the programming language I'm writing a compiler for, as in print(3). I am running into a segfault when executing the compiled IR.

Following this example, my code is

#include "llvm/ADT/APInt.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
#include <memory>
#include <vector>

using namespace llvm;

static LLVMContext TheContext;
static IRBuilder<> Builder(TheContext);

int main() {
  static std::unique_ptr<Module> TheModule;
  TheModule = std::make_unique<Module>("inputFile", TheContext);
  std::vector<Type *> Nats(1, Type::getInt32Ty(TheContext));
  FunctionType *PNFT =
      FunctionType::get(Type::getInt32Ty(TheContext), Nats, false);
  Function *PNF = Function::Create(PNFT, Function::ExternalLinkage, "printf",
                                   TheModule.get());
  for (auto &Arg : PNF->args()) {
    Arg.setName("x");
  }
  FunctionType *mainType = FunctionType::get(Builder.getInt32Ty(), false);
  Function *main = Function::Create(mainType, Function::ExternalLinkage, "main",
                                    TheModule.get());
  BasicBlock *entry = BasicBlock::Create(TheContext, "entry", main);
  Builder.SetInsertPoint(entry);

  std::vector<Value *> printArgs;
  printArgs.push_back(ConstantInt::get(TheContext, APInt(32, 20)));
  Builder.CreateCall(TheModule->getFunction("printf"), printArgs);
  Builder.CreateRet(ConstantInt::get(TheContext, APInt(32, 0)));

  TheModule->print(llvm::outs(), nullptr);
}

I compile this with clang++ `llvm-config --cxxflags --ldflags --system-libs --libs all` test.cpp

This outputs the LLVM IR

; ModuleID = 'inputFile'
source_filename = "inputFile"

declare i32 @printf(i32)

define i32 @main() {
entry:
  %0 = call i32 @printf(i32 20)
  ret i32 0
}

which I  put into a file test.ll and compile as clang test.ll. I threw the segfaulting code into lldb and found that the code segfaults in strchr:

(lldb) bt
* thread #1, name = 'a.out', stop reason = signal SIGSEGV: invalid address (fault address: 0x14)
  * frame #0: 0x00007ffff7f300fc libc.so.6`__strchrnul_avx2 + 28
    frame #1: 0x00007ffff7e38a53 libc.so.6`__vfprintf_internal + 163
    frame #2: 0x00007ffff7e25a2f libc.so.6`_IO_printf + 175
    frame #3: 0x000055555555514b a.out`main + 11
    frame #4: 0x00007ffff7df5002 libc.so.6`__libc_start_main + 242
    frame #5: 0x000055555555506e a.out`_start + 46

I don't think the problem is with compiling the IR, because in my actual code (that is, not the MVE I've shown above) I'm emitting object code directly using a pass (as suggested in part eight of the kaleidescope tutorial) and still experiencing the same issue. What am I doing wrong here?

Thank you.

Body:
Thanks to @arnt's comment, I found this resource which lead me to modify my program to the following:

#include "llvm/ADT/APInt.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
#include <memory>
#include <vector>

using namespace llvm;

static LLVMContext TheContext;
static IRBuilder<> Builder(TheContext);

int main() {
  static std::unique_ptr<Module> TheModule;
  TheModule = std::make_unique<Module>("inputFile", TheContext);

  std::vector<llvm::Type *> args;
  args.push_back(llvm::Type::getInt8PtrTy(TheContext));
  llvm::FunctionType *printfType =
      llvm::FunctionType::get(Builder.getInt32Ty(), args, true);
  llvm::Constant *printfFunc = Function::Create(
      printfType, Function::ExternalLinkage, "printf", TheModule.get());

  /*begin codegen for `main`*/
  FunctionType *mainType = FunctionType::get(Builder.getInt32Ty(), false);
  Function *main = Function::Create(mainType, Function::ExternalLinkage, "main",
                                    TheModule.get());
  BasicBlock *entry = BasicBlock::Create(TheContext, "entry", main);
  Builder.SetInsertPoint(entry);

  std::vector<Value *> printArgs;
  llvm::Value *formatStr = Builder.CreateGlobalStringPtr("%d\n");
  printArgs.push_back(formatStr);
  printArgs.push_back(ConstantInt::get(TheContext, APInt(32, 20)));
  Builder.CreateCall(TheModule->getFunction("printf"), printArgs);
  Builder.CreateRet(ConstantInt::get(TheContext, APInt(32, 0)));

  TheModule->print(llvm::outs(), nullptr);
}

This emits the following IR:

; ModuleID = 'inputFile'
source_filename = "inputFile"

@0 = private unnamed_addr constant [4 x i8] c"%d\0A\00", align 1

declare i32 @printf(i8*, ...)

define i32 @main() {
entry:
  %0 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @0, i32 0, i32 0), i32 20)
  ret i32 0
}

which works as expected.


问:
Git Remote Tracking Branch and Upstream Branch are different
I am not sure how this happened, but if you look at these outputs, emote tracking branch and upstream branch is different. Can somebody explain how could this happen. I know that my pushes are working. What happens when I pull ?

```<code>PS C:\DigitalOffers\RegPrice> git branch
* dev
  master

PS C:\DigitalOffers\RegPrice> git branch -vv
* dev    b62f88b [origin/master: ahead 52] Price Zone resolution change.
  master 78d5fb6 [origin/master: behind 37] Merge branch 'master' of https://github.com/xxxxxxxxx

PS C:\DigitalOffers\RegPrice> git log
commit b62f88b137fa067f7d0f75ec35fb8b63fc885f50 (HEAD -> dev, origin/dev)

PS C:\DigitalOffers\RegPrice> cat .git/config
[core]
    symlinks = false
    repositoryformatversion = 0
    filemode = false
    logallrefupdates = true
[remote "origin"]
    url = https://github.com/XXXXXX
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
    rebase = false
[branch "dev"]
    remote = origin
    merge = refs/heads/master
    rebase = false
[branch "origin/dev"]
    remote = origin
    merge = refs/heads/master
    rebase = false
[http "https://github.com"]
    sslVerify = false
[gui]
    wmstate = zoomed
    geometry = 584x210+234+234 469 196

PS C:\DigitalOffers\RegPrice> git push
fatal: The upstream branch of your current branch does not match
the name of your current branch.  To push to the upstream branch
on the remote, use

    git push origin HEAD:master

To push to the branch of the same name on the remote, use

    git push origin HEAD

To choose either option permanently, see push.default in 'git help config'.
</code>```

One more point I want add is- these refs were done by EGit in eclipse.

答:
A branch whose upstream has a different name is broken. That's the situation you are in; your dev branch has origin's master as its upstream. To fix it, repoint the dev branch's upstream so that it is origin's dev instead.

The reason this situation has not destroyed your ability to push is that Eclipse is giving explicit instructions about what to do, i.e. what branch to push to. It has been saving you. But it is better to save yourself by getting the branch's configuration right.

Body:
I am not sure how this happened, but if you look at these outputs, emote tracking branch and upstream branch is different. Can somebody explain how could this happen. I know that my pushes are working. What happens when I pull ?

PS C:\DigitalOffers\RegPrice> git branch
* dev
  master

PS C:\DigitalOffers\RegPrice> git branch -vv
* dev    b62f88b [origin/master: ahead 52] Price Zone resolution change.
  master 78d5fb6 [origin/master: behind 37] Merge branch 'master' of https://github.com/xxxxxxxxx

PS C:\DigitalOffers\RegPrice> git log
commit b62f88b137fa067f7d0f75ec35fb8b63fc885f50 (HEAD -> dev, origin/dev)

PS C:\DigitalOffers\RegPrice> cat .git/config
[core]
    symlinks = false
    repositoryformatversion = 0
    filemode = false
    logallrefupdates = true
[remote "origin"]
    url = https://github.com/XXXXXX
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
    rebase = false
[branch "dev"]
    remote = origin
    merge = refs/heads/master
    rebase = false
[branch "origin/dev"]
    remote = origin
    merge = refs/heads/master
    rebase = false
[http "https://github.com"]
    sslVerify = false
[gui]
    wmstate = zoomed
    geometry = 584x210+234+234 469 196

PS C:\DigitalOffers\RegPrice> git push
fatal: The upstream branch of your current branch does not match
the name of your current branch.  To push to the upstream branch
on the remote, use

    git push origin HEAD:master

To push to the branch of the same name on the remote, use

    git push origin HEAD

To choose either option permanently, see push.default in 'git help config'.

One more point I want add is- these refs were done by EGit in eclipse.


问:
How to apply the same function on paired elements
I have this code where I would like each textbox input will change its corresponding image. The function itself is typical for all partners in the list (txt & img). I've searched and read somewhat similar post but it's just beyond me at this point. How to make the function work without copying it multiple times?
Please help and thanks in advance :)

HTML

```<code><div id="sideleft">
<div class="pict" id="img01"></div>
<div class="pict" id="img02"></div>
<div class="pict" id="img03"></div>
<div class="pict" id="img04"></div>
<div class="pict" id="img05"></div>
<div class="pict" id="img06"></div>
<div class="pict" id="img07"></div>
<div class="pict" id="img08"></div>
<div class="pict" id="img09"></div>
</div>

<div id="sideright">
<input class="box" id="txt01" type="text" value="" onblur="change01()"/>
<input class="box" id="txt02" type="text" value="" onblur="change02()"/>
<input class="box" id="txt03" type="text" value="" onblur="change()"/>
<input class="box" id="txt04" type="text" value="" onblur="change()"/>
<input class="box" id="txt05" type="text" value="" onblur="change()"/>
<input class="box" id="txt06" type="text" value="" onblur="change()"/>
<input class="box" id="txt07" type="text" value="" onblur="change()"/>
<input class="box" id="txt08" type="text" value="" onblur="change()"/>
<input class="box" id="txt09" type="text" value="" onblur="change()"/>
</div>
</code>```

```<code>function change01() {
var image = "";
var answers = document.getElementById("txt01").value;
switch(answers) {
case "a": image='<img src="https://dummyimage.com/55X55/00a2ff/fff"></img>'; break;
case "b": image='<img src="https://dummyimage.com/55X55/1eff00/fff"></img>'; break;
case "c": image='<img src="https://dummyimage.com/55X55/ff0000/fff"></img>'; break;
case "":  image='<img src="https://dummyimage.com/55X55/000000/fff"></img>'; break;
default:  image='<img src="https://dummyimage.com/55X55/a3a3a3/fff"></img>'; break;
} document.getElementById("img01").innerHTML = image;
}

function change02() {
var image = "";
var answers = document.getElementById("txt02").value;
switch(answers) {
case "a": image='<img src="https://dummyimage.com/55X55/00a2ff/fff"></img>'; break;
case "b": image='<img src="https://dummyimage.com/55X55/1eff00/fff"></img>'; break;
case "c": image='<img src="https://dummyimage.com/55X55/ff0000/fff"></img>'; break;
case "":  image='<img src="https://dummyimage.com/55X55/000000/fff"></img>'; break;
default:  image='<img src="https://dummyimage.com/55X55/a3a3a3/fff"></img>'; break;
} document.getElementById("img02").innerHTML = image;
}
</code>```

CSS

```<code>#sideright, #sideleft{
  float:left;
  width:180px;
}

#sideleft div{
  float:left;
  border:1px solid red;
  width:55px;
  height:55px;
}
</code>```

答:
Very simply by passing an argument to your function. That's what arguments are for.

Write one parametric function :

```<code>function change( num ) { // <-- here num=='01' or '02'
    var image = "";
    var answers = document.getElementById("txt" + num ).value; // txt01, txt02
    switch(answers) {
         case "a": image='<img src="https://dummyimage.com/55X55/00a2ff/fff"></img>'; break;
         case "b": image='<img src="https://dummyimage.com/55X55/1eff00/fff"></img>'; break;
         case "c": image='<img src="https://dummyimage.com/55X55/ff0000/fff"></img>'; break;
         case "":  image='<img src="https://dummyimage.com/55X55/000000/fff"></img>'; break;
         default:  image='<img src="https://dummyimage.com/55X55/a3a3a3/fff"></img>';                            break;
    } document.getElementById("img" + num ).innerHTML = image; // img01, img02
}
</code>```

Then call it with a different argument each time :

```<code><input class="box" id="txt01" type="text" value="" onblur="change('01')"/>
<input class="box" id="txt02" type="text" value="" onblur="change('02')"/>
</code>```

Body:
I have this code where I would like each textbox input will change its corresponding image. The function itself is typical for all partners in the list (txt & img). I've searched and read somewhat similar post but it's just beyond me at this point. How to make the function work without copying it multiple times?
Please help and thanks in advance :)

HTML

<input class="box" id="txt01" type="text" value="" onblur="change01()"/>
<input class="box" id="txt02" type="text" value="" onblur="change02()"/>
<input class="box" id="txt03" type="text" value="" onblur="change()"/>
<input class="box" id="txt04" type="text" value="" onblur="change()"/>
<input class="box" id="txt05" type="text" value="" onblur="change()"/>
<input class="box" id="txt06" type="text" value="" onblur="change()"/>
<input class="box" id="txt07" type="text" value="" onblur="change()"/>
<input class="box" id="txt08" type="text" value="" onblur="change()"/>
<input class="box" id="txt09" type="text" value="" onblur="change()"/>

function change01() {
var image = "";
var answers = document.getElementById("txt01").value;
switch(answers) {
case "a": image=''; break;
case "b": image=''; break;
case "c": image=''; break;
case "":  image=''; break;
default:  image=''; break;
} document.getElementById("img01").innerHTML = image;
}

function change02() {
var image = "";
var answers = document.getElementById("txt02").value;
switch(answers) {
case "a": image=''; break;
case "b": image=''; break;
case "c": image=''; break;
case "":  image=''; break;
default:  image=''; break;
} document.getElementById("img02").innerHTML = image;
}

CSS

#sideright, #sideleft{
  float:left;
  width:180px;
}

#sideleft div{
  float:left;
  border:1px solid red;
  width:55px;
  height:55px;
}

Body:
Very simply by passing an argument to your function. That's what arguments are for.

Write one parametric function :

function change( num ) { // <-- here num=='01' or '02'
    var image = "";
    var answers = document.getElementById("txt" + num ).value; // txt01, txt02
    switch(answers) {
         case "a": image='<img src="https://dummyimage.com/55X55/00a2ff/fff"></img>'; break;
         case "b": image='<img src="https://dummyimage.com/55X55/1eff00/fff"></img>'; break;
         case "c": image='<img src="https://dummyimage.com/55X55/ff0000/fff"></img>'; break;
         case "":  image='<img src="https://dummyimage.com/55X55/000000/fff"></img>'; break;
         default:  image='<img src="https://dummyimage.com/55X55/a3a3a3/fff"></img>';                            break;
    } document.getElementById("img" + num ).innerHTML = image; // img01, img02
}

Then call it with a different argument each time :

<input class="box" id="txt01" type="text" value="" onblur="change('01')"/>
<input class="box" id="txt02" type="text" value="" onblur="change('02')"/>


问:
Using spatial index to boost distance query from point to polygon
Here introduces how to boost spatial intersection queries using R-Tree. Here @JHuw provides ways using R-Tree to calculate the nearest distance from point to point and line, respectively. Nevertheless, I have not found a solution to boost distance query from point to polygon using R-Tree. I followed those examples mentioned above and still have not figured out how to implement R-Tree in nearest distance query from point to polygon. Could anybody help me figure this out? Much appreciated. I use South America and a subset of cities from GeoPandas as an example in the following:</p>

```<code># Import libraries
import geopandas as gpd
import matplotlib.pyplot as plt

# Load data from GeoPandas
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
cities = gpd.read_file(gpd.datasets.get_path('naturalearth_cities'))

south_america = world[world.continent == 'South America']
city_sub = cities[cities.index < 20]

# Plot
ax= south_america.boundary.plot()
city_sub.plot(ax=ax)

# Nearest distance from point (city_sub) to polygon (south_america) using R-Tree
# "To be finished..."
</code>```

答:
Here's a more detailed walk-through of snapping points to a line using the spatial index (RTree) in geopandas that may help in this case: https://medium.com/@brendan_ward/how-to-leverage-geopandas-for-faster-snapping-of-points-to-lines-6113c94e59aa

It uses a tolerance based approach, so it only selects those that features are nearest within that tolerance.  You can use a larger tolerance in this approach, but it can increase processing time dramatically. It uses a bounding box based on that tolerance to query the features in RTree; the bigger the bounding box, the less effective it is for querying the tree.

With polygons, you have more cases to consider: a point that is within a polygon has a distance of 0.

You can handle this in 2 passes: first use a spatial join in geopandas to find all cases where the points are within polygons.  Then take all those that are not within polygons, and try to find the nearest polygon for each point.  Using a tolerance based bounding box to query RTree gives you a list of candidate polygons, then calculate the distance between the point and its candidate polygons, and take the one with the smallest distance.

You also need to decide what to do when a given point falls within multiple polygons: which one is "nearest" in that case?  One approach is to select the overlapping polygon whose centroid is closest to your point, but it really depends on your goals.

Body:
Here introduces how to boost spatial intersection queries using R-Tree. Here @JHuw provides ways using R-Tree to calculate the nearest distance from point to point and line, respectively. Nevertheless, I have not found a solution to boost distance query from point to polygon using R-Tree. I followed those examples mentioned above and still have not figured out how to implement R-Tree in nearest distance query from point to polygon. Could anybody help me figure this out? Much appreciated. I use South America and a subset of cities from GeoPandas as an example in the following:

# Import libraries
import geopandas as gpd
import matplotlib.pyplot as plt

# Load data from GeoPandas
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
cities = gpd.read_file(gpd.datasets.get_path('naturalearth_cities'))

south_america = world[world.continent == 'South America']
city_sub = cities[cities.index < 20]

# Plot
ax= south_america.boundary.plot()
city_sub.plot(ax=ax)

# Nearest distance from point (city_sub) to polygon (south_america) using R-Tree
# "To be finished..."


问:
What is the best way to represent honeycomb lattice?
I am trying to simulate a honeycomb lattice, I.e, each particle interacts with each of it's 3 neighbors. I want to represent in array such that it is automated. I.e, if any atom is picked at random, code should evaluate some parameter based on connected neighbors.

I can think of it in this way:

initialize n*n array.

every particle interacts with particles next to it on right and left sides

particle on odd row and odd column interact with it's bottom particle

particle on odd row and even column interact with it's top particle

particle on even row and odd column interact with it's top particle

particle on even row and even column interact with it's bottom particle

The equivalence is shown below in the pictures.

Is there a better method to represent the same?

答:
There is a reference here that might be of use:

https://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/AV0405/MARTIN/Hex.pdf

Also, there is a SE answer that might be of help:

Generate, fill and plot a hexagonal lattice in Python

Also, this:

https://www.redblobgames.com/grids/hexagons/


问:
NativeScript and Observables
I'am currently a rookie to Nativescript and Angular. I've created a API using laravel and it works fine. Now I'am trying to connect and fetch data from my API in NativeScript/Angular. I've followed this tutorial as guideline Alex Ziskind.

My API is build with PHP in Laravel and my calls works fine in Postman. I'am also capable of getting som data, but I cant return it in the HTML.

My service

export public ItemService {
    getItems():Observable<Item[]> {

        const authToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIyIiwianRpIjoiZmIzYjJmYzg3MWY2YTc5ZjVjMTM3NDNmMDllNGUwNzYwZDkyODljMmVjNTE3NGZiNDMzZTRjMGQ0MjBjYTJmYjlhMGQ1ZmFjNTQ1NmQ3ODkiLCJpYXQiOjE1OTA2NTAyMjksIm5iZiI6MTU5MDY1MDIyOSwiZXhwIjoxNjIyMTg2MjI5LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.Y3kidP6TP__DrwBDcGuk6M4p76INEdxG8UWrdakfkfcjCOlmHA0pb7a8vTvRQl2WLA_gwNWD4qA64ToOZb1YxkWCe8ESBTRDBg9Xq3DbSsZzlBZb9v8zS8PEeJVnfMtmxVIJb8IEU82DYGbpky-XdDfn67ge6fM3jTvwyivthlhaQLkjsh8e3VKlUx0P8lSxoHVw-N0369otRU6X0CTghl5lg9Khru4AtdJIBL3AOQAFEZmpzAGg9xZkvY923VkgkBHXt-adfvBwG2ZP0UhUVht-aiKK2z9HlR0eQ_-eqYlo-fqmTAE0U1k5ET99jbap8xO0dXJfdYVF0cAJ7p6FNjMoougwR89kz2xCcUHyFnPli3HcZx7j8IKDhqvneL8oWjaJuO41z1O69qsbk7_g8iLVI5vQlv6slrIe2YSbABkHzzCGndFX-smZkugB8aNmoRGpX8RJ5y5HxE6pJG8nn8CYih5ednDlWaTUBGk0p4zpck2z8788zyX41sPdB1oqR2gO0_CL-pBjCdTgDYXi_hy49_SO_4Vsf8lPL7vyhhvv7w_KgV7Jc7ju3Xm4HRLUG56K8CMy1KEfVuTDYs0gnybuFolfv2haeVgc_2h2A65O5nuUZg_RpePrSBZEftLsITWa3lUvnF380_htio-Zp3gXs3INoH7ms5KdTPt3mZ8";
        const URL = "http://10.0.2.2:8000/api/source";

        /*return this.http.get<Item[]>(
            URL,
            { headers: new HttpHeaders().append("Authorization", `Bearer ${authToken}`) }
        )*/

        const res = this.http.get<Item[]>(
            URL,
            { headers: new HttpHeaders().append("Authorization", `Bearer ${authToken}`) }
            )

            console.log()

        return res;

    }

    getItem(id) { }
    /*
        getItem(id: number): Item {
            return this.items.filter((item) => item.id === id)[0];
        }
    */
}
```

<p>My component</p>

<pre class="lang-js prettyprint-override"><code>export class ItemsComponent implements OnInit {
    public items$: Observable<Item[]>;

    constructor(private itemService: ItemService) { }

    ngOnInit(): void {
     this.itemService.getItems();
     console.log(this.itemService.getItems())
    }
}
</code>```

My Template

```<code><StackLayout class="page">
<ListView height="300" [items]="items$ | async" class="list-group">
    <ng-template let-item="item">
        <label [text]="item.data.first_name" class="list-group-item"></label>
    </ng-template>
</ListView>
</StackLayout>
</code>```

Terminal

答:
Since this.itemService.getItems() returns an observable you will either have to subscribe to it in your typescript file or use the async pipe on your template.

Using subscribe:

```<code>items;

constructor() {
  this.itemService.getItems().subscribe(res => {
    this.items = res;
  })
}

// in your template (Label here is just an example)

<Label [text]="items"></Label>
</code>```

Using async:

```<code>items$ = this.itemService.getItems();

// in your template (Label here is just an example of how you would use the async pipe)

<Label [text]="items$ | async"></Label>
</code>```

Title: NativeScript and Observables

Body:
I'am currently a rookie to Nativescript and Angular. I've created a API using laravel and it works fine. Now I'am trying to connect and fetch data from my API in NativeScript/Angular. I've followed this tutorial as guideline Alex Ziskind.

My API is build with PHP in Laravel and my calls works fine in Postman. I'am also capable of getting som data, but I cant return it in the HTML.

My service

export public ItemService {
    getItems():Observable<Item[]> {

        const authToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIyIiwianRpIjoiZmIzYjJmYzg3MWY2YTc5ZjVjMTM3NDNmMDllNGUwNzYwZDkyODljMmVjNTE3NGZiNDMzZTRjMGQ0MjBjYTJmYjlhMGQ1ZmFjNTQ1NmQ3ODkiLCJpYXQiOjE1OTA2NTAyMjksIm5iZiI6MTU5MDY1MDIyOSwiZXhwIjoxNjIyMTg2MjI5LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.Y3kidP6TP__DrwBDcGuk6M4p76INEdxG8UWrdakfkfcjCOlmHA0pb7a8vTvRQl2WLA_gwNWD4qA64ToOZb1YxkWCe8ESBTRDBg9Xq3DbSsZzlBZb9v8zS8PEeJVnfMtmxVIJb8IEU82DYGbpky-XdDfn67ge6fM3jTvwyivthlhaQLkjsh8e3VKlUx0P8lSxoHVw-N0369otRU6X0CTghl5lg9Khru4AtdJIBL3AOQAFEZmpzAGg9xZkvY923VkgkBHXt-adfvBwG2ZP0UhUVht-aiKK2z9HlR0eQ_-eqYlo-fqmTAE0U1k5ET99jbap8xO0dXJfdYVF0cAJ7p6FNjMoougwR89kz2xCcUHyFnPli3HcZx7j8IKDhqvneL8oWjaJuO41z1O69qsbk7_g8iLVI5vQlv6slrIe2YSbABkHzzCGndFX-smZkugB8aNmoRGpX8RJ5y5HxE6pJG8nn8CYih5ednDlWaTUBGk0p4zpck2z8788zyX41sPdB1oqR2gO0_CL-pBjCdTgDYXi_hy49_SO_4Vsf8lPL7vyhhvv7w_KgV7Jc7ju3Xm4HRLUG56K8CMy1KEfVuTDYs0gnybuFolfv2haeVgc_2h2A65O5nuUZg_RpePrSBZEftLsITWa3lUvnF380_htio-Zp3gXs3INoH7ms5KdTPt3mZ8";
        const URL = "http://10.0.2.2:8000/api/source";

        /*return this.http.get<Item[]>(
            URL,
            { headers: new HttpHeaders().append("Authorization", `Bearer ${authToken}`) }
        )*/

        const res = this.http.get<Item[]>(
            URL,
            { headers: new HttpHeaders().append("Authorization", `Bearer ${authToken}`) }
            )

            console.log()

        return res;

    }

    getItem(id) { }
    /*
        getItem(id: number): Item {
            return this.items.filter((item) => item.id === id)[0];
        }
    */
}

My component

export class ItemsComponent implements OnInit {
    public items$: Observable<Item[]>;

    constructor(private itemService: ItemService) { }

    ngOnInit(): void {
     this.itemService.getItems();
     console.log(this.itemService.getItems())
    }
}

My Template

<StackLayout class="page">
<ListView height="300" [items]="items$ | async" class="list-group">
    <ng-template let-item="item">

    </ng-template>
</ListView>
</StackLayout>

Terminal

Body:
Since this.itemService.getItems() returns an observable you will either have to subscribe to it in your typescript file or use the async pipe on your template.

Using subscribe:

items;

constructor() {
  this.itemService.getItems().subscribe(res => {
    this.items = res;
  })
}

// in your template (Label here is just an example)

<Label [text]="items"></Label>

Using async:

items$ = this.itemService.getItems();

// in your template (Label here is just an example of how you would use the async pipe)

<Label [text]="items$ | async"></Label>


问:
CKEditor Scrolls to Top in Firefox when Paragraph Format Changed
I have searched the CKEditor forum for this issue, but did not find it.

I am using CKEditor 4.5.3 with ASP.NET Web Forms (.NET Framework 4.6). Firefox version is 46.0.1. The problem does not appear in Chrome or Internet Explorer. Also, the problem does not appear in the official demo, even in Firefox.

There is only one instance of CKEditor on the page. I am using it to edit a job description. The job description is about three times longer than the height of the CKEditor window. To duplicate the bug, I scroll down to the bottom of the job description and select some text. I then use a dropdown on the CKEditor toolbar to change the paragraph format. For example, I might choose "Heading 2". As soon as I change the paragraph format, CKEditor immediately scrolls to the top of the job description, and the altered paragraph disappears below the bottom of the window. I must then scroll back down to the paragraph.

答:
I just encountered this problem in Firefox. We're using custom CSS and it turns out body {height: 100%;} was the culprit.

See
CKeditor jumps to top with certain css
and
https://www.drupal.org/node/1096164#comment-4603964


问:
How to display sum result of two column field even if one field is empty in sql?
I am having difficulty to show total value of two fileds in sql. I am getting result of first row but my second row is not showing any result just displaying empty.

Tabel Name: NumberTable

```<code>ID  VALUE1  VALUE2
===================
1   1       2
2   2
</code>```

Sql Query

```<code>Select id, (VALUE1  + VALUE2) as Total_Salary  From NumberTable;
</code>```

The following output that I am getting after running this query

```<code>ID  TOTAL
1    3
2    -
</code>```

But I want output like this:

```<code>ID  TOTAL
1    3
2    2
</code>```

答:
Please use NVL function,</p>

```<code>Select id, (NVL(VALUE1, 0)  + NVL(VALUE2, 0)) as Total_Salary  From NumberTable;
</code>```

Body:
I am having difficulty to show total value of two fileds in sql. I am getting result of first row but my second row is not showing any result just displaying empty.

Tabel Name: NumberTable

ID  VALUE1  VALUE2
===================
1   1       2
2   2

Sql Query

Select id, (VALUE1  + VALUE2) as Total_Salary  From NumberTable;

The following output that I am getting after running this query

ID  TOTAL
1    3
2    -

But I want output like this:

ID  TOTAL
1    3
2    2

Body:
Please use NVL function,

Select id, (NVL(VALUE1, 0)  + NVL(VALUE2, 0)) as Total_Salary  From NumberTable;


问:
working with the desired day in the dataset
He says that the object "europe" could not be found. this is what I want to learn. To find the death numbers of the European countries only in the dataset. to show the country name and number of deaths in two columns.

df <- read.csv ('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv')

df1 <- aggregate(death~countryName, subset(df, region =="Europe"), sum)

I will ask. but I want to learn something. In the data set, the number of deaths is given for each day. the code you have created has collected every day. my wish is only deaths. The prefix is enough to give the number of deaths of the day. He added the numbers of deaths everyday to date and added them. high figures.

not max. because he doesn't want the highest death. he wants to know how many died yesterday.

答:
The easiest way to do this, and to manipulate most data, if with the use of the dplyr R package.  As is the case with most R packages, dplyr can be installed by running install.pacakage("dplyr").  Make sure to call the dplyr library before using it by running library(dplyr) or by placing dplyr:: in front of any functions from the dplyr package you use.  My code chunks below will illustrate both methods.

Below returns two columns, countryName and a calculated column totalDeaths, for European countries only.  totalDeaths is defined as the total deaths in the data for the given country.

```<code>## load the data
df <- read.csv ('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv')
## copy the data to a new data frame to preserve original
df1 <- df
## filter data to only entries from the Europe region
df1 <- filter (df1, region == "Europe")
## group data by country
df1 <- dplyr::group_by(df1, countryName)
## calculate total deaths by grouping (in this case by country)
df1 <- dplyr::summarise(df1, totalDeaths = sum(deaths))
## ungroup to avoid errors
df1 <- dplyr::ungroup(df1)
</code>```

Below will calculate deaths yesterday in each country in the data set:

```<code>## call the dplyr library
library(dplyr)
## read the source data
df <- read.csv ('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv')
## copy df to df1 for preservation of original data
df1 <- df
## group the data by country for manipulation
df1 <- group_by(df1, countryName)
## create a variable yesterdayDeaths that adds the death column if the corresponding day  entry equals yesterday which will account for the possibility of duplicate country/day combinations
df1 <- summarise(df1, yesterdayDeaths = sum(ifelse(day == Sys.Date()-1, death, 0)))
## ungroup the data to avoid data manipulation errors
df1 <- ungroup(df1)
</code>```

Or if you'd like to cut straight to the chase you can use the dplyr R package to create "pipes".  This is done using %>% at the end of each function in a sequence or "pipe".  Pipes push data from the previous function  in the sequence to the next and allow for omitting the data input of each function after the first.

Below is how you'd use "pipes" from the dplyr package:

```<code>## if using this method make sure dplyr package is installed
## call dplyr library in order to pipe data
library(dplyr)
## create our data frame
df <-
  ## read the source data
  read.csv ('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv') %>%
  ## group data by country
  group_by(countryName) %>%
  ## create a variable yesterdayDeaths that adds the death column if the corresponding day  entry equals yesterday which will account for the possibility of duplicate country/day combinations
  summarise(yesterdayDeaths = sum(ifelse(day == Sys.Date()-1, death, 0))) %>%
  ## ungroup the data
  ungroup()
</code>```

If you wanted to instead calculate deaths yesterday in each region you would change countryName to region within the group_by() function in either set of code given above.

I hope this helps!

Body:
The easiest way to do this, and to manipulate most data, if with the use of the dplyr R package.  As is the case with most R packages, dplyr can be installed by running install.pacakage("dplyr").  Make sure to call the dplyr library before using it by running library(dplyr) or by placing dplyr:: in front of any functions from the dplyr package you use.  My code chunks below will illustrate both methods.

Below returns two columns, countryName and a calculated column totalDeaths, for European countries only.  totalDeaths is defined as the total deaths in the data for the given country.

## load the data
df <- read.csv ('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv')
## copy the data to a new data frame to preserve original
df1 <- df
## filter data to only entries from the Europe region
df1 <- filter (df1, region == "Europe")
## group data by country
df1 <- dplyr::group_by(df1, countryName)
## calculate total deaths by grouping (in this case by country)
df1 <- dplyr::summarise(df1, totalDeaths = sum(deaths))
## ungroup to avoid errors
df1 <- dplyr::ungroup(df1)

Below will calculate deaths yesterday in each country in the data set:

## call the dplyr library
library(dplyr)
## read the source data
df <- read.csv ('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv')
## copy df to df1 for preservation of original data
df1 <- df
## group the data by country for manipulation
df1 <- group_by(df1, countryName)
## create a variable yesterdayDeaths that adds the death column if the corresponding day  entry equals yesterday which will account for the possibility of duplicate country/day combinations
df1 <- summarise(df1, yesterdayDeaths = sum(ifelse(day == Sys.Date()-1, death, 0)))
## ungroup the data to avoid data manipulation errors
df1 <- ungroup(df1)

Or if you'd like to cut straight to the chase you can use the dplyr R package to create "pipes".  This is done using %>% at the end of each function in a sequence or "pipe".  Pipes push data from the previous function  in the sequence to the next and allow for omitting the data input of each function after the first.

Below is how you'd use "pipes" from the dplyr package:

## if using this method make sure dplyr package is installed
## call dplyr library in order to pipe data
library(dplyr)
## create our data frame
df <-
  ## read the source data
  read.csv ('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv') %>%
  ## group data by country
  group_by(countryName) %>%
  ## create a variable yesterdayDeaths that adds the death column if the corresponding day  entry equals yesterday which will account for the possibility of duplicate country/day combinations
  summarise(yesterdayDeaths = sum(ifelse(day == Sys.Date()-1, death, 0))) %>%
  ## ungroup the data
  ungroup()

If you wanted to instead calculate deaths yesterday in each region you would change countryName to region within the group_by() function in either set of code given above.

I hope this helps!


问:
How to test Flask views that edit the database?
I am trying to write tests to cover most of the functionality of a website I am building, but I keep getting the following error while running my tests.

```<code>Traceback (most recent call last):
  File "tests.py", line 291, in test_delete_post_page_li
    response = c.get('/delete_post/1', follow_redirects=True)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/werkzeug/test.py", line 1006, in get
    return self.open(*args, **kw)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/testing.py", line 227, in open
    follow_redirects=follow_redirects,
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/werkzeug/test.py", line 970, in open
    response = self.run_wsgi_app(environ.copy(), buffered=buffered)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/werkzeug/test.py", line 861, in run_wsgi_app
    rv = run_wsgi_app(self.application, environ, buffered=buffered)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/werkzeug/test.py", line 1096, in run_wsgi_app
    app_rv = app(environ, start_response)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/kody/Projects/lifeLongLearning/app/blogs/views.py", line 182, in delete_post
    db_session.delete(post)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 162, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2018, in delete
    self._delete_impl(state, instance, head=True)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2030, in _delete_impl
    to_attach = self._before_attach(state, obj)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2417, in _before_attach
    % (state_str(state), state.session_id, self.hash_key)
sqlalchemy.exc.InvalidRequestError: Object '<Post at 0x7fa75bb2ec50>' is already attached to session '19' (this is '4')
</code>```

The tests code is:

```<code>class LoggedDatabaseTests(TestCase):

############################
#### setup and teardown ####
############################

def create_app(self):
    app.config.from_object('config.TestConfiguration')

    return app

# executed prior to each test
def setUp(self):
    self.engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
    self.db_session = scoped_session(sessionmaker(autocommit=False,
                                     autoflush=False,
                                     bind=self.engine))
    Base.query = self.db_session.query_property()
    Base.metadata.create_all(bind=self.engine)

# executed after each test
def tearDown(self):
    self.db_session.close()
    self.db_session.remove()
    self.db_session.rollback()
    Base.metadata.drop_all(self.engine)

def test_delete_post_page_li(self):

    p_cat = PostCategory(name='froots')
    self.db_session.add(p_cat)
    self.db_session.commit()

    post = Post(name='Hello', content='3fhskajlga', category_id=1, category=p_cat)
    self.db_session.add(post)
    self.db_session.commit()
    with app.test_client() as c :
        login(c, '*****', '*****')

        response = c.get('/delete_post/1', follow_redirects=True)
        self.assertEqual(response.status_code, 302)

    assert post not in self.db_session
</code>```

The db_session mentioned in the test code is not the same db_session in the delete post view.

The code for the login function is:

```<code>def login(client, username, password):
    return client.post('/login', data=dict(
        username=username,
        password=password
    ), follow_redirects=True)
</code>```

The login view is:

```<code>@auth.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():

        if check_password_hash(passwrd, form.password.data) and form.username.data == 'LLLRocks':
            session['logged_in'] = True

            return redirect(url_for('other.home'))

    # load login template
    return render_template('login.html', form=form, title='Login')
</code>```

The delete view is:

```<code>#
# Delete Post
# Description:
#   This is a view that will delete a post. The id that is passed in is that of the
#   post that will be deleted.
#
@blogs.route('/delete_post/<int:id>', methods=['GET', 'POST'])
def delete_post(id):
    """
    Delete a post from the database
    """
    # check if user is logged in
    if not session.get('logged_in'):
        return redirect(url_for('other.home'))

    post = Post.query.get(id)

    db_session.delete(post)
    db_session.commit()

    db_session.close()
    db_session.remove()
    db_session.rollback()

    # redirect to the home page
    return redirect(url_for('other.home'))
</code>```

The database.py file is below. The db_session from this file is the db_session mentioned in the delete_post view.

```<code>from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# Need to connect to the new database
engine = create_engine('mysql+mysqldb://****:******@******/****', convert_unicode=True, pool_recycle=3600, pool_pre_ping=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    import app.models
    Base.metadata.create_all(bind=engine)
</code>```

One of these days I will dive deep into the documentation, but until then sorry for my ignorance. If I have missed posting any important code please tell me and I will post it right away.

答:
I have been able to get the code working and below I will post about how I was able to get it to work.

The test code now looks like the following.

```<code>from app.database import db
from config import TestConfiguration
from app import create_app as c_app

class TestingWhileLoggedIn(TestCase):
    def create_app(self):
        app = c_app(TestConfiguration)
        return app

    # executed prior to each test
    def setUp(self):
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()

        login(self.client, 'LLLRocks', 'h0ngk0ng')

    # executed after each test
    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_context.pop()

        logout(self.client)

  def test_delete_post_page_li(self):
        p_cat = PostCategory(name='froots')

        db.session.add(p_cat)
        db.session.commit()

        post = Post(name='Hello', content='3fhskajlga', category_id=1, category=p_cat)
        db.session.add(post)
        db.session.commit()

        response = self.client.get('/delete_post/1', follow_redirects=False)
        self.assertEqual(response.status_code, 302)

        deleted_post = Post.query.filter_by(name='Hello').first()

        self.assertEqual(deleted_post, None)

        assert post not in db.session
</code>```

The config file now looks like

```<code>import os
from os.path import abspath, dirname, join

# _cwd = dirname(abspath(__file__))

_basedir = os.path.abspath(os.path.dirname(__file__))

TOP_LEVEL_DIR = os.path.abspath(os.curdir)

class Config(object) :
    pass

class BaseConfiguration(object):
    SQLALCHEMY_TRACK_MODIFICATIONS = False

class ProductionConfiguration(BaseConfiguration):
    SQLALCHEMY_DATABASE_URI = '***************'
    SQLALCHEMY_POOL_PRE_PING = True
    SQLALCHEMY_ENGINE_OPTIONS = {'pool_recycle' : 3600}
    SECRET_KEY = '************'
    UPLOAD_FOLDER = TOP_LEVEL_DIR + '/app/static'

class TestConfiguration(BaseConfiguration):
    TESTING = True
    WTF_CSRF_ENABLED = False

    SECRET_KEY = '************'

    SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'testing.sqlite')
</code>```

The database.py file is as follows

```<code>from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
</code>```

and the create_app function being imported is

```<code>def create_app(config_class=Config):
    app = Flask(__name__)

    app.config.from_object(config_class)

    db.init_app(app)@blogs.route('/delete_post/<int:id>', methods=['GET', 'POST'])
def delete_post(id):
    """
    Delete a post from the database
    """
    # check if user is logged in
    if not session.get('logged_in'):
        return redirect(url_for('other.home'))

    post = Post.query.get(id)
    db.session.delete(post)
    db.session.commit()

    # redirect to the home page
    return redirect(url_for('other.home'))

    from app import models

    from .blogs import blogs as blogs_blueprint
    app.register_blueprint(blogs_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .other import other as other_blueprint
    app.register_blueprint(other_blueprint)

    from .worksheets import worksheets as worksheets_blueprint
    app.register_blueprint(worksheets_blueprint)

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db.session.close()
        db.session.remove()
        db.session.rollback()

    return app
</code>```

The view being tested is as follows

```<code>@blogs.route('/delete_post/<int:id>', methods=['GET', 'POST'])
def delete_post(id):
    """
    Delete a post from the database
    """
    # check if user is logged in
    if not session.get('logged_in'):
        return redirect(url_for('other.home'))

    post = Post.query.get(id)
    db.session.delete(post)
    db.session.commit()

    # redirect to the home page
    return redirect(url_for('other.home'))
</code>```

The changes that were made from the code in the question is as follows.

db_session was replaced with db.session

The database.py file was made to only initiate a blank Flask-SQLAlchemy instance

The setup of the tests were made to use the create_app function defined in init. The testing configuration was passed to it so it uses the test database. Then the db.drop_all and db.create_all Flask-SQLAlchemy functions were used to create and clean out the database.

The login and logout was added to the setup and teardown for the tests but that is unrelated to the original question.

What fixed the problem was to change the code to use Flask-SQLAlchemy instead of only SQLAlchemy.

Body:
I am trying to write tests to cover most of the functionality of a website I am building, but I keep getting the following error while running my tests.

Traceback (most recent call last):
  File "tests.py", line 291, in test_delete_post_page_li
    response = c.get('/delete_post/1', follow_redirects=True)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/werkzeug/test.py", line 1006, in get
    return self.open(*args, **kw)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/testing.py", line 227, in open
    follow_redirects=follow_redirects,
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/werkzeug/test.py", line 970, in open
    response = self.run_wsgi_app(environ.copy(), buffered=buffered)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/werkzeug/test.py", line 861, in run_wsgi_app
    rv = run_wsgi_app(self.application, environ, buffered=buffered)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/werkzeug/test.py", line 1096, in run_wsgi_app
    app_rv = app(environ, start_response)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/kody/Projects/lifeLongLearning/app/blogs/views.py", line 182, in delete_post
    db_session.delete(post)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 162, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2018, in delete
    self._delete_impl(state, instance, head=True)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2030, in _delete_impl
    to_attach = self._before_attach(state, obj)
  File "/home/kody/Projects/lifeLongLearning/venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2417, in _before_attach
    % (state_str(state), state.session_id, self.hash_key)
sqlalchemy.exc.InvalidRequestError: Object '<Post at 0x7fa75bb2ec50>' is already attached to session '19' (this is '4')

The tests code is:

class LoggedDatabaseTests(TestCase):

############################
#### setup and teardown ####
############################

def create_app(self):
    app.config.from_object('config.TestConfiguration')

    return app

# executed prior to each test
def setUp(self):
    self.engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
    self.db_session = scoped_session(sessionmaker(autocommit=False,
                                     autoflush=False,
                                     bind=self.engine))
    Base.query = self.db_session.query_property()
    Base.metadata.create_all(bind=self.engine)

# executed after each test
def tearDown(self):
    self.db_session.close()
    self.db_session.remove()
    self.db_session.rollback()
    Base.metadata.drop_all(self.engine)

def test_delete_post_page_li(self):

    p_cat = PostCategory(name='froots')
    self.db_session.add(p_cat)
    self.db_session.commit()

    post = Post(name='Hello', content='3fhskajlga', category_id=1, category=p_cat)
    self.db_session.add(post)
    self.db_session.commit()
    with app.test_client() as c :
        login(c, '*****', '*****')

        response = c.get('/delete_post/1', follow_redirects=True)
        self.assertEqual(response.status_code, 302)

    assert post not in self.db_session

The db_session mentioned in the test code is not the same db_session in the delete post view.

The code for the login function is:

def login(client, username, password):
    return client.post('/login', data=dict(
        username=username,
        password=password
    ), follow_redirects=True)

The login view is:

@auth.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():

        if check_password_hash(passwrd, form.password.data) and form.username.data == 'LLLRocks':
            session['logged_in'] = True

            return redirect(url_for('other.home'))

    # load login template
    return render_template('login.html', form=form, title='Login')

The delete view is:

#
# Delete Post
# Description:
#   This is a view that will delete a post. The id that is passed in is that of the
#   post that will be deleted.
#
@blogs.route('/delete_post/<int:id>', methods=['GET', 'POST'])
def delete_post(id):
    """
    Delete a post from the database
    """
    # check if user is logged in
    if not session.get('logged_in'):
        return redirect(url_for('other.home'))

    post = Post.query.get(id)

    db_session.delete(post)
    db_session.commit()

    db_session.close()
    db_session.remove()
    db_session.rollback()

    # redirect to the home page
    return redirect(url_for('other.home'))

The database.py file is below. The db_session from this file is the db_session mentioned in the delete_post view.

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# Need to connect to the new database
engine = create_engine('mysql+mysqldb://****:******@******/****', convert_unicode=True, pool_recycle=3600, pool_pre_ping=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    import app.models
    Base.metadata.create_all(bind=engine)

One of these days I will dive deep into the documentation, but until then sorry for my ignorance. If I have missed posting any important code please tell me and I will post it right away.

Body:
I have been able to get the code working and below I will post about how I was able to get it to work.

The test code now looks like the following.

from app.database import db
from config import TestConfiguration
from app import create_app as c_app

class TestingWhileLoggedIn(TestCase):
    def create_app(self):
        app = c_app(TestConfiguration)
        return app

    # executed prior to each test
    def setUp(self):
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()

        login(self.client, 'LLLRocks', 'h0ngk0ng')

    # executed after each test
    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_context.pop()

        logout(self.client)

  def test_delete_post_page_li(self):
        p_cat = PostCategory(name='froots')

        db.session.add(p_cat)
        db.session.commit()

        post = Post(name='Hello', content='3fhskajlga', category_id=1, category=p_cat)
        db.session.add(post)
        db.session.commit()

        response = self.client.get('/delete_post/1', follow_redirects=False)
        self.assertEqual(response.status_code, 302)

        deleted_post = Post.query.filter_by(name='Hello').first()

        self.assertEqual(deleted_post, None)

        assert post not in db.session

The config file now looks like

import os
from os.path import abspath, dirname, join

# _cwd = dirname(abspath(__file__))

_basedir = os.path.abspath(os.path.dirname(__file__))

TOP_LEVEL_DIR = os.path.abspath(os.curdir)

class Config(object) :
    pass

class BaseConfiguration(object):
    SQLALCHEMY_TRACK_MODIFICATIONS = False

class ProductionConfiguration(BaseConfiguration):
    SQLALCHEMY_DATABASE_URI = '***************'
    SQLALCHEMY_POOL_PRE_PING = True
    SQLALCHEMY_ENGINE_OPTIONS = {'pool_recycle' : 3600}
    SECRET_KEY = '************'
    UPLOAD_FOLDER = TOP_LEVEL_DIR + '/app/static'

class TestConfiguration(BaseConfiguration):
    TESTING = True
    WTF_CSRF_ENABLED = False

    SECRET_KEY = '************'

    SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'testing.sqlite')

The database.py file is as follows

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

and the create_app function being imported is

def create_app(config_class=Config):
    app = Flask(__name__)

    app.config.from_object(config_class)

    db.init_app(app)@blogs.route('/delete_post/<int:id>', methods=['GET', 'POST'])
def delete_post(id):
    """
    Delete a post from the database
    """
    # check if user is logged in
    if not session.get('logged_in'):
        return redirect(url_for('other.home'))

    post = Post.query.get(id)
    db.session.delete(post)
    db.session.commit()

    # redirect to the home page
    return redirect(url_for('other.home'))

    from app import models

    from .blogs import blogs as blogs_blueprint
    app.register_blueprint(blogs_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .other import other as other_blueprint
    app.register_blueprint(other_blueprint)

    from .worksheets import worksheets as worksheets_blueprint
    app.register_blueprint(worksheets_blueprint)

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db.session.close()
        db.session.remove()
        db.session.rollback()

    return app

The view being tested is as follows

@blogs.route('/delete_post/<int:id>', methods=['GET', 'POST'])
def delete_post(id):
    """
    Delete a post from the database
    """
    # check if user is logged in
    if not session.get('logged_in'):
        return redirect(url_for('other.home'))

    post = Post.query.get(id)
    db.session.delete(post)
    db.session.commit()

    # redirect to the home page
    return redirect(url_for('other.home'))

The changes that were made from the code in the question is as follows.

db_session was replaced with db.session

The database.py file was made to only initiate a blank Flask-SQLAlchemy instance

The setup of the tests were made to use the create_app function defined in init. The testing configuration was passed to it so it uses the test database. Then the db.drop_all and db.create_all Flask-SQLAlchemy functions were used to create and clean out the database.

The login and logout was added to the setup and teardown for the tests but that is unrelated to the original question.

What fixed the problem was to change the code to use Flask-SQLAlchemy instead of only SQLAlchemy.


问:
UseExceptionHandler is not working with ExceptionHandlingPath
In an Asp.Net Core Mvc app using .Net Core 3.0, I am trying to set up global exception handling using app.UseExceptionHandler("/Error/Show"), but the Error controller is never hit.

If I use:

```<code>public void Configure(
        IApplicationBuilder app,
        IWebHostEnvironment env,
        ILoggerFactory loggerFactory,
        IDataAccess dataAccess,
        IHttpContextAccessor httpContextAccessor)
{
    app.UseExceptionHandler("/Error/Show");
    ...
}
</code>```

The Error controller show Action never gets hit, neither does the Error controller constructor.

If I change the code to:

```<code>public void Configure(
        IApplicationBuilder app,
        IWebHostEnvironment env,
        ILoggerFactory loggerFactory,
        IDataAccess dataAccess,
        IHttpContextAccessor httpContextAccessor)
{
    app.UseExceptionHandler(new ExceptionHandlerOptions
    {
        ExceptionHandler = async context =>
        {
            await context.Response.WriteAsync(Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                title = "An Error Occurred",
                message = "The error was caught by UseExceptionHandler"
            }));
        }
    });
    ...
}
</code>```

The expected response is returned, but I'd really like to use the ExceptionHandlingPath so that I can return json if the request was made using ajax and a razor view if the request was a standard Get.

I also tried using:

```<code>app.UseExceptionHandler(new ExceptionHandlerOptions
{
    ExceptionHandlingPath = "/Error/Show"
});
</code>```

but this behaves the same as app.UseExceptionHandler("/Error/Show")

Any ideas why ExceptionHandlingPath wouldn't work, but ExceptionHandler would work as expected?

答:
It turns out the issue was that attempting to inject the IExceptionHandlerPathFeature into the Error Controller caused the ExceptionHandler to fail silently. After removing the IExceptionHandlerPathFeature parameter from the Error Controller constructor, the handler started working as expected.</p>

```<code>public async Task<IActionResult> Show()
{
  var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
}
</code>```

Body:
In an Asp.Net Core Mvc app using .Net Core 3.0, I am trying to set up global exception handling using app.UseExceptionHandler("/Error/Show"), but the Error controller is never hit.

If I use:

public void Configure(
        IApplicationBuilder app,
        IWebHostEnvironment env,
        ILoggerFactory loggerFactory,
        IDataAccess dataAccess,
        IHttpContextAccessor httpContextAccessor)
{
    app.UseExceptionHandler("/Error/Show");
    ...
}

The Error controller show Action never gets hit, neither does the Error controller constructor.

If I change the code to:

public void Configure(
        IApplicationBuilder app,
        IWebHostEnvironment env,
        ILoggerFactory loggerFactory,
        IDataAccess dataAccess,
        IHttpContextAccessor httpContextAccessor)
{
    app.UseExceptionHandler(new ExceptionHandlerOptions
    {
        ExceptionHandler = async context =>
        {
            await context.Response.WriteAsync(Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                title = "An Error Occurred",
                message = "The error was caught by UseExceptionHandler"
            }));
        }
    });
    ...
}

The expected response is returned, but I'd really like to use the ExceptionHandlingPath so that I can return json if the request was made using ajax and a razor view if the request was a standard Get.

I also tried using:

app.UseExceptionHandler(new ExceptionHandlerOptions
{
    ExceptionHandlingPath = "/Error/Show"
});

but this behaves the same as app.UseExceptionHandler("/Error/Show")

Any ideas why ExceptionHandlingPath wouldn't work, but ExceptionHandler would work as expected?

Body:
It turns out the issue was that attempting to inject the IExceptionHandlerPathFeature into the Error Controller caused the ExceptionHandler to fail silently. After removing the IExceptionHandlerPathFeature parameter from the Error Controller constructor, the handler started working as expected.

public async Task<IActionResult> Show()
{
  var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
}