问:
Swift: Gesture Recognizer doesn't register Taps after changing alpha to 0 and back to 1
the UIView in question is headerView:

```<code>    if isShown {
        stack.alpha = 1.0
        self.isStackShown = true
        DispatchQueue.main.async {
            self.headerView.isHidden = !isShown
            self.stack.addArrangedSubview(self.headerView)

            // add touch gesture recognizer to stack view header
            let tapFind = UIGestureRecognizer(target: self, action: #selector(self.handleFindTap))
            self.headerView.addGestureRecognizer(tapFind)
        }
    } else {
        stack.alpha = 0.0
        self.isStackShown = false
        DispatchQueue.main.async {
            self.headerView.isHidden = isShown
            self.stack.removeArrangedSubview(self.headerView)
        }
    }
</code>```

The tap gesture recognizer is not registering any taps

self.stack is the stack view which contains the headerView

The condition for either showing or hiding the headerView is being handled in a different method and just passes the boolean self.isStackShown to this method to show/hide accordingly.

答:
You are using a UIGestureRecognizer. UIGestureRecognizer is a polymorphic base class and should really be subclassed. UITapGestureRecognizer is the concrete subclass for handling taps. Use it instead.

```<code>let tapFind = UITapGestureRecognizer(target: self, action: #selector(self.handleFindTap))
self.headerView.addGestureRecognizer(tapFind)
</code>```

Your action is never getting called because UIGestureRecognizer has no inherent information about what kind of gesture to recognize. Only a concrete subclass of it does.

