问:
Set two columns as foreign keys references two primary keys in SQLAlchemy
I am using SQLALchemy in flask. And I am confused about how to set two columns as foreign keys reference two primary keys.

class Feature(db.Model):
    __tablename__ = 'feature'
    id = db.Column(Integer, primary_key=True)
    sample_id = db.Column(Integer, ForeignKey('sample.id'), primary_key=True)

class Move(db.Model):
    __tablename__ = 'move'
    id = db.Column(Integer, primary_key=True, autoincrement=True)
    feature_id = db.Column(Integer, ForeignKey(Feature.id), nullable=False)
    sample_id = db.Column(Integer, ForeignKey(Feature.sample_id), nullable=False)
    __table_args__ = (
        db.UniqueConstraint('feature_id', 'sample_id'),
    )
```

<p>I've tried several configurations but when I try to insert something I get:</p>

```sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) foreign key mismatch - "move" referencing "feature"
```

<p>In fact the create statement is wrong:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE TABLE move (
    id INTEGER NOT NULL,
    feature_id INTEGER NOT NULL,
    sample_id INTEGER NOT NULL,
    PRIMARY KEY (id),
    UNIQUE (feature_id, sample_id),
    FOREIGN KEY(feature_id) REFERENCES feature (id),
    FOREIGN KEY(sample_id) REFERENCES feature (sample_id)
)
</code>```

The last line should be:

FOREIGN KEY(feature_id, sample_id) REFERENCES feature (id, sample_id)

答:
Finally, I found a solution here

The working code is:

```<code>class Move(db.Model):
    __tablename__ = 'move'
    id = db.Column(Integer, primary_key=True, autoincrement=True)
    feature_id = db.Column(Integer)
    sample_id = db.Column(Integer)
    __table_args__ = (ForeignKeyConstraint([feature_id, sample_id],
                                           [Feature.id, Feature.sample_id]), {})
</code>```

Body:
I am using SQLALchemy in flask. And I am confused about how to set two columns as foreign keys reference two primary keys.

class Feature(db.Model):
    __tablename__ = 'feature'
    id = db.Column(Integer, primary_key=True)
    sample_id = db.Column(Integer, ForeignKey('sample.id'), primary_key=True)

class Move(db.Model):
    __tablename__ = 'move'
    id = db.Column(Integer, primary_key=True, autoincrement=True)
    feature_id = db.Column(Integer, ForeignKey(Feature.id), nullable=False)
    sample_id = db.Column(Integer, ForeignKey(Feature.sample_id), nullable=False)
    __table_args__ = (
        db.UniqueConstraint('feature_id', 'sample_id'),
    )

I've tried several configurations but when I try to insert something I get:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) foreign key mismatch - "move" referencing "feature"

In fact the create statement is wrong:

CREATE TABLE move (
    id INTEGER NOT NULL,
    feature_id INTEGER NOT NULL,
    sample_id INTEGER NOT NULL,
    PRIMARY KEY (id),
    UNIQUE (feature_id, sample_id),
    FOREIGN KEY(feature_id) REFERENCES feature (id),
    FOREIGN KEY(sample_id) REFERENCES feature (sample_id)
)

The last line should be:

FOREIGN KEY(feature_id, sample_id) REFERENCES feature (id, sample_id)

Body:
Finally, I found a solution here

The working code is:

class Move(db.Model):
    __tablename__ = 'move'
    id = db.Column(Integer, primary_key=True, autoincrement=True)
    feature_id = db.Column(Integer)
    sample_id = db.Column(Integer)
    __table_args__ = (ForeignKeyConstraint([feature_id, sample_id],
                                           [Feature.id, Feature.sample_id]), {})


来源: stackexchange

问:
Why is SQL Server providing a syntax error when it was working perfectly fine in Aginity/Redshift environment?
```<code>SELECT
    customer_id,
    SUM(extended_amount) AS total_spent,
    COUNT(DISTINCT(client_web_order_number)) AS #_of_orders,
    MAX(oms_order_date) AS last_purchase_date,
    (CURRENT_DATE - last_purchase_date) AS days_since_last_purchase,
    MIN(oms_order_date) AS registration_date,
    (CURRENT_DATE - registration_date) AS days_active,
    CASE
        WHEN (days_since_last_purchase = days_active) THEN 'One-time purchase'
        ELSE ''
    END AS notes

FROM
    mdwh.us_raw.l_dmw_order_report

WHERE
    quantity_ordered > 0
    AND customer_id IS NOT NULL
    AND customer_id != ('')
    AND customer_id LIKE 'US%'
    AND oms_order_date IS NOT NULL
    AND UPPER(line_status) NOT IN ('','RETURN', 'CANCELLED')
    AND UPPER(item_description_1) NOT IN ('','FREIGHT', 'RETURN LABEL FEE', 'VISIBLE STITCH')
    AND (quantity_ordered * unit_price_amount) > 0
    AND extended_amount < 1000 --NO BULK ORDERS
    AND oms_order_date BETWEEN '2018-01-01' AND CURRENT_DATE
    AND SUBSTRING(upc,1,6) IN (SELECT item_code FROM item_master_zs WHERE new_division BETWEEN '11' AND '39')

GROUP BY
    customer_id
--HAVING
--  SUM(extended_amount) BETWEEN 1 AND 50
</code>```

Here's the error message:

I've tried renaming the source in the query, updating SQL Server settings to the primary source.

This was a poor question, which I realize now. Will not delete, but tried my best to improve. Thank you for your help, everyone.

答:
You just need to change the syntax for date arithmetics to make the query valid in SQL Server. Also, you cannot access expressions declared in the SELECT clause in other columns, you need to repeat the expression.

So you want to change the SELECT clause to:

```<code>SELECT
    customer_id,
    SUM(extended_amount) AS total_spent,
    COUNT(DISTINCT(client_web_order_number)) AS #_of_orders,
    MAX(oms_order_date) AS last_purchase_date,
    DATEDIFF(day, last_purchase_date, CAST(GETDATE() AS DATE))  AS days_since_last_purchase,
    MIN(oms_order_date) AS registration_date,
    DATEDIFF(day, registration_date, CAST(GETDATE() AS DATE)) AS days_active,
    CASE
        WHEN DATEDIFF(day, last_purchase_date, CAST(GETDATE() AS DATE))
            = DATEDIFF(day, registration_date, CAST(GETDATE() AS DATE))
        THEN 'One-time purchase'
        ELSE ''
    END AS notes
FROM ...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
SELECT
    customer_id,
    SUM(extended_amount) AS total_spent,
    COUNT(DISTINCT(client_web_order_number)) AS #_of_orders,
    MAX(oms_order_date) AS last_purchase_date,
    (CURRENT_DATE - last_purchase_date) AS days_since_last_purchase,
    MIN(oms_order_date) AS registration_date,
    (CURRENT_DATE - registration_date) AS days_active,
    CASE
        WHEN (days_since_last_purchase = days_active) THEN 'One-time purchase'
        ELSE ''
    END AS notes

FROM
    mdwh.us_raw.l_dmw_order_report

WHERE
    quantity_ordered > 0
    AND customer_id IS NOT NULL
    AND customer_id != ('')
    AND customer_id LIKE 'US%'
    AND oms_order_date IS NOT NULL
    AND UPPER(line_status) NOT IN ('','RETURN', 'CANCELLED')
    AND UPPER(item_description_1) NOT IN ('','FREIGHT', 'RETURN LABEL FEE', 'VISIBLE STITCH')
    AND (quantity_ordered * unit_price_amount) > 0
    AND extended_amount < 1000 --NO BULK ORDERS
    AND oms_order_date BETWEEN '2018-01-01' AND CURRENT_DATE
    AND SUBSTRING(upc,1,6) IN (SELECT item_code FROM item_master_zs WHERE new_division BETWEEN '11' AND '39')

GROUP BY
    customer_id
--HAVING
--  SUM(extended_amount) BETWEEN 1 AND 50

Here's the error message:

I've tried renaming the source in the query, updating SQL Server settings to the primary source.

This was a poor question, which I realize now. Will not delete, but tried my best to improve. Thank you for your help, everyone.

Body:
You just need to change the syntax for date arithmetics to make the query valid in SQL Server. Also, you cannot access expressions declared in the SELECT clause in other columns, you need to repeat the expression.

So you want to change the SELECT clause to:

SELECT
    customer_id,
    SUM(extended_amount) AS total_spent,
    COUNT(DISTINCT(client_web_order_number)) AS #_of_orders,
    MAX(oms_order_date) AS last_purchase_date,
    DATEDIFF(day, last_purchase_date, CAST(GETDATE() AS DATE))  AS days_since_last_purchase,
    MIN(oms_order_date) AS registration_date,
    DATEDIFF(day, registration_date, CAST(GETDATE() AS DATE)) AS days_active,
    CASE
        WHEN DATEDIFF(day, last_purchase_date, CAST(GETDATE() AS DATE))
            = DATEDIFF(day, registration_date, CAST(GETDATE() AS DATE))
        THEN 'One-time purchase'
        ELSE ''
    END AS notes
FROM ...


问:
Problems with working shield in pygame platformer
Been messing around with Pygame for a while now and I wanted to make a 2d game where the player has the access to a shield which will only block enemy bullets if they are the same colour as the shield itself. I've been stuck on this problem a good few weeks now and was hoping anyone on here would be able to help me if possible. This is my first post on this website so I'm sorry if it's not the best.
This is a shortened down version of the code located below ….

```<code>import pygame
import random

pygame.init()

win = pygame.display.set_mode((600, 600))

pygame.display.set_caption("First Game")

walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'),
             pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'),
             pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]
walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'),
            pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'),
            pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]

walkRight2 = [pygame.image.load('R1E.png'), pygame.image.load('R2E.png'), pygame.image.load('R3E.png'),
              pygame.image.load('R4E.png'), pygame.image.load('R5E.png'), pygame.image.load('R6E.png'),
              pygame.image.load('R6E.png'), pygame.image.load('R5E.png'), pygame.image.load('R4E.png')]
walkLeft2 = [pygame.image.load('L1E.png'), pygame.image.load('L2E.png'), pygame.image.load('L3E.png'),
             pygame.image.load('L4E.png'), pygame.image.load('L5E.png'), pygame.image.load('L6E.png'),
             pygame.image.load('L6E.png'), pygame.image.load('L5E.png'), pygame.image.load('L4E.png')]

bg = pygame.image.load('Bg_1.png').convert()

clock = pygame.time.Clock()

