问:
Game of Life - Overwriting the current generation instead of updating to the next
Below I have added my game of life code. The rules are defined correctly, and it runs smoothly. However, the game does not work as supposed. It is not updating to the next generation, but it seems to be overwriting the current generation. As an example:  Three horizontal dots are supposed to turn into three vertical dots in the next generation, but this does not happen.

The solution:
I have two generations, the current and the next generation. It has to apply the rules to the current generation and update them in the next generation. Then it has to overwrite the current generation with the next generation in one go, not cell by cell. How can I fix this?

```<code>import tkinter as tk
import itertools, os, platform, pygame, random

# Defining the grid dimensions.
GRID_SIZE = WIDTH, HEIGHT = 750, 1000

# Defining the cell size and the number of cells in the X and Y direction.
CELL_SIZE = 10
X_CELLS = int(WIDTH/CELL_SIZE)
Y_CELLS = int(HEIGHT/CELL_SIZE)

# Defining the number and color for dead and living cells.
COLOR_DEAD = 0
COLOR_ALIVE = 1
colors = []
colors.append((0, 0, 0))  # Black
colors.append((0, 128, 128))  # blue

# Defining two lists: current generation and next generation.
current_generation = [[COLOR_DEAD for y in range(Y_CELLS)] for x in range(X_CELLS)]
next_generation = [[COLOR_DEAD for y in range(Y_CELLS)] for x in range(X_CELLS)]

# Defining the max frames per second/speed of the game.
FPS_MAX = 10

class GameOfLife:
    """
    describe what the method does.
    """
    def __init__(self):
        # Initializing the interpreter and creating a root window and title.
        self.root = tk.Tk()
        self.root.title("Game of Life - Created by - Have fun")
        # Defining the main frame, left-side frame and right-side frame.
        self.frame = tk.Frame(self.root , width=1000, height=1000, highlightbackground='red')
        self.menu = tk.Frame(self.frame, width=250, height=1000, highlightbackground='#595959', highlightthickness=10)
        self.game_border = tk.Frame(self.frame, width=750, height=1000, highlightbackground='green', highlightthickness=10)
        # Packing the windows.
        self.frame.pack()
        self.frame.pack_propagate(0)
        self.menu.pack(side="left")
        self.menu.pack_propagate(0)
        self.game_border.pack()

        # Defining the buttons.
        self.button_start = tk.Button(self.menu, text="Start", height=5, width=20, fg="black", activeforeground="red", background="grey80", activebackground="grey80", command=self.start_button)
        self.button_stop = tk.Button(self.menu, text="Stop", height=5, width=20, fg="black", activeforeground="red", background="grey80", activebackground="grey80", command=self.stop_button)
        self.button_iteration = tk.Button(self.menu, text="Next iteration", height=5, width=20, fg="black", activeforeground="red", background="grey80", activebackground="grey80", command=self.create_next_gen)
        self.button_random = tk.Button(self.menu, text="Random", height=5, width=20, fg="black", activeforeground="red", background="grey80", activebackground="grey80", command=self.random_grid)
        self.button_reset = tk.Button(self.menu, text="Reset", height=5, width=20, fg="black", activeforeground="red", background="grey80", activebackground="grey80", command=self.reset_button)
        self.button_quit = tk.Button(self.menu, text="Quit", height=5, width=20, fg="black", activeforeground="red", background="grey80", activebackground="grey80", command=self.quit_button)
        # Packing the buttons.
        self.button_start.pack()
        self.button_stop.pack()
        self.button_iteration.pack()
        self.button_random.pack()
        self.button_reset.pack()
        self.button_quit.pack()
        # Placing the buttons.
        self.button_start.place(x=40, y=50)
        self.button_stop.place(x=40, y=200)
        self.button_iteration.place(x=40, y=350)
        self.button_random.place(x=40, y=500)
        self.button_reset.place(x=40, y=650)
        self.button_quit.place(x=40, y=800)

        # Defining the slider.
        self.slider_random = tk.Scale(self.menu, from_=0, to=100, orient="horizontal", command=self.slider_value)
        self.slider_random.set(50)
        # Packing the slider.
        self.slider_random.pack()
        # Placing the slider.
        self.slider_random.place(x=62, y=590)

        # Defining a dropdown menu for the form and color.
        """
        self.options_figures = [
            "circles",
            "squares",
            "surprise"
        ]
        self.var_figure = tk.StringVar(self.root)
        self.dropdown_figure = tk.OptionMenu(self.menu, self.var_figure,
                                             self.options_figures[0], self.options_figures[1],
                                             self.options_figures[2])
        self.var_figure.set(self.options_figures[0])
        #self.var_color.trace("w", FUNCTIONNAME)
        self.dropdown_figure.pack()

        # Dropdown menu for the cell color
        self.options_colors = [
            "blue",
            "red",
            "white",
            "green",
            "yellow",
            "purple",
            "grey",
            "pink"
        ]
        self.var_color = tk.StringVar(self.root)
        self.dropdown_colors = tk.OptionMenu(self.menu, self.var_color,
                                             self.options_colors[0], self.options_colors[1],
                                             self.options_colors[2], self.options_colors[3],
                                             self.options_colors[4], self.options_colors[5],
                                             self.options_colors[6], self.options_colors[7])
        self.var_color.set(self.options_colors[0])
        #self.var_color.trace("w", FUNCTION NAME)
        self.dropdown_colors.pack()
        """

        # Defining the labels that count the dead and living cells.
        """
        self.label_alive = tk.Label(self.menu, text="Living cells:"+" 1000", height=5, width=20, fg="black", background="grey80")
        self.label_dead = tk.Label(self.menu, text="Dead cells"+" 1000", height=1, width=20, fg="black", background="grey80")
        Packing the labels
        self.label_alive.pack()
        self.label_dead.pack()
        self.label_alive.place(x=40, y=900)
        self.label_alive.place(x=40, y=900)
        """

        # This embeds the pygame window in the tkinter frame.
        os.environ['SDL_WINDOWID'] = str(self.game_border.winfo_id())
        system = platform.system()
        if system == "Windows":
            os.environ['SDL_VIDEODRIVER'] = 'windib'
        elif system == "Linux":
            os.environ['SDL_VIDEODRIVER'] = 'x11'

        # Initializing pygame.
        pygame.init()
        self.screen = pygame.display.set_mode(GRID_SIZE)
        # Initializing the generations.
        self.init_gen(current_generation, COLOR_DEAD)
        # Defining a clock to set the FPS.
        self.fps_clock = pygame.time.Clock()
        # Setting variables for later use.
        self.next_iteration = False
        self.game_over = False

    # Get the slider value to change the % of randomness.
    def slider_value(self, value):
        self.value = value

    # Button functions.
    def start_button(self):
        self.next_iteration = True
    def stop_button(self):
        self.next_iteration = False
    def reset_button(self):
        self.next_iteration = False
        self.init_gen(next_generation, COLOR_DEAD)
    def quit_button(self):
        self.game_over = True

    # Initializing all the cells.
    def init_gen(self, generation, c):
        for y in range(Y_CELLS):
            for x in range(X_CELLS):
                generation[x][y] = c

    # Creates a random grid based on the slider value.
    def random_grid(self):
        self.next_iteration = False
        self.init_gen(next_generation, COLOR_DEAD)
        self.percentage_zero = list(itertools.repeat(0,
                                                     (100 - self.slider_random.get())))
        self.percentage_one = list(itertools.repeat(1,
                                                    (self.slider_random.get())))
        # print(self.percentage_zero)
        # print(self.percentage_one)
        for row in range(X_CELLS):
            for col in range(Y_CELLS):
                next_generation[row][col] = random.choice(self.percentage_zero + self.percentage_one)
                # print(next_generation[row][col])

    # Drawing the cells, color black or blue at location (x,y).
    def draw_cell(self, x, y, c):
        pos = (int(x * CELL_SIZE + CELL_SIZE / 2),
               int(y * CELL_SIZE + CELL_SIZE / 2))
        # pygame.draw.rect(screen, colors[c], pygame.Rect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE-1, CELL_SIZE-1))
        # pygame.draw.circle(screen, colors[c], pos, CELL_SIZE, CELL_SIZE) #Weird form, can also be used instead of rectangles
        pygame.draw.circle(self.screen, colors[c], pos, 5, 0)

    # Updating the cells in the current generation.
    def update_gen(self):
        global current_generation
        for y in range(Y_CELLS):
            for x in range(X_CELLS):
                c = next_generation[x][y]
                self.draw_cell(x, y, c)
        current_generation = list(next_generation)

    # Activate a living cell.
    def activate_living_cell(self, x, y):
        global next_generation
        next_generation[x][y] = COLOR_ALIVE

    # Deactivate a living cell.
    def deactivate_living_cell(self, x, y):
        global next_generation
        next_generation[x][y] = COLOR_DEAD

    # Function to check neighbor cells.
    def check_cells(self, x, y):
        # Check the edges.
        if (x < 0) or (y < 0):
            return 0
        if (x >= X_CELLS) or (y >= Y_CELLS):
            return 0
        if current_generation[x][y] == COLOR_ALIVE:
            return 1
        else:
            return 0

    def check_cell_neighbors(self, row_index, col_index):
        # Get the number of alive cells surrounding the current cell.
        num_alive_neighbors = 0
        num_alive_neighbors += self.check_cells(row_index - 1, col_index - 1)
        num_alive_neighbors += self.check_cells(row_index - 1, col_index)
        num_alive_neighbors += self.check_cells(row_index - 1, col_index + 1)
        num_alive_neighbors += self.check_cells(row_index, col_index - 1)
        num_alive_neighbors += self.check_cells(row_index, col_index + 1)
        num_alive_neighbors += self.check_cells(row_index + 1, col_index - 1)
        num_alive_neighbors += self.check_cells(row_index + 1, col_index)
        num_alive_neighbors += self.check_cells(row_index + 1, col_index + 1)
        return num_alive_neighbors

    # Rules:
    # 1 Any live cell with fewer than two live neighbors dies, as if by underpopulation.
    # 2 Any live cell with two or three live neighbors lives on to the next generation.
    # 3 Any live cell with more than three live neighbors dies, as if by overpopulation.
    # 4 Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
    def create_next_gen(self):
        for y in range(Y_CELLS):
            for x in range(X_CELLS):
                n = self.check_cell_neighbors(x, y)  # Number of neighbors.
                c = current_generation[x][y]  # Current cell (either dead or alive).
                if c == COLOR_ALIVE:
                    if (n < 2):  # Rule number 1.
                        next_generation[x][y] = COLOR_DEAD
                    elif (n > 3):  # Rule number 3.
                        next_generation[x][y] = COLOR_DEAD
                    else:  # Rule number 2.
                        next_generation[x][y] = COLOR_ALIVE
                elif c == COLOR_DEAD:
                    if (n == 3):  # Rule number 4.
                        next_generation[x][y] = COLOR_ALIVE
                    else:
                        next_generation[x][y] = COLOR_DEAD
#Problem: first counting, then next iteration.

    # Defines button and mouse clicks.
    def handle_events(self):
        for event in pygame.event.get():
            # Turns the mouse position into a position in the grid.
            posn = pygame.mouse.get_pos()
            x = int(posn[0] / CELL_SIZE)
            y = int(posn[1] / CELL_SIZE)
            # Pressing quit --> quit the game.
            if event.type == pygame.QUIT:
                self.game_over = True
            # Pressing the left mouse button to activate or deactivate a cell.
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    if next_generation[x][y] == COLOR_DEAD:
                        self.activate_living_cell(x, y)
                    else:
                        self.deactivate_living_cell(x, y)
            # Keeping the right mouse button pressed activates drawing mode.
            if event.type == pygame.MOUSEMOTION and event.buttons[2]:
                self.activate_living_cell(x, y)

            # Define the keyboard key presses for q, space, a, s, r.
            if event.type == pygame.KEYDOWN:
                # Quit the game.
                if event.unicode == 'q':
                    self.game_over = True
                    print("q")
                # Next iteration - manually.
                elif event.key == pygame.K_SPACE:
                    self.create_next_gen()
                    print("keypress")
                # Next iteration - automated.
                elif event.unicode == 'a':  # a to automate the iterations.
                    self.next_iteration = True
                    print("a")
                # Stop the automated iterations.
                elif event.unicode == 's':
                    self.next_iteration = False
                    print("s")
                # Empty the grid.
                elif event.unicode == 'r':
                    self.next_iteration = False
                    self.init_gen(next_generation, COLOR_DEAD)
                    print("r")

    # Runs the game loop
    def run(self):
        while not self.game_over:
            self.handle_events()
            if self.next_iteration:
                self.create_next_gen()
            self.update_gen()
            pygame.display.flip()
            self.fps_clock.tick(FPS_MAX)
            self.root.update()

if __name__ == "__main__":
    GAME = GameOfLife()
    GAME.run()
</code>```