Body:
the UIView in question is headerView:

    if isShown {
        stack.alpha = 1.0
        self.isStackShown = true
        DispatchQueue.main.async {
            self.headerView.isHidden = !isShown
            self.stack.addArrangedSubview(self.headerView)

            // add touch gesture recognizer to stack view header
            let tapFind = UIGestureRecognizer(target: self, action: #selector(self.handleFindTap))
            self.headerView.addGestureRecognizer(tapFind)
        }
    } else {
        stack.alpha = 0.0
        self.isStackShown = false
        DispatchQueue.main.async {
            self.headerView.isHidden = isShown
            self.stack.removeArrangedSubview(self.headerView)
        }
    }

The tap gesture recognizer is not registering any taps

self.stack is the stack view which contains the headerView

The condition for either showing or hiding the headerView is being handled in a different method and just passes the boolean self.isStackShown to this method to show/hide accordingly.

Body:
You are using a UIGestureRecognizer. UIGestureRecognizer is a polymorphic base class and should really be subclassed. UITapGestureRecognizer is the concrete subclass for handling taps. Use it instead.

let tapFind = UITapGestureRecognizer(target: self, action: #selector(self.handleFindTap))
self.headerView.addGestureRecognizer(tapFind)

Your action is never getting called because UIGestureRecognizer has no inherent information about what kind of gesture to recognize. Only a concrete subclass of it does.


来源: stackexchange

问:
Pygame button single click
I made buttons in pygame for click events, but there is a problem. When I click the mouse button and move the mouse between the button boundaries, the click event is repeating itself.
I just want a single click until I release the mouse button.
How can I do that?</p>

```<code>import pygame,time
pygame.init()
x,y = (200,300)
pencere = pygame.display.set_mode((x,y))
pygame.display.set_caption("Click")

white = (255,255,255)
black = (0,0,0)
black2 = (30,30,30)

class Counter:
    count = 0
    def click(self):
        self.count += 1

number = Counter()
def text_objects(text, font, color):
    textSurface = font.render(text, True, color)
    return textSurface, textSurface.get_rect()

def button(msg,x,y,w,h,c,ic,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    pygame.draw.rect(pencere, c,(x,y,w,h))

    smallText = pygame.font.Font("freesansbold.ttf",20)
    textSurf, textRect = text_objects(msg, smallText, white)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    pencere.blit(textSurf, textRect)

    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(pencere, ic,(x,y,w,h))
        if click[0] == 1 != None:
            action()
        smallText = pygame.font.Font("freesansbold.ttf",20)
        textSurf, textRect = text_objects(msg, smallText, white)
        textRect.center = ( (x+(w/2)), (y+(h/2)) )
        pencere.blit(textSurf, textRect)
def loop():
    cikis = False
    while not cikis:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                cikis = True
                pygame.quit()
                quit()
            pencere.fill(white)
            smallText = pygame.font.Font("freesansbold.ttf",50)
            textSurf, textRect = text_objects(str(number.count), smallText, black)
            textRect.center = ((x/2)), (30)
            pencere.blit(textSurf, textRect)
            button("Click",0,100,200,200,black,black2,number.click)
            pygame.display.update()
loop()
pygame.quit()
quit()
</code>```

答:
There are several things that should be changed:

The drawing and button code shouldn't be in the event loop but in the outer while loop. You're calling the button function every time an event occurs (for example if the mouse moves).

The button function is doing too much. It creates and blits text surfaces, draws rects, checks for collisions and calls the click method.

You shouldn't use pygame.mouse.get_pressed() and instead handle the MOUSEBUTTONDOWN events in the event loop. mouse.get_pressed just checks if a mouse button is held and not if a single click occurred.

I'll just show you an easy solution without a function and with a rect as the button here. I handle the collision and update the number in the event loop. If you want to create several buttons, I'd suggest to rewrite it in an object-oriented manner (I can show you an example if you want).

```<code>import pygame

pygame.init()
width, height = (200,300)
screen = pygame.display.set_mode((width, height))

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (30, 30, 30)
FONT = pygame.font.Font("freesansbold.ttf", 50)

def loop():
    clock = pygame.time.Clock()
    number = 0
    # The button is just a rect.
    button = pygame.Rect(0, 100, 200, 200)
    done = False
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            # This block is executed once for each MOUSEBUTTONDOWN event.
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # 1 is the left mouse button, 2 is middle, 3 is right.
                if event.button == 1:
                    # `event.pos` is the mouse position.
                    if button.collidepoint(event.pos):
                        # Increment the number.
                        number += 1

        screen.fill(WHITE)
        pygame.draw.rect(screen, GRAY, button)
        text_surf = FONT.render(str(number), True, BLACK)
        # You can pass the center directly to the `get_rect` method.
        text_rect = text_surf.get_rect(center=(width/2, 30))
        screen.blit(text_surf, text_rect)
        pygame.display.update()

        clock.tick(30)

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

Addendum: I recommend using a object-oriented solution with a Button class that is a subclass of pygame.sprite.Sprite and can be added to sprite groups. You can pass your own images to the Button class or use the default images. You also have to pass a callback function or method to each button instance which will get called in the handle_event method to update the specific attributes of the game class (here I have a method that increments a counter and another one to quit the game).

```<code>import pygame as pg

pg.init()
screen = pg.display.set_mode((800, 600))
FONT = pg.font.SysFont('Comic Sans MS', 32)
# Default button images/pygame.Surfaces.
IMAGE_NORMAL = pg.Surface((100, 32))
IMAGE_NORMAL.fill(pg.Color('dodgerblue1'))
IMAGE_HOVER = pg.Surface((100, 32))
IMAGE_HOVER.fill(pg.Color('lightskyblue'))
IMAGE_DOWN = pg.Surface((100, 32))
IMAGE_DOWN.fill(pg.Color('aquamarine1'))

# Button is a sprite subclass, that means it can be added to a sprite group.
# You can draw and update all sprites in a group by
# calling `group.update()` and `group.draw(screen)`.
class Button(pg.sprite.Sprite):

    def __init__(self, x, y, width, height, callback,
                 font=FONT, text='', text_color=(0, 0, 0),
                 image_normal=IMAGE_NORMAL, image_hover=IMAGE_HOVER,
                 image_down=IMAGE_DOWN):
        super().__init__()
        # Scale the images to the desired size (doesn't modify the originals).
        self.image_normal = pg.transform.scale(image_normal, (width, height))
        self.image_hover = pg.transform.scale(image_hover, (width, height))
        self.image_down = pg.transform.scale(image_down, (width, height))

        self.image = self.image_normal  # The currently active image.
        self.rect = self.image.get_rect(topleft=(x, y))
        # To center the text rect.
        image_center = self.image.get_rect().center
        text_surf = font.render(text, True, text_color)
        text_rect = text_surf.get_rect(center=image_center)
        # Blit the text onto the images.
        for image in (self.image_normal, self.image_hover, self.image_down):
            image.blit(text_surf, text_rect)

        # This function will be called when the button gets pressed.
        self.callback = callback
        self.button_down = False

    def handle_event(self, event):
        if event.type == pg.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                self.image = self.image_down
                self.button_down = True
        elif event.type == pg.MOUSEBUTTONUP:
            # If the rect collides with the mouse pos.
            if self.rect.collidepoint(event.pos) and self.button_down:
                self.callback()  # Call the function.
                self.image = self.image_hover
            self.button_down = False
        elif event.type == pg.MOUSEMOTION:
            collided = self.rect.collidepoint(event.pos)
            if collided and not self.button_down:
                self.image = self.image_hover
            elif not collided:
                self.image = self.image_normal

class Game:

    def __init__(self, screen):
        self.done = False
        self.clock = pg.time.Clock()
        self.screen = screen
        # Contains all sprites. Also put the button sprites into a
        # separate group in your own game.
        self.all_sprites = pg.sprite.Group()
        self.number = 0
        # Create the button instances. You can pass your own images here.
        self.start_button = Button(
            320, 70, 170, 65, self.increment_number,
            FONT, 'Increment', (255, 255, 255),
            IMAGE_NORMAL, IMAGE_HOVER, IMAGE_DOWN)
        # If you don't pass images, the default images will be used.
        self.quit_button = Button(
            320, 240, 170, 65, self.quit_game,
            FONT, 'Quit', (255, 255, 255))
        # Add the button sprites to the sprite group.
        self.all_sprites.add(self.start_button, self.quit_button)

    def quit_game(self):
        """Callback method to quit the game."""
        self.done = True

    def increment_number(self):
        """Callback method to increment the number."""
        self.number += 1
        print(self.number)

    def run(self):
        while not self.done:
            self.dt = self.clock.tick(30) / 1000
            self.handle_events()
            self.run_logic()
            self.draw()

    def handle_events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True
            for button in self.all_sprites:
                button.handle_event(event)

    def run_logic(self):
        self.all_sprites.update(self.dt)

    def draw(self):
        self.screen.fill((30, 30, 30))
        self.all_sprites.draw(self.screen)
        pg.display.flip()

if __name__ == '__main__':
    pg.init()
    Game(screen).run()
    pg.quit()
</code>```

Addendum 2: A intermediate solution with buttons as dictionaries. It would also be possible to use lists, but dictionaries are more readable.

```<code>import pygame

pygame.init()

WHITE = (255, 255, 255)
ACTIVE_COLOR = pygame.Color('dodgerblue1')
INACTIVE_COLOR = pygame.Color('dodgerblue4')
FONT = pygame.font.Font(None, 50)

def draw_button(button, screen):
    """Draw the button rect and the text surface."""
    pygame.draw.rect(screen, button['color'], button['rect'])
    screen.blit(button['text'], button['text rect'])

def create_button(x, y, w, h, text, callback):
    """A button is a dictionary that contains the relevant data.

    Consists of a rect, text surface and text rect, color and a
    callback function.
    """
    # The button is a dictionary consisting of the rect, text,
    # text rect, color and the callback function.
    text_surf = FONT.render(text, True, WHITE)
    button_rect = pygame.Rect(x, y, w, h)
    text_rect = text_surf.get_rect(center=button_rect.center)
    button = {
        'rect': button_rect,
        'text': text_surf,
        'text rect': text_rect,
        'color': INACTIVE_COLOR,
        'callback': callback,
        }
    return button

def main():
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    done = False

    number = 0

    def increment_number():  # A callback function for the button.
        """Increment the `number` in the enclosing scope."""
        nonlocal number
        number += 1
        print(number)

    def quit_game():  # A callback function for the button.
        nonlocal done
        done = True

    button1 = create_button(100, 100, 250, 80, 'Click me!', increment_number)
    button2 = create_button(100, 200, 250, 80, 'Me too!', quit_game)
    # A list that contains all buttons.
    button_list = [button1, button2]

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            # This block is executed once for each MOUSEBUTTONDOWN event.
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # 1 is the left mouse button, 2 is middle, 3 is right.
                if event.button == 1:
                    for button in button_list:
                        # `event.pos` is the mouse position.
                        if button['rect'].collidepoint(event.pos):
                            # Increment the number by calling the callback
                            # function in the button list.
                            button['callback']()
            elif event.type == pygame.MOUSEMOTION:
                # When the mouse gets moved, change the color of the
                # buttons if they collide with the mouse.
                for button in button_list:
                    if button['rect'].collidepoint(event.pos):
                        button['color'] = ACTIVE_COLOR
                    else:
                        button['color'] = INACTIVE_COLOR

        screen.fill(WHITE)
        for button in button_list:
            draw_button(button, screen)
        pygame.display.update()
        clock.tick(30)

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

ContentLicense: CC BY-SA 4.0

Title: Pygame button single click

Body:
I made buttons in pygame for click events, but there is a problem. When I click the mouse button and move the mouse between the button boundaries, the click event is repeating itself.
I just want a single click until I release the mouse button.
How can I do that?

import pygame,time
pygame.init()
x,y = (200,300)
pencere = pygame.display.set_mode((x,y))
pygame.display.set_caption("Click")

white = (255,255,255)
black = (0,0,0)
black2 = (30,30,30)

class Counter:
    count = 0
    def click(self):
        self.count += 1

number = Counter()
def text_objects(text, font, color):
    textSurface = font.render(text, True, color)
    return textSurface, textSurface.get_rect()

def button(msg,x,y,w,h,c,ic,action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    pygame.draw.rect(pencere, c,(x,y,w,h))

    smallText = pygame.font.Font("freesansbold.ttf",20)
    textSurf, textRect = text_objects(msg, smallText, white)
    textRect.center = ( (x+(w/2)), (y+(h/2)) )
    pencere.blit(textSurf, textRect)

    if x+w > mouse[0] > x and y+h > mouse[1] > y:
        pygame.draw.rect(pencere, ic,(x,y,w,h))
        if click[0] == 1 != None:
            action()
        smallText = pygame.font.Font("freesansbold.ttf",20)
        textSurf, textRect = text_objects(msg, smallText, white)
        textRect.center = ( (x+(w/2)), (y+(h/2)) )
        pencere.blit(textSurf, textRect)
def loop():
    cikis = False
    while not cikis:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                cikis = True
                pygame.quit()
                quit()
            pencere.fill(white)
            smallText = pygame.font.Font("freesansbold.ttf",50)
            textSurf, textRect = text_objects(str(number.count), smallText, black)
            textRect.center = ((x/2)), (30)
            pencere.blit(textSurf, textRect)
            button("Click",0,100,200,200,black,black2,number.click)
            pygame.display.update()
loop()
pygame.quit()
quit()

Body:
There are several things that should be changed:

The drawing and button code shouldn't be in the event loop but in the outer while loop. You're calling the button function every time an event occurs (for example if the mouse moves).

The button function is doing too much. It creates and blits text surfaces, draws rects, checks for collisions and calls the click method.

You shouldn't use pygame.mouse.get_pressed() and instead handle the MOUSEBUTTONDOWN events in the event loop. mouse.get_pressed just checks if a mouse button is held and not if a single click occurred.

I'll just show you an easy solution without a function and with a rect as the button here. I handle the collision and update the number in the event loop. If you want to create several buttons, I'd suggest to rewrite it in an object-oriented manner (I can show you an example if you want).

import pygame

pygame.init()
width, height = (200,300)
screen = pygame.display.set_mode((width, height))

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (30, 30, 30)
FONT = pygame.font.Font("freesansbold.ttf", 50)

def loop():
    clock = pygame.time.Clock()
    number = 0
    # The button is just a rect.
    button = pygame.Rect(0, 100, 200, 200)
    done = False
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            # This block is executed once for each MOUSEBUTTONDOWN event.
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # 1 is the left mouse button, 2 is middle, 3 is right.
                if event.button == 1:
                    # `event.pos` is the mouse position.
                    if button.collidepoint(event.pos):
                        # Increment the number.
                        number += 1

        screen.fill(WHITE)
        pygame.draw.rect(screen, GRAY, button)
        text_surf = FONT.render(str(number), True, BLACK)
        # You can pass the center directly to the `get_rect` method.
        text_rect = text_surf.get_rect(center=(width/2, 30))
        screen.blit(text_surf, text_rect)
        pygame.display.update()

        clock.tick(30)

loop()
pygame.quit()

Addendum: I recommend using a object-oriented solution with a Button class that is a subclass of pygame.sprite.Sprite and can be added to sprite groups. You can pass your own images to the Button class or use the default images. You also have to pass a callback function or method to each button instance which will get called in the handle_event method to update the specific attributes of the game class (here I have a method that increments a counter and another one to quit the game).

import pygame as pg

pg.init()
screen = pg.display.set_mode((800, 600))
FONT = pg.font.SysFont('Comic Sans MS', 32)
# Default button images/pygame.Surfaces.
IMAGE_NORMAL = pg.Surface((100, 32))
IMAGE_NORMAL.fill(pg.Color('dodgerblue1'))
IMAGE_HOVER = pg.Surface((100, 32))
IMAGE_HOVER.fill(pg.Color('lightskyblue'))
IMAGE_DOWN = pg.Surface((100, 32))
IMAGE_DOWN.fill(pg.Color('aquamarine1'))

# Button is a sprite subclass, that means it can be added to a sprite group.
# You can draw and update all sprites in a group by
# calling `group.update()` and `group.draw(screen)`.
class Button(pg.sprite.Sprite):

    def __init__(self, x, y, width, height, callback,
                 font=FONT, text='', text_color=(0, 0, 0),
                 image_normal=IMAGE_NORMAL, image_hover=IMAGE_HOVER,
                 image_down=IMAGE_DOWN):
        super().__init__()
        # Scale the images to the desired size (doesn't modify the originals).
        self.image_normal = pg.transform.scale(image_normal, (width, height))
        self.image_hover = pg.transform.scale(image_hover, (width, height))
        self.image_down = pg.transform.scale(image_down, (width, height))

        self.image = self.image_normal  # The currently active image.
        self.rect = self.image.get_rect(topleft=(x, y))
        # To center the text rect.
        image_center = self.image.get_rect().center
        text_surf = font.render(text, True, text_color)
        text_rect = text_surf.get_rect(center=image_center)
        # Blit the text onto the images.
        for image in (self.image_normal, self.image_hover, self.image_down):
            image.blit(text_surf, text_rect)

        # This function will be called when the button gets pressed.
        self.callback = callback
        self.button_down = False

    def handle_event(self, event):
        if event.type == pg.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                self.image = self.image_down
                self.button_down = True
        elif event.type == pg.MOUSEBUTTONUP:
            # If the rect collides with the mouse pos.
            if self.rect.collidepoint(event.pos) and self.button_down:
                self.callback()  # Call the function.
                self.image = self.image_hover
            self.button_down = False
        elif event.type == pg.MOUSEMOTION:
            collided = self.rect.collidepoint(event.pos)
            if collided and not self.button_down:
                self.image = self.image_hover
            elif not collided:
                self.image = self.image_normal

class Game:

    def __init__(self, screen):
        self.done = False
        self.clock = pg.time.Clock()
        self.screen = screen
        # Contains all sprites. Also put the button sprites into a
        # separate group in your own game.
        self.all_sprites = pg.sprite.Group()
        self.number = 0
        # Create the button instances. You can pass your own images here.
        self.start_button = Button(
            320, 70, 170, 65, self.increment_number,
            FONT, 'Increment', (255, 255, 255),
            IMAGE_NORMAL, IMAGE_HOVER, IMAGE_DOWN)
        # If you don't pass images, the default images will be used.
        self.quit_button = Button(
            320, 240, 170, 65, self.quit_game,
            FONT, 'Quit', (255, 255, 255))
        # Add the button sprites to the sprite group.
        self.all_sprites.add(self.start_button, self.quit_button)

    def quit_game(self):
        """Callback method to quit the game."""
        self.done = True

    def increment_number(self):
        """Callback method to increment the number."""
        self.number += 1
        print(self.number)

    def run(self):
        while not self.done:
            self.dt = self.clock.tick(30) / 1000
            self.handle_events()
            self.run_logic()
            self.draw()

    def handle_events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True
            for button in self.all_sprites:
                button.handle_event(event)

    def run_logic(self):
        self.all_sprites.update(self.dt)

    def draw(self):
        self.screen.fill((30, 30, 30))
        self.all_sprites.draw(self.screen)
        pg.display.flip()

if __name__ == '__main__':
    pg.init()
    Game(screen).run()
    pg.quit()

Addendum 2: A intermediate solution with buttons as dictionaries. It would also be possible to use lists, but dictionaries are more readable.

import pygame

pygame.init()

WHITE = (255, 255, 255)
ACTIVE_COLOR = pygame.Color('dodgerblue1')
INACTIVE_COLOR = pygame.Color('dodgerblue4')
FONT = pygame.font.Font(None, 50)

def draw_button(button, screen):
    """Draw the button rect and the text surface."""
    pygame.draw.rect(screen, button['color'], button['rect'])
    screen.blit(button['text'], button['text rect'])

def create_button(x, y, w, h, text, callback):
    """A button is a dictionary that contains the relevant data.

    Consists of a rect, text surface and text rect, color and a
    callback function.
    """
    # The button is a dictionary consisting of the rect, text,
    # text rect, color and the callback function.
    text_surf = FONT.render(text, True, WHITE)
    button_rect = pygame.Rect(x, y, w, h)
    text_rect = text_surf.get_rect(center=button_rect.center)
    button = {
        'rect': button_rect,
        'text': text_surf,
        'text rect': text_rect,
        'color': INACTIVE_COLOR,
        'callback': callback,
        }
    return button

def main():
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    done = False

    number = 0

    def increment_number():  # A callback function for the button.
        """Increment the `number` in the enclosing scope."""
        nonlocal number
        number += 1
        print(number)

    def quit_game():  # A callback function for the button.
        nonlocal done
        done = True

    button1 = create_button(100, 100, 250, 80, 'Click me!', increment_number)
    button2 = create_button(100, 200, 250, 80, 'Me too!', quit_game)
    # A list that contains all buttons.
    button_list = [button1, button2]

    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            # This block is executed once for each MOUSEBUTTONDOWN event.
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # 1 is the left mouse button, 2 is middle, 3 is right.
                if event.button == 1:
                    for button in button_list:
                        # `event.pos` is the mouse position.
                        if button['rect'].collidepoint(event.pos):
                            # Increment the number by calling the callback
                            # function in the button list.
                            button['callback']()
            elif event.type == pygame.MOUSEMOTION:
                # When the mouse gets moved, change the color of the
                # buttons if they collide with the mouse.
                for button in button_list:
                    if button['rect'].collidepoint(event.pos):
                        button['color'] = ACTIVE_COLOR
                    else:
                        button['color'] = INACTIVE_COLOR

        screen.fill(WHITE)
        for button in button_list:
            draw_button(button, screen)
        pygame.display.update()
        clock.tick(30)

main()
pygame.quit()

ContentLicense: CC BY-SA 3.0


问:
Comparing tuple values from text file in Python 3
I'm aiming to display records of employees with a salary between 2 user inputted values (in a format specified in my function printTuple(data)). So far I use the function choice2() to open the file, read line by line in a for loop, convert the line (which is a string) to an int, then grab the index of the salary so I can compare it to the 2 inputted values (. After that I take the line as a variable in "record" and go to makeTuple to turn it into a tuple, and then finally print it in my desired format inside printTuple.

When I attempt to run the choice2 function I get an error: "local variable 'myTuple' referenced before assignment". However I need to change the myTuple value to an int before I can compare it with the values the user inputted, so I'm not sure how to fix this.

Here is my program:

```<code>def makeTuple (employee):

    myTuple = employee.split(" ")
    (payroll, salary, job_title, *othernames, surname) = myTuple
    return(myTuple)

def printTuple (data):

    employee_str = "{:<15} {:20} {:<10} {:<15} £{:>1}"
    print(employee_str.format(data[-1]+ ",", " ".join(data[3:-1]), data[0], data[2], data[1]))

def choice1():

    op_1 = str(input("Please enter a Pay Roll number: "))
    file = open(path)
    lines = file.readlines()
    for line in lines:
        if op_1 in line:
            record = line.strip()
    myTuple = makeTuple(record)
    printTuple(myTuple)

def choice2():

    op_2a = int(input("Please enter a lower bound for the Salary :"))
    op_2b = int(input("Please enter a higher bound for the Salary :"))

    file = open(path)
    lines = file.readlines()
    for line in lines:
        myTuple[0] = int(myTuple[0])
        if myTuple[0] >= op_2a and myTuple[0] <= op_2b:
            myTuple[0] = myTuple[0]
            record = line.strip()
    myTuple = makeTuple(record)
    print(myTuple)

get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"

try:
    f = open(path)
except IOError:
    print('The file could not be opened.')
    exit()

for line in iter(f):
    record = line.strip()
    myTuple = makeTuple(record)
    printTuple(myTuple)

print("\n\nDisplay full details of an Employee with a given payroll number     enter:     '1'")
print("Display all employees with a salary within a specified range, enter:           '2'")
print("Display the first and last name of all employees with a job title,     enter:  '3'")
print("Quit Program:                                                              '4'")

choice = int(input("Choose an option from 1-4: "))

while choice != 1 and choice != 2 and choice != 3 and choice != 4:

    print("Incorrect Value, please choose a number from 1-4")
    print("\n\nDisplay full details of an Employee with a given payroll     number enter:     '1'")
    print("Display all employees with a salary within a specified range,     enter:       '2'")
    print("Display the first and last name of all employees with a job     title, enter:  '3'")
    print("Quit Program:                                                                  '4'")

    choice = int(input("Choose an option from 1-4: "))

if choice == 1:
choice1()
if choice == 2:
choice2()
if choice == 3:
choice3()
if choice == 4:
exit()
</code>```

This is the text file I am reading from:

```<code>12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger
12349 30000 Wizard Harry Potter
12350 15000 Entertainer Herschel Shmoikel Krustofski
13123 75000 Consultant Zlatan Ibrahimovic
13124 150000 Manager Gareth Southgate
13125 75000 Manager Juergen Klopp
13126 35000 Lecturer Mike T Sanderson
13127 200000 Entertainer Adele Laurie Blue Adkins
13128 50 Timelord Peter Capaldi
13129 250000 Entertainer Edward Christopher Sheeran
13130 32000 Secretary Wilma Flintstone
</code>```

Any help is appreciated, thanks in advance.

答:
Your error message (local variable myTuple referenced before assignment) points out the required solution. I have:

reordered (record = line.strip() and myTuple = makeTuple(record) to top of loop)

renamed some variables (myTuple is not very descriptive, and is actually a list anyway, better naming makes code much easier to read and reason about)

heavily commenting (I would not normally comment my own code this much, more as indications of what I have done and why)

Here is the updated code for choice2

```<code>def choice2():

    lower_bound = int(input("Please enter a lower bound for the Salary :"))  # Renamed for clarity
    upper_bound = int(input("Please enter a higher bound for the Salary :"))  # Renamed for clarity

    # The following two lines are repeated multiple times, you should probably read
    # the file once and store into a list (or better yet a dictionary
    # keyed with pay roll number) and pass it into the function.
    file = open(path)
    lines = file.readlines()

    for line in lines:
        record = line.strip()
        employee_details = makeTuple(record)  # Rename muTuple to employee_details
        # OR MORE SIMPLY employee_details = makeTuple(line.strip())

        # Now we have the variable we can work with it
        salary = int(employee_details[0])  # The only thing we do with the tuple is print it, so no need to modify it
        if salary >= lower_bound and salary <= upper_bound:
            # This does nothing, so deleted - myTuple[0] = myTuple[0]
            print(employee_details) # Or more likely you want to use your custom print function printTuple(employee_details)
</code>```

Body:
I'm aiming to display records of employees with a salary between 2 user inputted values (in a format specified in my function printTuple(data)). So far I use the function choice2() to open the file, read line by line in a for loop, convert the line (which is a string) to an int, then grab the index of the salary so I can compare it to the 2 inputted values (. After that I take the line as a variable in "record" and go to makeTuple to turn it into a tuple, and then finally print it in my desired format inside printTuple.

When I attempt to run the choice2 function I get an error: "local variable 'myTuple' referenced before assignment". However I need to change the myTuple value to an int before I can compare it with the values the user inputted, so I'm not sure how to fix this.

Here is my program:

def makeTuple (employee):

    myTuple = employee.split(" ")
    (payroll, salary, job_title, *othernames, surname) = myTuple
    return(myTuple)

def printTuple (data):

    employee_str = "{:<15} {:20} {:<10} {:<15} £{:>1}"
    print(employee_str.format(data[-1]+ ",", " ".join(data[3:-1]), data[0], data[2], data[1]))

def choice1():

    op_1 = str(input("Please enter a Pay Roll number: "))
    file = open(path)
    lines = file.readlines()
    for line in lines:
        if op_1 in line:
            record = line.strip()
    myTuple = makeTuple(record)
    printTuple(myTuple)

def choice2():

    op_2a = int(input("Please enter a lower bound for the Salary :"))
    op_2b = int(input("Please enter a higher bound for the Salary :"))

    file = open(path)
    lines = file.readlines()
    for line in lines:
        myTuple[0] = int(myTuple[0])
        if myTuple[0] >= op_2a and myTuple[0] <= op_2b:
            myTuple[0] = myTuple[0]
            record = line.strip()
    myTuple = makeTuple(record)
    print(myTuple)

get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"

try:
    f = open(path)
except IOError:
    print('The file could not be opened.')
    exit()

for line in iter(f):
    record = line.strip()
    myTuple = makeTuple(record)
    printTuple(myTuple)

print("\n\nDisplay full details of an Employee with a given payroll number     enter:     '1'")
print("Display all employees with a salary within a specified range, enter:           '2'")
print("Display the first and last name of all employees with a job title,     enter:  '3'")
print("Quit Program:                                                              '4'")

choice = int(input("Choose an option from 1-4: "))

while choice != 1 and choice != 2 and choice != 3 and choice != 4:

    print("Incorrect Value, please choose a number from 1-4")
    print("\n\nDisplay full details of an Employee with a given payroll     number enter:     '1'")
    print("Display all employees with a salary within a specified range,     enter:       '2'")
    print("Display the first and last name of all employees with a job     title, enter:  '3'")
    print("Quit Program:                                                                  '4'")

    choice = int(input("Choose an option from 1-4: "))

if choice == 1:
choice1()
if choice == 2:
choice2()
if choice == 3:
choice3()
if choice == 4:
exit()

This is the text file I am reading from:

12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger
12349 30000 Wizard Harry Potter
12350 15000 Entertainer Herschel Shmoikel Krustofski
13123 75000 Consultant Zlatan Ibrahimovic
13124 150000 Manager Gareth Southgate
13125 75000 Manager Juergen Klopp
13126 35000 Lecturer Mike T Sanderson
13127 200000 Entertainer Adele Laurie Blue Adkins
13128 50 Timelord Peter Capaldi
13129 250000 Entertainer Edward Christopher Sheeran
13130 32000 Secretary Wilma Flintstone

Any help is appreciated, thanks in advance.

Body:
Your error message (local variable myTuple referenced before assignment) points out the required solution. I have:

reordered (record = line.strip() and myTuple = makeTuple(record) to top of loop)

renamed some variables (myTuple is not very descriptive, and is actually a list anyway, better naming makes code much easier to read and reason about)

heavily commenting (I would not normally comment my own code this much, more as indications of what I have done and why)

Here is the updated code for choice2

def choice2():

    lower_bound = int(input("Please enter a lower bound for the Salary :"))  # Renamed for clarity
    upper_bound = int(input("Please enter a higher bound for the Salary :"))  # Renamed for clarity

    # The following two lines are repeated multiple times, you should probably read
    # the file once and store into a list (or better yet a dictionary
    # keyed with pay roll number) and pass it into the function.
    file = open(path)
    lines = file.readlines()

    for line in lines:
        record = line.strip()
        employee_details = makeTuple(record)  # Rename muTuple to employee_details
        # OR MORE SIMPLY employee_details = makeTuple(line.strip())

        # Now we have the variable we can work with it
        salary = int(employee_details[0])  # The only thing we do with the tuple is print it, so no need to modify it
        if salary >= lower_bound and salary <= upper_bound:
            # This does nothing, so deleted - myTuple[0] = myTuple[0]
            print(employee_details) # Or more likely you want to use your custom print function printTuple(employee_details)


问:
How to simplify the following expression in mathematica
I have the following:

```<code>(p^a q (-1 + q^b))/(-p^a q - q^b + p^a q^b + q^(1 + b))
</code>```

I want to do two things:

1) both the numberator and denominator factor out p and q so that they can cancel

2) force -1 + q^b to be shown as 1 - q^b

3) I also need to simplify the denominator one further step by merging -q^b+q^(1+b)=q^b(1-q) since 1-q->p