class player(object):
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 5
        self.isjump = False
        self.jumpcount = 10
        self.left = False
        self.right = False
        self.walkcount = 0
        self.standing = True
        self.hitbox = (self.x + 20, self.y + 15, self.width - 40, self.height - 20)
        self.right_shield = (self.x + 15, self.y, self.width - 35, self.height)
        self.left_shield = (self.x + 17, self.y, self.width - 35, self.height)
        self.lifes = 35
    def draw(self, win):
        if self.walkcount + 1 >= 27:
            self.walkcount = 0

        if not (self.standing):
            if self.left == True:
                win.blit(walkLeft[self.walkcount // 3], (self.x, self.y))
                self.walkcount += 1
            elif self.right == True:
                win.blit(walkRight[self.walkcount // 3], (self.x, self.y))
                self.walkcount += 1
        else:
            if self.right == True:
                win.blit(walkRight[0], (self.x, self.y))
            else:
                win.blit(walkLeft[0], (self.x, self.y))
        self.hitbox = (self.x + 20, self.y + 15, self.width - 40, self.height - 20)
        self.right_shield = (self.x + 15, self.y, self.width - 35, self.height)
        self.left_shield = (self.x + 17, self.y, self.width - 35, self.height)
    def hit(self, win):
        global run
        global bad_guys_kiled
        if self.lifes > 0:
            self.lifes -= 1
            if self.lifes % 2 == 0:
                pass
        if self.lifes <= 0:
            run = False
            print("You have ran out of lifes!")
            print("Thank you for playing!")

class enemy(object):
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 5
        self.boss_vel = 2
        self.left = True
        self.right = False
        self.walkcount = 0
        self.isjump = False
        self.jumpcount = 10
        self.standing = True
        self.hitbox = (self.x + 20, self.y + 10, self.width - 40, self.height - 20)
        self.shootloop1 = 0
        self.bullets2 = []
        self.bullets3 = []
        self.lifes = 2
        self.half_health = False
    def draw(self, win):
        global half_health
        global bad_guys_kiled
        if bad_guys_kiled <= 25:
            if self.walkcount + 1 >= 27:
                self.walkcount = 0
            if not (self.standing):
                if self.left == True:
                    win.blit(walkLeft2[self.walkcount // 3], (self.x, self.y))
                    self.walkcount += 1
                elif self.right == True:
                    win.blit(walkRight2[self.walkcount // 3], (self.x, self.y))
                    self.walkcount += 1
            else:
                if self.right == True:
                    win.blit(walkRight2[0], (self.x, self.y))
                else:
                    win.blit(walkRight2[0], (self.x, self.y))
            self.hitbox = (self.x + 20, self.y + 10, self.width - 40, self.height - 20)
            enemy_health = (self.x + 25, self.y + 5, self.width - 40, self.height - 70)
            pygame.draw.rect(win, (0, 255, 0), enemy_health)
            if self.half_health == True:
                pygame.draw.rect(win, (255, 0, 0), (self.x + 50, self.y + 5, self.width - 75, self.height - 70))
    def draw2(self, win):
        global half_health
        global bad_guys_kiled
        if self.walkcount + 1 >= 27:
            self.walkcount = 0
        if not (self.standing):
            if self.left == True:
                win.blit(walkLeft2[self.walkcount // 3], (self.x, self.y))
                self.walkcount += 1
            elif self.right == True:
                win.blit(walkRight2[self.walkcount // 3], (self.x, self.y))
                self.walkcount += 1
        else:
            if self.right == True:
                win.blit(walkRight2[0], (self.x, self.y))
            else:
                win.blit(walkRight2[0], (self.x, self.y))
        self.hitbox = (self.x + 20, self.y + 10, self.width - 40, self.height - 20)

        enemy_health = (self.x + 25, self.y + 5, self.width - 40, self.height - 70)
        pygame.draw.rect(win, (0, 255, 0), enemy_health)
        if self.half_health == True:
            pygame.draw.rect(win, (255, 0, 0), (self.x + 50, self.y + 5, self.width - 75, self.height - 70))
    def walk(self, win):
        global shield
        global drop_spot
        global drop
        global shield_health
        global bad_guys_kiled
        global temp_num
        global temp_number
        global colours
        global shield_colour
        global shield_number
        global bullet_colour
        global test_number
        bullet_colour = random.choice(colours)
        if bullet_colour == "blue":
            colour_number = (0, 0, 255)
            test_number = 0
        else:
            colour_number = (255, 0, 0)
            test_number = 1
        if temp_num == False:
            temp_number = random.randint(4, 34)
            temp_num = True
        if self.shootloop1 > 0:
            self.shootloop1 += 1
        if self.shootloop1 > int(temp_number):
            self.shootloop1 = 0
        if bad_guys_kiled <= 25 and not (main_menu):
            for bullet in self.bullets2:
                if man.left:
                    if int(shield_number) == int(test_number):
                        if bullet.y - bullet.radius < man.right_shield[1] + man.right_shield[3] and bullet.y + bullet.radius > man.right_shield[1]:
                            if bullet.x + bullet.radius > man.right_shield[0] and bullet.x - bullet.radius < man.right_shield[0] + man.right_shield[2]:
                                try:
                                    self.bullets2.pop(self.bullets2.index(bullet))
                                except ValueError:
                                    pass
                elif man.right:
                    if int(shield_number) == int(test_number):
                        if bullet.y - bullet.radius < man.left_shield[1] + man.left_shield[3] and bullet.y + bullet.radius > man.left_shield[1]:
                            if bullet.x + bullet.radius > man.left_shield[0] and bullet.x - bullet.radius < man.left_shield[0] + man.left_shield[2]:
                                try:
                                    self.bullets2.pop(self.bullets2.index(bullet))
                                except ValueError:
                                    pass
                elif int(shield_number) != int(test_number):
                    if bullet.y - bullet.radius < man.hitbox[1] + man.hitbox[3] and bullet.y + bullet.radius > man.hitbox[1]:
                        if bullet.x + bullet.radius > man.hitbox[0] and bullet.x - bullet.radius < man.hitbox[0] + man.hitbox[2]:
                            man.hit(win)
                            try:
                                self.bullets2.pop(self.bullets2.index(bullet))
                            except ValueError:
                                pass
                if bullet.x < 800 and bullet.x > -50:
                    bullet.x += bullet.vel
                else:
                    try:
                        self.bullets2.pop(self.bullets2.index(bullet))
                    except ValueError:
                        pass
            if self.left:
                facing = -1
            elif self.right:
                facing = 1
            if len(self.bullets2) < 7 and self.shootloop1 == 0:
                self.bullets2.append(projectile(round(self.x + self.width // 2), round(self.y + self.height // 2), 6, (colour_number),facing))
                self.shootloop1 = 1
            if self.x != -50:
                self.x -= self.vel
                self.right = False
                self.left = True
                self.standing = False
            else:
                for x in range(1, 200):
                    if self.x >= 700:
                        self.x = 650
                    self.half_health = False
                    self.x += self.vel
                    self.right = False
                    self.left = True
                    self.standing = False
        else:
            for bullet in self.bullets2:
                try:
                    self.bullets2.pop(self.bullets2.index(bullet))
                except ValueError:
                    pass

    def hit(self, win):
        global bad_guys_kiled
        global drop
        global drop_spot
        global drop_count
        global min
        global max
        global score
        Hit_noise.play()
        if self.lifes > 0:
            self.lifes -= 1
            self.half_health = True
        if self.lifes <= 0:
            random_number = random.randint(min, max)
            if bad_guys_kiled <= 25:
                if random_number == 1:
                    if drop_count != 1:
                        drop = True
                        drop_count += 1
                        drop_spot = [self.x + 20]
                        drop_spot += [self.y + 10]
                        drop_spot += [self.width - 40]
                        drop_spot += [self.height - 40]
                    else:
                        try:
                            max -= 1
                        except ValueError:
                            max = 20
            if bad_guys_kiled >= 25:
                drop_spot = []

            self.half_health = False
            self.x = self.x + 700
            self.lifes = 2
            bad_guys_kiled += 1
            score += 1

class projectile(object):
    def __init__(self, x, y, radius, colour, facing):
        self.x = x
        self.y = y
        self.radius = radius
        self.colour = colour
        self.facing = facing
        self.vel = 8 * facing
    def draw(self, win):
        pygame.draw.circle(win, self.colour, (self.x, self.y), self.radius)
def redraw_game_window():
    global drop_spot
    global drop
    global bad_guys_kiled
    global jump_block
    global main_menu
    global run
    global count
    global score
    global shield
    global man_movement_block
    global shield_colour
    global bullet_colour
    global test_number
    global shield_number
    win.blit(bg, (0, 0))
    man.draw(win)
    print("man = ",shield_number)
    print("bullet =",test_number)
    text_score = font.render("Score:" + str(score), 1, (0, 0, 0))
    text_shield = font.render("Shield Colour:" + "temp", 1, (0, 0, 0))
    text_player_health = font.render("Player Health:" + str(man.lifes), 1, (0, 0, 0))
    win.blit(text_score, (450, 10))
    win.blit(text_shield, (225, 10))
    win.blit(text_player_health, (20, 10))

    if bad_guys_kiled <= 25:
        if drop == True:
            try:
                pygame.draw.rect(win, (0, 0, 255), (drop_spot[0], drop_spot[1], drop_spot[2], drop_spot[3]))
            except IndexError:
                pass
    if man.left == True and shield_colour == "blue":
        pygame.draw.rect(win, (0, 0, 255), (man.x + 17, man.y, man.width - 35, man.height), 2)
    elif not(main_menu) and shield_colour == "blue":
        pygame.draw.rect(win, (0, 0, 255), (man.x + 15, man.y, man.width - 35, man.height), 2)
    if man.right == True and shield_colour == "red":
        pygame.draw.rect(win, (255, 0, 0), (man.x + 17, man.y, man.width - 35, man.height), 2)
    elif not(main_menu) and shield_colour == "red":
        pygame.draw.rect(win, (255, 0, 0), (man.x + 15, man.y, man.width - 35, man.height), 2)
    if bad_guys_kiled <= 25 :
        bad_guy1.draw(win)
        bad_guy2.draw(win)
        bad_guy3.draw(win)

    for bullet in bullets:
        bullet.draw(win)
    for bullet in bad_guy1.bullets2:
        bullet.draw(win)
    for bullet in bad_guy2.bullets2:
        bullet.draw(win)
    for bullet in bad_guy3.bullets2:
        bullet.draw(win)

    pygame.display.update()

def game_credits():
    pygame.draw.rect(win, (40, 26, 13), (0, 0, 650, 650))
    text_help = font.render("CONTROLS", 1, (0, 255, 0))
    text_help1 = font.render("UP ARROW = JUMP", 1, (255, 255, 255))
    text_help2 = font.render("LEFT ARROW = LEFT", 1, (255, 255, 255))
    text_help3 = font.render("RIGHT ARROW = RIGHT", 1, (255, 255, 255))
    text_help4 = font.render("ZERO ON NUMPAD = FIRE", 1, (255, 255, 255))
    text_help5 = font.render("P = PAUSE", 1, (255, 255, 255))
    text_help6 = font.render("O = UNPAUSE ", 1, (255, 255, 255))
    text_help7 = font.render("(PRESSING P WILL NOT ", 1, (255, 255, 255))
    text_help8 = font.render("UNPAUSE THE GAME !)", 1, (255, 255, 255))
    text_help9 = font.render("B = SHIELD", 1, (255, 255, 255))
    win.blit(text_help, (22, 50))
    win.blit(text_help1, (22, 100))
    win.blit(text_help2, (22, 150))
    win.blit(text_help3, (22, 200))
    win.blit(text_help4, (22, 250))
    win.blit(text_help5, (22, 300))
    win.blit(text_help6, (22, 350))
    win.blit(text_help7, (22, 400))
    win.blit(text_help8, (22, 450))
    win.blit(text_help9, (22, 500))
# Main Loop #
Air_raid = pygame.mixer.Sound("Air raid.wav")
Godzilla_roar = pygame.mixer.Sound("Godzilla roar.wav")
Victory_noise = pygame.mixer.Sound("Victory noise.wav")
Gun_shot = pygame.mixer.Sound("Gun shot.wav")
Hit_noise = pygame.mixer.Sound("Hit noise.wav")
man = player(300, 450, 64, 64)
bad_guy1 = enemy(0, 450, 64, 64)
bad_guy2 = enemy(250, 450, 64, 64)
bad_guy3 = enemy(500, 450, 64, 64)
count = 0
bullets = []
shootloop = 0
bad_guys_kiled = 0
temp_num = False
temp_number = 0
drop = False
drop_spot = []
drop_count = 0
min = 1
max = 20
main_menu = False
main_spawn = False
score = 0
man_movement_block = False
shield_count = 0
colours = ["blue", "red"]
shield_colour = "blue"
bullet_colour = None
shield_number = 0
test_number = 0
font = pygame.font.SysFont("Calibri Light", 25, True)
run = True
while run == True:
    temp_number = random.randint(4, 34)
    if man.y >= 500:
        man.y = 450
    clock.tick(27)
    shield = True
    if shootloop > 0:
        shootloop += 1
    if shootloop > 5:
        shootloop = 0
    if shield_count > 0:
        shield_count += 1
    if shield_count > 5:
        shield_count = 0
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    for bullet in bullets:
        if bad_guys_kiled <= 25:
            if bullet.y - bullet.radius < bad_guy1.hitbox[1] + bad_guy1.hitbox[3] and bullet.y + bullet.radius > bad_guy1.hitbox[1]:
                if bullet.x + bullet.radius > bad_guy1.hitbox[0] and bullet.x - bullet.radius < bad_guy1.hitbox[0] + bad_guy1.hitbox[2]:
                    bad_guy1.hit(win)
                    bullets.pop(bullets.index(bullet))
            if bullet.y - bullet.radius < bad_guy2.hitbox[1] + bad_guy2.hitbox[3] and bullet.y + bullet.radius > bad_guy2.hitbox[1]:
                if bullet.x + bullet.radius > bad_guy2.hitbox[0] and bullet.x - bullet.radius < bad_guy2.hitbox[0] + bad_guy2.hitbox[2]:
                    bad_guy2.hit(win)
                    try:
                        bullets.pop(bullets.index(bullet))
                    except ValueError:
                        pass
            if bullet.y - bullet.radius < bad_guy3.hitbox[1] + bad_guy3.hitbox[3] and bullet.y + bullet.radius > bad_guy3.hitbox[1]:
                if bullet.x + bullet.radius > bad_guy3.hitbox[0] and bullet.x - bullet.radius < bad_guy3.hitbox[0] + bad_guy3.hitbox[2]:
                    bad_guy3.hit(win)
                    try:
                        bullets.pop(bullets.index(bullet))
                    except ValueError:
                        pass

        try:
            if man.hitbox[1] - (man.hitbox[3] / 2) < drop_spot[1] + (drop_spot[3] / 2) and man.hitbox[1] + (man.hitbox[3] / 2) > drop_spot[1]:
                if man.hitbox[0] + (man.hitbox[3] / 2) > drop_spot[0] and man.hitbox[0] - (man.hitbox[3] / 2) < drop_spot[0] + drop_spot[2]:
                    Gun_shot.stop()
                    if man.lifes <= 35:
                        man.lifes += 10
                    else:
                        Gun_shot.stop()
                        pass
                    try:
                        bullets.pop(bullets.index(bullet))
                        drop = False
                        drop_count = 0
                        drop_spot = []
                    except ValueError:
                        pass
        except:
            pass
        if bullet.x < 650 and bullet.x > -20:
            bullet.x += bullet.vel
        else:
            try:
                bullets.pop(bullets.index(bullet))
            except ValueError:
                pass
    keys = pygame.key.get_pressed()
    if keys[pygame.K_KP0] and not (main_menu):
        if man.left:
            facing = -1
        elif man.right:
            facing = 1
        else:
            facing = -1
        if len(bullets) < 5 and shootloop == 0:
            Gun_shot.play()
            bullets.append(projectile(round(man.x + man.width // 2), round(man.y + man.height // 2), 6, (0, 0, 255), facing))
            shootloop = 1
    if keys[pygame.K_LEFT] and man.x > man.vel and not(man_movement_block):
        man.x -= man.vel
        man.left = True
        man.right = False
        man.standing = False
    elif keys[pygame.K_RIGHT] and man.x < 620 - man.vel - man.width:
        man.x += man.vel
        man.right = True
        man.left = False
        man.standing = False
    elif keys[pygame.K_b] and shield_count == 0:
        if shield_colour == "blue":
            shield_colour = "red"
            shield_number = 1
        else:
            shield_colour = "blue"
            shield_number = 0
        shield_count = 1
    if not (man.isjump):
        if keys[pygame.K_UP]:
            man.isjump = True
            man.walkcount = 0

    else:
        if man.jumpcount >= -10:
            neg = 1
            if man.jumpcount < 0:
                neg = -1
            man.y -= (man.jumpcount ** 2) / 2 * neg
            man.jumpcount -= 1
        else:
            man.isjump = False
            man.jumpcount = 10

    bad_guy1.walk(win)
    bad_guy2.walk(win)
    bad_guy3.walk(win)

    redraw_game_window()

pygame.quit()
</code>```

答:
The problem is caused by the code in the walk method of the enemy class, where you check for collisions between enemy bullets and the player.

```<code>if man.left:
    ... # block bullets with the shield when the player is pointing left
elif man.right:
    ... # block bullets with the shield when the player is pointing right
elif int(shield_number) != int(test_number):
    ... # if the player has been hit, call man.hit
</code>```

Because you have used an elif, the code that checks if the player has been hit (and calls man.hit) will only be executed if both man.left and man.right are false, which never happens. Just changing it from an elif to an if should solve your problem.

```<code>if man.left:
    ... # block bullets with the shield when the player is pointing left
elif man.right:
    ... # block bullets with the shield when the player is pointing right

if int(shield_number) != int(test_number):
    ... # if the player has been hit, call man.hit
</code>```

Body:
Been messing around with Pygame for a while now and I wanted to make a 2d game where the player has the access to a shield which will only block enemy bullets if they are the same colour as the shield itself. I've been stuck on this problem a good few weeks now and was hoping anyone on here would be able to help me if possible. This is my first post on this website so I'm sorry if it's not the best.
This is a shortened down version of the code located below ….

import pygame
import random

pygame.init()

win = pygame.display.set_mode((600, 600))

pygame.display.set_caption("First Game")

walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'),
             pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'),
             pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]
walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'),
            pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'),
            pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]

walkRight2 = [pygame.image.load('R1E.png'), pygame.image.load('R2E.png'), pygame.image.load('R3E.png'),
              pygame.image.load('R4E.png'), pygame.image.load('R5E.png'), pygame.image.load('R6E.png'),
              pygame.image.load('R6E.png'), pygame.image.load('R5E.png'), pygame.image.load('R4E.png')]
walkLeft2 = [pygame.image.load('L1E.png'), pygame.image.load('L2E.png'), pygame.image.load('L3E.png'),
             pygame.image.load('L4E.png'), pygame.image.load('L5E.png'), pygame.image.load('L6E.png'),
             pygame.image.load('L6E.png'), pygame.image.load('L5E.png'), pygame.image.load('L4E.png')]

bg = pygame.image.load('Bg_1.png').convert()

clock = pygame.time.Clock()

class player(object):
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 5
        self.isjump = False
        self.jumpcount = 10
        self.left = False
        self.right = False
        self.walkcount = 0
        self.standing = True
        self.hitbox = (self.x + 20, self.y + 15, self.width - 40, self.height - 20)
        self.right_shield = (self.x + 15, self.y, self.width - 35, self.height)
        self.left_shield = (self.x + 17, self.y, self.width - 35, self.height)
        self.lifes = 35
    def draw(self, win):
        if self.walkcount + 1 >= 27:
            self.walkcount = 0

        if not (self.standing):
            if self.left == True:
                win.blit(walkLeft[self.walkcount // 3], (self.x, self.y))
                self.walkcount += 1
            elif self.right == True:
                win.blit(walkRight[self.walkcount // 3], (self.x, self.y))
                self.walkcount += 1
        else:
            if self.right == True:
                win.blit(walkRight[0], (self.x, self.y))
            else:
                win.blit(walkLeft[0], (self.x, self.y))
        self.hitbox = (self.x + 20, self.y + 15, self.width - 40, self.height - 20)
        self.right_shield = (self.x + 15, self.y, self.width - 35, self.height)
        self.left_shield = (self.x + 17, self.y, self.width - 35, self.height)
    def hit(self, win):
        global run
        global bad_guys_kiled
        if self.lifes > 0:
            self.lifes -= 1
            if self.lifes % 2 == 0:
                pass
        if self.lifes <= 0:
            run = False
            print("You have ran out of lifes!")
            print("Thank you for playing!")

class enemy(object):
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 5
        self.boss_vel = 2
        self.left = True
        self.right = False
        self.walkcount = 0
        self.isjump = False
        self.jumpcount = 10
        self.standing = True
        self.hitbox = (self.x + 20, self.y + 10, self.width - 40, self.height - 20)
        self.shootloop1 = 0
        self.bullets2 = []
        self.bullets3 = []
        self.lifes = 2
        self.half_health = False
    def draw(self, win):
        global half_health
        global bad_guys_kiled
        if bad_guys_kiled <= 25:
            if self.walkcount + 1 >= 27:
                self.walkcount = 0
            if not (self.standing):
                if self.left == True:
                    win.blit(walkLeft2[self.walkcount // 3], (self.x, self.y))
                    self.walkcount += 1
                elif self.right == True:
                    win.blit(walkRight2[self.walkcount // 3], (self.x, self.y))
                    self.walkcount += 1
            else:
                if self.right == True:
                    win.blit(walkRight2[0], (self.x, self.y))
                else:
                    win.blit(walkRight2[0], (self.x, self.y))
            self.hitbox = (self.x + 20, self.y + 10, self.width - 40, self.height - 20)
            enemy_health = (self.x + 25, self.y + 5, self.width - 40, self.height - 70)
            pygame.draw.rect(win, (0, 255, 0), enemy_health)
            if self.half_health == True:
                pygame.draw.rect(win, (255, 0, 0), (self.x + 50, self.y + 5, self.width - 75, self.height - 70))
    def draw2(self, win):
        global half_health
        global bad_guys_kiled
        if self.walkcount + 1 >= 27:
            self.walkcount = 0
        if not (self.standing):
            if self.left == True:
                win.blit(walkLeft2[self.walkcount // 3], (self.x, self.y))
                self.walkcount += 1
            elif self.right == True:
                win.blit(walkRight2[self.walkcount // 3], (self.x, self.y))
                self.walkcount += 1
        else:
            if self.right == True:
                win.blit(walkRight2[0], (self.x, self.y))
            else:
                win.blit(walkRight2[0], (self.x, self.y))
        self.hitbox = (self.x + 20, self.y + 10, self.width - 40, self.height - 20)

        enemy_health = (self.x + 25, self.y + 5, self.width - 40, self.height - 70)
        pygame.draw.rect(win, (0, 255, 0), enemy_health)
        if self.half_health == True:
            pygame.draw.rect(win, (255, 0, 0), (self.x + 50, self.y + 5, self.width - 75, self.height - 70))
    def walk(self, win):
        global shield
        global drop_spot
        global drop
        global shield_health
        global bad_guys_kiled
        global temp_num
        global temp_number
        global colours
        global shield_colour
        global shield_number
        global bullet_colour
        global test_number
        bullet_colour = random.choice(colours)
        if bullet_colour == "blue":
            colour_number = (0, 0, 255)
            test_number = 0
        else:
            colour_number = (255, 0, 0)
            test_number = 1
        if temp_num == False:
            temp_number = random.randint(4, 34)
            temp_num = True
        if self.shootloop1 > 0:
            self.shootloop1 += 1
        if self.shootloop1 > int(temp_number):
            self.shootloop1 = 0
        if bad_guys_kiled <= 25 and not (main_menu):
            for bullet in self.bullets2:
                if man.left:
                    if int(shield_number) == int(test_number):
                        if bullet.y - bullet.radius < man.right_shield[1] + man.right_shield[3] and bullet.y + bullet.radius > man.right_shield[1]:
                            if bullet.x + bullet.radius > man.right_shield[0] and bullet.x - bullet.radius < man.right_shield[0] + man.right_shield[2]:
                                try:
                                    self.bullets2.pop(self.bullets2.index(bullet))
                                except ValueError:
                                    pass
                elif man.right:
                    if int(shield_number) == int(test_number):
                        if bullet.y - bullet.radius < man.left_shield[1] + man.left_shield[3] and bullet.y + bullet.radius > man.left_shield[1]:
                            if bullet.x + bullet.radius > man.left_shield[0] and bullet.x - bullet.radius < man.left_shield[0] + man.left_shield[2]:
                                try:
                                    self.bullets2.pop(self.bullets2.index(bullet))
                                except ValueError:
                                    pass
                elif int(shield_number) != int(test_number):
                    if bullet.y - bullet.radius < man.hitbox[1] + man.hitbox[3] and bullet.y + bullet.radius > man.hitbox[1]:
                        if bullet.x + bullet.radius > man.hitbox[0] and bullet.x - bullet.radius < man.hitbox[0] + man.hitbox[2]:
                            man.hit(win)
                            try:
                                self.bullets2.pop(self.bullets2.index(bullet))
                            except ValueError:
                                pass
                if bullet.x < 800 and bullet.x > -50:
                    bullet.x += bullet.vel
                else:
                    try:
                        self.bullets2.pop(self.bullets2.index(bullet))
                    except ValueError:
                        pass
            if self.left:
                facing = -1
            elif self.right:
                facing = 1
            if len(self.bullets2) < 7 and self.shootloop1 == 0:
                self.bullets2.append(projectile(round(self.x + self.width // 2), round(self.y + self.height // 2), 6, (colour_number),facing))
                self.shootloop1 = 1
            if self.x != -50:
                self.x -= self.vel
                self.right = False
                self.left = True
                self.standing = False
            else:
                for x in range(1, 200):
                    if self.x >= 700:
                        self.x = 650
                    self.half_health = False
                    self.x += self.vel
                    self.right = False
                    self.left = True
                    self.standing = False
        else:
            for bullet in self.bullets2:
                try:
                    self.bullets2.pop(self.bullets2.index(bullet))
                except ValueError:
                    pass

    def hit(self, win):
        global bad_guys_kiled
        global drop
        global drop_spot
        global drop_count
        global min
        global max
        global score
        Hit_noise.play()
        if self.lifes > 0:
            self.lifes -= 1
            self.half_health = True
        if self.lifes <= 0:
            random_number = random.randint(min, max)
            if bad_guys_kiled <= 25:
                if random_number == 1:
                    if drop_count != 1:
                        drop = True
                        drop_count += 1
                        drop_spot = [self.x + 20]
                        drop_spot += [self.y + 10]
                        drop_spot += [self.width - 40]
                        drop_spot += [self.height - 40]
                    else:
                        try:
                            max -= 1
                        except ValueError:
                            max = 20
            if bad_guys_kiled >= 25:
                drop_spot = []

            self.half_health = False
            self.x = self.x + 700
            self.lifes = 2
            bad_guys_kiled += 1
            score += 1

class projectile(object):
    def __init__(self, x, y, radius, colour, facing):
        self.x = x
        self.y = y
        self.radius = radius
        self.colour = colour
        self.facing = facing
        self.vel = 8 * facing
    def draw(self, win):
        pygame.draw.circle(win, self.colour, (self.x, self.y), self.radius)
def redraw_game_window():
    global drop_spot
    global drop
    global bad_guys_kiled
    global jump_block
    global main_menu
    global run
    global count
    global score
    global shield
    global man_movement_block
    global shield_colour
    global bullet_colour
    global test_number
    global shield_number
    win.blit(bg, (0, 0))
    man.draw(win)
    print("man = ",shield_number)
    print("bullet =",test_number)
    text_score = font.render("Score:" + str(score), 1, (0, 0, 0))
    text_shield = font.render("Shield Colour:" + "temp", 1, (0, 0, 0))
    text_player_health = font.render("Player Health:" + str(man.lifes), 1, (0, 0, 0))
    win.blit(text_score, (450, 10))
    win.blit(text_shield, (225, 10))
    win.blit(text_player_health, (20, 10))

    if bad_guys_kiled <= 25:
        if drop == True:
            try:
                pygame.draw.rect(win, (0, 0, 255), (drop_spot[0], drop_spot[1], drop_spot[2], drop_spot[3]))
            except IndexError:
                pass
    if man.left == True and shield_colour == "blue":
        pygame.draw.rect(win, (0, 0, 255), (man.x + 17, man.y, man.width - 35, man.height), 2)
    elif not(main_menu) and shield_colour == "blue":
        pygame.draw.rect(win, (0, 0, 255), (man.x + 15, man.y, man.width - 35, man.height), 2)
    if man.right == True and shield_colour == "red":
        pygame.draw.rect(win, (255, 0, 0), (man.x + 17, man.y, man.width - 35, man.height), 2)
    elif not(main_menu) and shield_colour == "red":
        pygame.draw.rect(win, (255, 0, 0), (man.x + 15, man.y, man.width - 35, man.height), 2)
    if bad_guys_kiled <= 25 :
        bad_guy1.draw(win)
        bad_guy2.draw(win)
        bad_guy3.draw(win)

    for bullet in bullets:
        bullet.draw(win)
    for bullet in bad_guy1.bullets2:
        bullet.draw(win)
    for bullet in bad_guy2.bullets2:
        bullet.draw(win)
    for bullet in bad_guy3.bullets2:
        bullet.draw(win)

    pygame.display.update()

def game_credits():
    pygame.draw.rect(win, (40, 26, 13), (0, 0, 650, 650))
    text_help = font.render("CONTROLS", 1, (0, 255, 0))
    text_help1 = font.render("UP ARROW = JUMP", 1, (255, 255, 255))
    text_help2 = font.render("LEFT ARROW = LEFT", 1, (255, 255, 255))
    text_help3 = font.render("RIGHT ARROW = RIGHT", 1, (255, 255, 255))
    text_help4 = font.render("ZERO ON NUMPAD = FIRE", 1, (255, 255, 255))
    text_help5 = font.render("P = PAUSE", 1, (255, 255, 255))
    text_help6 = font.render("O = UNPAUSE ", 1, (255, 255, 255))
    text_help7 = font.render("(PRESSING P WILL NOT ", 1, (255, 255, 255))
    text_help8 = font.render("UNPAUSE THE GAME !)", 1, (255, 255, 255))
    text_help9 = font.render("B = SHIELD", 1, (255, 255, 255))
    win.blit(text_help, (22, 50))
    win.blit(text_help1, (22, 100))
    win.blit(text_help2, (22, 150))
    win.blit(text_help3, (22, 200))
    win.blit(text_help4, (22, 250))
    win.blit(text_help5, (22, 300))
    win.blit(text_help6, (22, 350))
    win.blit(text_help7, (22, 400))
    win.blit(text_help8, (22, 450))
    win.blit(text_help9, (22, 500))
# Main Loop #
Air_raid = pygame.mixer.Sound("Air raid.wav")
Godzilla_roar = pygame.mixer.Sound("Godzilla roar.wav")
Victory_noise = pygame.mixer.Sound("Victory noise.wav")
Gun_shot = pygame.mixer.Sound("Gun shot.wav")
Hit_noise = pygame.mixer.Sound("Hit noise.wav")
man = player(300, 450, 64, 64)
bad_guy1 = enemy(0, 450, 64, 64)
bad_guy2 = enemy(250, 450, 64, 64)
bad_guy3 = enemy(500, 450, 64, 64)
count = 0
bullets = []
shootloop = 0
bad_guys_kiled = 0
temp_num = False
temp_number = 0
drop = False
drop_spot = []
drop_count = 0
min = 1
max = 20
main_menu = False
main_spawn = False
score = 0
man_movement_block = False
shield_count = 0
colours = ["blue", "red"]
shield_colour = "blue"
bullet_colour = None
shield_number = 0
test_number = 0
font = pygame.font.SysFont("Calibri Light", 25, True)
run = True
while run == True:
    temp_number = random.randint(4, 34)
    if man.y >= 500:
        man.y = 450
    clock.tick(27)
    shield = True
    if shootloop > 0:
        shootloop += 1
    if shootloop > 5:
        shootloop = 0
    if shield_count > 0:
        shield_count += 1
    if shield_count > 5:
        shield_count = 0
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    for bullet in bullets:
        if bad_guys_kiled <= 25:
            if bullet.y - bullet.radius < bad_guy1.hitbox[1] + bad_guy1.hitbox[3] and bullet.y + bullet.radius > bad_guy1.hitbox[1]:
                if bullet.x + bullet.radius > bad_guy1.hitbox[0] and bullet.x - bullet.radius < bad_guy1.hitbox[0] + bad_guy1.hitbox[2]:
                    bad_guy1.hit(win)
                    bullets.pop(bullets.index(bullet))
            if bullet.y - bullet.radius < bad_guy2.hitbox[1] + bad_guy2.hitbox[3] and bullet.y + bullet.radius > bad_guy2.hitbox[1]:
                if bullet.x + bullet.radius > bad_guy2.hitbox[0] and bullet.x - bullet.radius < bad_guy2.hitbox[0] + bad_guy2.hitbox[2]:
                    bad_guy2.hit(win)
                    try:
                        bullets.pop(bullets.index(bullet))
                    except ValueError:
                        pass
            if bullet.y - bullet.radius < bad_guy3.hitbox[1] + bad_guy3.hitbox[3] and bullet.y + bullet.radius > bad_guy3.hitbox[1]:
                if bullet.x + bullet.radius > bad_guy3.hitbox[0] and bullet.x - bullet.radius < bad_guy3.hitbox[0] + bad_guy3.hitbox[2]:
                    bad_guy3.hit(win)
                    try:
                        bullets.pop(bullets.index(bullet))
                    except ValueError:
                        pass

        try:
            if man.hitbox[1] - (man.hitbox[3] / 2) < drop_spot[1] + (drop_spot[3] / 2) and man.hitbox[1] + (man.hitbox[3] / 2) > drop_spot[1]:
                if man.hitbox[0] + (man.hitbox[3] / 2) > drop_spot[0] and man.hitbox[0] - (man.hitbox[3] / 2) < drop_spot[0] + drop_spot[2]:
                    Gun_shot.stop()
                    if man.lifes <= 35:
                        man.lifes += 10
                    else:
                        Gun_shot.stop()
                        pass
                    try:
                        bullets.pop(bullets.index(bullet))
                        drop = False
                        drop_count = 0
                        drop_spot = []
                    except ValueError:
                        pass
        except:
            pass
        if bullet.x < 650 and bullet.x > -20:
            bullet.x += bullet.vel
        else:
            try:
                bullets.pop(bullets.index(bullet))
            except ValueError:
                pass
    keys = pygame.key.get_pressed()
    if keys[pygame.K_KP0] and not (main_menu):
        if man.left:
            facing = -1
        elif man.right:
            facing = 1
        else:
            facing = -1
        if len(bullets) < 5 and shootloop == 0:
            Gun_shot.play()
            bullets.append(projectile(round(man.x + man.width // 2), round(man.y + man.height // 2), 6, (0, 0, 255), facing))
            shootloop = 1
    if keys[pygame.K_LEFT] and man.x > man.vel and not(man_movement_block):
        man.x -= man.vel
        man.left = True
        man.right = False
        man.standing = False
    elif keys[pygame.K_RIGHT] and man.x < 620 - man.vel - man.width:
        man.x += man.vel
        man.right = True
        man.left = False
        man.standing = False
    elif keys[pygame.K_b] and shield_count == 0:
        if shield_colour == "blue":
            shield_colour = "red"
            shield_number = 1
        else:
            shield_colour = "blue"
            shield_number = 0
        shield_count = 1
    if not (man.isjump):
        if keys[pygame.K_UP]:
            man.isjump = True
            man.walkcount = 0

    else:
        if man.jumpcount >= -10:
            neg = 1
            if man.jumpcount < 0:
                neg = -1
            man.y -= (man.jumpcount ** 2) / 2 * neg
            man.jumpcount -= 1
        else:
            man.isjump = False
            man.jumpcount = 10

    bad_guy1.walk(win)
    bad_guy2.walk(win)
    bad_guy3.walk(win)

    redraw_game_window()

pygame.quit()

Body:
The problem is caused by the code in the walk method of the enemy class, where you check for collisions between enemy bullets and the player.

if man.left:
    ... # block bullets with the shield when the player is pointing left
elif man.right:
    ... # block bullets with the shield when the player is pointing right
elif int(shield_number) != int(test_number):
    ... # if the player has been hit, call man.hit

Because you have used an elif, the code that checks if the player has been hit (and calls man.hit) will only be executed if both man.left and man.right are false, which never happens. Just changing it from an elif to an if should solve your problem.

if man.left:
    ... # block bullets with the shield when the player is pointing left
elif man.right:
    ... # block bullets with the shield when the player is pointing right

if int(shield_number) != int(test_number):
    ... # if the player has been hit, call man.hit


问:
How to get the value of an object ID stored in a variable - in python
I have a schoolID variable that is an Object. This is what prints out to the console when I print it:

```<code>school._id
Out[60]:
0    5ca588639d83cb7261b73231
Name: _id, dtype: object
</code>```

However, in order for my function to work, I need it to be a string. So at the moment I am having to create another variable and type in the string value myself. Below is my function currently:

```<code>fun = '5ca588639d83cb7261b73231'
update_this = Example.query.filter_by(_id=fun).first()
</code>```

I want to be able to to use the schoolID variable in the function like this:

```<code>update_this = Example.query.filter_by(_id=schoolID).first()
</code>```

I have tried converting the object to a string using the str function, but that creates the whole object as a string, rather than just the ID number that I need, see below:

```<code>str(school._id)
Out[59]: '0    5ca588639d83cb7261b73231\nName: _id, dtype: object'
</code>```

Does anyone know how I can get just the '5ca588639d83cb7261b73231' part of the object saved into a variable so I can use it in my function?

答: school._id is a series, hence your problem. You can quickly fix by school._id.iloc[0] if you are sure the required id is the first one in the series. Consider keeping school._id as a str instead of pd.Series.

Body:
I have a schoolID variable that is an Object. This is what prints out to the console when I print it:

school._id
Out[60]:
0    5ca588639d83cb7261b73231
Name: _id, dtype: object

However, in order for my function to work, I need it to be a string. So at the moment I am having to create another variable and type in the string value myself. Below is my function currently:

fun = '5ca588639d83cb7261b73231'
update_this = Example.query.filter_by(_id=fun).first()

I want to be able to to use the schoolID variable in the function like this:

update_this = Example.query.filter_by(_id=schoolID).first()

I have tried converting the object to a string using the str function, but that creates the whole object as a string, rather than just the ID number that I need, see below:

str(school._id)
Out[59]: '0    5ca588639d83cb7261b73231\nName: _id, dtype: object'

Does anyone know how I can get just the '5ca588639d83cb7261b73231' part of the object saved into a variable so I can use it in my function?


问:
URLField appending to 'http://127.0.0.1:8000/'
I have a ULRField that I'm trying to link using href but when I click it I am takn to something like http://127.0.0.1:8000/www.example.com rather than www.example.com

models.py

```<code>class Website(models.Model):
    website = models.URLField(max_length=100)
</code>```

template.html

```<code><a href="{{ dealer.website }}">{{ dealer.website }}</p>
</code>```

答:
Moving my comment to an answer:

Save the value with the https:// protocol.

Body:
I have a ULRField that I'm trying to link using href but when I click it I am takn to something like http://127.0.0.1:8000/www.example.com rather than www.example.com

models.py

class Website(models.Model):
    website = models.URLField(max_length=100)

template.html

{{ dealer.website }}


问:
Merging a list of numpy arrays into one array (fast)
what would be the fastest way to merge a list of numpy arrays into one array if one knows the length of the list and the size of the arrays, which is the same for all?

I tried two approaches:

merged_array = array(list_of_arrays) from Pythonic way to create a numpy array from a list of numpy arrays and

vstack

A you can see vstack is faster, but for some reason the first run takes three times longer than the second. I assume this caused by (missing) preallocation. So how would I preallocate an array for vstack? Or do you know a faster methode?

Thanks!

[UPDATE]

I want (25280, 320) not (80, 320, 320) which means, merged_array = array(list_of_arrays) wont work for me. Thanks Joris for pointing that out!!!

Output:

```<code>0.547468900681 s merged_array = array(first_list_of_arrays)
0.547191858292 s merged_array = array(second_list_of_arrays)
0.656183958054 s vstack first
0.236850976944 s vstack second
</code>```

Code:

```<code>import numpy
import time
width = 320
height = 320
n_matrices=80

secondmatrices = list()
for i in range(n_matrices):
    temp = numpy.random.rand(height, width).astype(numpy.float32)
    secondmatrices.append(numpy.round(temp*9))

firstmatrices = list()
for i in range(n_matrices):
    temp = numpy.random.rand(height, width).astype(numpy.float32)
    firstmatrices.append(numpy.round(temp*9))

t1 = time.time()
first1=numpy.array(firstmatrices)
print time.time() - t1, "s merged_array = array(first_list_of_arrays)"

t1 = time.time()
second1=numpy.array(secondmatrices)
print time.time() - t1, "s merged_array = array(second_list_of_arrays)"

t1 = time.time()
first2 = firstmatrices.pop()
for i in range(len(firstmatrices)):
    first2 = numpy.vstack((firstmatrices.pop(),first2))
print time.time() - t1, "s vstack first"

t1 = time.time()
second2 = secondmatrices.pop()
for i in range(len(secondmatrices)):
    second2 = numpy.vstack((secondmatrices.pop(),second2))

print time.time() - t1, "s vstack second"
</code>```

答:
You have 80 arrays 320x320? So you probably want to use dstack:

```<code>first3 = numpy.dstack(firstmatrices)
</code>```

This returns one 80x320x320 array just like numpy.array(firstmatrices) does:

```<code>timeit numpy.dstack(firstmatrices)
10 loops, best of 3: 47.1 ms per loop

timeit numpy.array(firstmatrices)
1 loops, best of 3: 750 ms per loop
</code>```

If you want to use vstack, it will return a 25600x320 array:

```<code>timeit numpy.vstack(firstmatrices)
100 loops, best of 3: 18.2 ms per loop
</code>```

ContentLicense: CC BY-SA 3.0

Body:
what would be the fastest way to merge a list of numpy arrays into one array if one knows the length of the list and the size of the arrays, which is the same for all?

I tried two approaches:

merged_array = array(list_of_arrays) from Pythonic way to create a numpy array from a list of numpy arrays and

vstack

A you can see vstack is faster, but for some reason the first run takes three times longer than the second. I assume this caused by (missing) preallocation. So how would I preallocate an array for vstack? Or do you know a faster methode?

Thanks!

[UPDATE]

I want (25280, 320) not (80, 320, 320) which means, merged_array = array(list_of_arrays) wont work for me. Thanks Joris for pointing that out!!!

Output:

0.547468900681 s merged_array = array(first_list_of_arrays)
0.547191858292 s merged_array = array(second_list_of_arrays)
0.656183958054 s vstack first
0.236850976944 s vstack second

Code:

import numpy
import time
width = 320
height = 320
n_matrices=80

secondmatrices = list()
for i in range(n_matrices):
    temp = numpy.random.rand(height, width).astype(numpy.float32)
    secondmatrices.append(numpy.round(temp*9))

firstmatrices = list()
for i in range(n_matrices):
    temp = numpy.random.rand(height, width).astype(numpy.float32)
    firstmatrices.append(numpy.round(temp*9))

t1 = time.time()
first1=numpy.array(firstmatrices)
print time.time() - t1, "s merged_array = array(first_list_of_arrays)"

t1 = time.time()
second1=numpy.array(secondmatrices)
print time.time() - t1, "s merged_array = array(second_list_of_arrays)"

t1 = time.time()
first2 = firstmatrices.pop()
for i in range(len(firstmatrices)):
    first2 = numpy.vstack((firstmatrices.pop(),first2))
print time.time() - t1, "s vstack first"

t1 = time.time()
second2 = secondmatrices.pop()
for i in range(len(secondmatrices)):
    second2 = numpy.vstack((secondmatrices.pop(),second2))

print time.time() - t1, "s vstack second"

Body:
You have 80 arrays 320x320? So you probably want to use dstack:

first3 = numpy.dstack(firstmatrices)

This returns one 80x320x320 array just like numpy.array(firstmatrices) does:

timeit numpy.dstack(firstmatrices)
10 loops, best of 3: 47.1 ms per loop

timeit numpy.array(firstmatrices)
1 loops, best of 3: 750 ms per loop

If you want to use vstack, it will return a 25600x320 array:

timeit numpy.vstack(firstmatrices)
100 loops, best of 3: 18.2 ms per loop


问:
Is it possible to add a postgresql trigger to notify my Django app when a table changes?
My Django app connects to a PostgreSQL 9.x database. To this database, a legacy Java app is connected, too. So two different apps use the same database.

Is it possible for PostgreSQL to notify my Django (2.2.x) app when a table changes? I know that I can create a cron job to check on tables on a timely basis, but the Server administrator does not let me do cron jobs (why?) and the Java guy is too busy on other things to do code rewiring (so I can't ask him him to send me url requests after table changes).

Or any other idea would be much appreciated. Thanks.

EDIT: After some google-search I found this tool: pgsql-http but the database admin won't install it.

答:
You can use triggers to NOTIFY when INSERTs, UPDATEs, or DELETEs occur. But something needs to LISTEN to the notices, on a persistent connection.  I don't know how easy it is arrange for that to happen under Django.

I know that I can create a cron job to check on tables on a timely basis, but the Server administrator does not let me do cron jobs

You can run cron on any other box on the network you have access to, and have it use curl or wget to hit an endpoint on Django on production, which then does whatever it is you want done.


问:
How to detect if my COM object is being used from a .NET application?
I have a COM DLL written in Visual C++. I fully control that COM DLL code. Of course it can be consumed from both managed and unmanaged applications. I want to insert a very specific check that should only be run when the COM DLL is consumed by a .NET application.

Is there some programmatic way for my COM object to detect whether it is being consumed from a .NET application or from an unmanaged application?

答:
Two possibilities:

Create a native .NET assembly wrapping the COM object and initializing it appropriately

Try to detect whether your process is a .NET process and live with the problems (no mono detection, false positives, most likely invalid detection when used in the context of DCOM/COM+)


问:
Firebase + Proguard/R8
I am currently working on setting up Firebase (FCM) in my project and have encountered a problem when I run my R8-obfuscated app, the Firebase service (FirebaseMessagingService) no longer works. Has anyone encountered the same problem? Any solution?

UPD: Finally I fixed it for FCM by downgrading to

```<code>com.google.firebase:firebase-messaging:15.0.0
</code>```

There are some deprecated classes in use now but it works.

UPD2:
While running obfuscated app with the newest versions of libraries I also noticed warnings in the logs:

```<code>W/FA: Failed to retrieve Firebase Instance Id
</code>```

This is most likely the root of the problem.

答:
Finally got it fixed, next proguard rules did a trick for me:</p>

```<code># Firebase
-keep class com.google.android.gms.** { *; }
-keep class com.google.firebase.** { *; } // especially this one
</code>```

Title: Firebase + Proguard/R8

Body:
I am currently working on setting up Firebase (FCM) in my project and have encountered a problem when I run my R8-obfuscated app, the Firebase service (FirebaseMessagingService) no longer works. Has anyone encountered the same problem? Any solution?

UPD: Finally I fixed it for FCM by downgrading to

com.google.firebase:firebase-messaging:15.0.0

There are some deprecated classes in use now but it works.

UPD2:
While running obfuscated app with the newest versions of libraries I also noticed warnings in the logs:

W/FA: Failed to retrieve Firebase Instance Id

This is most likely the root of the problem.

Body:
Finally got it fixed, next proguard rules did a trick for me:

# Firebase
-keep class com.google.android.gms.** { *; }
-keep class com.google.firebase.** { *; } // especially this one


问:
Insert result in DB using laravel
I new in laravel framework, I want to pass the result of the calculation from water.blade.php TO controller because I want to insert this result on database

water.blade.php

PageController.php

答:
But wich way you want to pass this result?

If you want with post, you can make a form, and a submit button.

in the view..

```<code><form action="{{route('myRouteToPost')}}">
<!-- Insert your code here -->
</form>
</code>```

In the routes/web.php you must define this route:

```<code>Route::post('nameOftheController@methodOfTheController')->name('myRouteToPost')
</code>```

And when someone submit the form, the method of the controller you has specificated will recive on $request.

Title: Insert result in DB using laravel

Body:
But wich way you want to pass this result?

If you want with post, you can make a form, and a submit button.

in the view..

<form action="{{route('myRouteToPost')}}">
<!-- Insert your code here -->
</form>

In the routes/web.php you must define this route:

Route::post('nameOftheController@methodOfTheController')->name('myRouteToPost')

And when someone submit the form, the method of the controller you has specificated will recive on $request.


问:
How can I find the actual Clang version on Mac?
Note: None of the answers provided at Get Apple clang version and corresponding upstream LLVM version seems to work anymore.

The download page at http://releases.llvm.org/download.html and the Wikipedia article at https://en.wikipedia.org/wiki/Clang seems to indicate that the most recent Clang version is 6.0.0.

But on my macOS High Sierra version 10.13.3, I see this output:

```<code>$ clang --version
Apple LLVM version 9.1.0 (clang-902.0.39.1)
Target: x86_64-apple-darwin17.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
$ which clang
/usr/bin/clang
</code>```

This does not seem right. Why is the Apple's version of Clang greater than the current version of Clang?

How do I find out which version of Clang hosted on http://releases.llvm.org/download.html does my Mac's version of Clang correspond to?

I ask this because I see http://releases.llvm.org/6.0.0/tools/clang/docs/UsersManual.html documenting a -pedantic option for the clang command line, but it is not documented in the man page of clang on my system.

```<code>$ man clang | grep pedantic
$ clang --help | grep pedantic
$
</code>```

答:
This wikipedia table maps Xcode and Apple clang versions to LLVM versions.
Your clang-902.0.39.1 appears to be based on LLVM 5.0.2.</p>

Body:
Note: None of the answers provided at Get Apple clang version and corresponding upstream LLVM version seems to work anymore.

The download page at http://releases.llvm.org/download.html and the Wikipedia article at https://en.wikipedia.org/wiki/Clang seems to indicate that the most recent Clang version is 6.0.0.

But on my macOS High Sierra version 10.13.3, I see this output:

$ clang --version
Apple LLVM version 9.1.0 (clang-902.0.39.1)
Target: x86_64-apple-darwin17.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
$ which clang
/usr/bin/clang

This does not seem right. Why is the Apple's version of Clang greater than the current version of Clang?

How do I find out which version of Clang hosted on http://releases.llvm.org/download.html does my Mac's version of Clang correspond to?

I ask this because I see http://releases.llvm.org/6.0.0/tools/clang/docs/UsersManual.html documenting a -pedantic option for the clang command line, but it is not documented in the man page of clang on my system.

$ man clang | grep pedantic
$ clang --help | grep pedantic
$


问:
How to put $ symbol in HCONF config file?
I am using the slick of alpakka to config the database. I want to configure the slick config in runtime, for example:

For slick.jdbc.PostgresProfile$ section, how to put "$" in the config?

```<code>

s"""
       |config {
       |  profile = "slick.jdbc.PostgresProfile$"
       |  db {
       |    dataSourceClass = "slick.jdbc.DriverDataSource"
       |    properties = {
       |      driver = "org.postgresql.Driver"
       |      url = "${dbUrl}"
       |      user = "${dbUser}"
       |      password = "${dbPassword}"
       |    }
       |  }
       |}
       |
     """.stripMargin

</code>```

```<code>
</code>```

答:
Try</p>

```<code>profile = "slick.jdbc.PostgresProfile$$"

</code>```

Body:
I am using the slick of alpakka to config the database. I want to configure the slick config in runtime, for example:

For slick.jdbc.PostgresProfile$ section, how to put "$" in the config?

s"""
       |config {
       |  profile = "slick.jdbc.PostgresProfile$"
       |  db {
       |    dataSourceClass = "slick.jdbc.DriverDataSource"
       |    properties = {
       |      driver = "org.postgresql.Driver"
       |      url = "${dbUrl}"
       |      user = "${dbUser}"
       |      password = "${dbPassword}"
       |    }
       |  }
       |}
       |
     """.stripMargin

Body:
Try

profile = "slick.jdbc.PostgresProfile$$"


问:
How to read comma separated data set using scanf_s - C Programming
I don't have a working code I can share right now, but basically what I am trying to achieve is to read a user input or from a file in the following format:

```<code>1,2
2,5
3,4
4,5
etc...
</code>```

or

1,3 4,5 6,7 8,6 ...
So a comma separated pair of real numbers and I would need to assign them to an array or 2d array and calculate their means, median, mode etc...

I tried scanf_s("%d,",&n) and stuff like that but none of them have worked out so far. I am really new to C and came from Java so everything been very confusing. If any tips or just an example would be greatly appreciated. I know you can also use fgets, gets or sscanf, however I have not learned those yet.

This was a code sent by another user:(but i don't really understand it, because it gave me src could be 0 error)

```<code>#include <stdio.h>
#include <stdlib.h>
int main( void )
{
  char *src = (char*)malloc(sizeof(char) * 500);
  fgets(src, 500, stdin);
  int arr[500];
  int index = 0;
  int n;

  while ( sscanf ( src, "%d,%n", &arr[index], &n ) == 1 ) {
    printf("%d\n", arr[index]);
    index++;
    src += n;
  }
  return 0;
}
</code>```

答:
Use

```<code>scanf_s("%d,%d", &n1, &n2);
</code>```

to read both numbers on each line at once. You can't use %d, for the second number, because there's no comma after it.

scanf() returns the number of inputs that were processed. Since you're reading two numbers at once, you should check that it returns 2, not 1.

```<code>int n1, n2;
while (scanf("%d , %d", &n1, &n2) == 2 ) {
    printf("first number = %d, second number = %d\n", n1, n2);
}
</code>```

Body:
I don't have a working code I can share right now, but basically what I am trying to achieve is to read a user input or from a file in the following format:

1,2
2,5
3,4
4,5
etc...

or

1,3 4,5 6,7 8,6 ...
So a comma separated pair of real numbers and I would need to assign them to an array or 2d array and calculate their means, median, mode etc...

I tried scanf_s("%d,",&n) and stuff like that but none of them have worked out so far. I am really new to C and came from Java so everything been very confusing. If any tips or just an example would be greatly appreciated. I know you can also use fgets, gets or sscanf, however I have not learned those yet.

This was a code sent by another user:(but i don't really understand it, because it gave me src could be 0 error)

#include <stdio.h>
#include <stdlib.h>
int main( void )
{
  char *src = (char*)malloc(sizeof(char) * 500);
  fgets(src, 500, stdin);
  int arr[500];
  int index = 0;
  int n;

  while ( sscanf ( src, "%d,%n", &arr[index], &n ) == 1 ) {
    printf("%d\n", arr[index]);
    index++;
    src += n;
  }
  return 0;
}

Body:
Use

scanf_s("%d,%d", &n1, &n2);

to read both numbers on each line at once. You can't use %d, for the second number, because there's no comma after it.

scanf() returns the number of inputs that were processed. Since you're reading two numbers at once, you should check that it returns 2, not 1.

int n1, n2;
while (scanf("%d , %d", &n1, &n2) == 2 ) {
    printf("first number = %d, second number = %d\n", n1, n2);
}


问:
flex 4 mobile problem with ViewNavigatorApplication states and firstView
I'm having a crack at making my first Flex mobile application (although I'm not new to Flex), and I've tripped at the first hurdle.

I cannot get ViewNavigatorApplication to display a view when trying to use firstView with states e.g. firstView.phone, firstView.tablet.

I'm just left with a blank action bar and content area.

If I try setting setting firstView with no state (e.g. firstView="view.HomeView") the view loads fine.

Here's the code:

```<code><s:ViewNavigatorApplication
    xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    firstView.phone="views.HomeView"
    firstView.tablet="views.TabletHomeView"
    applicationDPI="160"
    creationComplete="initApplication()">
    <s:states>
        <s:State name="portraitPhone" stateGroups="portrait, phone"/>
        <s:State name="landscapePhone" stateGroups="landscape, phone"/>
        <s:State name="portraitTablet" stateGroups="portrait, tablet"/>
        <s:State name="landscapeTablet" stateGroups="landscape, tablet"/>
    </s:states>
    <fx:Style source="assets/css/application.css"/>
    <fx:Script>
        <![CDATA[
            import mx.events.ResizeEvent;

            private var isPortrait:Boolean;
            private var isTablet:Boolean;

            private function initApplication():void
            {
                addEventListener(ResizeEvent.RESIZE, resizeHandler);
                addEventListener(Event.ADDED_TO_STAGE, resizeHandler);
            }

            private function resizeHandler(event:*):void
            {
                isPortrait = (stage.height > stage.width);
                isTablet = (stage.height > 950 || stage.width > 950);

                currentState = (isPortrait ? "portrait" : "landscape") + (isTablet ? "Tablet" : "Phone");
            }
        ]]>
    </fx:Script>
</s:ViewNavigatorApplication>
</code>```

I've googled this to death, read though the ViewNavigatorApplication specification and not found anyone else with this problem or any evidence that I'm simply doing it wrong (although i still suspect that is the case).

Thanks in advance!

答:
Why would you want to have states in your view navigator if the views themselves are states?  I fairly sure it's not meant to be used that way and that it isn't possible to 'load' a new view through first view.  Just set the firstView and after it loads and switch the views accordingly.

If you want to do something that 'resizes', I would add the resizing code to each view or have a separate application for each form factor to give a better experience while reusing your code (this is my preferred method).

Body:
I'm having a crack at making my first Flex mobile application (although I'm not new to Flex), and I've tripped at the first hurdle.

I cannot get ViewNavigatorApplication to display a view when trying to use firstView with states e.g. firstView.phone, firstView.tablet.

I'm just left with a blank action bar and content area.

If I try setting setting firstView with no state (e.g. firstView="view.HomeView") the view loads fine.

Here's the code:

<s:ViewNavigatorApplication
    xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    firstView.phone="views.HomeView"
    firstView.tablet="views.TabletHomeView"
    applicationDPI="160"
    creationComplete="initApplication()">
    <s:states>
        <s:State name="portraitPhone" stateGroups="portrait, phone"/>
        <s:State name="landscapePhone" stateGroups="landscape, phone"/>
        <s:State name="portraitTablet" stateGroups="portrait, tablet"/>
        <s:State name="landscapeTablet" stateGroups="landscape, tablet"/>
    </s:states>
    <fx:Style source="assets/css/application.css"/>
    <fx:Script>
        <![CDATA[
            import mx.events.ResizeEvent;

            private var isPortrait:Boolean;
            private var isTablet:Boolean;

            private function initApplication():void
            {
                addEventListener(ResizeEvent.RESIZE, resizeHandler);
                addEventListener(Event.ADDED_TO_STAGE, resizeHandler);
            }

            private function resizeHandler(event:*):void
            {
                isPortrait = (stage.height > stage.width);
                isTablet = (stage.height > 950 || stage.width > 950);

                currentState = (isPortrait ? "portrait" : "landscape") + (isTablet ? "Tablet" : "Phone");
            }
        ]]>
    </fx:Script>
</s:ViewNavigatorApplication>

I've googled this to death, read though the ViewNavigatorApplication specification and not found anyone else with this problem or any evidence that I'm simply doing it wrong (although i still suspect that is the case).

Thanks in advance!


问:
Reliably capture the output of an external command
I need to call lots of short-lived (and occasionally some long-lived) external processes in rapid succession and process both stdout and stderr in realtime. I've found numerous solutions for this using StdoutPipe and StderrPipe with a bufio.Scanner for each, packaged into goroutines. This works most of the time, but it swallows the external command's output occasionally, and I can't figure out why.

Here's a minimal example displaying that behaviour on MacOS X (Mojave) and on Linux:

package main

import (
    "bufio"
    "log"
    "os/exec"
    "sync"
)

func main() {
    for i := 0; i < 50000; i++ {
        log.Println("Loop")

        var wg sync.WaitGroup

        cmd := exec.Command("echo", "1")
        stdout, err := cmd.StdoutPipe()
        if err != nil {
            panic(err)
        }

        cmd.Start()

        stdoutScanner := bufio.NewScanner(stdout)
        stdoutScanner.Split(bufio.ScanLines)

        wg.Add(1)
        go func() {
            for stdoutScanner.Scan() {
                line := stdoutScanner.Text()
                log.Printf("[stdout] %s\n", line)
            }
            wg.Done()
        }()

        cmd.Wait()
        wg.Wait()
    }
}
```

I've left out the stderr handling for this. When running this, I get only about 49,900 [stdout] 1 lines (the actual number varies with each run), though there should be 50,000. I'm seeing 50,000 loop lines, so it doesn't seem to die prematurely. This smells like a race condition somewhere, but I can't figure out where.

It works just fine if I don't put the scanning loop in a goroutine, but then I lose the ability to simultaneously read stderr, which I need.

I've tried running this with -race, Go reports no data races.

I'm out of ideas, what am I getting wrong?

答:
You're not checking for errors in several places.

In some, this is not actually causing problems, but it's still a good idea to check:

```<code>cmd.Start()
</code>```

may return an error, in which case the command was never run.  (This is not the actual problem.)

When stdoutScanner.Scan() returns false, stdoutScanner.Err() may show an error.  If you start checking this, you'll find some errors:

```<code>2020/02/19 15:38:17 [stdout err] read |0: file already closed
</code>```

This isn't the actual problem, but—aha—this matches the symptoms you see: not all of the output got seen.  Now, why would reading stdout claim that the file is closed?  Well, where did stdout come from?  It's from here:

```<code>stdout, err := cmd.StdoutPipe()
</code>```

Take a look at the source code for this function, which ends with these lines:

```<code>c.closeAfterStart = append(c.closeAfterStart, pw)
c.closeAfterWait = append(c.closeAfterWait, pr)
return pr, nil
</code>```

(and pr is the pipe-read return value).  Hmm: what could closeAfterWait mean?

Now, here are your last two lines in your loop:

```<code>cmd.Wait()
wg.Wait()
</code>```

That is, first we wait for cmd to finish.  (When cmd finishes, what gets closed?)  Then we wait for the goroutine that's reading cmd's stdout to finish.  (Hm, what could still be reading from the pr pipe?)

The fix is now obvious: swap the wg.Wait(), which waits for the consumer of the stdout pipe to finish reading it, with the cmd.Wait(), which waits for echo ... to exit and then closes the read end of the pipe.  If you close while the readers are still reading, they may never read what you expected.

Body:
I need to call lots of short-lived (and occasionally some long-lived) external processes in rapid succession and process both stdout and stderr in realtime. I've found numerous solutions for this using StdoutPipe and StderrPipe with a bufio.Scanner for each, packaged into goroutines. This works most of the time, but it swallows the external command's output occasionally, and I can't figure out why.

Here's a minimal example displaying that behaviour on MacOS X (Mojave) and on Linux:

package main

import (
    "bufio"
    "log"
    "os/exec"
    "sync"
)

func main() {
    for i := 0; i < 50000; i++ {
        log.Println("Loop")

        var wg sync.WaitGroup

        cmd := exec.Command("echo", "1")
        stdout, err := cmd.StdoutPipe()
        if err != nil {
            panic(err)
        }

        cmd.Start()

        stdoutScanner := bufio.NewScanner(stdout)
        stdoutScanner.Split(bufio.ScanLines)

        wg.Add(1)
        go func() {
            for stdoutScanner.Scan() {
                line := stdoutScanner.Text()
                log.Printf("[stdout] %s\n", line)
            }
            wg.Done()
        }()

        cmd.Wait()
        wg.Wait()
    }
}

I've left out the stderr handling for this. When running this, I get only about 49,900 [stdout] 1 lines (the actual number varies with each run), though there should be 50,000. I'm seeing 50,000 loop lines, so it doesn't seem to die prematurely. This smells like a race condition somewhere, but I can't figure out where.

It works just fine if I don't put the scanning loop in a goroutine, but then I lose the ability to simultaneously read stderr, which I need.

I've tried running this with -race, Go reports no data races.

I'm out of ideas, what am I getting wrong?

Body:
You're not checking for errors in several places.

In some, this is not actually causing problems, but it's still a good idea to check:

cmd.Start()

may return an error, in which case the command was never run.  (This is not the actual problem.)

When stdoutScanner.Scan() returns false, stdoutScanner.Err() may show an error.  If you start checking this, you'll find some errors:

2020/02/19 15:38:17 [stdout err] read |0: file already closed

This isn't the actual problem, but—aha—this matches the symptoms you see: not all of the output got seen.  Now, why would reading stdout claim that the file is closed?  Well, where did stdout come from?  It's from here:

stdout, err := cmd.StdoutPipe()

Take a look at the source code for this function, which ends with these lines:

c.closeAfterStart = append(c.closeAfterStart, pw)
c.closeAfterWait = append(c.closeAfterWait, pr)
return pr, nil

(and pr is the pipe-read return value).  Hmm: what could closeAfterWait mean?

Now, here are your last two lines in your loop:

cmd.Wait()
wg.Wait()

That is, first we wait for cmd to finish.  (When cmd finishes, what gets closed?)  Then we wait for the goroutine that's reading cmd's stdout to finish.  (Hm, what could still be reading from the pr pipe?)

The fix is now obvious: swap the wg.Wait(), which waits for the consumer of the stdout pipe to finish reading it, with the cmd.Wait(), which waits for echo ... to exit and then closes the read end of the pipe.  If you close while the readers are still reading, they may never read what you expected.


问:
Iterate table and return count of pairs on lists in Python
Having a column of people and a column of say locations of those people, where their locations are ordered by time, e.g.:

```<code>People=["A", "A", "B", "B", "B", "C", "C", "C"]
Location=["GA", "IL", "GA", "IL", "GA", "CA", "IL", "GA"]
</code>```

How would you program an iteration that returns this:

Change_of_location=["GA-IL","IL-GA","CA-IL] and count=[2, 2, 1], since the pair "GA-IL" appears twice etc. That is, the iteration should return the trips taken (change of location) based on rows of the people's locations.

答:
I threw some simple code together that seems to do this in Python 3.6.

```<code>#PYTHON 3.6

# Input arrays
people = ["A", "A", "B", "B", "B", "C", "C", "C"]
location = ["GA", "IL", "GA", "IL", "GA", "CA", "IL", "GA"]

# Output arrays
Change_of_location = []
count = []

# Other variables
temp = []           # Temporary array for storing sorted values
lastPerson = ''     # String for storing last person in array
cnt = 0             # Counter for cycling through array

# Cycle through the records of people
for i in people:
    # Check if the current person is the same as the last
    if lastPerson == people[cnt]:
        # Save the locations travelled by this person
        temp.append(location[cnt-1] + '-' + location[cnt])
    # Update the last person and increment the counter
    lastPerson = people[cnt]
    cnt+=1

# Sort the temporary array
temp.sort()

# Create a counter variable for cycling through the temporary array,
#  a variable for counting the number of trips, and a string to store
#  the last trip
cnt2 = 0
cntTrip = 1
lastTrip = ''

# Cycle through the temporary array
for i in temp:
    # check if the current trip is the same as the last
    if lastTrip == temp[cnt2]:
        # increment the counter
        cntTrip+=1
    # else, check if the last trip string is empty (first iter)
    elif lastTrip != temp[cnt2] and lastTrip != '':
        # append trip to array
        Change_of_location.append(lastTrip)
        # append trip count to array
        count.append(cntTrip)
        # reset the trip counter to 1
        cntTrip = 1
    # set the last trip to the current trip
    lastTrip = temp[cnt2]
    # increment the counter
    cnt2+=1

# Append the last values from the temporary array
Change_of_location.append(lastTrip)
count.append(cntTrip)

# Print the results
print(Change_of_location)
print(count)
</code>```

There's definitely a more efficient way to do this; but this works and doesn't rely on any imports.

Output is Change_of_location = ['CA-IL','GA-IL','IL-GA'] and count = [1,2,2]

Body:
Having a column of people and a column of say locations of those people, where their locations are ordered by time, e.g.:

People=["A", "A", "B", "B", "B", "C", "C", "C"]
Location=["GA", "IL", "GA", "IL", "GA", "CA", "IL", "GA"]

How would you program an iteration that returns this:

Change_of_location=["GA-IL","IL-GA","CA-IL] and count=[2, 2, 1], since the pair "GA-IL" appears twice etc. That is, the iteration should return the trips taken (change of location) based on rows of the people's locations.

Body:
I threw some simple code together that seems to do this in Python 3.6.

#PYTHON 3.6

# Input arrays
people = ["A", "A", "B", "B", "B", "C", "C", "C"]
location = ["GA", "IL", "GA", "IL", "GA", "CA", "IL", "GA"]

# Output arrays
Change_of_location = []
count = []

# Other variables
temp = []           # Temporary array for storing sorted values
lastPerson = ''     # String for storing last person in array
cnt = 0             # Counter for cycling through array

# Cycle through the records of people
for i in people:
    # Check if the current person is the same as the last
    if lastPerson == people[cnt]:
        # Save the locations travelled by this person
        temp.append(location[cnt-1] + '-' + location[cnt])
    # Update the last person and increment the counter
    lastPerson = people[cnt]
    cnt+=1

# Sort the temporary array
temp.sort()

# Create a counter variable for cycling through the temporary array,
#  a variable for counting the number of trips, and a string to store
#  the last trip
cnt2 = 0
cntTrip = 1
lastTrip = ''

# Cycle through the temporary array
for i in temp:
    # check if the current trip is the same as the last
    if lastTrip == temp[cnt2]:
        # increment the counter
        cntTrip+=1
    # else, check if the last trip string is empty (first iter)
    elif lastTrip != temp[cnt2] and lastTrip != '':
        # append trip to array
        Change_of_location.append(lastTrip)
        # append trip count to array
        count.append(cntTrip)
        # reset the trip counter to 1
        cntTrip = 1
    # set the last trip to the current trip
    lastTrip = temp[cnt2]
    # increment the counter
    cnt2+=1

# Append the last values from the temporary array
Change_of_location.append(lastTrip)
count.append(cntTrip)

# Print the results
print(Change_of_location)
print(count)

There's definitely a more efficient way to do this; but this works and doesn't rely on any imports.

Output is Change_of_location = ['CA-IL','GA-IL','IL-GA'] and count = [1,2,2]


问:
How do I get a list of all models in Laravel?
I would like to find a list of all models, database tables as a backup, in a Laravel project.

I want to do this to build a dashboard that displays the way data in all of the models has changed over time, I.E. if there is a user model, how many users have been added or modified each day for the last 90 days.

答:
I would like to suggest a different approach by using PHP reflection instead of relying that all models will reside in a namespace or directory called Model.

The code sample below collects all the application classes, verifies if they actually extend the Eloquent Model class and are not abstract.

<?php

use Illuminate\Container\Container;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\File;

function getModels(): Collection
{
    $models = collect(File::allFiles(app_path()))
        ->map(function ($item) {
            $path = $item->getRelativePathName();
            $class = sprintf('\%s%s',
                Container::getInstance()->getNamespace(),
                strtr(substr($path, 0, strrpos($path, '.')), '/', '\\'));

            return $class;
        })
        ->filter(function ($class) {
            $valid = false;

            if (class_exists($class)) {
                $reflection = new \ReflectionClass($class);
                $valid = $reflection->isSubclassOf(Model::class) &&
                    !$reflection->isAbstract();
            }

            return $valid;
        });

    return $models->values();
}
```


问:
Serialization and Deserialization in Flutter
I have tried storing classes on files in java.
Something like shown in this link

To my knowledge java converts the class into a byte steam and stores it.

I am relatively new to flutter and don't know much about dart, I've searched a lot but not able to find how to do the same in flutter.

I was able to find only JSON serialization for flutter, would like to know how to serialize my class to a byte stream and save to file and then retrieve deserialized class back.

P.S.: I think java serialization stores data in other format than JSON, if it's not the case and if java does store it in JSON format then I am sorry for the inconvenience caused by me.

Thank you.

答:
Dart doesn't have a built in serialization mechanism the way Java does. This means you have to choose some approach for serialization.

This doc covers some options using pure JSON serializations that may meet your needs.

If you are already using the built_value package, classes which implement Built can be serialized easily with a little extra boilerplate. The readme covers this and links to some articles and tutorials with more guidance.


问:
Quicksight: Aggregation Over Last Day of Month
I am working on a chart bar that the x-axis is a date aggregated by month. ¿Is is posible to aggregate by day but only show the last day of each month using a filter o by other way? Other possibility i see is to create a calculated field to show the value for the last day of the aggregated period but i have not been able to do it ¿Is it posible?</p>

答:
I'm not exactly sure what you are trying to do to provide the best guidance.

If I had to write an expression to calculate last day of the month, I would

Use truncDate function to extract month and year information from the date

Add 1 to the month, unless it is December

Get first day of the month (which always has 1 as the day)

Use addDateTime to subtract one day

For example, given a date 02/19/20 (in the format MM/DD/YYYY).
02 is the month number
20 is the year number
The following month is 03
Beginning of that month is 03/01/20
Last day of the previous month will be 02/29/20 which I will get by subtracting a day from March 1st.


问:
Timber.io + Django + Heroku | How to only display application logs
I have a Django application running on Heroku with a drain sending logs to my Timber.io source.

Currently, my Timber.io logs display:

The logs that I wrote in my app to display (All I want)

app logs

heroku logs

Here is a link to what a section of my Timber.io logs look like. Notice how there are app web.1 and heroku router logs.

I don't want any other logs other than the ones I write in my Django application.

Django code:

```<code>logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
timber_handler = timber.TimberHandler(
    source_id=config('TIMBER_SOURCE_ID'),
    api_key=config('TIMBER_API_KEY'),
    level=logging.DEBUG
)
logger.addHandler(timber_handler)

...

logger.warning('A user has navigated to the homepage') # To reiterate, logs like this are all I want to display in my Timber.io logs.
</code>```

I have sent a few emails posing this question to Timber.io's support email. But, after a week, I haven't received a response.

This is my first question so I apologize if I did something incorrectly. Thanks in advance for responses.

答:
What about defining a custom debug logger

my_logger.py

```<code>import logging
logger = logging.getLogger("my_logger")
logger.setLevel(logging.INFO)
timber_handler = timber.TimberHandler(
    source_id=config('TIMBER_SOURCE_ID'),
    api_key=config('TIMBER_API_KEY'),
    level=logging.DEBUG
)
logger.addHandler(timber_handler)
</code>```

Views.py:

```<code>from my_logger import logger as debug_logger

debug_logger.warning('A user has navigated to the homepage')
</code>```

Edit:

Looking at their documentation, you can filter on the Timber Side as well.

In your shell issue the following curl command:

Replace YOUR_API_KEY with your actual API key.

Replace YOUR_ORGANIZATION_ID with your Timber organization ID.

Replace FILTER_NAME with the name of your filter (ex: "Drop health check    logs")

Replace MATCH with the sub-string that your logs must contain    to qualify dropping.

Replace SOURCE_ID with the ID of the relevant source. Add as many as you like.

```<code>  curl https://api.timber.io/log_filters \
  -s \
  -X POST \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '
    {
      "organization_id": "YOUR_ORGANIZATION_ID",
      "name":"FILTER_NAME",
      "match":"MATCH",
      "source_ids": ["SOURCE_ID"]
    }
  ' \
  | jq
</code>```

Body:
I have a Django application running on Heroku with a drain sending logs to my Timber.io source.

Currently, my Timber.io logs display:

The logs that I wrote in my app to display (All I want)

app logs

heroku logs

Here is a link to what a section of my Timber.io logs look like. Notice how there are app web.1 and heroku router logs.

I don't want any other logs other than the ones I write in my Django application.

Django code:

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
timber_handler = timber.TimberHandler(
    source_id=config('TIMBER_SOURCE_ID'),
    api_key=config('TIMBER_API_KEY'),
    level=logging.DEBUG
)
logger.addHandler(timber_handler)

...

logger.warning('A user has navigated to the homepage') # To reiterate, logs like this are all I want to display in my Timber.io logs.

I have sent a few emails posing this question to Timber.io's support email. But, after a week, I haven't received a response.

This is my first question so I apologize if I did something incorrectly. Thanks in advance for responses.

Body:
What about defining a custom debug logger

my_logger.py

import logging
logger = logging.getLogger("my_logger")
logger.setLevel(logging.INFO)
timber_handler = timber.TimberHandler(
    source_id=config('TIMBER_SOURCE_ID'),
    api_key=config('TIMBER_API_KEY'),
    level=logging.DEBUG
)
logger.addHandler(timber_handler)

Views.py:

from my_logger import logger as debug_logger

debug_logger.warning('A user has navigated to the homepage')

Edit:

Looking at their documentation, you can filter on the Timber Side as well.

In your shell issue the following curl command:

Replace YOUR_API_KEY with your actual API key.

Replace YOUR_ORGANIZATION_ID with your Timber organization ID.

Replace FILTER_NAME with the name of your filter (ex: "Drop health check    logs")

Replace MATCH with the sub-string that your logs must contain    to qualify dropping.

Replace SOURCE_ID with the ID of the relevant source. Add as many as you like.

  curl https://api.timber.io/log_filters \
  -s \
  -X POST \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '
    {
      "organization_id": "YOUR_ORGANIZATION_ID",
      "name":"FILTER_NAME",
      "match":"MATCH",
      "source_ids": ["SOURCE_ID"]
    }
  ' \
  | jq


问:
Where does this DOM element get its styling from?
I have this website where there is a green band displayed at the very top.
Below an abstract from the html code:

```<code><div id="wrapper">
    <!-- start header -->
<header>
    <div class="site-top"> !this makes the green band at the top!
        <div class="container">
          <div>
            <div class="pull-right">
              <strong>
                <a href="http://localhost/dimi_test/admin">  ! this element is displayed as green text!
                 <i class="fa fa-cog"></i> Dashboard
                </a>
              </strong>
            </div>
          ...
</code>```

My problem is that the background of the
 is green and the font colour of the  element is the same green, making it invisible.
I tried to find out in which style sheet the  element is defined, so I opened google devtools. This is the result:

screenshot Google devtools

It seems the element is defined in .(index):36, in the style sheets that are in the screenshot, the font colour is stricken through. So I do not understand where the DOM element  gets its styling from.

Hope my question is more clear now.

答:
I believe what you are describing is happening because there is internal/embedded CSS within the HTML on that particular page in the  section.

```<code><head>
  <style type="text/css">
    1 ...
    2 ...
    ...
    36 a...{
         color: #72c02c;
       }
  </style>
</head>
</code>```

You will need to remove or modify that to prevent it from overriding your external stylesheet (style.css).

Body:
I have this website where there is a green band displayed at the very top.
Below an abstract from the html code:

 !this makes the green band at the top!

                  ! this element is displayed as green text!
                  Dashboard

          ...

My problem is that the background of the
 is green and the font colour of the  element is the same green, making it invisible.
I tried to find out in which style sheet the  element is defined, so I opened google devtools. This is the result:

screenshot Google devtools

It seems the element is defined in .(index):36, in the style sheets that are in the screenshot, the font colour is stricken through. So I do not understand where the DOM element  gets its styling from.

Hope my question is more clear now.

Body:
I believe what you are describing is happening because there is internal/embedded CSS within the HTML on that particular page in the <head> section.

<head>
  <style type="text/css">
    1 ...
    2 ...
    ...
    36 a...{
         color: #72c02c;
       }
  </style>
</head>

You will need to remove or modify that to prevent it from overriding your external stylesheet (style.css).