答:
You've to deep copy next_generation to current_generation. But

```<code>current_generation = list(next_generation)
</code>```

doesn't do what you expect it to do, since the elements of next_generation are a list, too.

To deep copy a list of where each element is a list of numbers (objects won't be copied) you've to:

current_generation = [list(e) for e in next_generation]
```

<p>or</p>

<pre class="lang-py prettyprint-override"><code>current_generation = [[i for i in j] for j in next_generation]
</code>```

or

current_generation = [e[:] for e in next_generation]
```

<p>Since there is a nested loop in the method <code>GameOfLife.update_gen</code>, the issue can be solved by an simple assignment, too:</p>

```class GameOfLife:

    # [...]

    # Updating the cells in the current generation.
    def update_gen(self):
        global current_generation
        for y in range(Y_CELLS):
            for x in range(X_CELLS):
                c = next_generation[x][y]
                self.draw_cell(x, y, c)
                current_generation[x][y] = next_generation[x][y] # assign element by element

```

<hr>

<p>There is a further issue, when the animation is running and the game is manipulated by the mouse. When the mouse is pressed, then <code>next_generation</code> is changed by either <code>.activate_living_cell</code> or <code>.deactivate_living_cell</code>.<br>
But after that <code>next_generation</code> is recalculated by the data in <code>current_generation</code>.</p>

<blockquote>
```while not self.game_over:
     self.handle_events()       # change "next_generation" by click
     if self.next_iteration:
         self.create_next_gen() # compute "next_generation" from "current_generation"
     self.update_gen()          # copy "current_generation" from "next_generation"
```
</blockquote>

<p>The issue can be solved with ease. Consider that when the game is manipulated by the mouse, the content of <code>current_generation</code> and <code>next_generation</code> is equal.</p>

<p>Either change <code>current_generation</code> instead of <code>next_generation</code> or update <code>current_generation</code> after the manipulation:</p>

<pre class="lang-py prettyprint-override"><code>def handle_events(self):
    for event in pygame.event.get():

        # [...]

        # Pressing the left mouse button to activate or deactivate a cell.
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                if next_generation[x][y] == COLOR_DEAD:
                    self.activate_living_cell(x, y)
                else:
                   self.deactivate_living_cell(x, y)
                self.update_gen() # <----------------------------
</code>```

Body:
Below I have added my game of life code. The rules are defined correctly, and it runs smoothly. However, the game does not work as supposed. It is not updating to the next generation, but it seems to be overwriting the current generation. As an example:  Three horizontal dots are supposed to turn into three vertical dots in the next generation, but this does not happen.

The solution:
I have two generations, the current and the next generation. It has to apply the rules to the current generation and update them in the next generation. Then it has to overwrite the current generation with the next generation in one go, not cell by cell. How can I fix this?

import tkinter as tk
import itertools, os, platform, pygame, random

# Defining the grid dimensions.
GRID_SIZE = WIDTH, HEIGHT = 750, 1000

# Defining the cell size and the number of cells in the X and Y direction.
CELL_SIZE = 10
X_CELLS = int(WIDTH/CELL_SIZE)
Y_CELLS = int(HEIGHT/CELL_SIZE)

# Defining the number and color for dead and living cells.
COLOR_DEAD = 0
COLOR_ALIVE = 1
colors = []
colors.append((0, 0, 0))  # Black
colors.append((0, 128, 128))  # blue

# Defining two lists: current generation and next generation.
current_generation = [[COLOR_DEAD for y in range(Y_CELLS)] for x in range(X_CELLS)]
next_generation = [[COLOR_DEAD for y in range(Y_CELLS)] for x in range(X_CELLS)]

# Defining the max frames per second/speed of the game.
FPS_MAX = 10

class GameOfLife:
    """
    describe what the method does.
    """
    def __init__(self):
        # Initializing the interpreter and creating a root window and title.
        self.root = tk.Tk()
        self.root.title("Game of Life - Created by - Have fun")
        # Defining the main frame, left-side frame and right-side frame.
        self.frame = tk.Frame(self.root , width=1000, height=1000, highlightbackground='red')
        self.menu = tk.Frame(self.frame, width=250, height=1000, highlightbackground='#595959', highlightthickness=10)
        self.game_border = tk.Frame(self.frame, width=750, height=1000, highlightbackground='green', highlightthickness=10)
        # Packing the windows.
        self.frame.pack()
        self.frame.pack_propagate(0)
        self.menu.pack(side="left")
        self.menu.pack_propagate(0)
        self.game_border.pack()

        # Defining the buttons.
        self.button_start = tk.Button(self.menu, text="Start", height=5, width=20, fg="black", activeforeground="red", background="grey80", activebackground="grey80", command=self.start_button)
        self.button_stop = tk.Button(self.menu, text="Stop", height=5, width=20, fg="black", activeforeground="red", background="grey80", activebackground="grey80", command=self.stop_button)
        self.button_iteration = tk.Button(self.menu, text="Next iteration", height=5, width=20, fg="black", activeforeground="red", background="grey80", activebackground="grey80", command=self.create_next_gen)
        self.button_random = tk.Button(self.menu, text="Random", height=5, width=20, fg="black", activeforeground="red", background="grey80", activebackground="grey80", command=self.random_grid)
        self.button_reset = tk.Button(self.menu, text="Reset", height=5, width=20, fg="black", activeforeground="red", background="grey80", activebackground="grey80", command=self.reset_button)
        self.button_quit = tk.Button(self.menu, text="Quit", height=5, width=20, fg="black", activeforeground="red", background="grey80", activebackground="grey80", command=self.quit_button)
        # Packing the buttons.
        self.button_start.pack()
        self.button_stop.pack()
        self.button_iteration.pack()
        self.button_random.pack()
        self.button_reset.pack()
        self.button_quit.pack()
        # Placing the buttons.
        self.button_start.place(x=40, y=50)
        self.button_stop.place(x=40, y=200)
        self.button_iteration.place(x=40, y=350)
        self.button_random.place(x=40, y=500)
        self.button_reset.place(x=40, y=650)
        self.button_quit.place(x=40, y=800)

        # Defining the slider.
        self.slider_random = tk.Scale(self.menu, from_=0, to=100, orient="horizontal", command=self.slider_value)
        self.slider_random.set(50)
        # Packing the slider.
        self.slider_random.pack()
        # Placing the slider.
        self.slider_random.place(x=62, y=590)

        # Defining a dropdown menu for the form and color.
        """
        self.options_figures = [
            "circles",
            "squares",
            "surprise"
        ]
        self.var_figure = tk.StringVar(self.root)
        self.dropdown_figure = tk.OptionMenu(self.menu, self.var_figure,
                                             self.options_figures[0], self.options_figures[1],
                                             self.options_figures[2])
        self.var_figure.set(self.options_figures[0])
        #self.var_color.trace("w", FUNCTIONNAME)
        self.dropdown_figure.pack()

        # Dropdown menu for the cell color
        self.options_colors = [
            "blue",
            "red",
            "white",
            "green",
            "yellow",
            "purple",
            "grey",
            "pink"
        ]
        self.var_color = tk.StringVar(self.root)
        self.dropdown_colors = tk.OptionMenu(self.menu, self.var_color,
                                             self.options_colors[0], self.options_colors[1],
                                             self.options_colors[2], self.options_colors[3],
                                             self.options_colors[4], self.options_colors[5],
                                             self.options_colors[6], self.options_colors[7])
        self.var_color.set(self.options_colors[0])
        #self.var_color.trace("w", FUNCTION NAME)
        self.dropdown_colors.pack()
        """

        # Defining the labels that count the dead and living cells.
        """
        self.label_alive = tk.Label(self.menu, text="Living cells:"+" 1000", height=5, width=20, fg="black", background="grey80")
        self.label_dead = tk.Label(self.menu, text="Dead cells"+" 1000", height=1, width=20, fg="black", background="grey80")
        Packing the labels
        self.label_alive.pack()
        self.label_dead.pack()
        self.label_alive.place(x=40, y=900)
        self.label_alive.place(x=40, y=900)
        """

        # This embeds the pygame window in the tkinter frame.
        os.environ['SDL_WINDOWID'] = str(self.game_border.winfo_id())
        system = platform.system()
        if system == "Windows":
            os.environ['SDL_VIDEODRIVER'] = 'windib'
        elif system == "Linux":
            os.environ['SDL_VIDEODRIVER'] = 'x11'

        # Initializing pygame.
        pygame.init()
        self.screen = pygame.display.set_mode(GRID_SIZE)
        # Initializing the generations.
        self.init_gen(current_generation, COLOR_DEAD)
        # Defining a clock to set the FPS.
        self.fps_clock = pygame.time.Clock()
        # Setting variables for later use.
        self.next_iteration = False
        self.game_over = False

    # Get the slider value to change the % of randomness.
    def slider_value(self, value):
        self.value = value

    # Button functions.
    def start_button(self):
        self.next_iteration = True
    def stop_button(self):
        self.next_iteration = False
    def reset_button(self):
        self.next_iteration = False
        self.init_gen(next_generation, COLOR_DEAD)
    def quit_button(self):
        self.game_over = True

    # Initializing all the cells.
    def init_gen(self, generation, c):
        for y in range(Y_CELLS):
            for x in range(X_CELLS):
                generation[x][y] = c

    # Creates a random grid based on the slider value.
    def random_grid(self):
        self.next_iteration = False
        self.init_gen(next_generation, COLOR_DEAD)
        self.percentage_zero = list(itertools.repeat(0,
                                                     (100 - self.slider_random.get())))
        self.percentage_one = list(itertools.repeat(1,
                                                    (self.slider_random.get())))
        # print(self.percentage_zero)
        # print(self.percentage_one)
        for row in range(X_CELLS):
            for col in range(Y_CELLS):
                next_generation[row][col] = random.choice(self.percentage_zero + self.percentage_one)
                # print(next_generation[row][col])

    # Drawing the cells, color black or blue at location (x,y).
    def draw_cell(self, x, y, c):
        pos = (int(x * CELL_SIZE + CELL_SIZE / 2),
               int(y * CELL_SIZE + CELL_SIZE / 2))
        # pygame.draw.rect(screen, colors[c], pygame.Rect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE-1, CELL_SIZE-1))
        # pygame.draw.circle(screen, colors[c], pos, CELL_SIZE, CELL_SIZE) #Weird form, can also be used instead of rectangles
        pygame.draw.circle(self.screen, colors[c], pos, 5, 0)

    # Updating the cells in the current generation.
    def update_gen(self):
        global current_generation
        for y in range(Y_CELLS):
            for x in range(X_CELLS):
                c = next_generation[x][y]
                self.draw_cell(x, y, c)
        current_generation = list(next_generation)

    # Activate a living cell.
    def activate_living_cell(self, x, y):
        global next_generation
        next_generation[x][y] = COLOR_ALIVE

    # Deactivate a living cell.
    def deactivate_living_cell(self, x, y):
        global next_generation
        next_generation[x][y] = COLOR_DEAD

    # Function to check neighbor cells.
    def check_cells(self, x, y):
        # Check the edges.
        if (x < 0) or (y < 0):
            return 0
        if (x >= X_CELLS) or (y >= Y_CELLS):
            return 0
        if current_generation[x][y] == COLOR_ALIVE:
            return 1
        else:
            return 0

    def check_cell_neighbors(self, row_index, col_index):
        # Get the number of alive cells surrounding the current cell.
        num_alive_neighbors = 0
        num_alive_neighbors += self.check_cells(row_index - 1, col_index - 1)
        num_alive_neighbors += self.check_cells(row_index - 1, col_index)
        num_alive_neighbors += self.check_cells(row_index - 1, col_index + 1)
        num_alive_neighbors += self.check_cells(row_index, col_index - 1)
        num_alive_neighbors += self.check_cells(row_index, col_index + 1)
        num_alive_neighbors += self.check_cells(row_index + 1, col_index - 1)
        num_alive_neighbors += self.check_cells(row_index + 1, col_index)
        num_alive_neighbors += self.check_cells(row_index + 1, col_index + 1)
        return num_alive_neighbors

    # Rules:
    # 1 Any live cell with fewer than two live neighbors dies, as if by underpopulation.
    # 2 Any live cell with two or three live neighbors lives on to the next generation.
    # 3 Any live cell with more than three live neighbors dies, as if by overpopulation.
    # 4 Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
    def create_next_gen(self):
        for y in range(Y_CELLS):
            for x in range(X_CELLS):
                n = self.check_cell_neighbors(x, y)  # Number of neighbors.
                c = current_generation[x][y]  # Current cell (either dead or alive).
                if c == COLOR_ALIVE:
                    if (n < 2):  # Rule number 1.
                        next_generation[x][y] = COLOR_DEAD
                    elif (n > 3):  # Rule number 3.
                        next_generation[x][y] = COLOR_DEAD
                    else:  # Rule number 2.
                        next_generation[x][y] = COLOR_ALIVE
                elif c == COLOR_DEAD:
                    if (n == 3):  # Rule number 4.
                        next_generation[x][y] = COLOR_ALIVE
                    else:
                        next_generation[x][y] = COLOR_DEAD
#Problem: first counting, then next iteration.

    # Defines button and mouse clicks.
    def handle_events(self):
        for event in pygame.event.get():
            # Turns the mouse position into a position in the grid.
            posn = pygame.mouse.get_pos()
            x = int(posn[0] / CELL_SIZE)
            y = int(posn[1] / CELL_SIZE)
            # Pressing quit --> quit the game.
            if event.type == pygame.QUIT:
                self.game_over = True
            # Pressing the left mouse button to activate or deactivate a cell.
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    if next_generation[x][y] == COLOR_DEAD:
                        self.activate_living_cell(x, y)
                    else:
                        self.deactivate_living_cell(x, y)
            # Keeping the right mouse button pressed activates drawing mode.
            if event.type == pygame.MOUSEMOTION and event.buttons[2]:
                self.activate_living_cell(x, y)

            # Define the keyboard key presses for q, space, a, s, r.
            if event.type == pygame.KEYDOWN:
                # Quit the game.
                if event.unicode == 'q':
                    self.game_over = True
                    print("q")
                # Next iteration - manually.
                elif event.key == pygame.K_SPACE:
                    self.create_next_gen()
                    print("keypress")
                # Next iteration - automated.
                elif event.unicode == 'a':  # a to automate the iterations.
                    self.next_iteration = True
                    print("a")
                # Stop the automated iterations.
                elif event.unicode == 's':
                    self.next_iteration = False
                    print("s")
                # Empty the grid.
                elif event.unicode == 'r':
                    self.next_iteration = False
                    self.init_gen(next_generation, COLOR_DEAD)
                    print("r")

    # Runs the game loop
    def run(self):
        while not self.game_over:
            self.handle_events()
            if self.next_iteration:
                self.create_next_gen()
            self.update_gen()
            pygame.display.flip()
            self.fps_clock.tick(FPS_MAX)
            self.root.update()

if __name__ == "__main__":
    GAME = GameOfLife()
    GAME.run()

Body:
You've to deep copy next_generation to current_generation. But

current_generation = list(next_generation)

doesn't do what you expect it to do, since the elements of next_generation are a list, too.

To deep copy a list of where each element is a list of numbers (objects won't be copied) you've to:

current_generation = [list(e) for e in next_generation]

or

current_generation = [[i for i in j] for j in next_generation]

or

current_generation = [e[:] for e in next_generation]

Since there is a nested loop in the method GameOfLife.update_gen, the issue can be solved by an simple assignment, too:

class GameOfLife:

    # [...]

    # Updating the cells in the current generation.
    def update_gen(self):
        global current_generation
        for y in range(Y_CELLS):
            for x in range(X_CELLS):
                c = next_generation[x][y]
                self.draw_cell(x, y, c)
                current_generation[x][y] = next_generation[x][y] # assign element by element

There is a further issue, when the animation is running and the game is manipulated by the mouse. When the mouse is pressed, then next_generation is changed by either .activate_living_cell or .deactivate_living_cell.

But after that next_generation is recalculated by the data in current_generation.

while not self.game_over:
     self.handle_events()       # change "next_generation" by click
     if self.next_iteration:
         self.create_next_gen() # compute "next_generation" from "current_generation"
     self.update_gen()          # copy "current_generation" from "next_generation"

The issue can be solved with ease. Consider that when the game is manipulated by the mouse, the content of current_generation and next_generation is equal.

Either change current_generation instead of next_generation or update current_generation after the manipulation:

def handle_events(self):
    for event in pygame.event.get():

        # [...]

        # Pressing the left mouse button to activate or deactivate a cell.
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                if next_generation[x][y] == COLOR_DEAD:
                    self.activate_living_cell(x, y)
                else:
                   self.deactivate_living_cell(x, y)
                self.update_gen() # <----------------------------


来源: stackexchange

问:
How to stop programme from reading if -1 is entered, and calculate average accordingly
I'm a beginner in C, and my task is to:
Write a program that reads in an array of up to 10 integers representing peoples ages in years and calculates and prints the maximum age and the minimum age and the average age. Your program should stop reading when either the 10th number is entered or the user enters -1. If the user enters any other negative number or a value above 150, they should be warned and prompted again for a valid age.

My code can find the maximum and minimum numbers and calculate the average, as well as ensuring the value is between 0 to 150. However I can't get the programme to stop if -1 is entered. My average, minimum, and maximum also just consider that 10 values are entered, so I need help in counting the amount of values entered by the user before (/if) -1 is entered, so they can be accurate.

```<code>int ages[10];
int i, j;
double sum=0;

for (i=0; i<10; i++){
    printf("Enter number %d: ",i+1);
    scanf("%d", &ages[i]);
    if (ages[i]<-2 || ages[i]>150){
        printf("Invalid number, enter again: ");
            scanf("%d",&ages[i]);
        while (ages[i]==-1){
            break;
        }
    }
}

for (i=0; i<10; i++){
    sum=sum+ages[i];
}
printf("Average: %f \n", (sum/10));
int min=ages[0];
int max=ages[0];

for (j=0; j<10;j++){
    if (ages[j]>max){
       max=ages[j];
    }
    else if (ages[j]<min){
        min=ages[j];
    }
}
printf("Minimum: %d. Maximum: %d. \n", min, max);
</code>```

答:
Work from the outside in.  The condition of your main loop is “while i is less than 10 and ages[i] is not -1”.  That suggests the following structure:

```<code>i = 0;
do
{
  // enter data
} while ( ages[i++] != -1 && i < 10 );
</code>```

This will loop while the last entered age is not -1 and less than 10 entries have been accepted. When this loop exits, i will be the number of entries in ages.  For example, if you enter -1 for the third input, i will be 3.  If you didn't enter -1 for any inputs, i will be 10.  Then your averaging operation will be

```<code>for ( int j = 0; j < i; j++ )
  // sum up ages
// divide ages by i
</code>```

For reading input, you can use another do/while loop:

```<code>do
{
  printf( "Enter a number between 0 and 150, or -1 to quit: " )
  scanf( "%d", &ages[i] )
} while ( ages[i] < -1 || ages[i] > 150 );
</code>```

Putting that together, you get

```<code>int i = 0;
do
{
  do
  {
    printf( "Enter a number between 0 and 150, or -1 to quit: " );
    scanf( "%d", &ages[i] );
  } while ( ages[i] < -1 || ages[i] > 150 );
} while ( ages[i++] != -1 && i < 10 );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm a beginner in C, and my task is to:
Write a program that reads in an array of up to 10 integers representing peoples ages in years and calculates and prints the maximum age and the minimum age and the average age. Your program should stop reading when either the 10th number is entered or the user enters -1. If the user enters any other negative number or a value above 150, they should be warned and prompted again for a valid age.

My code can find the maximum and minimum numbers and calculate the average, as well as ensuring the value is between 0 to 150. However I can't get the programme to stop if -1 is entered. My average, minimum, and maximum also just consider that 10 values are entered, so I need help in counting the amount of values entered by the user before (/if) -1 is entered, so they can be accurate.

int ages[10];
int i, j;
double sum=0;

for (i=0; i<10; i++){
    printf("Enter number %d: ",i+1);
    scanf("%d", &ages[i]);
    if (ages[i]<-2 || ages[i]>150){
        printf("Invalid number, enter again: ");
            scanf("%d",&ages[i]);
        while (ages[i]==-1){
            break;
        }
    }
}

for (i=0; i<10; i++){
    sum=sum+ages[i];
}
printf("Average: %f \n", (sum/10));
int min=ages[0];
int max=ages[0];

for (j=0; j<10;j++){
    if (ages[j]>max){
       max=ages[j];
    }
    else if (ages[j]<min){
        min=ages[j];
    }
}
printf("Minimum: %d. Maximum: %d. \n", min, max);

Body:
Work from the outside in.  The condition of your main loop is “while i is less than 10 and ages[i] is not -1”.  That suggests the following structure:

i = 0;
do
{
  // enter data
} while ( ages[i++] != -1 && i < 10 );

This will loop while the last entered age is not -1 and less than 10 entries have been accepted. When this loop exits, i will be the number of entries in ages.  For example, if you enter -1 for the third input, i will be 3.  If you didn't enter -1 for any inputs, i will be 10.  Then your averaging operation will be

for ( int j = 0; j < i; j++ )
  // sum up ages
// divide ages by i

For reading input, you can use another do/while loop:

do
{
  printf( "Enter a number between 0 and 150, or -1 to quit: " )
  scanf( "%d", &ages[i] )
} while ( ages[i] < -1 || ages[i] > 150 );

Putting that together, you get

int i = 0;
do
{
  do
  {
    printf( "Enter a number between 0 and 150, or -1 to quit: " );
    scanf( "%d", &ages[i] );
  } while ( ages[i] < -1 || ages[i] > 150 );
} while ( ages[i++] != -1 && i < 10 );


问:
Can not fetch repository from Google Cloud Storage
I have library hosted on Google Cloud storage. I am using Jenkins to deploy my application into GKE.

I am using CloudStorageMaven library (V1.0) to push project to GCS.

I am able to deploy my library project but, when I am trying to run test for microservice on Jenkins server, maven is not able to download my library.

I have tried making GCS bucket public but it did not make any difference.

Jenkinsfile

```<code>#!/usr/bin/env groovy
podTemplate(
    label: 'slavepod',
    containers: [
        containerTemplate (
            name: 'maven',
            image: 'maven:3.5.2-alpine',
            command: 'cat',
            ttyEnabled: true,
            resourceRequestCpu: '256m',
            resourceLimitCpu: '512m',
            resourceRequestMemory: '512Mi',
            resourceLimitMemory: '1024Mi'
        ),
        containerTemplate (
            name: 'docker',
            image: 'gcr.io/cloud-builders/docker',
            command: 'cat',
            ttyEnabled: true,
            resourceRequestCpu: '512m',
            resourceLimitCpu: '1024m',
            resourceRequestMemory: '512Mi',
            resourceLimitMemory: '1024Mi'
        ),
        containerTemplate (
            name: 'kubectl',
            image: 'gcr.io/cloud-builders/kubectl',
            command: 'cat',
            ttyEnabled: true,
            resourceRequestCpu: '512m',
            resourceLimitCpu: '1024m',
            resourceRequestMemory: '512Mi',
            resourceLimitMemory: '1024Mi'
        ),
        containerTemplate (
            name: 'gcloud',
            image: 'gcr.io/cloud-builders/gcloud',
            command: 'cat',
            ttyEnabled: true,
            resourceRequestCpu: '512m',
            resourceLimitCpu: '1024m',
            resourceRequestMemory: '512Mi',
            resourceLimitMemory: '1024Mi'
        )
    ],
    volumes: [
        hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock'),
        persistentVolumeClaim(claimName: 'maven-repo', mountPath: '/home/jenkins/.m2')
    ]
)
{
    node('slavepod') {

        stage('Clone repository') {
            checkout scm

        }

        stage('Unit Test') {
          container('maven') {
              echo 'Running Maven tests'
              sh("mvn -Dmaven.repo.local=/home/jenkins/.m2/ test")
          }
      }

} // end of pipeline

</code>```

I have extension and repository configured in pom.xml

```<code><build>
....

<extensions>
    <extension>
        <groupId>com.gkatzioura.maven.cloud</groupId>
        <artifactId>google-storage-wagon</artifactId>
        <version>1.0</version>
    </extension>
</extensions>
</build>

<repositories>
    <repository>
        <id>ca.performance.common</id>
        <url>gs://performance-repository</url>
    </repository>
</repositories>
</code>```

Error I am getting in Jenkins pipeline console is as below:

```<code>Downloading from ca.performance.common: gs://url/to/repository/jar-1.0.0.pom
[ERROR] Could not establish connection with google cloud
com.google.cloud.storage.StorageException: Insufficient Permission
    at com.google.cloud.storage.spi.v1.HttpStorageRpc.translate (HttpStorageRpc.java:219)
    at com.google.cloud.storage.spi.v1.HttpStorageRpc.list (HttpStorageRpc.java:314)
    at com.google.cloud.storage.StorageImpl$6.call (StorageImpl.java:272)
    at com.google.cloud.storage.StorageImpl$6.call (StorageImpl.java:269)
    at com.google.api.gax.retrying.DirectRetryingExecutor.submit (DirectRetryingExecutor.java:89)
    at com.google.cloud.RetryHelper.run (RetryHelper.java:74)
    at com.google.cloud.RetryHelper.runWithRetries (RetryHelper.java:51)
    at com.google.cloud.storage.StorageImpl.listBuckets (StorageImpl.java:268)
    at com.google.cloud.storage.StorageImpl.list (StorageImpl.java:257)
    at com.gkatzioura.maven.cloud.gcs.GoogleStorageRepository.connect (GoogleStorageRepository.java:55)
    at com.gkatzioura.maven.cloud.gcs.GoogleStorageWagon.connect (GoogleStorageWagon.java:135)
    at org.eclipse.aether.transport.wagon.WagonTransporter.connectWagon (WagonTransporter.java:342)
    at org.eclipse.aether.transport.wagon.WagonTransporter.pollWagon (WagonTransporter.java:382)
    at org.eclipse.aether.transport.wagon.WagonTransporter.execute (WagonTransporter.java:431)
    at org.eclipse.aether.transport.wagon.WagonTransporter.get (WagonTransporter.java:412)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector$GetTaskRunner.runTask (BasicRepositoryConnector.java:453)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector$TaskRunner.run (BasicRepositoryConnector.java:360)
    at org.eclipse.aether.util.concurrency.RunnableErrorForwarder$1.run (RunnableErrorForwarder.java:75)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector$DirectExecutor.execute (BasicRepositoryConnector.java:583)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector.get (BasicRepositoryConnector.java:259)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads (DefaultArtifactResolver.java:498)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve (DefaultArtifactResolver.java:399)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts (DefaultArtifactResolver.java:224)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifact (DefaultArtifactResolver.java:201)
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom (DefaultArtifactDescriptorReader.java:261)
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.readArtifactDescriptor (DefaultArtifactDescriptorReader.java:192)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.resolveCachedArtifactDescriptor (DefaultDependencyCollector.java:539)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.getArtifactDescriptorResult (DefaultDependencyCollector.java:522)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency (DefaultDependencyCollector.java:411)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency (DefaultDependencyCollector.java:365)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.process (DefaultDependencyCollector.java:353)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.collectDependencies (DefaultDependencyCollector.java:256)
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.collectDependencies (DefaultRepositorySystem.java:282)
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve (DefaultProjectDependenciesResolver.java:169)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies (LifecycleDependencyResolver.java:223)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies (LifecycleDependencyResolver.java:145)
    at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved (MojoExecutor.java:246)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:200)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:309)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:194)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:107)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:955)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:290)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:194)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Insufficient Permission",
    "reason" : "insufficientPermissions"
  } ],
  "message" : "Insufficient Permission"
}
</code>```

答:
Ensure that you follow the instructions in the full guide from the CloudStorageMaven link you posted?

As the official docs states, you need to grant sufficient permissions to specific users, or allow public (allUsers) readability at bucket-level to make all objects in that given bucket accessible to specified users or allUsers.

The error code from your attempt points to access permission issues:

```<code>{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Insufficient Permission",
    "reason" : "insufficientPermissions"
  } ],
  "message" : "Insufficient Permission"
}
</code>```

If you haven't already tried it, you could grant the allUsers access at the bucket-level by running:

```<code>$ gsutil iam ch allUsers:objectViewer gs://[BUCKET_NAME]
</code>```

However, keeping with best practices, I would recommend granting granular access at the bucket-level for only the user accounts or service accounts you wish to have read/write access to the objects within a given bucket. You can read more about how to do that here.

If the problem persists then the "Insufficient Permissions" issue is with the GKE cluster. Check what Storage permissions your cluster has like so:

From the Cloud Console --> Click on Kubernets Engine

Click on the 'Cluster Name' ---> Find 'Storage' under Permissions section.

If you only have 'Read Only' then you'll need to recreate your cluster like so:

Click Create a new cluster (as you defined before)

Find 'Node pools' then click 'Advanced Edit'

Select 'read write' from dropdown list on Storage

Create the new cluster for your project

Deploy your project to the new cluster and try it again.

Body:
I have library hosted on Google Cloud storage. I am using Jenkins to deploy my application into GKE.

I am using CloudStorageMaven library (V1.0) to push project to GCS.

I am able to deploy my library project but, when I am trying to run test for microservice on Jenkins server, maven is not able to download my library.

I have tried making GCS bucket public but it did not make any difference.

Jenkinsfile

#!/usr/bin/env groovy
podTemplate(
    label: 'slavepod',
    containers: [
        containerTemplate (
            name: 'maven',
            image: 'maven:3.5.2-alpine',
            command: 'cat',
            ttyEnabled: true,
            resourceRequestCpu: '256m',
            resourceLimitCpu: '512m',
            resourceRequestMemory: '512Mi',
            resourceLimitMemory: '1024Mi'
        ),
        containerTemplate (
            name: 'docker',
            image: 'gcr.io/cloud-builders/docker',
            command: 'cat',
            ttyEnabled: true,
            resourceRequestCpu: '512m',
            resourceLimitCpu: '1024m',
            resourceRequestMemory: '512Mi',
            resourceLimitMemory: '1024Mi'
        ),
        containerTemplate (
            name: 'kubectl',
            image: 'gcr.io/cloud-builders/kubectl',
            command: 'cat',
            ttyEnabled: true,
            resourceRequestCpu: '512m',
            resourceLimitCpu: '1024m',
            resourceRequestMemory: '512Mi',
            resourceLimitMemory: '1024Mi'
        ),
        containerTemplate (
            name: 'gcloud',
            image: 'gcr.io/cloud-builders/gcloud',
            command: 'cat',
            ttyEnabled: true,
            resourceRequestCpu: '512m',
            resourceLimitCpu: '1024m',
            resourceRequestMemory: '512Mi',
            resourceLimitMemory: '1024Mi'
        )
    ],
    volumes: [
        hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock'),
        persistentVolumeClaim(claimName: 'maven-repo', mountPath: '/home/jenkins/.m2')
    ]
)
{
    node('slavepod') {

        stage('Clone repository') {
            checkout scm

        }

        stage('Unit Test') {
          container('maven') {
              echo 'Running Maven tests'
              sh("mvn -Dmaven.repo.local=/home/jenkins/.m2/ test")
          }
      }

} // end of pipeline

I have extension and repository configured in pom.xml

<build>
....

<extensions>
    <extension>
        <groupId>com.gkatzioura.maven.cloud</groupId>
        <artifactId>google-storage-wagon</artifactId>
        <version>1.0</version>
    </extension>
</extensions>
</build>

<repositories>
    <repository>
        <id>ca.performance.common</id>
        <url>gs://performance-repository</url>
    </repository>
</repositories>

Error I am getting in Jenkins pipeline console is as below:

Downloading from ca.performance.common: gs://url/to/repository/jar-1.0.0.pom
[ERROR] Could not establish connection with google cloud
com.google.cloud.storage.StorageException: Insufficient Permission
    at com.google.cloud.storage.spi.v1.HttpStorageRpc.translate (HttpStorageRpc.java:219)
    at com.google.cloud.storage.spi.v1.HttpStorageRpc.list (HttpStorageRpc.java:314)
    at com.google.cloud.storage.StorageImpl$6.call (StorageImpl.java:272)
    at com.google.cloud.storage.StorageImpl$6.call (StorageImpl.java:269)
    at com.google.api.gax.retrying.DirectRetryingExecutor.submit (DirectRetryingExecutor.java:89)
    at com.google.cloud.RetryHelper.run (RetryHelper.java:74)
    at com.google.cloud.RetryHelper.runWithRetries (RetryHelper.java:51)
    at com.google.cloud.storage.StorageImpl.listBuckets (StorageImpl.java:268)
    at com.google.cloud.storage.StorageImpl.list (StorageImpl.java:257)
    at com.gkatzioura.maven.cloud.gcs.GoogleStorageRepository.connect (GoogleStorageRepository.java:55)
    at com.gkatzioura.maven.cloud.gcs.GoogleStorageWagon.connect (GoogleStorageWagon.java:135)
    at org.eclipse.aether.transport.wagon.WagonTransporter.connectWagon (WagonTransporter.java:342)
    at org.eclipse.aether.transport.wagon.WagonTransporter.pollWagon (WagonTransporter.java:382)
    at org.eclipse.aether.transport.wagon.WagonTransporter.execute (WagonTransporter.java:431)
    at org.eclipse.aether.transport.wagon.WagonTransporter.get (WagonTransporter.java:412)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector$GetTaskRunner.runTask (BasicRepositoryConnector.java:453)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector$TaskRunner.run (BasicRepositoryConnector.java:360)
    at org.eclipse.aether.util.concurrency.RunnableErrorForwarder$1.run (RunnableErrorForwarder.java:75)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector$DirectExecutor.execute (BasicRepositoryConnector.java:583)
    at org.eclipse.aether.connector.basic.BasicRepositoryConnector.get (BasicRepositoryConnector.java:259)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads (DefaultArtifactResolver.java:498)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve (DefaultArtifactResolver.java:399)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts (DefaultArtifactResolver.java:224)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifact (DefaultArtifactResolver.java:201)
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom (DefaultArtifactDescriptorReader.java:261)
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.readArtifactDescriptor (DefaultArtifactDescriptorReader.java:192)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.resolveCachedArtifactDescriptor (DefaultDependencyCollector.java:539)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.getArtifactDescriptorResult (DefaultDependencyCollector.java:522)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency (DefaultDependencyCollector.java:411)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency (DefaultDependencyCollector.java:365)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.process (DefaultDependencyCollector.java:353)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.collectDependencies (DefaultDependencyCollector.java:256)
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.collectDependencies (DefaultRepositorySystem.java:282)
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve (DefaultProjectDependenciesResolver.java:169)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies (LifecycleDependencyResolver.java:223)
    at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies (LifecycleDependencyResolver.java:145)
    at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved (MojoExecutor.java:246)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:200)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:309)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:194)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:107)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:955)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:290)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:194)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Insufficient Permission",
    "reason" : "insufficientPermissions"
  } ],
  "message" : "Insufficient Permission"
}

Body:
Ensure that you follow the instructions in the full guide from the CloudStorageMaven link you posted?

As the official docs states, you need to grant sufficient permissions to specific users, or allow public (allUsers) readability at bucket-level to make all objects in that given bucket accessible to specified users or allUsers.

The error code from your attempt points to access permission issues:

{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Insufficient Permission",
    "reason" : "insufficientPermissions"
  } ],
  "message" : "Insufficient Permission"
}

If you haven't already tried it, you could grant the allUsers access at the bucket-level by running:

$ gsutil iam ch allUsers:objectViewer gs://[BUCKET_NAME]

However, keeping with best practices, I would recommend granting granular access at the bucket-level for only the user accounts or service accounts you wish to have read/write access to the objects within a given bucket. You can read more about how to do that here.

If the problem persists then the "Insufficient Permissions" issue is with the GKE cluster. Check what Storage permissions your cluster has like so:

From the Cloud Console --> Click on Kubernets Engine

Click on the 'Cluster Name' ---> Find 'Storage' under Permissions section.

If you only have 'Read Only' then you'll need to recreate your cluster like so:

Click Create a new cluster (as you defined before)

Find 'Node pools' then click 'Advanced Edit'

Select 'read write' from dropdown list on Storage

Create the new cluster for your project

Deploy your project to the new cluster and try it again.


问:
Add-Type doesn't work on first run of a PowerShell script
I'm working on a powershell script which interacts with a local SQL Server 2016 database instance.  When I open the script in ISE and run it, it fails with an error: "verify that the assembly containing this type is loaded".  If I run it again immediately after, it works.

I'm currently loading the code like:

Add-Type -AssemblyName "Microsoft.SqlServer.Smo, Version=14.0.0.0, Culture=neutral, PublicKeyToken89845dcd8080cc91"

but I've previously tried

[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") and got the same results.

I have also tried adding:

start-sleep -s 120

in case this was just an issue related to timing, but this has no effect.

I would expect that the assemblies would be loaded within a couple of seconds and then be immediately available. In addition to the "verify that the assembly containing this type is loaded" I'm also getting NullReferenceExceptions on the objects created from the missing assemblies.

答:
I finally found the answer. The correct and recommended way to load the SMO assemblies is to import the SqlServer module:

```<code>Import-Module SqlServer
</code>```

This is included in this Microsoft article

Body:
I finally found the answer. The correct and recommended way to load the SMO assemblies is to import the SqlServer module:

Import-Module SqlServer

This is included in this Microsoft article


问:
How to generate a shuffled number series query with id in postgresql?
I would like to generate unique 'random' numbers in posgresql.

```<code>select s
from generate_series(1, 5) as s
order by random();
</code>```

This query results the following:

```<code>| s |
|---|
| 2 |
| 5 |
| 1 |
| 3 |
| 4 |
</code>```

But I would like to append it with an id, like this:

```<code>| id | s |
|----|---|
|  1 | 2 |
|  2 | 5 |
|  3 | 1 |
|  4 | 3 |
|  5 | 4 |
</code>```

答:
You can use the ROW_NUMBER Function.</p>

```<code>SELECT
ROW_NUMBER () OVER (ORDER BY random()) AS id,
s
FROM generate_series(1, 5) AS s;
</code>```

Body:
I would like to generate unique 'random' numbers in posgresql.

select s
from generate_series(1, 5) as s
order by random();

This query results the following:

| s |
|---|
| 2 |
| 5 |
| 1 |
| 3 |
| 4 |

But I would like to append it with an id, like this:

| id | s |
|----|---|
|  1 | 2 |
|  2 | 5 |
|  3 | 1 |
|  4 | 3 |
|  5 | 4 |

Body:
You can use the ROW_NUMBER Function.

SELECT
ROW_NUMBER () OVER (ORDER BY random()) AS id,
s
FROM generate_series(1, 5) AS s;


问:
flutter: File download from server
I am downloading file from server but I don't know what happened so, kindly tell me how to solve this issue?

```<code>await Dio().post("https://test.blockchainhuissieray.com/api/download_file.php", data: {
          "jwt" : token,
          "fileID" : id,
          "directory" : widget.folderName
        },
            options: Options(
                contentType: ContentType.parse("application/json")
            )).then((res) => res.data).then((data) async{
              var intList = data.toString().codeUnits;
              print('File : $intList');
              print(data);
              var filePath = await ImagePickerSaver.saveFile(fileData: Uint8List.fromList(intList));
              print(filePath);
              var savedFile = File.fromUri(Uri.file(filePath));
              setState(() {
                _imageFile = Future<File>.sync(() => savedFile);
                images.add(File(data));
                imagel = File(data);
              });
        }).catchError((err){print(err);});

      print(images);
      setState(() {
        showDialog(
            context: context,
            builder: (context){
              return AlertDialog(
                content: Center(
                  child: Image.file(imagel,
                  fit: BoxFit.cover,),
                ),
              );
            }
        );
      });