Would appreciate your help and suggestions.

答:
For the second one, you could do:

```<code>expr = (p^a q (-1 + q^b))/(-p^a q - q^b + p^a q^b + q^(1 + b)) //.
       {x__ (-1 + q ^b) -> -x (1 - q^ b)}
</code>```

Out:

```<code>-((p^a*q*(1 - q^b))/(-(p^a*q) - q^b + p^a*q^b + q^(1 + b)))
</code>```

As for the first one, I don't see any gain ...

HTH!

Edit

Answering your comment:

I'm still not sure what are you trying to achieve with the first tranformation, but here is a try:

```<code>Numerator@expr/q/Collect[Distribute[Denominator@expr/q], q^(b - 1)]

(p^a (1 - q^b))/(-p^a + (-1 + p^a) q^(-1 + b) + q^b)
</code>```

Anyway, I think a warning is a must here: Forcing Mathematica to show results in an "elegant" way can be very tricky for large expressions. I suggest trying to learn how to do it only after you master Mma quite a bit. Then, as a simple exercise to get started you may try several ways to force Mma to show

```<code>-1+a
</code>```

as

```<code> a-1
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following:

(p^a q (-1 + q^b))/(-p^a q - q^b + p^a q^b + q^(1 + b))

I want to do two things:

1) both the numberator and denominator factor out p and q so that they can cancel

2) force -1 + q^b to be shown as 1 - q^b

3) I also need to simplify the denominator one further step by merging -q^b+q^(1+b)=q^b(1-q) since 1-q->p

Would appreciate your help and suggestions.

Body:
For the second one, you could do:

expr = (p^a q (-1 + q^b))/(-p^a q - q^b + p^a q^b + q^(1 + b)) //.
       {x__ (-1 + q ^b) -> -x (1 - q^ b)}

Out:

-((p^a*q*(1 - q^b))/(-(p^a*q) - q^b + p^a*q^b + q^(1 + b)))

As for the first one, I don't see any gain ...

HTH!

Edit

Answering your comment:

I'm still not sure what are you trying to achieve with the first tranformation, but here is a try:

Numerator@expr/q/Collect[Distribute[Denominator@expr/q], q^(b - 1)]

(p^a (1 - q^b))/(-p^a + (-1 + p^a) q^(-1 + b) + q^b)

Anyway, I think a warning is a must here: Forcing Mathematica to show results in an "elegant" way can be very tricky for large expressions. I suggest trying to learn how to do it only after you master Mma quite a bit. Then, as a simple exercise to get started you may try several ways to force Mma to show

-1+a

as

 a-1


问:
issue using $.ajax with php effectively
I'm having trouble understanding what I'm missing or not doing here (obviously something), and maybe someone can help.

I have a database site that displays a table generated from a SQL database on the client side. When the table is initialized, this code is executed and pulls the data needed for the dropdown in question (comments added by me for this post):

```<code>$selectOwner = "SELECT DISTINCT [Contacts].[Alias], [Contacts].[Last Name], [Contacts].[ID] FROM [TechInv].[dbo].[Contacts]";

//this is the file that contains the above query variable
require('custom/Connection.php');

$owner_arr = array();

//$conn is our connection string
$response = sqlsrv_query($conn, $selectOwner);
while ($row = sqlsrv_fetch_array($response)){
    array_push($owner_arr, $row['Alias'] . " " . $row['Last Name']);
}
</code>```

This generates a list of name records pulled from the database in a Alias(first name) Last Name format.

Here's where I'm having trouble

Another function of the site is a menu that allows users of a certain priveledge level to add additional contacts to the table. Everything works fine with that except nowhere in the code is the above array updated when a contact is added, which forces the user to reload the page, ew.

I know i need to use $.ajax for this, so I took a stab at it, and put the following code into the click handler for the 'add contact' submit button:

```<code>$.ajax({
    type: 'POST',
    data: 'listRefresh();',
    url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
    success: function() {
        alert("this succeeded?");
    }
});
</code>```

The data: 'listRefresh();' line refers to a function I created that is the same as the first block of code, in an attempt to just refresh the variables with new data. That's obviously where I've gone wrong, (try not to laugh) but I am out of ideas here. Can anyone shed some light?

答:
Your ajax call is wrong. The 'data' value is what you send to the server.

Try this:

```<code>$.ajax({
    type: 'POST',
    url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
    success: function(data) {
        listRefresh(data);
        alert("this succeeded?");
    }
});
</code>```

The data variable is what the server gives you back, so you can pass that data to the listRefresh() function and re-render the upated list.

In alternative, you could just reload the page putting location.reload(); into success function

Title: issue using $.ajax with php effectively

Body:
I'm having trouble understanding what I'm missing or not doing here (obviously something), and maybe someone can help.

I have a database site that displays a table generated from a SQL database on the client side. When the table is initialized, this code is executed and pulls the data needed for the dropdown in question (comments added by me for this post):

$selectOwner = "SELECT DISTINCT [Contacts].[Alias], [Contacts].[Last Name], [Contacts].[ID] FROM [TechInv].[dbo].[Contacts]";

//this is the file that contains the above query variable
require('custom/Connection.php');

$owner_arr = array();

//$conn is our connection string
$response = sqlsrv_query($conn, $selectOwner);
while ($row = sqlsrv_fetch_array($response)){
    array_push($owner_arr, $row['Alias'] . " " . $row['Last Name']);
}

This generates a list of name records pulled from the database in a Alias(first name) Last Name format.

Here's where I'm having trouble

Another function of the site is a menu that allows users of a certain priveledge level to add additional contacts to the table. Everything works fine with that except nowhere in the code is the above array updated when a contact is added, which forces the user to reload the page, ew.

I know i need to use $.ajax for this, so I took a stab at it, and put the following code into the click handler for the 'add contact' submit button:

$.ajax({
    type: 'POST',
    data: 'listRefresh();',
    url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
    success: function() {
        alert("this succeeded?");
    }
});

The data: 'listRefresh();' line refers to a function I created that is the same as the first block of code, in an attempt to just refresh the variables with new data. That's obviously where I've gone wrong, (try not to laugh) but I am out of ideas here. Can anyone shed some light?

Body:
Your ajax call is wrong. The 'data' value is what you send to the server.

Try this:

$.ajax({
    type: 'POST',
    url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
    success: function(data) {
        listRefresh(data);
        alert("this succeeded?");
    }
});

The data variable is what the server gives you back, so you can pass that data to the listRefresh() function and re-render the upated list.

In alternative, you could just reload the page putting location.reload(); into success function


问:
Unknown column error in procedure with if statement
When I call this stored procedure it shows error: unknown column...

```<code>BEGIN
  if (
  `LastRow.Transaction`=4 and `LastRow.Xre`>1)
  then
  SELECT
  sleep(2);
END if;
end
</code>```

Please note that sleep(2) is just to demonstrate to do something if condition is true. What would be the proper way to accomplish a test based on value of a specific record? In the above example the table (actually a View) has only one row.

答:
Q: What would be the proper way to accomplish a test based on value of a specific record?

If you mean, based on values in columns stored in one row of a table... it seems like we would need a query that references the table that retrieve the values stored in the row. And then we can have those values available in the procedure.

As an example

```<code>BEGIN
   -- local procedure variables, specify appropriate datatypes
   DECLARE lr_transaction BIGINT DEFAULT NULL;
   DECLARE lr_xre         BIGINT DEFAULT NULL;

   -- retrieve values from columns into local procedure variables
   SELECT `LastRow`.`Transaction`
        , `LastRow`.`Xre`
     INTO lr_transaction
        , lr_xre
     FROM `LastRow`
    WHERE someconditions
    ORDER BY someexpressions
    LIMIT 1
   ;

   IF ( lr_transaction = 4 AND lr_xre > 1 ) THEN
      -- do something
   END IF;
END$$
</code>```

That's an example of how we can retrieve a row from a table, and do some check. We could also do the check with SQL and just return a boolean

```<code>BEGIN
   -- local procedure variables, specify appropriate datatypes
   DECLARE lb_check TINYINT(1) UNSIGNED DEFAULT 0;

   -- retrieve values from columns into local procedure variables
   SELECT IF(`LastRow`.`Transaction` = 4 AND `LastRow`.`Xre` > 1,1,0)
     INTO lb_check
     FROM `LastRow`
    WHERE someconditions
    ORDER BY someexpressions
    LIMIT 1
   ;

   IF ( lb_check ) THEN
      -- do something
   END IF;