</code>```

I/flutter ( 6918): File : [65533, 65533, 65533, 65533, 2, 118, 69, 120, 105, 102, 0, 0, 77, 77, 0, 42, 0, 0, 0, 8, 0, 8, 1, 16, 0, 2, 0, 0, 0, 26, 0, 0, 0, 110, 1, 0, 0, 4, 0, 0, 0, 1, 0, 0, 3, 65533, 1, 1, 0, 4, 0, 0, 0, 1, 0, 0, 5, 0, 1, 50, 0, 2, 0, 0, 0, 20, 0, 0, 0, 65533, 1, 18, 0, 3, 0, 0, 0, 1, 0, 1, 0, 0, 65533, 105, 0, 4, 0, 0, 0, 1, 0, 0, 0, 65533, 65533, 37, 0, 4, 0, 0, 0, 1, 0, 0, 1, 65533, 1, 15, 0, 2, 0, 0, 0, 7, 0, 0, 0, 65533, 0, 0, 0, 0, 65, 110, 100, 114, 111, 105, 100, 32, 83, 68, 75, 32, 98, 117, 105, 108, 116, 32, 102, 111, 114, 32, 120, 56, 54, 0, 50, 48, 49, 57, 58, 48, 53, 58, 49, 55, 32, 49, 48, 58, 52, 54, 58, 48, 53, 0, 71, 111, 111, 103, 108, 101, 0, 0, 16, 65533, 65533, 0, 5, 0, 0, 0, 1, 0, 0, 1, 105, 65533, 65533, 0, 5, 0, 0, 0, 1, 0, 0, 1, 113, 65533, 65533, 0, 2, 0, 0, 0, 4, 52, 50, 54, 0, 65533, 65533, 0, 2, 0, 0, 0, 4, 52, 50, 54, 0, 65533, 65533, 0, 2, 0, 0, 0, 4, 52, 50, 54, 0, 65533, 10, 0, 5, 0, 0, 0, 1, 0, 0, 1, 121, 65533, 9, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 65533, 39, 0, 3, 0, 0, 0, 1, 0,
I/flutter ( 6918): ����vExif
V/MediaStore( 6918): Create the thumbnail in memory: origId=266, kind=1, isVideo=false
D/skia    ( 6918): --- Failed to create image decoder with message 'unimplemented'
I/chatty  ( 6918): uid=10087(io.hexasoft.bch) identical 1 line
D/skia    ( 6918): --- Failed to create image decoder with message 'unimplemented'
I/flutter ( 6918): saved filePath:
I/flutter ( 6918):
I/flutter ( 6918): [File: '����vExif

答: You may want to use the path_provider package instead of the ImagePicker plugin. Then write those raw bytes to a file in the temporary directory. Use the file path you generated from there and display the image that way. Or, if you don't need to save the image to the local storage you could display the image with the raw bytearray by using Image.memory instead of Image.file

Title: flutter: File download from server

Body:
I am downloading file from server but I don't know what happened so, kindly tell me how to solve this issue?

await Dio().post("https://test.blockchainhuissieray.com/api/download_file.php", data: {
          "jwt" : token,
          "fileID" : id,
          "directory" : widget.folderName
        },
            options: Options(
                contentType: ContentType.parse("application/json")
            )).then((res) => res.data).then((data) async{
              var intList = data.toString().codeUnits;
              print('File : $intList');
              print(data);
              var filePath = await ImagePickerSaver.saveFile(fileData: Uint8List.fromList(intList));
              print(filePath);
              var savedFile = File.fromUri(Uri.file(filePath));
              setState(() {
                _imageFile = Future<File>.sync(() => savedFile);
                images.add(File(data));
                imagel = File(data);
              });
        }).catchError((err){print(err);});

      print(images);
      setState(() {
        showDialog(
            context: context,
            builder: (context){
              return AlertDialog(
                content: Center(
                  child: Image.file(imagel,
                  fit: BoxFit.cover,),
                ),
              );
            }
        );
      });

I/flutter ( 6918): File : [65533, 65533, 65533, 65533, 2, 118, 69, 120, 105, 102, 0, 0, 77, 77, 0, 42, 0, 0, 0, 8, 0, 8, 1, 16, 0, 2, 0, 0, 0, 26, 0, 0, 0, 110, 1, 0, 0, 4, 0, 0, 0, 1, 0, 0, 3, 65533, 1, 1, 0, 4, 0, 0, 0, 1, 0, 0, 5, 0, 1, 50, 0, 2, 0, 0, 0, 20, 0, 0, 0, 65533, 1, 18, 0, 3, 0, 0, 0, 1, 0, 1, 0, 0, 65533, 105, 0, 4, 0, 0, 0, 1, 0, 0, 0, 65533, 65533, 37, 0, 4, 0, 0, 0, 1, 0, 0, 1, 65533, 1, 15, 0, 2, 0, 0, 0, 7, 0, 0, 0, 65533, 0, 0, 0, 0, 65, 110, 100, 114, 111, 105, 100, 32, 83, 68, 75, 32, 98, 117, 105, 108, 116, 32, 102, 111, 114, 32, 120, 56, 54, 0, 50, 48, 49, 57, 58, 48, 53, 58, 49, 55, 32, 49, 48, 58, 52, 54, 58, 48, 53, 0, 71, 111, 111, 103, 108, 101, 0, 0, 16, 65533, 65533, 0, 5, 0, 0, 0, 1, 0, 0, 1, 105, 65533, 65533, 0, 5, 0, 0, 0, 1, 0, 0, 1, 113, 65533, 65533, 0, 2, 0, 0, 0, 4, 52, 50, 54, 0, 65533, 65533, 0, 2, 0, 0, 0, 4, 52, 50, 54, 0, 65533, 65533, 0, 2, 0, 0, 0, 4, 52, 50, 54, 0, 65533, 10, 0, 5, 0, 0, 0, 1, 0, 0, 1, 121, 65533, 9, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 65533, 39, 0, 3, 0, 0, 0, 1, 0,
I/flutter ( 6918): ����vExif
V/MediaStore( 6918): Create the thumbnail in memory: origId=266, kind=1, isVideo=false
D/skia    ( 6918): --- Failed to create image decoder with message 'unimplemented'
I/chatty  ( 6918): uid=10087(io.hexasoft.bch) identical 1 line
D/skia    ( 6918): --- Failed to create image decoder with message 'unimplemented'
I/flutter ( 6918): saved filePath:
I/flutter ( 6918):
I/flutter ( 6918): [File: '����vExif


问:
bigquery backup all view definitions
I am working with bigquery, and there have been a few hundred views created.  Most of these are not used and should be deleted. However, there is a chance that some are used and I cannot just blindly delete all.  Therefore, I need to backup all view definitions somehow before deleting them.

Does anyone know of a good way? I am not trying to save the data, just the view definition queries and their names.

Thanks for reading!

答: You could try using bqup, which is a python script that some colleagues and I have been using to regularly back up BigQuery views and table schemata.</p>

ContentLicense: CC BY-SA 3.0

Title: bigquery backup all view definitions


问:
Run Destroy-Time Provisioner before local_file is deleted
I have a Terraform script which creates a config.json file and then runs a command that uses that config.json:

```<code>resource "local_file" "config" {
  # Output vars to config
  filename = "config.json"
  content  = "..."

  # Deploy using config
  provisioner "local-exec" {
    command     = "deploy"
  }
}
</code>```

This all works great, but when I run terraform destroy I'd like to run a different command - I tried to do this with a destroy-time provisioner in a null_resource by adding the following:

```<code>resource "null_resource" "test" {
    provisioner "local-exec" {
        when        = "destroy"
        command     = "delete"
    }
}
</code>```

The script is run, but it runs after the config file is deleted - it errors, because it needs that config file to exist for it to know what to delete.

How would I fix this?

Thanks!

答:
I moved the destroy time provisioner into the original resource, and it worked great:</p>

```<code>resource "local_file" "config" {
  # Output vars to config
  filename = "config.json"
  content  = "..."

  # Deploy using config
  provisioner "local-exec" {
    command     = "deploy"
  }

  # Delete on_destroy
  provisioner "local-exec" {
        when        = "destroy"
        command     = "delete"
  }
}
</code>```

Body:
I have a Terraform script which creates a config.json file and then runs a command that uses that config.json:

resource "local_file" "config" {
  # Output vars to config
  filename = "config.json"
  content  = "..."

  # Deploy using config
  provisioner "local-exec" {
    command     = "deploy"
  }
}

This all works great, but when I run terraform destroy I'd like to run a different command - I tried to do this with a destroy-time provisioner in a null_resource by adding the following:

resource "null_resource" "test" {
    provisioner "local-exec" {
        when        = "destroy"
        command     = "delete"
    }
}

The script is run, but it runs after the config file is deleted - it errors, because it needs that config file to exist for it to know what to delete.

How would I fix this?

Thanks!

Body:
I moved the destroy time provisioner into the original resource, and it worked great:

resource "local_file" "config" {
  # Output vars to config
  filename = "config.json"
  content  = "..."

  # Deploy using config
  provisioner "local-exec" {
    command     = "deploy"
  }

  # Delete on_destroy
  provisioner "local-exec" {
        when        = "destroy"
        command     = "delete"
  }
}


问:
Difference between two lists
I Have two generic list filled with CustomsObjects.

I need to retrieve the difference between those two lists(Items who are in the first without the items in the second one)  in a third one.

I was thinking using .Except() was a good idea but I don't see how to use this..
Help!

答:
```<code>var third = first.Except(second);
</code>```

(you can also call ToList() after Except(), if you don't like referencing lazy collections.)

The Except() method compares the values using the default comparer, if the values being compared are of base data types, such as int, string, decimal etc.

Otherwise the comparison will be made by object address, which is probably not what you want... In that case, make your custom objects implement IComparable (or implement a custom IEqualityComparer and pass it to the Except() method).

Title: Difference between two lists

Body:
var third = first.Except(second);

(you can also call ToList() after Except(), if you don't like referencing lazy collections.)

The Except() method compares the values using the default comparer, if the values being compared are of base data types, such as int, string, decimal etc.

Otherwise the comparison will be made by object address, which is probably not what you want... In that case, make your custom objects implement IComparable (or implement a custom IEqualityComparer and pass it to the Except() method).


问:
Select file to delete. To delete,type file No<space>file No. example 3 1
need to delete multiple files in an array can't figure out how

```<code>Console.WriteLine("Select file to delete To delete,type file No<space>file No. example 3 1");
string bye = Console.ReadLine();
foreach(FileInfo f in fiArr)
    {
        File.Delete(f.FullName);
    }