END$$
</code>```

Body:
When I call this stored procedure it shows error: unknown column...

BEGIN
  if (
  `LastRow.Transaction`=4 and `LastRow.Xre`>1)
  then
  SELECT
  sleep(2);
END if;
end

Please note that sleep(2) is just to demonstrate to do something if condition is true. What would be the proper way to accomplish a test based on value of a specific record? In the above example the table (actually a View) has only one row.

Body:
Q: What would be the proper way to accomplish a test based on value of a specific record?

If you mean, based on values in columns stored in one row of a table... it seems like we would need a query that references the table that retrieve the values stored in the row. And then we can have those values available in the procedure.

As an example

BEGIN
   -- local procedure variables, specify appropriate datatypes
   DECLARE lr_transaction BIGINT DEFAULT NULL;
   DECLARE lr_xre         BIGINT DEFAULT NULL;

   -- retrieve values from columns into local procedure variables
   SELECT `LastRow`.`Transaction`
        , `LastRow`.`Xre`
     INTO lr_transaction
        , lr_xre
     FROM `LastRow`
    WHERE someconditions
    ORDER BY someexpressions
    LIMIT 1
   ;

   IF ( lr_transaction = 4 AND lr_xre > 1 ) THEN
      -- do something
   END IF;
END$$

That's an example of how we can retrieve a row from a table, and do some check. We could also do the check with SQL and just return a boolean

BEGIN
   -- local procedure variables, specify appropriate datatypes
   DECLARE lb_check TINYINT(1) UNSIGNED DEFAULT 0;

   -- retrieve values from columns into local procedure variables
   SELECT IF(`LastRow`.`Transaction` = 4 AND `LastRow`.`Xre` > 1,1,0)
     INTO lb_check
     FROM `LastRow`
    WHERE someconditions
    ORDER BY someexpressions
    LIMIT 1
   ;

   IF ( lb_check ) THEN
      -- do something
   END IF;
END$$


问:
How to access and print dictionary values that contain nested lists?
I'm learning Python and am a bit stuck with the concept of dictionaries and nested lists.

The lab I'm currently working on calls for us to create a dict with some keys having just a single list of values and other keys having two or more lists associated. The code below properly prints the list elements for the key that has multiple lists, but if I change the get statement to a key with a single list I just get the first two digits of the string.

```<code>my_dict = {1: ['test', 'values'],
           2: [['test2', 'value2'], ['test3', 'value3']],
           3: ['test4', 'value4']}

for item in my_dict.get(2):
   print('%s, %s' %(item[0], item[1]))
</code>```

Would someone explain how to access list values from the dictionary regardless of whether the key has a single list, or multiple lists?

Ultimately the output if key 1 or 3 is used would be

```<code>test, values  or test4, value4
</code>```

If key 2 is selected the output would be

```<code>test2, value2
test3, value3
</code>```

答:
I'm not exactly sure if this is what you mean but the code below prints out each text value:

```<code>my_dict= {1: ['test', 'values'],
      2: [['test2', 'value2'], ['test3', 'value3']],
      3: ['test4', 'value4']}

for key, value in my_dict.items():
    for x in value:
        if not isinstance(x, list):
            print(x)
        else:
            for y in x:
                print(y)

#output
test
values
test2
value2
test3
value3
test4
value4
</code>```

So loop through your dictionary and create a sub-loop through each element (x) of each value in your dictionary. If x is not itself a list, print x. If x is a list, then loop through x, printing each element (y) contained within x.

Body:
I'm learning Python and am a bit stuck with the concept of dictionaries and nested lists.

The lab I'm currently working on calls for us to create a dict with some keys having just a single list of values and other keys having two or more lists associated. The code below properly prints the list elements for the key that has multiple lists, but if I change the get statement to a key with a single list I just get the first two digits of the string.

my_dict = {1: ['test', 'values'],
           2: [['test2', 'value2'], ['test3', 'value3']],
           3: ['test4', 'value4']}

for item in my_dict.get(2):
   print('%s, %s' %(item[0], item[1]))

Would someone explain how to access list values from the dictionary regardless of whether the key has a single list, or multiple lists?

Ultimately the output if key 1 or 3 is used would be

test, values  or test4, value4

If key 2 is selected the output would be

test2, value2
test3, value3

Body:
I'm not exactly sure if this is what you mean but the code below prints out each text value:

my_dict= {1: ['test', 'values'],
      2: [['test2', 'value2'], ['test3', 'value3']],
      3: ['test4', 'value4']}

for key, value in my_dict.items():
    for x in value:
        if not isinstance(x, list):
            print(x)
        else:
            for y in x:
                print(y)

#output
test
values
test2
value2
test3
value3
test4
value4

So loop through your dictionary and create a sub-loop through each element (x) of each value in your dictionary. If x is not itself a list, print x. If x is a list, then loop through x, printing each element (y) contained within x.


问:
How to replace a string in an existing file in Perl
I want to replace the word "blue" with "red" in all text files named as 1_classification.dat, 2_classification.dat and so on. I want to edit the same file so I tried the following code, but it does not work. Where am I going wrong?</p>
```<code>@files = glob("*_classification.dat");
foreach my $file (@files)
{
    open(IN,$file) or die $!;
    <IN>;
    while(<IN>)
    {
        $_ = '~s/blue/red/g';
        print IN $file;
    }
    close(IN)
}
</code>```

答:
None of the existing answers here have provided a complete example of how to do this from within a script (not a one-liner). Here is what I did:</p>
```<code>rename($file, $file . '.bak');
open(IN, '<' . $file . '.bak') or die $!;
open(OUT, '>' . $file) or die $!;
while(<IN>)
{
    $_ =~ s/blue/red/g;
    print OUT $_;
}
close(IN);
close(OUT);
</code>```

Body:
I want to replace the word "blue" with "red" in all text files named as 1_classification.dat, 2_classification.dat and so on. I want to edit the same file so I tried the following code, but it does not work. Where am I going wrong?

@files = glob("*_classification.dat");
foreach my $file (@files)
{
    open(IN,$file) or die $!;
    <IN>;
    while(<IN>)
    {
        $_ = '~s/blue/red/g';
        print IN $file;
    }
    close(IN)
}

Body:
None of the existing answers here have provided a complete example of how to do this from within a script (not a one-liner). Here is what I did:

rename($file, $file . '.bak');
open(IN, '<' . $file . '.bak') or die $!;
open(OUT, '>' . $file) or die $!;
while(<IN>)
{
    $_ =~ s/blue/red/g;
    print OUT $_;
}
close(IN);
close(OUT);


问:
Returning JSON from a PHP Script
I want to return JSON from a PHP script.

Do I just echo the result? Do I have to set the Content-Type header?

答:
An easy way to format your domain objects to JSON is to use the Marshal Serializer.
Then pass the data to json_encode and send the correct Content-Type header for your needs.
If you are using a framework like Symfony, you don't need to take care of setting the headers manually. There you can use the JsonResponse.

For example the correct Content-Type for dealing with Javascript would be application/javascript.

Or if you need to support some pretty old browsers the safest would be text/javascript.

For all other purposes like a mobile app use application/json as the Content-Type.

Here is a small example:

```<code><?php
...
$userCollection = [$user1, $user2, $user3];

$data = Marshal::serializeCollectionCallable(function (User $user) {
    return [
        'username' => $user->getUsername(),
        'email'    => $user->getEmail(),
        'birthday' => $user->getBirthday()->format('Y-m-d'),
        'followers => count($user->getFollowers()),
    ];
}, $userCollection);

header('Content-Type: application/json');
echo json_encode($data);
</code>```

Title: Returning JSON from a PHP Script

Body:
An easy way to format your domain objects to JSON is to use the Marshal Serializer.
Then pass the data to json_encode and send the correct Content-Type header for your needs.
If you are using a framework like Symfony, you don't need to take care of setting the headers manually. There you can use the JsonResponse.

For example the correct Content-Type for dealing with Javascript would be application/javascript.

Or if you need to support some pretty old browsers the safest would be text/javascript.

For all other purposes like a mobile app use application/json as the Content-Type.

Here is a small example:

<?php
...
$userCollection = [$user1, $user2, $user3];

$data = Marshal::serializeCollectionCallable(function (User $user) {
    return [
        'username' => $user->getUsername(),
        'email'    => $user->getEmail(),
        'birthday' => $user->getBirthday()->format('Y-m-d'),
        'followers => count($user->getFollowers()),
    ];
}, $userCollection);

header('Content-Type: application/json');
echo json_encode($data);


问:
client_id and client_secret sent via param vs in url
I'm having some problems with my Oauth2 server (Spring) when trying to access some protected endpoints.

If I want to get a token (via Zuul gateway), I'd do something like this:

```<code>http://localhost:4444/auth/oauth/token?client_id=gateway&client_secret=1234&grant_type=password&username=user&password=password
</code>```

(Asume above client and user exist correctly and the Content-Type being application/x-www-form-urlencoded).

This call doesn't work, but, if I do it like this:

```<code>gateway:1234@localhost:4444/auth/oauth/token?grant_type=password&username=user&password=password
</code>```

Then, it works.

Is this considered normal behavior? As far as I could read, this should work. It's like the id and the secret are not being handled when I sent those as params but when I modify the url, the it's taken and everything works. Do I need implement something extra?

To clarify, the Oauth2 server works when I send the client_id and the client_secret like in the second url but if I send those as params (first url), it doesn't.

You can check the code here (OAuth2-service): https://github.com/otamega93/CloudBasedUserRegistration2/tree/master/OAuth2-service

The configuration is mostly at OAuth2Configuration, WebSecurityConfig and AuthServerApplication. I'm testing with Postman. This also happens when I access directly the Oauth2 server.

答:
The token endpoint (oauth/token) is protected, see TokenEndpoint:

Clients must be authenticated using a Spring Security Authentication to access this endpoint, and the client id is extracted from the authentication token. The best way to arrange this (as per the OAuth2 spec) is to use HTTP basic authentication for this endpoint with standard Spring Security support.

and see OAuth 2 Developers Guide:

The token endpoint is protected for you by default by Spring OAuth in the @Configuration support using HTTP Basic authentication of the client secret. This is not the case in XML (so it should be protected explicitly).

The client has to authenticate itself with Basic authentication scheme, therefore the client has to add an Authorization header to the request, see RFC 2617:

To receive authorization, the client sends the userid and password,
separated by a single colon (":") character, within a base64 [7]
encoded string in the credentials.

 basic-credentials = base64-user-pass
 base64-user-pass  = <base64 [4] encoding of user-pass,
                     except not limited to 76 char/line>
 user-pass   = userid ":" password
 userid      = *<TEXT excluding ":">
 password    = *TEXT
```
<p>Userids might be case sensitive.</p>
<p>If the user agent wishes to send the userid "Aladdin" and password
"open sesame", it would use the following header field:</p>
<pre class="lang-none prettyprint-override"><code> Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
</code>```

Your first request contains no Authorization header.

Your second request contains a URL with a "userinfo" subcompontent, see RFC 3986:

The userinfo subcomponent may consist of a user name and, optionally,
scheme-specific information about how to gain authorization to access
the resource.  The user information, if present, is followed by a
commercial at-sign ("@") that delimits it from the host.

Body:
I'm having some problems with my Oauth2 server (Spring) when trying to access some protected endpoints.

If I want to get a token (via Zuul gateway), I'd do something like this:

http://localhost:4444/auth/oauth/token?client_id=gateway&client_secret=1234&grant_type=password&username=user&password=password

(Asume above client and user exist correctly and the Content-Type being application/x-www-form-urlencoded).

This call doesn't work, but, if I do it like this:

gateway:1234@localhost:4444/auth/oauth/token?grant_type=password&username=user&password=password

Then, it works.

Is this considered normal behavior? As far as I could read, this should work. It's like the id and the secret are not being handled when I sent those as params but when I modify the url, the it's taken and everything works. Do I need implement something extra?

To clarify, the Oauth2 server works when I send the client_id and the client_secret like in the second url but if I send those as params (first url), it doesn't.

You can check the code here (OAuth2-service): https://github.com/otamega93/CloudBasedUserRegistration2/tree/master/OAuth2-service

The configuration is mostly at OAuth2Configuration, WebSecurityConfig and AuthServerApplication. I'm testing with Postman. This also happens when I access directly the Oauth2 server.

Body:
The token endpoint (oauth/token) is protected, see TokenEndpoint:

Clients must be authenticated using a Spring Security Authentication to access this endpoint, and the client id is extracted from the authentication token. The best way to arrange this (as per the OAuth2 spec) is to use HTTP basic authentication for this endpoint with standard Spring Security support.

and see OAuth 2 Developers Guide:

The token endpoint is protected for you by default by Spring OAuth in the @Configuration support using HTTP Basic authentication of the client secret. This is not the case in XML (so it should be protected explicitly).

The client has to authenticate itself with Basic authentication scheme, therefore the client has to add an Authorization header to the request, see RFC 2617:

To receive authorization, the client sends the userid and password,
separated by a single colon (":") character, within a base64 [7]
encoded string in the credentials.

 basic-credentials = base64-user-pass
 base64-user-pass  = <base64 [4] encoding of user-pass,
                     except not limited to 76 char/line>
 user-pass   = userid ":" password
 userid      = *<TEXT excluding ":">
 password    = *TEXT

Userids might be case sensitive.

If the user agent wishes to send the userid "Aladdin" and password
"open sesame", it would use the following header field:

 Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

Your first request contains no Authorization header.

Your second request contains a URL with a "userinfo" subcompontent, see RFC 3986:

The userinfo subcomponent may consist of a user name and, optionally,
scheme-specific information about how to gain authorization to access
the resource.  The user information, if present, is followed by a
commercial at-sign ("@") that delimits it from the host.


问:
Linker Errors LNK2019 and LNK1120 in single file code
C++ code of my compiler
There is only one .cpp file in my Win32 console project. I am facing these LNK compile-time errors in my code. I am working on Visual Studio 12. I have tried a lot of things but nothing seems to have solved my issue.

I am writing code for a compiler that was originally built in Java and now the task at hand is to convert it in C++. I am looking forward to some useful solutions.
Can anyone help me with this task?

答:
The specific error in the screenshot says that the string terminalEP(void) function being called from the terminalP function does not exist - and it is true because your terminalEP function is definaed as string terminalEP(string str) but the line that calls it from the terminalP function is s=terminalEP();

You need to pass a parameter to the terminalEP function or you need to make the parameter for the terminalEP function have a default value.


问:
Why does Entity Framework make certain fields EnityKeys when they are not even PK's in the source DB?
Starting out on an Entity Framework project.

Imported the Db I am going to use and right away noticed that many table fields were made into EntityKey types and the source fields are not even Keys. Doesn't seem to be a pattern as to which fields were made EntityKeys and which were not.

Is this normal? There were no options for this in the wizard. I don;t want to have to go through and remove this property for all the fields where it was added.

Thanks for your advice!

答:
Each entity on your model requires a unique key, so EF can track and retrieve/persist these entities based on their unique identifier.

If your tables in your database don't have primary keys, then your database is not relational and therefore should not be used by an ORM like EF which is predominantly designed for RDBMS.

If you had an entity like this:

```<code>public class Orders
{
   public string Name { get; set; }
   public double Price { get; set; }
}
</code>```

How would you retrieve a single order? How would you save a single order?

Crucial LINQ methods such as SingleOrDefault() would be useless, as there is no guarantee that this won't throw an exception:

```<code>var singleOrder = ctx.Orders.SingleOrDefault(x => x.Name == "Foo");
</code>```

Whilst if you had an EntityKey and PK called "OrderId", this is guaranteed to not throw an exception:

```<code>var singleOrder = ctx.Orders.SingleOrDefault(x => x.OrderId == 1);
</code>```

Body:
Each entity on your model requires a unique key, so EF can track and retrieve/persist these entities based on their unique identifier.

If your tables in your database don't have primary keys, then your database is not relational and therefore should not be used by an ORM like EF which is predominantly designed for RDBMS.

If you had an entity like this:

public class Orders
{
   public string Name { get; set; }
   public double Price { get; set; }
}

How would you retrieve a single order? How would you save a single order?

Crucial LINQ methods such as SingleOrDefault() would be useless, as there is no guarantee that this won't throw an exception:

var singleOrder = ctx.Orders.SingleOrDefault(x => x.Name == "Foo");

Whilst if you had an EntityKey and PK called "OrderId", this is guaranteed to not throw an exception:

var singleOrder = ctx.Orders.SingleOrDefault(x => x.OrderId == 1);


问:
incompatible types: void cannot be converted to ArrayList<String>
I'm new to Java and certain that this is a simple fix that I just don't know how to do. This part of the program is meant to take a text file, turn it into an ArrayList and then return it but I get an error when returning it.</p>

```<code>   package albumdatabase;

   import java.io.FileReader;
   import java.util.ArrayList;
   import java.util.Scanner;

public class Duration {

    public static void getLength(String[] args){
        ArrayList<String> listOfAlbums;
        listOfAlbums = getList();
        String arrayOfAlbums[] = new String[listOfAlbums.size()];
        arrayOfAlbums = listOfAlbums.toArray(arrayOfAlbums);
        System.out.println(arrayOfAlbums);

        for( int i = 0; i < arrayOfAlbums.length - 1; i++){
            System.out.println(i);
        }
    }

    public static void getList()throws Exception{
        ArrayList<String> listOfAlbums;
        listOfAlbums = new ArrayList<String>();
        FileReader albums = new FileReader("albums.txt");
        Scanner scanner = new Scanner(albums);
        while (scanner.hasNextLine()){
            listOfAlbums.add(scanner.nextLine());

        }
        System.out.println(listOfAlbums);
        scanner.close();
        return listOfAlbums;

    }
}
</code>```

答:
Your getList() method return type is void and if you want to be able to assign the result of that method to an ArrayList<T> it will have to return ArrayList<T>, in your case it needs to return ArrayList<String>, so the header of your getList() should be as follows:

```<code>public static ArrayList<String> getList();
</code>```

Body:
I'm new to Java and certain that this is a simple fix that I just don't know how to do. This part of the program is meant to take a text file, turn it into an ArrayList and then return it but I get an error when returning it.

   package albumdatabase;

   import java.io.FileReader;
   import java.util.ArrayList;
   import java.util.Scanner;

public class Duration {

    public static void getLength(String[] args){
        ArrayList<String> listOfAlbums;
        listOfAlbums = getList();
        String arrayOfAlbums[] = new String[listOfAlbums.size()];
        arrayOfAlbums = listOfAlbums.toArray(arrayOfAlbums);
        System.out.println(arrayOfAlbums);

        for( int i = 0; i < arrayOfAlbums.length - 1; i++){
            System.out.println(i);
        }
    }

    public static void getList()throws Exception{
        ArrayList<String> listOfAlbums;
        listOfAlbums = new ArrayList<String>();
        FileReader albums = new FileReader("albums.txt");
        Scanner scanner = new Scanner(albums);
        while (scanner.hasNextLine()){
            listOfAlbums.add(scanner.nextLine());

        }
        System.out.println(listOfAlbums);
        scanner.close();
        return listOfAlbums;

    }
}

Body:
Your getList() method return type is void and if you want to be able to assign the result of that method to an ArrayList<T> it will have to return ArrayList<T>, in your case it needs to return ArrayList<String>, so the header of your getList() should be as follows:

public static ArrayList<String> getList();


问:
Saving Tensorflow Graph and Variables while excluding Adam Optimizer Variables
I am saving a tensor flow graph and variables using :

```<code> builder = tf.saved_model.builder.SavedModelBuilder(export_dir)
 builder.add_meta_graph_and_variables(sess, ["nn"])
 builder.save(as_text=False)
</code>```

I would like the smallest save file with which I can run classification with. Specifically I am looking to exclude Adam variables that were created during training from the save file.

When I iterate on the values returned by tf.all_variables() prior to saving, I get variables I expect like:

```<code>tf.Variable 'mymodel/fully_connected/weights:0' shape=(128, 100) dtype=float32_ref
</code>```

But also two Adam copies of the same:

```<code>tf.Variable 'mymodel/train/mymodel/fully_connected/weights/Adam:0' shape=(128, 100) dtype=float32_ref