</code>```

this code will delete all files in the array i need it to only delete selected files in the array

答:
One way to do this would be to convert the user input into an array of integers, and then for each integer they entered, delete that item from our file array using the integer index.

I've subtracted 1 from each index entered by the user, because arrays are zero-based. So if the user enters 1 to delete the first item, we want to delete the item at index 0.

Note that since it appears you have an array of FileInfo objects, I'm calling the Delete() method on the object itself:

```<code>int temp = 0;

// Convert input string to an integer array by splitting on the space character and
// using int.TryParse to convert the entry to an integer.
// Also, since arrays are zero-based, we subtract 1 from the input value.
// Finally, we only select integers that are valid indexes in our file array.
int[] indexesToDelete = bye
    .Split(' ')
    .Where(item => int.TryParse(item, out temp) && temp > 0 && temp <= fiArr.Length)
    .Select(x => temp - 1)
    .ToArray();

// For each index, call 'Delete' on that object
foreach(int index in indexesToDelete)
{
    fiArr[index].Delete();
}
</code>```

Body:
need to delete multiple files in an array can't figure out how

Console.WriteLine("Select file to delete To delete,type file No<space>file No. example 3 1");
string bye = Console.ReadLine();
foreach(FileInfo f in fiArr)
    {
        File.Delete(f.FullName);
    }

this code will delete all files in the array i need it to only delete selected files in the array

Body:
One way to do this would be to convert the user input into an array of integers, and then for each integer they entered, delete that item from our file array using the integer index.

I've subtracted 1 from each index entered by the user, because arrays are zero-based. So if the user enters 1 to delete the first item, we want to delete the item at index 0.

Note that since it appears you have an array of FileInfo objects, I'm calling the Delete() method on the object itself:

int temp = 0;

// Convert input string to an integer array by splitting on the space character and
// using int.TryParse to convert the entry to an integer.
// Also, since arrays are zero-based, we subtract 1 from the input value.
// Finally, we only select integers that are valid indexes in our file array.
int[] indexesToDelete = bye
    .Split(' ')
    .Where(item => int.TryParse(item, out temp) && temp > 0 && temp <= fiArr.Length)
    .Select(x => temp - 1)
    .ToArray();

// For each index, call 'Delete' on that object
foreach(int index in indexesToDelete)
{
    fiArr[index].Delete();
}


问:
how can i improve on my convnet performance with small dataset
I have a very small image data set (about 8 images). I am aware that my model can result in overfitting with a small dataset and I wanted some ideas on ways to deal with situations where the dataset is as small as stated above.</p>

答:
The best way to deal with this kind of issue is to use Image Augmentation. There are several libraries present which provides this like opencv2, keras, scikit-image. The basic idea behind image augmentation is to artificially create more images from one image by introducing certain changes in the data like rotating the image, blurring it at certain sides, zooming in/out on images, changing the coloring, flipping the image and a lot more. You can create 10x, 20x, 40x, etc images from one image.

This method will help you generate more images but remember that 8 images is a very small data and these new augmented images will in one way or another will have, to some extent, similar features to that of the original.


问:
Call multiple different charts in flutter - charts_flutter 0.5.0 Package
I have this Simple Bar chart from the package charts_flutter 0.5.0 and i want to call it in another page like this, or what my goal is, is to get more charts into it like pie charts and some other once.

```<code> Widget build(BuildContext context) {

    List<Series> seriesList;

    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: Text(
          "Charts",
          style: TextStyle(color: Colors.blueGrey),
          textAlign: TextAlign.center,
        ),
        backgroundColor: Colors.transparent,
        iconTheme: IconThemeData(color: Colors.blueGrey),
      ),
      body: ListView(
        children: <Widget>[
          SimpleBarChart(seriesList), //<-- I've added this line
        ],
      ),
    );
  }