tf.Variable 'mymodel/train/mymodel/fully_connected/weights/Adam_1:0' shape=(128, 100) dtype=float32_ref
</code>```

This triples the size of my checkpoint file and I am constrained by the target system. The save file will only be used for classification, not training, so I don't need Adam optimizer variables.

Any suggestions on how I can most easily not have these written to the save file?

Any other suggestions for reducing save file size while still being able to run classification are appreciated.

答:
You can specify the variables in the saver:

saver = tf.train.Saver(...variables...)
saver.save(sess, 'my-model', global_step=step)

Reference: https://www.tensorflow.org/api_docs/python/tf/train/Saver

Body:
I am saving a tensor flow graph and variables using :

 builder = tf.saved_model.builder.SavedModelBuilder(export_dir)
 builder.add_meta_graph_and_variables(sess, ["nn"])
 builder.save(as_text=False)

I would like the smallest save file with which I can run classification with. Specifically I am looking to exclude Adam variables that were created during training from the save file.

When I iterate on the values returned by tf.all_variables() prior to saving, I get variables I expect like:

tf.Variable 'mymodel/fully_connected/weights:0' shape=(128, 100) dtype=float32_ref

But also two Adam copies of the same:

tf.Variable 'mymodel/train/mymodel/fully_connected/weights/Adam:0' shape=(128, 100) dtype=float32_ref

tf.Variable 'mymodel/train/mymodel/fully_connected/weights/Adam_1:0' shape=(128, 100) dtype=float32_ref

This triples the size of my checkpoint file and I am constrained by the target system. The save file will only be used for classification, not training, so I don't need Adam optimizer variables.

Any suggestions on how I can most easily not have these written to the save file?

Any other suggestions for reducing save file size while still being able to run classification are appreciated.


问:
javascript output not showing in html
I’m trying to write code that removes some special characters from any string URL and then displays the cleaned string via html.

The JavaScript works but I can’t get the result to show in the browser.

The whole point of the code is to have someone put in input and then the input is then cleaned up and the result is then inserted in “result1” and/or “result2”

So when the page loads and the user types something in “myTextarea” and clicks the button, cleanupurl(x) is supposed to run.

pls help ;(

code so far

```<code><!DOCTYPE html>
    <html>
    <head>
        <title>Clean Strings</title>
    </head>
        <body>
            <div id="display-area" >
                <textarea placeholder="insert URL here :)" id="myTextarea">.
                </textarea>
                <button class = 'btn btn-default' id="demo" onclick=“cleanupurl(myTextarea.text())> Cleanup URL</button>
            </div>

            <div id ="result1">
                <p></p>
            </div>

            <div id ="result2">
                <p></p>
            </div>
        </body>
    </html>
   <script>
    var splitstring = [''];
    var finaloutput = ''; var i = 0;

    function cleanupurl(urlstring) {

        //==========================================//
        urlstring = urlstring.replace(/%21/gi, '!');
        urlstring = urlstring.replace(/%23/gi, '#');
        urlstring = urlstring.replace(/%24/gi, '$');
        urlstring = urlstring.replace(/%26/gi, '&');

        //==========================================//
        splitstring = urlstring.split('http://');
        document.getElementById("result1").innerHTML =  cleanurloutput1();
        //return
    }

    function cleanurloutput1(){
    return splitstring[1];
        }

    function cleanurloutput2(){
    return splitstring[2];
        }

        //document.getElementById("result1").innerHTML = cleanurloutput1();

        var x = document.getElementById("myTextarea").value;
        cleanupurl(x);

    </script>
</code>```

答:
Your onclick is passing myTextarea.text() while the element myTextArea doesn't have text method (check your browser's console for errors).

use myTextarea.value instead

```<code><button class='btn btn-default' id="demo" onclick=“cleanupurl( myTextarea.value ) > Cleanup URL</button>
</code>```

Title: javascript output not showing in html

Body:
I’m trying to write code that removes some special characters from any string URL and then displays the cleaned string via html.

The JavaScript works but I can’t get the result to show in the browser.

The whole point of the code is to have someone put in input and then the input is then cleaned up and the result is then inserted in “result1” and/or “result2”

So when the page loads and the user types something in “myTextarea” and clicks the button, cleanupurl(x) is supposed to run.

pls help ;(

code so far

<!DOCTYPE html>

        <title>Clean Strings</title>

                <textarea placeholder="insert URL here :)" id="myTextarea">.
                </textarea>
                <button class = 'btn btn-default' id="demo" onclick=“cleanupurl(myTextarea.text())> Cleanup URL</button>

Body:
Your onclick is passing myTextarea.text() while the element myTextArea doesn't have text method (check your browser's console for errors).

use myTextarea.value instead

<button class='btn btn-default' id="demo" onclick=“cleanupurl( myTextarea.value ) > Cleanup URL</button>


问:
Does linking external JavaScript in HTML document take up bandwidth?
For instance, my HTML document looks like:

```<code><html>
<head> ... </head>
<body>
    <script ...></script>
    // more scripts here, excuse the syntax
</body>
</html>
</code>```

If I remove some of the inline JavaScript, would that free up bandwidth? Moreover, would removing the inline JavaScript and removing the actual JavaScript source files free up even more bandwidth when my page loads?

I'm a bit new to HTML/JavaScript/network concepts and am unsure about how this works. I believe I could use Chrome developer tools to test the load time and infer that lower load time means use of less bandwidth, but I'd like to check with more experienced folks.

EDIT: A follow-up question for specificity: does the act of linking take up bandwidth? Assume we're ignoring the fact that text in HTML takes up some bandwidth.

EDIT 2: After testing the load time and looking at the KBs transferred with Chrome developer tools, the change in KBs transferred when removing the linking seemed to make no difference.

答:
Inline JavaScript would increase size of your HTML file, and external .js files also take up some bandwidth to go through network, so in short, answer is yes. You would save up some bandwidth if you were to remove some JavaScript, but you would have to remove a lot of it to save significant amount of bandwidth.

To save on bandwidth you can leverage browser caching  instead.

Basically, you would keep all your JavaScript, but you just wouldn't be sending it every time user requests your page. Instead it would be kept in clients browser for some time.

Another way to reduce size of JavaScript files without removing any part of it is minification/uglification of code, so you can take a look into that as well

Body:
For instance, my HTML document looks like:

 ...

    // more scripts here, excuse the syntax

If I remove some of the inline JavaScript, would that free up bandwidth? Moreover, would removing the inline JavaScript and removing the actual JavaScript source files free up even more bandwidth when my page loads?

I'm a bit new to HTML/JavaScript/network concepts and am unsure about how this works. I believe I could use Chrome developer tools to test the load time and infer that lower load time means use of less bandwidth, but I'd like to check with more experienced folks.

EDIT: A follow-up question for specificity: does the act of linking take up bandwidth? Assume we're ignoring the fact that text in HTML takes up some bandwidth.

EDIT 2: After testing the load time and looking at the KBs transferred with Chrome developer tools, the change in KBs transferred when removing the linking seemed to make no difference.


问:
 tag not working despite HTML set up correctly
I'm working on a portfolio website and have the following HTML for the nav section (wanted to create a hamburger nav):

```<code><!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="description" content="Annettte Lin Personal Portfolio">

    <title>Annette Lin Personal Porfolio</title>
    <link href="https://fonts.googleapis.com/css?
        family=Source+Sans+Pro:400,600,600i,700" rel="stylesheet">
    <!-- external CSS files -->
    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/styles.css">
    <link href="css/peeler.css" rel="stylesheet"><br type="_moz">
</head>

<body>
    <article>
        <nav class="navigation">
            <div id="menuToggle">
                <input type="checkbox" />
                <span></span>
                <span></span>
                <span></span>
                <ul id="menu">
                    <a href="#">
                        <li>Home</li>
                    </a>
                    <a href="#about">
                        <li>About Me</li>
                    </a>
                    <a href="#resume">
                        <li>Resume</li>
                    </a>
                    <li>Contact</li>
                </ul>
            </div>
        </nav>
        <div class="homepage-image">
            <h1>Annette Lin</h1>
            <h2>New York City tech enthusiast embracing her inner nerd and always on the hunt for good food. Constantly. </h2>
            <p>“Tell me and I forget, teach me and I may remember, involve me and I learn.”</p>
        </div>
    </article>
    <article>
        <div class="about-me">
            <h1 id="about">About Me</h1>
            <p> about me text </p>
        </div>
    </article>
</code>```

However, when I'm trying to link internally, it doesn't go anywhere (about me for instance). I have the ID set up for the section I want it to link to, but it doesn't work. Tried switching div class to div id as well and didn't work.

I have a feeling it's because of this peeler feature I added in the JS that creates a peeling effect for the website when user scrolls:

```<code>(function() {
   var ABOVE = "1000";

   var root = this,
   Peeler = function(opts) {
    this.options = opts || {};
  },
  articles = document.querySelectorAll("article"),
  backgroundImages = document.querySelectorAll(".background"),
  viewportWidth = root.innerWidth,
  aspectRatio = 1200/1440,
  bodyHeight = 0,
  articleStates = [];

  Peeler.prototype.bind = function(opts) {
  var article,
    i,
    len,
    height,
    currentOffset,
    backgroundImage,
    prevScroll = 0;

    root.onscroll = function(event) {
    var yOffset = window.pageYOffset,
      i = 0,
      j = 0,
      triggered = false,
      below = 999,
      curr,
      len = articles.length,
      scrollingDown;

  for (; i < len; i++) {
    if (yOffset <= articleStates[i].max && yOffset >=
  articleStates[i].min) {
      offset = -(yOffset-(articleStates[i].min));
      scrollingDown = prevScroll < document.body.scrollTop;

      // Trigger peel event when the offset reset
      if (offset > currentOffset) {
        // If we are scrolling down, trigger next callback
        if (scrollingDown && typeof this.options.nextCallback ===
      "function") {
          this.options.nextCallback(articles[i]);
        } else {

        }
      }

      prevScroll = document.body.scrollTop;
      currentOffset = offset;

      articles[i].style.marginTop = -(yOffset-(articleStates[i].min)) +
     "px";
      articles[i].style.zIndex = ABOVE;
      triggered = true;
      curr = i;
      break;
    }
  }

  for (;j < len; j++) {
    if (i !== curr && i < len) {
      articles[i].style.marginTop = "0px";
      articles[i].style.zIndex = below--;
    }
    i++;
    // Reset at rotation point
    if (i == len) {
      i = 0;
    }
  }

  if (!triggered) {
      articles[0].style.marginTop = "0px";
      articles[0].style.zIndex = ABOVE;
  }
}.bind(this);

articles[0].style.zIndex = "2";

for (i = 0, len = articles.length; i < len; i++) {
  article = articles[i];

  height = article.getAttribute("data-height") || window.innerHeight;
  article.style.height = parseInt(height) + "px";
  articleStates.push({min: bodyHeight, max: bodyHeight+height});
  bodyHeight += height;
}

for (i = 0, len = backgroundImages.length; i < len; i++) {
  backgroundImage = backgroundImages[i];
  backgroundImage.style.background = "url(" + backgroundImage.src + ")
  no-repeat center center";
  backgroundImage.style.backgroundSize = "cover";
  backgroundImage.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
}

  document.body.style.height = bodyHeight + "px";
  };

 Peeler.prototype.peel = function() {
 };

root.Peeler = Peeler;
}).call(this);
</code>```

Appreciate any help, thanks!!

Annette

答:
Your mistake is at:

```<code><div class="about-me">
    <h1 id = "about">About Me</h1>
    <p> about me text </p>