</code>```

the code of the chart is this: find more here: https://google.github.io/charts/flutter/gallery.html

```<code>/// Bar chart example
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';

class SimpleBarChart extends StatelessWidget {
  final List<charts.Series> seriesList;
  final bool animate;

  SimpleBarChart(this.seriesList, {this.animate});

  /// Creates a [BarChart] with sample data and no transition.
  factory SimpleBarChart.withSampleData() {
    return new SimpleBarChart(
      _createSampleData(),
      // Disable animations for image tests.
      animate: false,
    );
  }

  @override
  Widget build(BuildContext context) {
    return new charts.BarChart(
      seriesList,
      animate: animate,
    );
  }

  /// Create one series with sample hard coded data.
  static List<charts.Series<OrdinalSales, String>> _createSampleData() {
    final data = [
      new OrdinalSales('2014', 5),
      new OrdinalSales('2015', 25),
      new OrdinalSales('2016', 100),
      new OrdinalSales('2017', 75),
    ];

    return [
      new charts.Series<OrdinalSales, String>(
        id: 'Sales',
        colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
        domainFn: (OrdinalSales sales, _) => sales.year,
        measureFn: (OrdinalSales sales, _) => sales.sales,
        data: data,
      )
    ];
  }
}

/// Sample ordinal data type.
class OrdinalSales {
  final String year;
  final int sales;

  OrdinalSales(this.year, this.sales);
}
</code>```

Currently I'm getting a white page, with this error

E/flutter (14450): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:

E/flutter (14450): Cannot hit test a render box that has never been laid out.

E/flutter (14450): The hitTest() method was called on this RenderBox:

E/flutter (14450):   RenderErrorBox#20cd4 NEEDS-LAYOUT NEEDS-PAINT

E/flutter (14450): Unfortunately, this object's geometry is not known at this time, probably because it has never been laid out. This means it cannot be accurately hit-tested. If you are trying to perform a hit test during the layout phase itself, make sure you only hit test nodes that have completed layout (e.g. the node's children, after their layout() method has been called).

this is the Package: https://pub.dartlang.org/packages/charts_flutter#-readme-tab-

答:
To get multiple charts in one screen you can achieve that with Flexible() Widget which is better than hardcode sizes (in my opinion). With flexible you define for example flex:5 on both and it will automatically divide the space equally to both charts</p>

```<code>  Column(
  children: [
    Flexible( flex: 5,
    child:
    Card(
      child:
        new charts.PieChart(
          seriesList,
          animate: animate,
            defaultRenderer: new charts.ArcRendererConfig(
                arcWidth: 30,
                arcRendererDecorators: [new charts.ArcLabelDecorator()])

        ),
    ),),
    Flexible(
      flex:5,
          child:
    Card(
      child:
      new charts.PieChart(
          seriesList,
          animate: animate,
          defaultRenderer: new charts.ArcRendererConfig(
              arcWidth: 30,
              arcRendererDecorators: [new charts.ArcLabelDecorator()])

      ),
    ),),
  ],
);
</code>```

Body:
I have this Simple Bar chart from the package charts_flutter 0.5.0 and i want to call it in another page like this, or what my goal is, is to get more charts into it like pie charts and some other once.

 Widget build(BuildContext context) {

    List<Series> seriesList;

    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: Text(
          "Charts",
          style: TextStyle(color: Colors.blueGrey),
          textAlign: TextAlign.center,
        ),
        backgroundColor: Colors.transparent,
        iconTheme: IconThemeData(color: Colors.blueGrey),
      ),
      body: ListView(
        children: <Widget>[
          SimpleBarChart(seriesList), //<-- I've added this line
        ],
      ),
    );
  }

the code of the chart is this: find more here: https://google.github.io/charts/flutter/gallery.html

/// Bar chart example
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';

class SimpleBarChart extends StatelessWidget {
  final List<charts.Series> seriesList;
  final bool animate;

  SimpleBarChart(this.seriesList, {this.animate});

  /// Creates a [BarChart] with sample data and no transition.
  factory SimpleBarChart.withSampleData() {
    return new SimpleBarChart(
      _createSampleData(),
      // Disable animations for image tests.
      animate: false,
    );
  }

  @override
  Widget build(BuildContext context) {
    return new charts.BarChart(
      seriesList,
      animate: animate,
    );
  }

  /// Create one series with sample hard coded data.
  static List<charts.Series<OrdinalSales, String>> _createSampleData() {
    final data = [
      new OrdinalSales('2014', 5),
      new OrdinalSales('2015', 25),
      new OrdinalSales('2016', 100),
      new OrdinalSales('2017', 75),
    ];

    return [
      new charts.Series<OrdinalSales, String>(
        id: 'Sales',
        colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
        domainFn: (OrdinalSales sales, _) => sales.year,
        measureFn: (OrdinalSales sales, _) => sales.sales,
        data: data,
      )
    ];
  }
}

/// Sample ordinal data type.
class OrdinalSales {
  final String year;
  final int sales;

  OrdinalSales(this.year, this.sales);
}

Currently I'm getting a white page, with this error

E/flutter (14450): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:

E/flutter (14450): Cannot hit test a render box that has never been laid out.

E/flutter (14450): The hitTest() method was called on this RenderBox:

E/flutter (14450):   RenderErrorBox#20cd4 NEEDS-LAYOUT NEEDS-PAINT

E/flutter (14450): Unfortunately, this object's geometry is not known at this time, probably because it has never been laid out. This means it cannot be accurately hit-tested. If you are trying to perform a hit test during the layout phase itself, make sure you only hit test nodes that have completed layout (e.g. the node's children, after their layout() method has been called).

this is the Package: https://pub.dartlang.org/packages/charts_flutter#-readme-tab-

Body:
To get multiple charts in one screen you can achieve that with Flexible() Widget which is better than hardcode sizes (in my opinion). With flexible you define for example flex:5 on both and it will automatically divide the space equally to both charts

  Column(
  children: [
    Flexible( flex: 5,
    child:
    Card(
      child:
        new charts.PieChart(
          seriesList,
          animate: animate,
            defaultRenderer: new charts.ArcRendererConfig(
                arcWidth: 30,
                arcRendererDecorators: [new charts.ArcLabelDecorator()])

        ),
    ),),
    Flexible(
      flex:5,
          child:
    Card(
      child:
      new charts.PieChart(
          seriesList,
          animate: animate,
          defaultRenderer: new charts.ArcRendererConfig(
              arcWidth: 30,
              arcRendererDecorators: [new charts.ArcLabelDecorator()])

      ),
    ),),
  ],
);


问:
customTokenIssuer Extension point on WSO2IS 5.7.0 not working as expected
I have deployed extension bundle in component/lib folder. WSO2IS still uses JWTTokenIssuer to generate the token. I don't see any error in extension bundle.

I have override OauthTokenIssuerImpl lets say customTokenIssuer to obtain custom created tokens. but when i debug the log, It is instantiating both customTokenIssuer and JWTTokenIssuer but framework do not use customTokenIssuer to generate token.

I have updated identity.xml with customTokenIssuer class.

Is it something I am missing in the POM or missing some entries in any of the XML ?

```<code>