</div>
</code>```

You need something with the name tag not the id tag to have the anchor working.

```<code><div class="about-me">
    <h1 id = "about" name = "about">About Me</h1>
    <p> about me text </p>
</div>
</code>```

Title: <a> tag not working despite HTML set up correctly

Body:
I'm working on a portfolio website and have the following HTML for the nav section (wanted to create a hamburger nav):

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="description" content="Annettte Lin Personal Portfolio">

    <title>Annette Lin Personal Porfolio</title>
    <link href="https://fonts.googleapis.com/css?
        family=Source+Sans+Pro:400,600,600i,700" rel="stylesheet">

    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/styles.css">
    <link href="css/peeler.css" rel="stylesheet">

                <input type="checkbox" />

Home

About Me

Resume

Contact

Annette Lin

New York City tech enthusiast embracing her inner nerd and always on the hunt for good food. Constantly.

“Tell me and I forget, teach me and I may remember, involve me and I learn.”

About Me

 about me text

However, when I'm trying to link internally, it doesn't go anywhere (about me for instance). I have the ID set up for the section I want it to link to, but it doesn't work. Tried switching div class to div id as well and didn't work.

I have a feeling it's because of this peeler feature I added in the JS that creates a peeling effect for the website when user scrolls:

(function() {
   var ABOVE = "1000";

   var root = this,
   Peeler = function(opts) {
    this.options = opts || {};
  },
  articles = document.querySelectorAll("article"),
  backgroundImages = document.querySelectorAll(".background"),
  viewportWidth = root.innerWidth,
  aspectRatio = 1200/1440,
  bodyHeight = 0,
  articleStates = [];

  Peeler.prototype.bind = function(opts) {
  var article,
    i,
    len,
    height,
    currentOffset,
    backgroundImage,
    prevScroll = 0;

    root.onscroll = function(event) {
    var yOffset = window.pageYOffset,
      i = 0,
      j = 0,
      triggered = false,
      below = 999,
      curr,
      len = articles.length,
      scrollingDown;

  for (; i < len; i++) {
    if (yOffset <= articleStates[i].max && yOffset >=
  articleStates[i].min) {
      offset = -(yOffset-(articleStates[i].min));
      scrollingDown = prevScroll < document.body.scrollTop;

      // Trigger peel event when the offset reset
      if (offset > currentOffset) {
        // If we are scrolling down, trigger next callback
        if (scrollingDown && typeof this.options.nextCallback ===
      "function") {
          this.options.nextCallback(articles[i]);
        } else {

        }
      }

      prevScroll = document.body.scrollTop;
      currentOffset = offset;

      articles[i].style.marginTop = -(yOffset-(articleStates[i].min)) +
     "px";
      articles[i].style.zIndex = ABOVE;
      triggered = true;
      curr = i;
      break;
    }
  }

  for (;j < len; j++) {
    if (i !== curr && i < len) {
      articles[i].style.marginTop = "0px";
      articles[i].style.zIndex = below--;
    }
    i++;
    // Reset at rotation point
    if (i == len) {
      i = 0;
    }
  }

  if (!triggered) {
      articles[0].style.marginTop = "0px";
      articles[0].style.zIndex = ABOVE;
  }
}.bind(this);

articles[0].style.zIndex = "2";

for (i = 0, len = articles.length; i < len; i++) {
  article = articles[i];

  height = article.getAttribute("data-height") || window.innerHeight;
  article.style.height = parseInt(height) + "px";
  articleStates.push({min: bodyHeight, max: bodyHeight+height});
  bodyHeight += height;
}

for (i = 0, len = backgroundImages.length; i < len; i++) {
  backgroundImage = backgroundImages[i];
  backgroundImage.style.background = "url(" + backgroundImage.src + ")
  no-repeat center center";
  backgroundImage.style.backgroundSize = "cover";
  backgroundImage.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
}

  document.body.style.height = bodyHeight + "px";
  };

 Peeler.prototype.peel = function() {
 };

root.Peeler = Peeler;
}).call(this);

Appreciate any help, thanks!!

Annette

Body:
Your mistake is at:

<div class="about-me">
    <h1 id = "about">About Me</h1>
    <p> about me text </p>
</div>

You need something with the name tag not the id tag to have the anchor working.

<div class="about-me">
    <h1 id = "about" name = "about">About Me</h1>
    <p> about me text </p>
</div>


问:
Can not find namespace or data type NavMeshAgent Unity 3d
I am trying to run simple Unity script (which is attached as a component of my object) in Visual Studio. Here is the code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class BlackPawnParticleSystem : MonoBehaviour {

    // Use this for initialization
    void Start () {
        ParticleSystem ps = GetComponent<ParticleSystem);
        var em = ps.emission;
        em.enabled = true;

        em.SetBursts(
            new ParticleSystem.Burst[]{
                new ParticleSystem.Burst(2.0f, 100),
                new ParticleSystem.Burst(4.0f, 100)
            });
    }

  // Update is called once per frame
  void Update () {

  }
}
</code>```

The problem is that when I run it I get an error: "Can not find namespace or data type NavMeshAgent". I have read that there might be a problem with simple UnityEngine import. So I have replaced it with using UnityEngine.AI.

But all the classes like ParticleSystem and MonoBehavior are underlined and show the same "Can not find namespace" error like they are not in this namespace. So how I can define my namespaces imports to run the code properly?

UPDATE: full error message is

```<code>D:\userdata\Documents\Scene1\Assets\RPG Character Animation Pack\Code\RPGCharacterControllerFREE.cs(21,10,21,22): error CS0246: Can not find namespace or data type NavMeshAgent
</code>```

答:
Don't remove the UnityEngine import, just add the UnityEngine.AI import on the next line.

```<code>using UnityEngine;
using UnityEngine.AI;
</code>```

You'll have to add this import to the actual file that is giving the error, so in this case that means you need to go to RPGCharacterControllerFREE.cs and add using UnityEngine.AI; to that file.

Body:
I am trying to run simple Unity script (which is attached as a component of my object) in Visual Studio. Here is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class BlackPawnParticleSystem : MonoBehaviour {

    // Use this for initialization
    void Start () {
        ParticleSystem ps = GetComponent<ParticleSystem);
        var em = ps.emission;
        em.enabled = true;

        em.SetBursts(
            new ParticleSystem.Burst[]{
                new ParticleSystem.Burst(2.0f, 100),
                new ParticleSystem.Burst(4.0f, 100)
            });
    }

  // Update is called once per frame
  void Update () {

  }
}

The problem is that when I run it I get an error: "Can not find namespace or data type NavMeshAgent". I have read that there might be a problem with simple UnityEngine import. So I have replaced it with using UnityEngine.AI.

But all the classes like ParticleSystem and MonoBehavior are underlined and show the same "Can not find namespace" error like they are not in this namespace. So how I can define my namespaces imports to run the code properly?

UPDATE: full error message is

D:\userdata\Documents\Scene1\Assets\RPG Character Animation Pack\Code\RPGCharacterControllerFREE.cs(21,10,21,22): error CS0246: Can not find namespace or data type NavMeshAgent

Body:
Don't remove the UnityEngine import, just add the UnityEngine.AI import on the next line.

using UnityEngine;
using UnityEngine.AI;

You'll have to add this import to the actual file that is giving the error, so in this case that means you need to go to RPGCharacterControllerFREE.cs and add using UnityEngine.AI; to that file.


问:
Resubscribe Observers on onError - RxJava

I have subscribed an observer as follows

```<code>public PublishSubject<ChannelModel> publisher = PublishSubject.create();

publisher.subscribe(observer);

Observer<ChannelListModel> observer = new Observer<ChannelListModel>() {
    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onNext(ChannelListModel model) {
        adapter.setChannels(model.getChannels());
    }
};
</code>```

It works perfectly fine the first time I request data and display the same. But if request fails and as soon as the onError is called, the publisher will lose its observer. I want to re-subscribe to the same observer. So that when I retry the failed request, I can publish the result to the observer.

答:
In order to re-subscribe an Observable on error, you should use Retry operator. In RxJava, you can do it as follows

```<code>publisher
  .retry()
  .subscribe(observer);
</code>```

After that subscription should be retried infinitely as long as error will be thrown.

You can also specify limit of possible retries like that:

```<code>publisher
  .retry(5)
  .subscribe(observer);
</code>```

In the example above, subscriber will retry operation 5 times. When the error will be still persisted after 5 tries, then subscription will fail.

Body:
I have subscribed an observer as follows

public PublishSubject<ChannelModel> publisher = PublishSubject.create();

publisher.subscribe(observer);

Observer<ChannelListModel> observer = new Observer<ChannelListModel>() {
    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onNext(ChannelListModel model) {
        adapter.setChannels(model.getChannels());
    }
};

It works perfectly fine the first time I request data and display the same. But if request fails and as soon as the onError is called, the publisher will lose its observer. I want to re-subscribe to the same observer. So that when I retry the failed request, I can publish the result to the observer.

Body:
In order to re-subscribe an Observable on error, you should use Retry operator. In RxJava, you can do it as follows

publisher
  .retry()
  .subscribe(observer);

After that subscription should be retried infinitely as long as error will be thrown.

You can also specify limit of possible retries like that:

publisher
  .retry(5)
  .subscribe(observer);

In the example above, subscriber will retry operation 5 times. When the error will be still persisted after 5 tries, then subscription will fail.


问:
How I Can Receive Element Value Of Another Site With Javascript
Example : How I Received "duration" id value on "http://www.imdb.com/title/tt0145487/" (its not really exists!)

If you know better way to received IMDB Info with JavaScript please tell me :)
Thanks !

答: IMDb forbids scraping. Try the OMDb API.</p>