[2019-05-23 10:53:59,900]  INFO {org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration} -  An instance of abc.xxx.xxx.xx.customTokenIssuer is created for Identity OAuth token generation.

..........

[2019-05-23 10:54:00,084] DEBUG {org.wso2.carbon.identity.oauth2.util.OAuth2Util} -  Added OAuthTokenReqMessageContext to threadlocal
[2019-05-23 10:54:00,086] DEBUG {org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer} -  JWT Access token builder is initiated
[2019-05-23 10:54:00,086]  INFO {org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration} -  An instance of org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer is created for Identity OAuth token generation.

...................

[2019-05-23 10:54:00,092] DEBUG {org.wso2.carbon.identity.oauth2.token.handlers.grant.AbstractAuthorizationGrantHandler} -  OAuth application id: XXxXXXXXXXXXXXXX, user access token validity time 3600000ms
[2019-05-23 10:54:00,092] DEBUG {org.wso2.carbon.identity.oauth2.token.handlers.grant.AbstractAuthorizationGrantHandler} -  OAuth application id : XXxXXXXXXXXXXXXX, access token validity time in milliseconds : 3600000
[2019-05-23 10:54:00,096] DEBUG {org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer} -  Access token request with token request message context. Authorized user XXxXX@carbon.super
[2019-05-23 10:54:00,096] DEBUG {org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer} -  User Access Token Life time set to : 3600000ms.
[2019-05-23 10:54:00,097] DEBUG {org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer} -  JWT Self Signed Access Token Life time set to : 3600000ms.
[2019-05-23 10:54:00,098] DEBUG {org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer} -  Scope exist for the jwt access token with subject XXxXX@carbon.super and the scope is openid
[2019-05-23 10:54:00,154] DEBUG {org.wso2.carbon.identity.oauth2.token.handlers.grant.AbstractAuthorizationGrantHandler} -  Existing access token has expired, but refresh token is still valid for client: XXxXXXXXXXXXXXXX. Remaining time: 17420133ms. Using existing refresh token.

</code>```

As per me only customTokenIssuer should be instantiated and used to generate the token.

答: Forgot to select token issuer in service provider, Once you deploy the custom token generator jar and update identity.xml file you have to select the Token issuer from the service provider.</p>

Body:
I have deployed extension bundle in component/lib folder. WSO2IS still uses JWTTokenIssuer to generate the token. I don't see any error in extension bundle.

I have override OauthTokenIssuerImpl lets say customTokenIssuer to obtain custom created tokens. but when i debug the log, It is instantiating both customTokenIssuer and JWTTokenIssuer but framework do not use customTokenIssuer to generate token.

I have updated identity.xml with customTokenIssuer class.

Is it something I am missing in the POM or missing some entries in any of the XML ?

[2019-05-23 10:53:59,900]  INFO {org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration} -  An instance of abc.xxx.xxx.xx.customTokenIssuer is created for Identity OAuth token generation.

..........

[2019-05-23 10:54:00,084] DEBUG {org.wso2.carbon.identity.oauth2.util.OAuth2Util} -  Added OAuthTokenReqMessageContext to threadlocal
[2019-05-23 10:54:00,086] DEBUG {org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer} -  JWT Access token builder is initiated
[2019-05-23 10:54:00,086]  INFO {org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration} -  An instance of org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer is created for Identity OAuth token generation.

...................

[2019-05-23 10:54:00,092] DEBUG {org.wso2.carbon.identity.oauth2.token.handlers.grant.AbstractAuthorizationGrantHandler} -  OAuth application id: XXxXXXXXXXXXXXXX, user access token validity time 3600000ms
[2019-05-23 10:54:00,092] DEBUG {org.wso2.carbon.identity.oauth2.token.handlers.grant.AbstractAuthorizationGrantHandler} -  OAuth application id : XXxXXXXXXXXXXXXX, access token validity time in milliseconds : 3600000
[2019-05-23 10:54:00,096] DEBUG {org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer} -  Access token request with token request message context. Authorized user XXxXX@carbon.super
[2019-05-23 10:54:00,096] DEBUG {org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer} -  User Access Token Life time set to : 3600000ms.
[2019-05-23 10:54:00,097] DEBUG {org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer} -  JWT Self Signed Access Token Life time set to : 3600000ms.
[2019-05-23 10:54:00,098] DEBUG {org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer} -  Scope exist for the jwt access token with subject XXxXX@carbon.super and the scope is openid
[2019-05-23 10:54:00,154] DEBUG {org.wso2.carbon.identity.oauth2.token.handlers.grant.AbstractAuthorizationGrantHandler} -  Existing access token has expired, but refresh token is still valid for client: XXxXXXXXXXXXXXXX. Remaining time: 17420133ms. Using existing refresh token.

As per me only customTokenIssuer should be instantiated and used to generate the token.


问:
YouTube embed showinfo has been deprecated
We are using a YouTube video on our website as a hero banner.

However few days ago it started showing it's title, watch later button and a share button. We were able to hide them using &showinfo=0 at the end if the URL.

I found out that showinfo has been deprecated and thus you can no longer hide the fact that it is a YouTube video showing there.

Is there any other parameter that might be able to do the same thing?

You cannot do it with CSS or JavaScript as it is an iframe.

Any ideas are much appreciated.

UPDATE:

Any layer or mask over the video doesn't help, as the info shows when the video is loading, or if you click outside the browser, the video will pause and the info shows.

Hiding the top ~60px works, but it is not a good solution for me.

Body:
<div id="schnitt">

<iframe width="500" height="280" src="https://www.youtube.com/embed/rlR4PJn8b8I?controls=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

</div>

<style>
#schnitt {
height:250px;
overflow:hidden;
}

iframe {
margin-top:-55px;
}


答:
Using Except is exactly the right way to go. If your type overrides Equals and GetHashCode, or you're only interested in reference type equality (i.e. two references are only "equal" if they refer to the exact same object), you can just use:

```<code>var list3 = list1.Except(list2).ToList();
</code>```

If you need to express a custom idea of equality, e.g. by ID, you'll need to implement IEqualityComparer<T>. For example:

```<code>public class IdComparer : IEqualityComparer<CustomObject>
{
    public int GetHashCode(CustomObject co)
    {
        if (co == null)
        {
            return 0;
        }
        return co.Id.GetHashCode();
    }

    public bool Equals(CustomObject x1, CustomObject x2)
    {
        if (object.ReferenceEquals(x1, x2))
        {
            return true;
        }
        if (object.ReferenceEquals(x1, null) ||
            object.ReferenceEquals(x2, null))
        {
            return false;
        }
        return x1.Id == x2.Id;
    }
}
</code>```

Then use:

```<code>var list3 = list1.Except(list2, new IdComparer()).ToList();
</code>```

Note that this will remove any duplicate elements. If you need duplicates to be preserved, it would probably be easiest to create a set from list2 and use something like:

```<code>var list3 = list1.Where(x => !set2.Contains(x)).ToList();
</code>```

Title: Difference between two lists

Body:
I Have two generic list filled with CustomsObjects.

I need to retrieve the difference between those two lists(Items who are in the first without the items in the second one)  in a third one.

I was thinking using .Except() was a good idea but I don't see how to use this..
Help!

Body:
Using Except is exactly the right way to go. If your type overrides Equals and GetHashCode, or you're only interested in reference type equality (i.e. two references are only "equal" if they refer to the exact same object), you can just use:

var list3 = list1.Except(list2).ToList();

If you need to express a custom idea of equality, e.g. by ID, you'll need to implement IEqualityComparer<T>. For example:

public class IdComparer : IEqualityComparer<CustomObject>
{
    public int GetHashCode(CustomObject co)
    {
        if (co == null)
        {
            return 0;
        }
        return co.Id.GetHashCode();
    }

    public bool Equals(CustomObject x1, CustomObject x2)
    {
        if (object.ReferenceEquals(x1, x2))
        {
            return true;
        }
        if (object.ReferenceEquals(x1, null) ||
            object.ReferenceEquals(x2, null))
        {
            return false;
        }
        return x1.Id == x2.Id;
    }
}

Then use:

var list3 = list1.Except(list2, new IdComparer()).ToList();

Note that this will remove any duplicate elements. If you need duplicates to be preserved, it would probably be easiest to create a set from list2 and use something like:

var list3 = list1.Where(x => !set2.Contains(x)).ToList();