问:
struggling to complete a tic tac toe game in python using ezgraphics
it's a simple tic tac toe game but there are 6 questions i need to answer so i can make the game options work and you will find the description of the questions commented in the code and called test Q1, test Q2 and so on

i finished question 2 and 4 but if you want to make any correction feel free to do so

question 1 is to add code to detect empty box
if the box already has a O or X in it
if there is no X or O, then return the box number found
but there is already O or X, then stay in the while loop
keep waiting for another mouse click

question 2 is to add code to detect game over conditions:
1. there is a line forming with 3X or 3 'O'
2. All the boxes are played, but no lines (draw)
important here is to use the date in boxXY, especially the value of the third element
boxXY[i][2].  To start, you can make a list with just those nine data values.

question 3 is to make the computerPlayTicTacToeSmart function work so option 3 and option 5 work

question 4 is to make the computerPlayTicTacToeRandom function work so option 2 and 4 work

question 5 is to write a code so a computer play random vs computer play smart

question 6 is to write a code to put all the results in an excel whenever the game is played

and last thing is the game options

option 1 : two human play

option 2 : human O, computer X play random

option 3 : computer O play smart, human X

option 4 : two computers playing random

option 5 : one computer play random, the other plays smart

i hope i explained everything and its clear enough

this is the code i tried to solve with my solutions in question 2 and 4

```<code>import random
from ezgraphics import GraphicsWindow
win = GraphicsWindow(800, 800)
win.setTitle("Tic-Tac-Toe")
canvas = win.canvas()

side=(int)(800/3)

x=[]
for i in range(9):
    value = (i % 3) * side
    x.append(value)

y=[]
for i in range(9):
    if i < 3:
        y.append(0)
    elif i < 6:
        y.append(side)
    else:
        y.append(side*2)

boxXY=[]                                # The third element, initialized to zero is to represent empty, X or O,
for i in range(9):                      # empty, X or O are the possible values in each box.
    boxXY.append([x[i], y[i], 0 ])      # We will use 0 to represent empty, 1 for X and -1 for O.

def ticTacToeBoard():
    for i in range(9):
        canvas.drawRectangle(x[i], y[i], side, side)
        canvas.drawText(x[i]+10, y[i]+10,i+1)

def drawO(x,y,size):
    canvas.drawOval(x, y, size, size)

def drawX(x,y):
    canvas.drawLine(x, y, x+100, y+100)
    canvas.drawLine(x, y+100, x+100, y)

def findBox():
    box = -1
    side=(int)(800/3)
    while (box == -1):
        boxTuple=win.getMouse()  # get the XY coordinate of the mouse.
        mouseX = boxTuple[0]
        mouseY = boxTuple[1]
        for i in range(9):
            if(x[i]<mouseX and x[i]+side>mouseX):
                if(y[i]<mouseY and y[i]+side>mouseY):
                    box = i+1
            # Test Q1: add code to detect empty box
            # if the box already has a O or X in it
            # if there is no X or O, then return the box number found
            # but there is already O or X, then stay in the while loop
            # keep waiting for another mouse click
            #if(boxXY[i][2] == -1 or boxXY[i][2] == 1):

    return box

def playO(boxnumber):
    size=100
    margin=(int)((side-size)/2)
    x1=x[boxnumber-1]+margin
    y1=y[boxnumber-1]+margin
    drawO(x1, y1, size)
    boxXY[boxnumber-1][2] = -1        # -1 means played an O

def playX(boxnumber):
    size=100
    margin=(int)((side-size)/2)
    x1=x[boxnumber-1]+margin
    y1=y[boxnumber-1]+margin
    drawX(x1, y1)
    boxXY[boxnumber-1][2] = 1       # +1 means played an X

def TicTacToeOver():
    #
    # Test Question 2 :  Please add code to detect game over conditions:
    #                 1. there is a line forming with 3X or 3 'O'
    #                 2. All the boxes are played, but no lines (draw)
    #      Important here is to use the date in boxXY, especially the value of the third element
    #       boxXY[i][2].  To start, you can make a list with just those nine data values.
    #

    ######## D O N E ########

    # checking O
    if(boxXY[0][2] == -1 and boxXY[1][2] == -1 and boxXY[2][2] == -1):
        return True
    elif (boxXY[3][2] == -1 and boxXY[4][2] == -1 and boxXY[5][2] == -1):
        return True
    elif (boxXY[6][2] == -1 and boxXY[7][2] == -1 and boxXY[8][2] == -1):
        return True
    elif (boxXY[0][2] == -1 and boxXY[3][2] == -1 and boxXY[6][2] == -1):
        return True
    elif (boxXY[1][2] == -1 and boxXY[4][2] == -1 and boxXY[7][2] == -1):
        return True
    elif (boxXY[2][2] == -1 and boxXY[5][2] == -1 and boxXY[8][2] == -1):
        return True
    elif (boxXY[0][2] == -1 and boxXY[4][2] == -1 and boxXY[8][2] == -1):
        return True
    elif (boxXY[2][2] == -1 and boxXY[4][2] == -1 and boxXY[6][2] == -1):
        return True
    #checking X
    elif(boxXY[0][2] == 1 and boxXY[1][2] == 1 and boxXY[2][2] == 1):
        return True
    elif (boxXY[3][2] == 1 and boxXY[4][2] == 1 and boxXY[5][2] == 1):
        return True
    elif (boxXY[6][2] == 1 and boxXY[7][2] == 1 and boxXY[8][2] == 1):
        return True
    elif (boxXY[0][2] == 1 and boxXY[3][2] == 1 and boxXY[6][2] == 1):
        return True
    elif (boxXY[1][2] == 1 and boxXY[4][2] == 1 and boxXY[7][2] == 1):
        return True
    elif (boxXY[2][2] == 1 and boxXY[5][2] == 1 and boxXY[8][2] == 1):
        return True
    elif (boxXY[0][2] == 1 and boxXY[4][2] == 1 and boxXY[8][2] == 1):
        return True
    elif (boxXY[2][2] == 1 and boxXY[4][2] == 1 and boxXY[6][2] == 1):
        return True

    return False # place holder
    #
    # Below is Placeholder/filler code that allows a human to decide if the game is over...
    stop = input("Do you want to end the game? ")
    if(stop=="yes"):
        return True
    else:
        return False

def playTicTacToe():
    ticTacToeBoard()
    playOption = input("O will be first.\nPlease select\n1. two human play;\n2. human O, computer X play random;\n3. computer O play smart, human X;\n4. two computers playing random;\n5. one computer play random, the other plays smart: ")
    if (playOption == "1"):
        while 1:                            # Optional Question:   Can you change the loop? max of 9 moves can be made.
            oNumber = findBox()
            playO(int(oNumber))
            if(TicTacToeOver()==True):
                print("Game Over, Player O Won")
                break
            xNumber = findBox()
            playX(int(xNumber))
            if(TicTacToeOver()==True):
                print("Game Over, PLayer X Won")
                break
            else:
                #print("Keep going!")
                continue
    elif (playOption == "2"):
        #
        while 1:
            oNumber = findBox()
            playO(int(oNumber))
            if(TicTacToeOver()==True):
                print("Game Over, You won")
                break
            xNumber = computerPlayTicTacToeRandom()
            playX(int(xNumber))
            if(TicTacToeOver()==True):
                print("Game is over, Computer won")
                break
            else:
                #print("Keep going!")
                continue
    elif (playOption == "3"):
        # Test Question 3, can you make this work?
        #
        while 1:
            oNumber = computerPlayTicTacToeSmart(1)
            playO(oNumber)
            if(TicTacToeOver()==True):
                    #print("Game is over")
                break
            xNumber = findBox()
            playX(int(xNumber))
            if(TicTacToeOver()==True):
                    #print("Game is over")
                break
            else:
                    #print("Keep going!")
                continue
    elif (playOption == "4"):
        ####### D O N E #######
        # Test Question 4, can you make this option work?
        while 1:
            oNumber = computerPlayTicTacToeRandom()
            playO(int(oNumber))
            if(TicTacToeOver()==True):
                print("Game is over, Computer O Won")
                break
            xNumber = computerPlayTicTacToeRandom()
            playX(int(xNumber))
            if(TicTacToeOver()==True):
                print("Game is over, Computer X Won")
                break
            else:
                #print("Keep going!")
                continue
    elif (playOption == "5"):
        while 1:
            break
    # Test Question 5:  Can you make the option 5 work ?
    #
    #
    #
    #

    # Test Question 6:  after the game is over
    # storePlay(boxXY)    # boxXY has the data.
    # Add the code to record the Board using an excel spreadsheet with nine columns
    # each time the game is played, we APPEND a row into the sheet.
    #  This will require you to:
    #        1. add code to access the openpyxl library in the beginning of the code file
    #        2. open the file before the play.
    #        3. put the board final config into a list
    #        4. write/append the list into EXCEL
    # Hint: the boxXY[] array has the data of each play in the third column.
    #
    #f

def computerPlayTicTacToeRandom():
    ######## D O N E ########
    # test Question 4.using the code above and the random() in the random library.
    count = 0
    while count < 9:
        box = random.randint(1, 9)
        count +=1
    return(box)  # Just a placeholder

def twoInALine( xorO ): # the parameter is 1 or -1, representing x or o
    theThirdBox = 5
    if (xorO == -1):
        #checking rows
        if (boxXY[1][2] == -1 and boxXY[2][2] == -1):
            theThirdBox = 1
        elif (boxXY[0][2] == -1 and boxXY[2][2] == -1):
            theThirdBox = 2
        elif (boxXY[0][2] == -1 and boxXY[1][2] == -1):
            theThirdBox = 3

        elif (boxXY[4][2] == -1 and boxXY[5][2] == -1):
            theThirdBox = 4
        elif (boxXY[3][2] == -1 and boxXY[5][2] == -1):
            theThirdBox = 5
        elif (boxXY[3][2] == -1 and boxXY[4][2] == -1):
            theThirdBox = 4

        elif (boxXY[7][2] == -1 and boxXY[8][2] == -1):
            theThirdBox = 1
        elif (boxXY[6][2] == -1 and boxXY[8][2] == -1):
            theThirdBox = 2
        elif (boxXY[6][2] == -1 and boxXY[7][2] == -1):
            theThirdBox = 3

        #checking cols
        elif (boxXY[3][2] == -1 and boxXY[6][2] == -1):
            theThirdBox = 1
        elif (boxXY[0][2] == -1 and boxXY[6][2] == -1):
            theThirdBox = 4
        elif (boxXY[0][2] == -1 and boxXY[3][2] == -1):
            theThirdBox = 7

        elif (boxXY[4][2] == -1 and boxXY[7][2] == -1):
            theThirdBox = 2
        elif (boxXY[1][2] == -1 and boxXY[7][2] == -1):
            theThirdBox = 5
        elif (boxXY[1][2] == -1 and boxXY[4][2] == -1):
            theThirdBox = 4

        elif (boxXY[5][2] == -1 and boxXY[8][2] == -1):
            theThirdBox = 3
        elif (boxXY[2][2] == -1 and boxXY[8][2] == -1):
            theThirdBox = 6
        elif (boxXY[2][2] == -1 and boxXY[5][2] == -1):
            theThirdBox = 9

        #checking diagonals
        elif (boxXY[4][2] == -1 and boxXY[8][2] == -1):
            theThirdBox = 1
        elif (boxXY[0][2] == -1 and boxXY[8][2] == -1):
            theThirdBox = 5
        elif (boxXY[0][2] == -1 and boxXY[4][2] == -1):
            theThirdBox = 9

        elif (boxXY[4][2] == -1 and boxXY[6][2] == -1):
            theThirdBox = 3
        elif (boxXY[2][2] == -1 and boxXY[6][2] == -1):
            theThirdBox = 5
        elif (boxXY[2][2] == -1 and boxXY[4][2] == -1):
            theThirdBox = 7

    elif (xorO == 1):
        if (boxXY[1][2] == 1 and boxXY[2][2] == 1):
            theThirdBox = 1
        elif (boxXY[0][2] == 1 and boxXY[2][2] == 1):
            theThirdBox = 2
        elif (boxXY[0][2] == 1 and boxXY[1][2] == 1):
            theThirdBox = 3

        elif (boxXY[4][2] == 1 and boxXY[5][2] == 1):
            theThirdBox = 4
        elif (boxXY[3][2] == 1 and boxXY[5][2] == 1):
            theThirdBox = 5
        elif (boxXY[3][2] == 1 and boxXY[4][2] == 1):
            theThirdBox = 4

        elif (boxXY[7][2] == 1 and boxXY[8][2] == 1):
            theThirdBox = 1
        elif (boxXY[6][2] == 1 and boxXY[8][2] == 1):
            theThirdBox = 2
        elif (boxXY[6][2] == 1 and boxXY[7][2] == 1):
            theThirdBox = 3

        #checking cols
        elif (boxXY[3][2] == 1 and boxXY[6][2] == 1):
            theThirdBox = 1
        elif (boxXY[0][2] == 1 and boxXY[6][2] == 1):
            theThirdBox = 4
        elif (boxXY[0][2] == 1 and boxXY[3][2] == 1):
            theThirdBox = 7

        elif (boxXY[4][2] == 1 and boxXY[7][2] == 1):
            theThirdBox = 2
        elif (boxXY[1][2] == 1 and boxXY[7][2] == 1):
            theThirdBox = 5
        elif (boxXY[1][2] == 1 and boxXY[4][2] == 1):
            theThirdBox = 4

        elif (boxXY[5][2] == 1 and boxXY[8][2] == 1):
            theThirdBox = 3
        elif (boxXY[2][2] == 1 and boxXY[8][2] == 1):
            theThirdBox = 6
        elif (boxXY[2][2] == 1 and boxXY[5][2] == 1):
            theThirdBox = 9

        #checking diagonals
        elif (boxXY[4][2] == 1 and boxXY[8][2] == 1):
            theThirdBox = 1
        elif (boxXY[0][2] == 1 and boxXY[8][2] == 1):
            theThirdBox = 5
        elif (boxXY[0][2] == 1 and boxXY[4][2] == 1):
            theThirdBox = 9

        elif (boxXY[4][2] == 1 and boxXY[6][2] == 1):
            theThirdBox = 3
        elif (boxXY[2][2] == 1 and boxXY[6][2] == 1):
            theThirdBox = 5
        elif (boxXY[2][2] == 1 and boxXY[4][2] == 1):
            theThirdBox = 7
    else:
        theThirdBox = detectingMiddleSquare()
        print(theThirdBox)

    return theThirdBox   # if there is 2 in a line, return the third box to stop the line forming

def computerPlayTicTacToeSmart( xOrO ):  # the parameter indicates the opponent's symbol O or X
    # make the computer play according to these rules:
    #    if the there are two of my symbol in a line, play the third to win.
    mySymbol = -xOrO  # 1 or minus 1
    thirdBox = twoInALine( mySymbol )
    if ( thirdBox > 0 ):
         if (mySymbol == 1 ):
             playX(thirBox)
         else: playO(thirdBox)
         return(thirdBox)
    #    if the opponent has two in a line, then stop the oppnent
    thirdBox = twoInALine( xOrO )
    if ( thirdBox > 0):
        if (mySymbol == 1 ):
             playX(thirBox)
        else: playO(thirdBox)
        return(thirdBox)
    #    if the center is empty, play the center
    if (boxXY[4][2] == 0):
        if (mySymbol == 1 ):
             playX(5)
        else: playO(5)

def detectingMiddleSquare():
    if(boxXY[1][2] == 1 or boxXY[3][2] == 1 or boxXY[5][2] == 1 or boxXY[7][2] == 1):
        ranBox = random.choice([1,3,7,9])
        if (mySymbol == 1 ):
             playX(ranBox)
        else: playO(ranBox)
    return ranBox

    #    else if the opponent has a middle square on the side, play one of the corner next to the square
    #   Hint:  Please write the function that
    #        1. detect the opponent has a middle square on the side
    #        2. play the first corner next to the middle square

playTicTacToe()

</code>```

Body:
it's a simple tic tac toe game but there are 6 questions i need to answer so i can make the game options work and you will find the description of the questions commented in the code and called test Q1, test Q2 and so on

i finished question 2 and 4 but if you want to make any correction feel free to do so

question 1 is to add code to detect empty box
if the box already has a O or X in it
if there is no X or O, then return the box number found
but there is already O or X, then stay in the while loop
keep waiting for another mouse click

question 2 is to add code to detect game over conditions:
1. there is a line forming with 3X or 3 'O'
2. All the boxes are played, but no lines (draw)
important here is to use the date in boxXY, especially the value of the third element
boxXY[i][2].  To start, you can make a list with just those nine data values.

question 3 is to make the computerPlayTicTacToeSmart function work so option 3 and option 5 work

question 4 is to make the computerPlayTicTacToeRandom function work so option 2 and 4 work

question 5 is to write a code so a computer play random vs computer play smart

question 6 is to write a code to put all the results in an excel whenever the game is played

and last thing is the game options

option 1 : two human play

option 2 : human O, computer X play random

option 3 : computer O play smart, human X

option 4 : two computers playing random

option 5 : one computer play random, the other plays smart

i hope i explained everything and its clear enough

this is the code i tried to solve with my solutions in question 2 and 4

import random
from ezgraphics import GraphicsWindow
win = GraphicsWindow(800, 800)
win.setTitle("Tic-Tac-Toe")
canvas = win.canvas()

side=(int)(800/3)

x=[]
for i in range(9):
    value = (i % 3) * side
    x.append(value)

y=[]
for i in range(9):
    if i < 3:
        y.append(0)
    elif i < 6:
        y.append(side)
    else:
        y.append(side*2)

boxXY=[]                                # The third element, initialized to zero is to represent empty, X or O,
for i in range(9):                      # empty, X or O are the possible values in each box.
    boxXY.append([x[i], y[i], 0 ])      # We will use 0 to represent empty, 1 for X and -1 for O.

def ticTacToeBoard():
    for i in range(9):
        canvas.drawRectangle(x[i], y[i], side, side)
        canvas.drawText(x[i]+10, y[i]+10,i+1)

def drawO(x,y,size):
    canvas.drawOval(x, y, size, size)

def drawX(x,y):
    canvas.drawLine(x, y, x+100, y+100)
    canvas.drawLine(x, y+100, x+100, y)

def findBox():
    box = -1
    side=(int)(800/3)
    while (box == -1):
        boxTuple=win.getMouse()  # get the XY coordinate of the mouse.
        mouseX = boxTuple[0]
        mouseY = boxTuple[1]
        for i in range(9):
            if(x[i]<mouseX and x[i]+side>mouseX):
                if(y[i]<mouseY and y[i]+side>mouseY):
                    box = i+1
            # Test Q1: add code to detect empty box
            # if the box already has a O or X in it
            # if there is no X or O, then return the box number found
            # but there is already O or X, then stay in the while loop
            # keep waiting for another mouse click
            #if(boxXY[i][2] == -1 or boxXY[i][2] == 1):

    return box

def playO(boxnumber):
    size=100
    margin=(int)((side-size)/2)
    x1=x[boxnumber-1]+margin
    y1=y[boxnumber-1]+margin
    drawO(x1, y1, size)
    boxXY[boxnumber-1][2] = -1        # -1 means played an O

def playX(boxnumber):
    size=100
    margin=(int)((side-size)/2)
    x1=x[boxnumber-1]+margin
    y1=y[boxnumber-1]+margin
    drawX(x1, y1)
    boxXY[boxnumber-1][2] = 1       # +1 means played an X

def TicTacToeOver():
    #
    # Test Question 2 :  Please add code to detect game over conditions:
    #                 1. there is a line forming with 3X or 3 'O'
    #                 2. All the boxes are played, but no lines (draw)
    #      Important here is to use the date in boxXY, especially the value of the third element
    #       boxXY[i][2].  To start, you can make a list with just those nine data values.
    #

    ######## D O N E ########

    # checking O
    if(boxXY[0][2] == -1 and boxXY[1][2] == -1 and boxXY[2][2] == -1):
        return True
    elif (boxXY[3][2] == -1 and boxXY[4][2] == -1 and boxXY[5][2] == -1):
        return True
    elif (boxXY[6][2] == -1 and boxXY[7][2] == -1 and boxXY[8][2] == -1):
        return True
    elif (boxXY[0][2] == -1 and boxXY[3][2] == -1 and boxXY[6][2] == -1):
        return True
    elif (boxXY[1][2] == -1 and boxXY[4][2] == -1 and boxXY[7][2] == -1):
        return True
    elif (boxXY[2][2] == -1 and boxXY[5][2] == -1 and boxXY[8][2] == -1):
        return True
    elif (boxXY[0][2] == -1 and boxXY[4][2] == -1 and boxXY[8][2] == -1):
        return True
    elif (boxXY[2][2] == -1 and boxXY[4][2] == -1 and boxXY[6][2] == -1):
        return True
    #checking X
    elif(boxXY[0][2] == 1 and boxXY[1][2] == 1 and boxXY[2][2] == 1):
        return True
    elif (boxXY[3][2] == 1 and boxXY[4][2] == 1 and boxXY[5][2] == 1):
        return True
    elif (boxXY[6][2] == 1 and boxXY[7][2] == 1 and boxXY[8][2] == 1):
        return True
    elif (boxXY[0][2] == 1 and boxXY[3][2] == 1 and boxXY[6][2] == 1):
        return True
    elif (boxXY[1][2] == 1 and boxXY[4][2] == 1 and boxXY[7][2] == 1):
        return True
    elif (boxXY[2][2] == 1 and boxXY[5][2] == 1 and boxXY[8][2] == 1):
        return True
    elif (boxXY[0][2] == 1 and boxXY[4][2] == 1 and boxXY[8][2] == 1):
        return True
    elif (boxXY[2][2] == 1 and boxXY[4][2] == 1 and boxXY[6][2] == 1):
        return True

    return False # place holder
    #
    # Below is Placeholder/filler code that allows a human to decide if the game is over...
    stop = input("Do you want to end the game? ")
    if(stop=="yes"):
        return True
    else:
        return False

def playTicTacToe():
    ticTacToeBoard()
    playOption = input("O will be first.\nPlease select\n1. two human play;\n2. human O, computer X play random;\n3. computer O play smart, human X;\n4. two computers playing random;\n5. one computer play random, the other plays smart: ")
    if (playOption == "1"):
        while 1:                            # Optional Question:   Can you change the loop? max of 9 moves can be made.
            oNumber = findBox()
            playO(int(oNumber))
            if(TicTacToeOver()==True):
                print("Game Over, Player O Won")
                break
            xNumber = findBox()
            playX(int(xNumber))
            if(TicTacToeOver()==True):
                print("Game Over, PLayer X Won")
                break
            else:
                #print("Keep going!")
                continue
    elif (playOption == "2"):
        #
        while 1:
            oNumber = findBox()
            playO(int(oNumber))
            if(TicTacToeOver()==True):
                print("Game Over, You won")
                break
            xNumber = computerPlayTicTacToeRandom()
            playX(int(xNumber))
            if(TicTacToeOver()==True):
                print("Game is over, Computer won")
                break
            else:
                #print("Keep going!")
                continue
    elif (playOption == "3"):
        # Test Question 3, can you make this work?
        #
        while 1:
            oNumber = computerPlayTicTacToeSmart(1)
            playO(oNumber)
            if(TicTacToeOver()==True):
                    #print("Game is over")
                break
            xNumber = findBox()
            playX(int(xNumber))
            if(TicTacToeOver()==True):
                    #print("Game is over")
                break
            else:
                    #print("Keep going!")
                continue
    elif (playOption == "4"):
        ####### D O N E #######
        # Test Question 4, can you make this option work?
        while 1:
            oNumber = computerPlayTicTacToeRandom()
            playO(int(oNumber))
            if(TicTacToeOver()==True):
                print("Game is over, Computer O Won")
                break
            xNumber = computerPlayTicTacToeRandom()
            playX(int(xNumber))
            if(TicTacToeOver()==True):
                print("Game is over, Computer X Won")
                break
            else:
                #print("Keep going!")
                continue
    elif (playOption == "5"):
        while 1:
            break
    # Test Question 5:  Can you make the option 5 work ?
    #
    #
    #
    #

    # Test Question 6:  after the game is over
    # storePlay(boxXY)    # boxXY has the data.
    # Add the code to record the Board using an excel spreadsheet with nine columns
    # each time the game is played, we APPEND a row into the sheet.
    #  This will require you to:
    #        1. add code to access the openpyxl library in the beginning of the code file
    #        2. open the file before the play.
    #        3. put the board final config into a list
    #        4. write/append the list into EXCEL
    # Hint: the boxXY[] array has the data of each play in the third column.
    #
    #f

def computerPlayTicTacToeRandom():
    ######## D O N E ########
    # test Question 4.using the code above and the random() in the random library.
    count = 0
    while count < 9:
        box = random.randint(1, 9)
        count +=1
    return(box)  # Just a placeholder

def twoInALine( xorO ): # the parameter is 1 or -1, representing x or o
    theThirdBox = 5
    if (xorO == -1):
        #checking rows
        if (boxXY[1][2] == -1 and boxXY[2][2] == -1):
            theThirdBox = 1
        elif (boxXY[0][2] == -1 and boxXY[2][2] == -1):
            theThirdBox = 2
        elif (boxXY[0][2] == -1 and boxXY[1][2] == -1):
            theThirdBox = 3

        elif (boxXY[4][2] == -1 and boxXY[5][2] == -1):
            theThirdBox = 4
        elif (boxXY[3][2] == -1 and boxXY[5][2] == -1):
            theThirdBox = 5
        elif (boxXY[3][2] == -1 and boxXY[4][2] == -1):
            theThirdBox = 4

        elif (boxXY[7][2] == -1 and boxXY[8][2] == -1):
            theThirdBox = 1
        elif (boxXY[6][2] == -1 and boxXY[8][2] == -1):
            theThirdBox = 2
        elif (boxXY[6][2] == -1 and boxXY[7][2] == -1):
            theThirdBox = 3

        #checking cols
        elif (boxXY[3][2] == -1 and boxXY[6][2] == -1):
            theThirdBox = 1
        elif (boxXY[0][2] == -1 and boxXY[6][2] == -1):
            theThirdBox = 4
        elif (boxXY[0][2] == -1 and boxXY[3][2] == -1):
            theThirdBox = 7

        elif (boxXY[4][2] == -1 and boxXY[7][2] == -1):
            theThirdBox = 2
        elif (boxXY[1][2] == -1 and boxXY[7][2] == -1):
            theThirdBox = 5
        elif (boxXY[1][2] == -1 and boxXY[4][2] == -1):
            theThirdBox = 4

        elif (boxXY[5][2] == -1 and boxXY[8][2] == -1):
            theThirdBox = 3
        elif (boxXY[2][2] == -1 and boxXY[8][2] == -1):
            theThirdBox = 6
        elif (boxXY[2][2] == -1 and boxXY[5][2] == -1):
            theThirdBox = 9

        #checking diagonals
        elif (boxXY[4][2] == -1 and boxXY[8][2] == -1):
            theThirdBox = 1
        elif (boxXY[0][2] == -1 and boxXY[8][2] == -1):
            theThirdBox = 5
        elif (boxXY[0][2] == -1 and boxXY[4][2] == -1):
            theThirdBox = 9

        elif (boxXY[4][2] == -1 and boxXY[6][2] == -1):
            theThirdBox = 3
        elif (boxXY[2][2] == -1 and boxXY[6][2] == -1):
            theThirdBox = 5
        elif (boxXY[2][2] == -1 and boxXY[4][2] == -1):
            theThirdBox = 7

    elif (xorO == 1):
        if (boxXY[1][2] == 1 and boxXY[2][2] == 1):
            theThirdBox = 1
        elif (boxXY[0][2] == 1 and boxXY[2][2] == 1):
            theThirdBox = 2
        elif (boxXY[0][2] == 1 and boxXY[1][2] == 1):
            theThirdBox = 3

        elif (boxXY[4][2] == 1 and boxXY[5][2] == 1):
            theThirdBox = 4
        elif (boxXY[3][2] == 1 and boxXY[5][2] == 1):
            theThirdBox = 5
        elif (boxXY[3][2] == 1 and boxXY[4][2] == 1):
            theThirdBox = 4

        elif (boxXY[7][2] == 1 and boxXY[8][2] == 1):
            theThirdBox = 1
        elif (boxXY[6][2] == 1 and boxXY[8][2] == 1):
            theThirdBox = 2
        elif (boxXY[6][2] == 1 and boxXY[7][2] == 1):
            theThirdBox = 3

        #checking cols
        elif (boxXY[3][2] == 1 and boxXY[6][2] == 1):
            theThirdBox = 1
        elif (boxXY[0][2] == 1 and boxXY[6][2] == 1):
            theThirdBox = 4
        elif (boxXY[0][2] == 1 and boxXY[3][2] == 1):
            theThirdBox = 7

        elif (boxXY[4][2] == 1 and boxXY[7][2] == 1):
            theThirdBox = 2
        elif (boxXY[1][2] == 1 and boxXY[7][2] == 1):
            theThirdBox = 5
        elif (boxXY[1][2] == 1 and boxXY[4][2] == 1):
            theThirdBox = 4

        elif (boxXY[5][2] == 1 and boxXY[8][2] == 1):
            theThirdBox = 3
        elif (boxXY[2][2] == 1 and boxXY[8][2] == 1):
            theThirdBox = 6
        elif (boxXY[2][2] == 1 and boxXY[5][2] == 1):
            theThirdBox = 9

        #checking diagonals
        elif (boxXY[4][2] == 1 and boxXY[8][2] == 1):
            theThirdBox = 1
        elif (boxXY[0][2] == 1 and boxXY[8][2] == 1):
            theThirdBox = 5
        elif (boxXY[0][2] == 1 and boxXY[4][2] == 1):
            theThirdBox = 9

        elif (boxXY[4][2] == 1 and boxXY[6][2] == 1):
            theThirdBox = 3
        elif (boxXY[2][2] == 1 and boxXY[6][2] == 1):
            theThirdBox = 5
        elif (boxXY[2][2] == 1 and boxXY[4][2] == 1):
            theThirdBox = 7
    else:
        theThirdBox = detectingMiddleSquare()
        print(theThirdBox)

    return theThirdBox   # if there is 2 in a line, return the third box to stop the line forming

def computerPlayTicTacToeSmart( xOrO ):  # the parameter indicates the opponent's symbol O or X
    # make the computer play according to these rules:
    #    if the there are two of my symbol in a line, play the third to win.
    mySymbol = -xOrO  # 1 or minus 1
    thirdBox = twoInALine( mySymbol )
    if ( thirdBox > 0 ):
         if (mySymbol == 1 ):
             playX(thirBox)
         else: playO(thirdBox)
         return(thirdBox)
    #    if the opponent has two in a line, then stop the oppnent
    thirdBox = twoInALine( xOrO )
    if ( thirdBox > 0):
        if (mySymbol == 1 ):
             playX(thirBox)
        else: playO(thirdBox)
        return(thirdBox)
    #    if the center is empty, play the center
    if (boxXY[4][2] == 0):
        if (mySymbol == 1 ):
             playX(5)
        else: playO(5)

def detectingMiddleSquare():
    if(boxXY[1][2] == 1 or boxXY[3][2] == 1 or boxXY[5][2] == 1 or boxXY[7][2] == 1):
        ranBox = random.choice([1,3,7,9])
        if (mySymbol == 1 ):
             playX(ranBox)
        else: playO(ranBox)
    return ranBox

    #    else if the opponent has a middle square on the side, play one of the corner next to the square
    #   Hint:  Please write the function that
    #        1. detect the opponent has a middle square on the side
    #        2. play the first corner next to the middle square

playTicTacToe()


来源: stackexchange

问:
AES-128-CBC issue with PHP and C#
I have a php code code like below

```<code>        $cipher = "AES-128-CBC";
        $key = openssl_digest("OfVb3CjsZhnX81ZzjfAHuIiMtKEUyrt6", 'SHA256', TRUE);
        $ivlen = openssl_cipher_iv_length($cipher);
        $iv = openssl_random_pseudo_bytes($ivlen);
        $ciphertext_raw = openssl_encrypt("wsUser", $cipher, $key, OPENSSL_RAW_DATA, $iv);
        $hmac = hash_hmac('sha256', $ciphertext_raw, $key, true);
        $result = base64_encode($iv . $hmac . $ciphertext_raw);
        //$result value will decode by http_build_query
        // $request_query["Key"] = $result;
        // $last_query = http_build_query($request_query);

</code>```

I converted PHPcode to C# like this ;

```<code>            var cipher = "AES-128-CBC-----";
            var key = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes("OfVb3CjsZhnX81ZzjfAHuIiMtKEUyrt6"));
            var ivlen = cipher.Length;
            byte[] iv = new byte[16]; Random rnd = new Random();
            rnd.NextBytes(iv);
            var aes = Aes.Create("AesManaged");

            //C# 4.5
            byte[] m = new byte[16];
            Array.Copy(key, 0, m, 0, 16);
            aes.Key =  m;
            //C# 8.0
            aes.Key = key[0..16];
            aes.IV = iv;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            var encryptor = aes.CreateEncryptor(aes.Key,iv);
            var ciphertextRaw = encryptor.TransformFinalBlock(Encoding.UTF8.GetBytes(txtwsuser.Text), 0, txtwsuser.Text.Length); //this is "wsUser"
            var hmac = new HMACSHA256(key).ComputeHash(ciphertextRaw);
            string cw = Convert.ToBase64String(iv.Concat(hmac).Concat(ciphertextRaw).ToArray());
            textBox1.Text =  HttpUtility.UrlEncode(cw).Replace("%3d", "%3D"); //this line for debug purposes

</code>```

but even though the two hashes (key value and hmac value) are the same, PHP decryptor block doesn'T work.
my PHP decryptor code block like this;

```<code>        $encrypted_value = urldecode("data_from_client"); // can be used textBox1.Text value for this.
        $cipher = "AES-128-CBC";
        $key = openssl_digest(wsKey, 'SHA256', TRUE);
        $cw = base64_decode($encrypted_value);
        $ivlen = openssl_cipher_iv_length($cipher);
        $iv = substr($cw, 0, $ivlen);
        $hmac = substr($cw, $ivlen, $sha2len=32);
        $cw3 = substr($cw, $ivlen+$sha2len);
        $calcmac = hash_hmac('SHA256', $cw3, $key, true);
        $result = openssl_decrypt($cw3, $cipher, $key, OPENSSL_RAW_DATA, $iv);
</code>```

decrytor PHP code works with PHP code above, but C# doesn't work. I tried some AES methods but no change.How can AES-128 encryption be the same in php and C#. ?

Thanks in advance

C# code generated

```<code>sCn1%2bY2Kx9RzIiDIsWL1xWRxecMO%2bkPhIdkBfXbV6uD7%2by75f3EvwpyP4e3CHLDjBZ7U0CrVDsK4MdBUn25K0Q%3D%3D
</code>```

value. PHP cannot decrypt the data. but hash values are correct.
PHP Code generated

```<code>%2FUMZJmd2LfIJzJntETKcgo%2F7VDaBV8U9iLY%2Bopq2Up5%2BrtOLRMxR%2B3OzbzgLEx0ZZErjZFP8oOtMmnZ%2FEX1dxA%3D%3D
</code>```

this works fine.

After Add lines to C# Code at belows, problem solved

```<code>            //C# 4.5
            byte[] m = new byte[16];
            Array.Copy(key, 0, m, 0, 16);
            aes.Key =  m;
            //C# 8.0
            aes.Key = key[0..16];
</code>```

ContentLicense: CC BY-SA 4.0

Title: AES-128-CBC issue with PHP and C#

Body:
I have a php code code like below

        $cipher = "AES-128-CBC";
        $key = openssl_digest("OfVb3CjsZhnX81ZzjfAHuIiMtKEUyrt6", 'SHA256', TRUE);
        $ivlen = openssl_cipher_iv_length($cipher);
        $iv = openssl_random_pseudo_bytes($ivlen);
        $ciphertext_raw = openssl_encrypt("wsUser", $cipher, $key, OPENSSL_RAW_DATA, $iv);
        $hmac = hash_hmac('sha256', $ciphertext_raw, $key, true);
        $result = base64_encode($iv . $hmac . $ciphertext_raw);
        //$result value will decode by http_build_query
        // $request_query["Key"] = $result;
        // $last_query = http_build_query($request_query);

I converted PHPcode to C# like this ;

            var cipher = "AES-128-CBC-----";
            var key = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes("OfVb3CjsZhnX81ZzjfAHuIiMtKEUyrt6"));
            var ivlen = cipher.Length;
            byte[] iv = new byte[16]; Random rnd = new Random();
            rnd.NextBytes(iv);
            var aes = Aes.Create("AesManaged");

            //C# 4.5
            byte[] m = new byte[16];
            Array.Copy(key, 0, m, 0, 16);
            aes.Key =  m;
            //C# 8.0
            aes.Key = key[0..16];
            aes.IV = iv;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            var encryptor = aes.CreateEncryptor(aes.Key,iv);
            var ciphertextRaw = encryptor.TransformFinalBlock(Encoding.UTF8.GetBytes(txtwsuser.Text), 0, txtwsuser.Text.Length); //this is "wsUser"
            var hmac = new HMACSHA256(key).ComputeHash(ciphertextRaw);
            string cw = Convert.ToBase64String(iv.Concat(hmac).Concat(ciphertextRaw).ToArray());
            textBox1.Text =  HttpUtility.UrlEncode(cw).Replace("%3d", "%3D"); //this line for debug purposes

but even though the two hashes (key value and hmac value) are the same, PHP decryptor block doesn'T work.
my PHP decryptor code block like this;

        $encrypted_value = urldecode("data_from_client"); // can be used textBox1.Text value for this.
        $cipher = "AES-128-CBC";
        $key = openssl_digest(wsKey, 'SHA256', TRUE);
        $cw = base64_decode($encrypted_value);
        $ivlen = openssl_cipher_iv_length($cipher);
        $iv = substr($cw, 0, $ivlen);
        $hmac = substr($cw, $ivlen, $sha2len=32);
        $cw3 = substr($cw, $ivlen+$sha2len);
        $calcmac = hash_hmac('SHA256', $cw3, $key, true);
        $result = openssl_decrypt($cw3, $cipher, $key, OPENSSL_RAW_DATA, $iv);

decrytor PHP code works with PHP code above, but C# doesn't work. I tried some AES methods but no change.How can AES-128 encryption be the same in php and C#. ?

Thanks in advance

C# code generated

sCn1%2bY2Kx9RzIiDIsWL1xWRxecMO%2bkPhIdkBfXbV6uD7%2by75f3EvwpyP4e3CHLDjBZ7U0CrVDsK4MdBUn25K0Q%3D%3D

value. PHP cannot decrypt the data. but hash values are correct.
PHP Code generated

%2FUMZJmd2LfIJzJntETKcgo%2F7VDaBV8U9iLY%2Bopq2Up5%2BrtOLRMxR%2B3OzbzgLEx0ZZErjZFP8oOtMmnZ%2FEX1dxA%3D%3D

this works fine.

After Add lines to C# Code at belows, problem solved

            //C# 4.5
            byte[] m = new byte[16];
            Array.Copy(key, 0, m, 0, 16);
            aes.Key =  m;
            //C# 8.0
            aes.Key = key[0..16];


问:
Filter over jsonfiled with unknown keys in Django ORM
There is a model with JSONfield in Django model:

```<code>class MyClass(models.Model):
    is_info = models.BooleanField()
    info = models.JSONField()
</code>```

The data inside table is like:

is_info
info

false

true
{'key123':{'a':'1', 'b':'2', 'search_key':'text'},'key456':{'a':'1', 'b':'2', 'search_key':'another_value'}}

And I need to filter somehow a query set to receive a set of rows where compound key 'search_key'='text' and not include in result values from 'info' field where 'search_key' has some other values.
My keys of 'info' field (key123, key456 and etc.) are always different and I don't know the exact value.

Please, help me!!!)

I've tried:

```<code>q = queryset.filter(info__icontains='text')
</code>```

but it return for me all the field info:

```<code>{'key123':{'a':'1', 'b':'2', 'search_key':'text'},'key456':{'a':'1', 'b':'2', 'search_key':'another_value'}}
</code>```

when I need to receive only:

```<code>{'key123':{'a':'1', 'b':'2', 'search_key':'text'}}
</code>```

Body:
There is a model with JSONfield in Django model:

class MyClass(models.Model):
    is_info = models.BooleanField()
    info = models.JSONField()

The data inside table is like:

is_info
info

false

true
{'key123':{'a':'1', 'b':'2', 'search_key':'text'},'key456':{'a':'1', 'b':'2', 'search_key':'another_value'}}

And I need to filter somehow a query set to receive a set of rows where compound key 'search_key'='text' and not include in result values from 'info' field where 'search_key' has some other values.
My keys of 'info' field (key123, key456 and etc.) are always different and I don't know the exact value.

Please, help me!!!)

I've tried:

q = queryset.filter(info__icontains='text')

but it return for me all the field info:

{'key123':{'a':'1', 'b':'2', 'search_key':'text'},'key456':{'a':'1', 'b':'2', 'search_key':'another_value'}}

when I need to receive only:

{'key123':{'a':'1', 'b':'2', 'search_key':'text'}}


问:
Adding code to chart and getting an error `Compilation error.'`
I get an error when i try add this code to my chart
`

```<code>//@version=4
fastLength = 5
slowLength = 15
tradeAmount = 1

// Set up variables for the take profit and stop loss levels
takeProfit = 1.05  // Take profit at a 5% profit
stopLoss = 0.95  // Stop loss at a 5% loss

// Set up variables for the grid trading strategy
gridSpacing = 0.01  // Grid spacing of 1%
gridSize = 5  // Number of grid levels

// Set up variables for the moving averages
fastMA = sma(close, fastLength)
slowMA = sma(close, slowLength)

// If the fast moving average crosses above the slow moving average, buy
if (fastMA > slowMA and !(fastMA[1] < slowMA[1]))
    // Set the take profit and stop loss levels for the trade
    strategy.exit("long", "TP", takeProfit)
    strategy.exit("long", "SL", stopLoss)

    // Set up the grid trading strategy
    for i = 1 to gridSize
        strategy.entry("long", strategy.long + i * gridSpacing)

// If the fast moving average crosses below the slow moving average, sell
if (fastMA < slowMA and !(fastMA[1] > slowMA[1]))
    // Set the take profit and stop loss levels for the trade
    strategy.exit("short", "TP", takeProfit)
    strategy.exit("short", "SL", stopLoss)

    // Set up the grid trading strategy
    for i = 1 to gridSize
        strategy.entry("short", strategy.short + i * gridSpacing)

</code>```

`
the error is  Compilation error. Line 19: mismatched character '(' expecting '='

I tried adding the code to my chart but i got an error Compilation error. Line 19: mismatched character '(' expecting '='

Body:
I get an error when i try add this code to my chart
`

//@version=4
fastLength = 5
slowLength = 15
tradeAmount = 1

// Set up variables for the take profit and stop loss levels
takeProfit = 1.05  // Take profit at a 5% profit
stopLoss = 0.95  // Stop loss at a 5% loss

// Set up variables for the grid trading strategy
gridSpacing = 0.01  // Grid spacing of 1%
gridSize = 5  // Number of grid levels

// Set up variables for the moving averages
fastMA = sma(close, fastLength)
slowMA = sma(close, slowLength)

// If the fast moving average crosses above the slow moving average, buy
if (fastMA > slowMA and !(fastMA[1] < slowMA[1]))
    // Set the take profit and stop loss levels for the trade
    strategy.exit("long", "TP", takeProfit)
    strategy.exit("long", "SL", stopLoss)

    // Set up the grid trading strategy
    for i = 1 to gridSize
        strategy.entry("long", strategy.long + i * gridSpacing)

// If the fast moving average crosses below the slow moving average, sell
if (fastMA < slowMA and !(fastMA[1] > slowMA[1]))
    // Set the take profit and stop loss levels for the trade
    strategy.exit("short", "TP", takeProfit)
    strategy.exit("short", "SL", stopLoss)

    // Set up the grid trading strategy
    for i = 1 to gridSize
        strategy.entry("short", strategy.short + i * gridSpacing)

`
the error is  Compilation error. Line 19: mismatched character '(' expecting '='

I tried adding the code to my chart but i got an error Compilation error. Line 19: mismatched character '(' expecting '='


问:
Faster mathematical operations over a vector using libsimdpp
Searching around on how I can improve my waveform generation code, I've come across SIMD and the libsimdpp library, but I have no idea how to use it. If I got it right using raw SIMD will require me to write code for each architecture while libsimdpp will handle that for me.

What I need to do is, to calculate the squared and rms value of a chunk of samples, which I managed to boost the process using vectorization, which worked perfectly until I introduced the same calculation for both left and right channel of an audio file.

So, my question and what I need help with, is how can I use libsimdpp (or any library that will make simdp easier for me) to improve the bellow code?

 // STRAT: vector containing all the audio samples
 std::vector<double> samples;
 nv_samples = samples.size();
 // END

 // START: Loop through the samples vector, incrementing ecah time the index with samples_per_pixel
 for (int i = 0; i < nb_samples; i+= samples_per_pixel)
{
    // START: Create chunk of samples with the size of samples_per_pixel
    double* chunk = &samplesL[i];
    // END

    // START: Calculate rms and sqared sum
    float sum = 0;
    float squaredsum = 0;
    /// there are multiple definitions of above for both channels but I won't include them
    //// to make the code easier to be read

    for (int j = 0; j < samples_per_pixel; j++)
    {
        if (chunk[j] < 0)
            sum += -chunk[j]
        else
            sum += chunk[j]
        squaredsum += chunk[j] * chunk[j]
    }

    /// average
    float average_point = (sumL * 2) / samples_per_pixel;

    // rms
    float meanL = squaredsumL / samples_per_pixel;
    rms_pointL = qSqrt(meanL);

    /// Drawing of both avearge point and rms
    //// [...]

    // END

}
```


问:
ReactJS - Resize image with a fixed height
I am working on a Front end feature that requires to resize an image uploaded by users (with various dimensions) to a new resized image with a fixed height of 200px. The width will change based on the given height in order to keep the aspect ratio.

I have tried to search for several solutions by using canvas, but unfortunately there are no answers that can precisely solve my problem.

I know resizing images have been a challenge for years, and i am really looking forward to your helps


问:
Can not connect to service inside ECS, health checks won't even pass
I want to run a Rust application in ECS. The Rust application has a health API and a websocket API. I can not connect to both from my machine to ECS and ECS itself even fails to query the health API using localhost, so I am doing a lot of stuff wrong and I do not know what. It works on my machine.

I checked my security groups, it allows everything. The whole Rust application can be found here: https://github.com/Jasperav/ssh-dockerfile/blob/master/src/main.rs. The relevant code (main.rs) can be found below.

I uploaded the Rust image to ECR public as well: https://eu-central-1.console.aws.amazon.com/ecr/repositories/public/465984508737/hello?region=eu-central-1. This can be deployed on an ARM machine.

The steps I took:

Made a Rust application which serves 2 endpoints, websocket and HTTP

Created an image and uploaded to ECR

In ECS, I created a new cluster with 1 public subnet. I used Fargate as infrastructure.

In the task definition, I mapped port 3014 and 3015 to TCP HTTP and selected my image. In the health api, I added CMD-SHELL curl -f localhost:3015/health

I deployed the task as a service to the cluster.

I verified I see the logging of the server that it is deployed successfully. However, I can not connect through the public ipv4 address to either the websocket API or health API.

What did I do wrong? This is the relevant code:

```<code>use std::net::SocketAddr;
use tokio::net::TcpListener;
use warp::Filter;
use warp::hyper::StatusCode;

#[tokio::main]
async fn main() {
    println!("Starting up...");
    let url = "0.0.0.0:3014";
    let listener = TcpListener::bind(url)
        .await
        .unwrap();

    println!("Listing on default URL");

    tokio::spawn(async move {
        run_health_check().await;
    });

    loop {
        match listener.accept().await {
            Ok((stream, _)) => {
                let addr = stream.peer_addr().expect("connected streams should have a peer address");
                println!("Peer address: {}", addr);

                let ws_stream = tokio_tungstenite::accept_async(stream)
                    .await
                    .expect("Error during the websocket handshake occurred");

                println!("New WebSocket connection: {}", addr);

                drop(ws_stream);
            }
            Err(e) => panic!("{:#?}", e),
        }
    }
}

async fn run_health_check() {
    let routes = warp::get()
        .and(warp::path("health"))
        .map(move || Ok(warp::reply::with_status("", StatusCode::OK)))
        .with(warp::cors().allow_any_origin());

    let socket_address: SocketAddr = "0.0.0.0:3015".to_string().parse().unwrap();

    warp::serve(routes).run(socket_address).await;
}
</code>```

This is the ECS configuration:

```<code>{
    "taskDefinitionArn": "arn:aws:ecs:eu-central-1:XXXX:task-definition/websocket:3",
    "containerDefinitions": [
        {
            "name": "websocket",
            "image": "XXX.dkr.ecr.eu-central-1.amazonaws.com/hello3",
            "cpu": 0,
            "links": [],
            "portMappings": [
                {
                    "name": "websocket-3015-tcp",
                    "containerPort": 3015,
                    "hostPort": 3015,
                    "protocol": "tcp",
                    "appProtocol": "http"
                },
                {
                    "name": "websocket-3014-tcp",
                    "containerPort": 3014,
                    "hostPort": 3014,
                    "protocol": "tcp",
                    "appProtocol": "http"
                }
            ],
            "essential": true,
            "entryPoint": [],
            "command": [],
            "environment": [],
            "environmentFiles": [],
            "mountPoints": [],
            "volumesFrom": [],
            "secrets": [],
            "dnsServers": [],
            "dnsSearchDomains": [],
            "extraHosts": [],
            "dockerSecurityOptions": [],
            "dockerLabels": {},
            "ulimits": [],
            "logConfiguration": {
                "logDriver": "awslogs",
                "options": {
                    "awslogs-create-group": "true",
                    "awslogs-group": "/ecs/websocket",
                    "awslogs-region": "eu-central-1",
                    "awslogs-stream-prefix": "ecs"
                },
                "secretOptions": []
            },
            "healthCheck": {
                "command": [
                    "CMD-SHELL curl -f localhost:3015/health"
                ],
                "interval": 30,
                "timeout": 5,
                "retries": 3
            },
            "systemControls": []
        }
    ],
    "family": "websocket",
    "executionRoleArn": "arn:aws:iam::XXX:role/ecsTaskExecutionRole",
    "networkMode": "awsvpc",
    "revision": 3,
    "volumes": [],
    "status": "ACTIVE",
    "requiresAttributes": [
        {
            "name": "com.amazonaws.ecs.capability.logging-driver.awslogs"
        },
        {
            "name": "com.amazonaws.ecs.capability.docker-remote-api.1.24"
        },
        {
            "name": "ecs.capability.execution-role-awslogs"
        },
        {
            "name": "com.amazonaws.ecs.capability.ecr-auth"
        },
        {
            "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
        },
        {
            "name": "com.amazonaws.ecs.capability.docker-remote-api.1.17"
        },
        {
            "name": "ecs.capability.container-health-check"
        },
        {
            "name": "ecs.capability.execution-role-ecr-pull"
        },
        {
            "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
        },
        {
            "name": "ecs.capability.task-eni"
        },
        {
            "name": "com.amazonaws.ecs.capability.docker-remote-api.1.29"
        }
    ],
    "placementConstraints": [],
    "compatibilities": [
        "EC2",
        "FARGATE"
    ],
    "requiresCompatibilities": [
        "FARGATE"
    ],
    "cpu": "1024",
    "memory": "3072",
    "runtimePlatform": {
        "cpuArchitecture": "ARM64",
        "operatingSystemFamily": "LINUX"
    },
    "registeredAt": "2022-12-11T11:19:54.622Z",
    "registeredBy": "arn:aws:iam::465984508737:root",
    "tags": [
        {
            "key": "ecs:taskDefinition:createdFrom",
            "value": "ecs-console-v2"
        },
        {
            "key": "ecs:taskDefinition:stackId",
            "value": "arn:aws:cloudformation:eu-central-1:XX:stack/ECS-Console-V2-TaskDefinition-c246faa1-4ba5-4b54-ac4a-49ae00ab2f0d/8fd98e10-7944-11ed-abb2-0a564ca58c2a"
        }
    ]
}
</code>```

Dockerfile:

```<code>FROM rustlang/rust:nightly-bullseye AS builder

WORKDIR app

COPY . .
RUN cargo build --bin hello -Z sparse-registry

FROM debian:11.5
COPY --from=builder ./app/target/debug/hello .

CMD ["./hello"]
</code>```

Body:
I want to run a Rust application in ECS. The Rust application has a health API and a websocket API. I can not connect to both from my machine to ECS and ECS itself even fails to query the health API using localhost, so I am doing a lot of stuff wrong and I do not know what. It works on my machine.

I checked my security groups, it allows everything. The whole Rust application can be found here: https://github.com/Jasperav/ssh-dockerfile/blob/master/src/main.rs. The relevant code (main.rs) can be found below.

I uploaded the Rust image to ECR public as well: https://eu-central-1.console.aws.amazon.com/ecr/repositories/public/465984508737/hello?region=eu-central-1. This can be deployed on an ARM machine.

The steps I took:

Made a Rust application which serves 2 endpoints, websocket and HTTP

Created an image and uploaded to ECR

In ECS, I created a new cluster with 1 public subnet. I used Fargate as infrastructure.

In the task definition, I mapped port 3014 and 3015 to TCP HTTP and selected my image. In the health api, I added CMD-SHELL curl -f localhost:3015/health

I deployed the task as a service to the cluster.

I verified I see the logging of the server that it is deployed successfully. However, I can not connect through the public ipv4 address to either the websocket API or health API.

What did I do wrong? This is the relevant code:

use std::net::SocketAddr;
use tokio::net::TcpListener;
use warp::Filter;
use warp::hyper::StatusCode;

#[tokio::main]
async fn main() {
    println!("Starting up...");
    let url = "0.0.0.0:3014";
    let listener = TcpListener::bind(url)
        .await
        .unwrap();

    println!("Listing on default URL");

    tokio::spawn(async move {
        run_health_check().await;
    });

    loop {
        match listener.accept().await {
            Ok((stream, _)) => {
                let addr = stream.peer_addr().expect("connected streams should have a peer address");
                println!("Peer address: {}", addr);

                let ws_stream = tokio_tungstenite::accept_async(stream)
                    .await
                    .expect("Error during the websocket handshake occurred");

                println!("New WebSocket connection: {}", addr);

                drop(ws_stream);
            }
            Err(e) => panic!("{:#?}", e),
        }
    }
}

async fn run_health_check() {
    let routes = warp::get()
        .and(warp::path("health"))
        .map(move || Ok(warp::reply::with_status("", StatusCode::OK)))
        .with(warp::cors().allow_any_origin());

    let socket_address: SocketAddr = "0.0.0.0:3015".to_string().parse().unwrap();

    warp::serve(routes).run(socket_address).await;
}

This is the ECS configuration:

{
    "taskDefinitionArn": "arn:aws:ecs:eu-central-1:XXXX:task-definition/websocket:3",
    "containerDefinitions": [
        {
            "name": "websocket",
            "image": "XXX.dkr.ecr.eu-central-1.amazonaws.com/hello3",
            "cpu": 0,
            "links": [],
            "portMappings": [
                {
                    "name": "websocket-3015-tcp",
                    "containerPort": 3015,
                    "hostPort": 3015,
                    "protocol": "tcp",
                    "appProtocol": "http"
                },
                {
                    "name": "websocket-3014-tcp",
                    "containerPort": 3014,
                    "hostPort": 3014,
                    "protocol": "tcp",
                    "appProtocol": "http"
                }
            ],
            "essential": true,
            "entryPoint": [],
            "command": [],
            "environment": [],
            "environmentFiles": [],
            "mountPoints": [],
            "volumesFrom": [],
            "secrets": [],
            "dnsServers": [],
            "dnsSearchDomains": [],
            "extraHosts": [],
            "dockerSecurityOptions": [],
            "dockerLabels": {},
            "ulimits": [],
            "logConfiguration": {
                "logDriver": "awslogs",
                "options": {
                    "awslogs-create-group": "true",
                    "awslogs-group": "/ecs/websocket",
                    "awslogs-region": "eu-central-1",
                    "awslogs-stream-prefix": "ecs"
                },
                "secretOptions": []
            },
            "healthCheck": {
                "command": [
                    "CMD-SHELL curl -f localhost:3015/health"
                ],
                "interval": 30,
                "timeout": 5,
                "retries": 3
            },
            "systemControls": []
        }
    ],
    "family": "websocket",
    "executionRoleArn": "arn:aws:iam::XXX:role/ecsTaskExecutionRole",
    "networkMode": "awsvpc",
    "revision": 3,
    "volumes": [],
    "status": "ACTIVE",
    "requiresAttributes": [
        {
            "name": "com.amazonaws.ecs.capability.logging-driver.awslogs"
        },
        {
            "name": "com.amazonaws.ecs.capability.docker-remote-api.1.24"
        },
        {
            "name": "ecs.capability.execution-role-awslogs"
        },
        {
            "name": "com.amazonaws.ecs.capability.ecr-auth"
        },
        {
            "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
        },
        {
            "name": "com.amazonaws.ecs.capability.docker-remote-api.1.17"
        },
        {
            "name": "ecs.capability.container-health-check"
        },
        {
            "name": "ecs.capability.execution-role-ecr-pull"
        },
        {
            "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
        },
        {
            "name": "ecs.capability.task-eni"
        },
        {
            "name": "com.amazonaws.ecs.capability.docker-remote-api.1.29"
        }
    ],
    "placementConstraints": [],
    "compatibilities": [
        "EC2",
        "FARGATE"
    ],
    "requiresCompatibilities": [
        "FARGATE"
    ],
    "cpu": "1024",
    "memory": "3072",
    "runtimePlatform": {
        "cpuArchitecture": "ARM64",
        "operatingSystemFamily": "LINUX"
    },
    "registeredAt": "2022-12-11T11:19:54.622Z",
    "registeredBy": "arn:aws:iam::465984508737:root",
    "tags": [
        {
            "key": "ecs:taskDefinition:createdFrom",
            "value": "ecs-console-v2"
        },
        {
            "key": "ecs:taskDefinition:stackId",
            "value": "arn:aws:cloudformation:eu-central-1:XX:stack/ECS-Console-V2-TaskDefinition-c246faa1-4ba5-4b54-ac4a-49ae00ab2f0d/8fd98e10-7944-11ed-abb2-0a564ca58c2a"
        }
    ]
}

Dockerfile:

FROM rustlang/rust:nightly-bullseye AS builder

WORKDIR app

COPY . .
RUN cargo build --bin hello -Z sparse-registry

FROM debian:11.5
COPY --from=builder ./app/target/debug/hello .

CMD ["./hello"]


问:
Can I put python code to an bootable .iso file and then boot it?
I don't want to create a bootable iso with a python script, I wanna put a python script on an .iso so I could then boot it. Is there like a simple OS that is actually just a cli python interpreter?

I tried searching for it but I couldn't find any answers


问:
Is there any meaning to measure ture negative over all negative response?
When we want to assess the quality of a positive prediction made by the model, which is the number of true positives divided by the total number of positive predictions.

Also, the recall shows the model's ability to detect positive samples and biases towrds negative predictions, which is the ratio between the numbers of true positivto the total number of positive samples.

Is there any meaning in the ratio between True negative and all negative predictions??


问:
Passing map parameters to a function in Clojure
I have the following function:

```<code>(defn add-column-2
  [catalog columns]
  (println "Add-column-2")
  (update-in catalog ["streams" (column->tap-stream-id (:v1 columns))]
             add-column-to-stream
             (:v1 columns)
             (:v2 columns)))
</code>```

In other words, I want that columns parameter as a map so that I can use the parameters v1 and v2 inside the function.

For that purpose, I am calling this function like:

```<code>(reduce add-column-2 empty-catalog all-columns)
</code>```

Where all-columns is a map that contains v1 and v2 keys as you can see from this image:

And empty-catalog is:

```<code>(def empty-catalog {"streams" {}})
</code>```

However, when I am debugging, in the add-column-2 function parameters:

catalog: Comes as expected.

columns: Only map entry with v1 key is passing as you can see from the image below.

The question is, why the v2 key is not passing to the add-column-2 function? How can I pass whole map as a parameter?

P.S. During my investigation, I saw this question however when I try like this, I am still unable to get that v2 key (it returns null).

Body:
I have the following function:

(defn add-column-2
  [catalog columns]
  (println "Add-column-2")
  (update-in catalog ["streams" (column->tap-stream-id (:v1 columns))]
             add-column-to-stream
             (:v1 columns)
             (:v2 columns)))

In other words, I want that columns parameter as a map so that I can use the parameters v1 and v2 inside the function.

For that purpose, I am calling this function like:

(reduce add-column-2 empty-catalog all-columns)

Where all-columns is a map that contains v1 and v2 keys as you can see from this image:

And empty-catalog is:

(def empty-catalog {"streams" {}})

However, when I am debugging, in the add-column-2 function parameters:

catalog: Comes as expected.

columns: Only map entry with v1 key is passing as you can see from the image below.

The question is, why the v2 key is not passing to the add-column-2 function? How can I pass whole map as a parameter?

P.S. During my investigation, I saw this question however when I try like this, I am still unable to get that v2 key (it returns null).


问:
How is it possible that node.js creates 2 instances of singleton class?
Setup: typescript 4.9.4, next.js 13.0.6

What I’m trying to do: messenger app. Messaging system based in Server-sent events (SSE), not WS

What’s the idea: incoming messages are handled by SSE endpoint: https://github.com/sincerely-manny/messenger.nextjs/blob/main/pages/api/messenger/incoming.ts

outgoing messages are being accepted as POST-requests here: https://github.com/sincerely-manny/messenger.nextjs/blob/main/pages/api/messenger/outgoing.ts

Singleton-class is collecting list of clients/connections and response-objects: https://github.com/sincerely-manny/messenger.nextjs/blob/main/lib/sse/serverSentEvents.ts

Whenever anyone needs to send a message he is to grab the instance of SSE class and trigger the "send" method.

Front-end part: https://github.com/sincerely-manny/messenger.nextjs/blob/main/app/messenger/page.tsx

Expected behaviour: upon establishing first connection instance of SSE class is created. Then every call of the send method finds corresponding to the client response object and and puts message to the stream

Actual behaviour: upon connecting to sse endpoint instance (1) of the class is created. Client is registered in list. But (!) sending a message creates another (2) instance of singleton-class with empty clients list. Hence sent message is lost. But (!!) after refreshing the page and creating new connection app takes this second (2) instance, puts client there and everything starts working as expected.

The question: how’s that possible and what should I do to avoid this unwanted behaviour.

Update: turns out the problem persists only in dev mode, while compiling pages on-the-fly. That makes it easier, but doesn’t explain why it happens.


问:
Display Image from ftp server Reactjs
I have upload image To my ftp server,How to display it in reactjs as image src??

I try this "http://ftpsevername/img.jpg"
but it didn't work

Title: Display Image from ftp server Reactjs


问:
java.lang.IllegalArgumentException: Unable to find GatewayFilterFactory with name Hystrix
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-12-11 19:54:13.499 ERROR 17248 --- [ main] o.s.boot.SpringApplication : Application run failed

org.springframework.context.ApplicationContextException: Failed to start bean 'eurekaAutoServiceRegistration'; nested exception is java.lang.IllegalArgumentException: Unable to find GatewayFilterFactory with name Hystrix
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.24.jar:5.3.24]
at java.lang.Iterable.forEach(Iterable.java:75) ~[na:1.8.0_292]
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:66) ~[spring-boot-2.7.6.jar:2.7.6]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:731) [spring-boot-2.7.6.jar:2.7.6]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) [spring-boot-2.7.6.jar:2.7.6]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-2.7.6.jar:2.7.6]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) [spring-boot-2.7.6.jar:2.7.6]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) [spring-boot-2.7.6.jar:2.7.6]
at com.example.gatewayserve.GatewayServeApplication.main(GatewayServeApplication.java:10) [classes/:na]
Caused by: java.lang.IllegalArgumentException: Unable to find GatewayFilterFactory with name Hystrix
at org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator.loadGatewayFilters(RouteDefinitionRouteLocator.java:130) ~[spring-cloud-gateway-server-3.1.4.jar:3.1.4]
at org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator.getFilters(RouteDefinitionRouteLocator.java:176) ~[spring-cloud-gateway-server-3.1.4.jar:3.1.4]
at org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator.convertToRoute(RouteDefinitionRouteLocator.java:117) ~[spring-cloud-gateway-server-3.1.4.jar:3.1.4]
at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:106) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxFlatMap$FlatMapMain.tryEmitScalar(FluxFlatMap.java:488) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxFlatMap$FlatMapMain.onNext(FluxFlatMap.java:421) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxMergeSequential$MergeSequentialMain.drain(FluxMergeSequential.java:432) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxMergeSequential$MergeSequentialMain.innerComplete(FluxMergeSequential.java:328) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxMergeSequential$MergeSequentialInner.onSubscribe(FluxMergeSequential.java:552) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:165) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:87) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.Flux.subscribe(Flux.java:8642) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxMergeSequential$MergeSequentialMain.onNext(FluxMergeSequential.java:237) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable$IterableSubscription.slowPath(FluxIterable.java:272) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable$IterableSubscription.request(FluxIterable.java:230) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxMergeSequential$MergeSequentialMain.onSubscribe(FluxMergeSequential.java:198) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:165) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:87) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.Flux.subscribe(Flux.java:8642) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxMergeSequential$MergeSequentialMain.onNext(FluxMergeSequential.java:237) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable$IterableSubscription.slowPath(FluxIterable.java:272) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable$IterableSubscription.request(FluxIterable.java:230) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxMergeSequential$MergeSequentialMain.onSubscribe(FluxMergeSequential.java:198) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:165) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:87) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.InternalFluxOperator.subscribe(InternalFluxOperator.java:62) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxDefer.subscribe(FluxDefer.java:54) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.Flux.subscribe(Flux.java:8642) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.Flux.blockLast(Flux.java:2760) ~[reactor-core-3.4.25.jar:3.4.25]
at org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter.lambda$onApplicationEvent$0(WeightCalculatorWebFilter.java:133) ~[spring-cloud-gateway-server-3.1.4.jar:3.1.4]
at org.springframework.beans.factory.support.DefaultListableBeanFactory$DependencyObjectProvider.ifAvailable(DefaultListableBeanFactory.java:2046) ~[spring-beans-5.3.24.jar:5.3.24]
at org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter.onApplicationEvent(WeightCalculatorWebFilter.java:133) ~[spring-cloud-gateway-server-3.1.4.jar:3.1.4]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:421) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:378) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.cloud.gateway.route.RouteRefreshListener.reset(RouteRefreshListener.java:73) ~[spring-cloud-gateway-server-3.1.4.jar:3.1.4]
at org.springframework.cloud.gateway.route.RouteRefreshListener.onApplicationEvent(RouteRefreshListener.java:54) ~[spring-cloud-gateway-server-3.1.4.jar:3.1.4]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:421) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:378) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration.start(EurekaAutoServiceRegistration.java:85) ~[spring-cloud-netflix-eureka-client-3.1.4.jar:3.1.4]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ~[spring-context-5.3.24.jar:5.3.24]
... 14 common frames omitted
Suppressed: java.lang.Exception: #block terminated with an error
at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:99) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.Flux.blockLast(Flux.java:2761) ~[reactor-core-3.4.25.jar:3.4.25]
... 31 common frames omitted

and this is my pom dependies
jdk version 1.8

```<code>    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
        <version>2.7.6</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        <version>2.2.10.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-netflix-hystrix -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-netflix-hystrix</artifactId>
        <version>2.2.10.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-server -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        <version>3.1.4</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
</code>```

and this is application.yaml

```<code>spring:
  application:
    name: gateway-server
  cloud:
    gateway:
      discovery:
        locator:
          lower-case-service-id: true
          enabled: true
      routes:
        - id: one
          uri: http://127.0.0.1:7001
          predicates:
            - Path=/**
            - Header=Connection,keep-alive
            - Method=GET,POST
          filters:
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 1
                redis-rate-limiter.burstCapacity: 3
                key-resolver: '#{@abcComponent}'
            - name: Hystrix
              args:
                name: fallbackcmd
                fallbackUri: forward:/myhystrix
  redis:
    host: 192.168.85.129
    port: 6379
    database: 10

eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka
server:
  port: 9999
</code>```

i already try to use hystrix 2.2.5,it doesnt work.

how can i resolve this problem..

Body:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-12-11 19:54:13.499 ERROR 17248 --- [ main] o.s.boot.SpringApplication : Application run failed

org.springframework.context.ApplicationContextException: Failed to start bean 'eurekaAutoServiceRegistration'; nested exception is java.lang.IllegalArgumentException: Unable to find GatewayFilterFactory with name Hystrix
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.24.jar:5.3.24]
at java.lang.Iterable.forEach(Iterable.java:75) ~[na:1.8.0_292]
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:66) ~[spring-boot-2.7.6.jar:2.7.6]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:731) [spring-boot-2.7.6.jar:2.7.6]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) [spring-boot-2.7.6.jar:2.7.6]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-2.7.6.jar:2.7.6]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) [spring-boot-2.7.6.jar:2.7.6]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) [spring-boot-2.7.6.jar:2.7.6]
at com.example.gatewayserve.GatewayServeApplication.main(GatewayServeApplication.java:10) [classes/:na]
Caused by: java.lang.IllegalArgumentException: Unable to find GatewayFilterFactory with name Hystrix
at org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator.loadGatewayFilters(RouteDefinitionRouteLocator.java:130) ~[spring-cloud-gateway-server-3.1.4.jar:3.1.4]
at org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator.getFilters(RouteDefinitionRouteLocator.java:176) ~[spring-cloud-gateway-server-3.1.4.jar:3.1.4]
at org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator.convertToRoute(RouteDefinitionRouteLocator.java:117) ~[spring-cloud-gateway-server-3.1.4.jar:3.1.4]
at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:106) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxFlatMap$FlatMapMain.tryEmitScalar(FluxFlatMap.java:488) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxFlatMap$FlatMapMain.onNext(FluxFlatMap.java:421) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxMergeSequential$MergeSequentialMain.drain(FluxMergeSequential.java:432) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxMergeSequential$MergeSequentialMain.innerComplete(FluxMergeSequential.java:328) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxMergeSequential$MergeSequentialInner.onSubscribe(FluxMergeSequential.java:552) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:165) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:87) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.Flux.subscribe(Flux.java:8642) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxMergeSequential$MergeSequentialMain.onNext(FluxMergeSequential.java:237) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable$IterableSubscription.slowPath(FluxIterable.java:272) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable$IterableSubscription.request(FluxIterable.java:230) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxMergeSequential$MergeSequentialMain.onSubscribe(FluxMergeSequential.java:198) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:165) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:87) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.Flux.subscribe(Flux.java:8642) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxMergeSequential$MergeSequentialMain.onNext(FluxMergeSequential.java:237) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable$IterableSubscription.slowPath(FluxIterable.java:272) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable$IterableSubscription.request(FluxIterable.java:230) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxMergeSequential$MergeSequentialMain.onSubscribe(FluxMergeSequential.java:198) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:165) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxIterable.subscribe(FluxIterable.java:87) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.InternalFluxOperator.subscribe(InternalFluxOperator.java:62) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.FluxDefer.subscribe(FluxDefer.java:54) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.Flux.subscribe(Flux.java:8642) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.Flux.blockLast(Flux.java:2760) ~[reactor-core-3.4.25.jar:3.4.25]
at org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter.lambda$onApplicationEvent$0(WeightCalculatorWebFilter.java:133) ~[spring-cloud-gateway-server-3.1.4.jar:3.1.4]
at org.springframework.beans.factory.support.DefaultListableBeanFactory$DependencyObjectProvider.ifAvailable(DefaultListableBeanFactory.java:2046) ~[spring-beans-5.3.24.jar:5.3.24]
at org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter.onApplicationEvent(WeightCalculatorWebFilter.java:133) ~[spring-cloud-gateway-server-3.1.4.jar:3.1.4]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:421) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:378) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.cloud.gateway.route.RouteRefreshListener.reset(RouteRefreshListener.java:73) ~[spring-cloud-gateway-server-3.1.4.jar:3.1.4]
at org.springframework.cloud.gateway.route.RouteRefreshListener.onApplicationEvent(RouteRefreshListener.java:54) ~[spring-cloud-gateway-server-3.1.4.jar:3.1.4]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:421) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:378) ~[spring-context-5.3.24.jar:5.3.24]
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration.start(EurekaAutoServiceRegistration.java:85) ~[spring-cloud-netflix-eureka-client-3.1.4.jar:3.1.4]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ~[spring-context-5.3.24.jar:5.3.24]
... 14 common frames omitted
Suppressed: java.lang.Exception: #block terminated with an error
at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:99) ~[reactor-core-3.4.25.jar:3.4.25]
at reactor.core.publisher.Flux.blockLast(Flux.java:2761) ~[reactor-core-3.4.25.jar:3.4.25]
... 31 common frames omitted

and this is my pom dependies
jdk version 1.8

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
        <version>2.7.6</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        <version>2.2.10.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-netflix-hystrix</artifactId>
        <version>2.2.10.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        <version>3.1.4</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

and this is application.yaml

spring:
  application:
    name: gateway-server
  cloud:
    gateway:
      discovery:
        locator:
          lower-case-service-id: true
          enabled: true
      routes:
        - id: one
          uri: http://127.0.0.1:7001
          predicates:
            - Path=/**
            - Header=Connection,keep-alive
            - Method=GET,POST
          filters:
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 1
                redis-rate-limiter.burstCapacity: 3
                key-resolver: '#{@abcComponent}'
            - name: Hystrix
              args:
                name: fallbackcmd
                fallbackUri: forward:/myhystrix
  redis:
    host: 192.168.85.129
    port: 6379
    database: 10

eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka
server:
  port: 9999

i already try to use hystrix 2.2.5,it doesnt work.

how can i resolve this problem..


问:
'async_hooks' cant be found
I'm trying to bundle my js file with browserify and babel: browserify ./src/background.js > ./dist/bundle.js -t babelify

The full error message I get is: Error: Can't walk dependency graph: ENOENT: no such file or directory, lstat 'D:\prog\html\extvone\async_hooks' required by D:\prog\html\extvone\node_modules\on-finished\index.js

When I looked into on-finished\index.js I saw there was a require for require('async_hooks'), but async_hooks didn't lead to a .js file, or anything.

I tried installing all the packages to the same version with npm i and update NPM globally as mentioned here, and also intalling async_hooks with npm install.

Edit:

background.js first lines:

```<code>import PythonShell from 'python-shell';

const express = require('express');
const app = express();
</code>```

package.json includes:

```<code>  "dependencies": {
    "express": "^4.18.2",
    "python-shell": "^3.0.1"
  },
  "devDependencies": {
    "@babel/core": "^7.20.5",
    "@babel/preset-env": "^7.20.2",
    "@types/express": "^4.17.14",
    "babelify": "^10.0.0"
  }
</code>```

Versions are the following: Node -> 18.12.1 LTS 'express' -> 4.18.2

The 'express' module is the root of the problem. Without it - everything works smoothly.

Update:

As mentioned in the comments, I tried to use a node-only nodule in the browser. What I actually did is deleted all the dependency on it. In a more general note, I started using VITE instead of Browserify.

Title: 'async_hooks' cant be found

Body:
I'm trying to bundle my js file with browserify and babel: browserify ./src/background.js > ./dist/bundle.js -t babelify

The full error message I get is: Error: Can't walk dependency graph: ENOENT: no such file or directory, lstat 'D:\prog\html\extvone\async_hooks' required by D:\prog\html\extvone\node_modules\on-finished\index.js

When I looked into on-finished\index.js I saw there was a require for require('async_hooks'), but async_hooks didn't lead to a .js file, or anything.

I tried installing all the packages to the same version with npm i and update NPM globally as mentioned here, and also intalling async_hooks with npm install.

Edit:

background.js first lines:

import PythonShell from 'python-shell';

const express = require('express');
const app = express();

package.json includes:

  "dependencies": {
    "express": "^4.18.2",
    "python-shell": "^3.0.1"
  },
  "devDependencies": {
    "@babel/core": "^7.20.5",
    "@babel/preset-env": "^7.20.2",
    "@types/express": "^4.17.14",
    "babelify": "^10.0.0"
  }

Versions are the following: Node -> 18.12.1 LTS 'express' -> 4.18.2

The 'express' module is the root of the problem. Without it - everything works smoothly.

Update:

As mentioned in the comments, I tried to use a node-only nodule in the browser. What I actually did is deleted all the dependency on it. In a more general note, I started using VITE instead of Browserify.


问:
Why is Kotlin’s ArrayDeque a concrete class without an interface?
Of course, I can use the whole Java standard library as long as I stay on the JVM, but quite often Kotlin offers equivalent classes, sometimes shadowing Java’s classes (and using them behind my back). As such, Kotlin offers an ArrayDeque to replace Java’s ArrayDeque.

Now, the good old java.util.ArrayDeque, being in line with the other collection classes, implements the interface java.util.Deque (it’s actually one of four such implementations in java.util. That is usually considered good practice, if you just care for a Deque you should not need to know whether it is implemented using an array or a list.

However, the new-fangled kotlin.collections.ArrayDeque (where actually the package name is redundant, since it is accessible without) has no interface it implements, apart from MutableList, which is too generic.

I don’t want to trigger opinion-based answers here, even if I can already imagine a few of them. Rather, I wonder if there may exist a hard technical reason to decide against using a strategy used in other places of the Kotlin standard library itself.


问:
"IndexError: string index out of range" when injecting SQL statements from a list via for-loop
I try to read a column of a .csv file into a database with psycopg2.
The data from the column in the .csv comes in form:
<other_col>   genres
<...>       Rock|Pop|Metallic Doom Rock|...

I first read these values row-wise and split "|", them and append everything to one list where I remove duplicates with set.
My input file needed a little formatting and have to be unique, thus I transformed the values into a list(set(data))).

When for-looping over said list to build SQL statements that should implant the values, I get "IndexError: string index out of range" and I don't understand why, since I read elements from a list and not a single string. Can someone give me a hint, where I fail?

test = csv_to_dict("artists.csv", "\t")    #this is a predefined function, that just reads csv.dictReader and the csv-file is tab-separated.

genre_list =[]
for row in test:
    genres = (row['genres'])
    genres = (genres.split(sep="|"))    # this is to "clean" and generate list with unique genres
    for p in genres:
        genre_list.append(p.title())
genre_list = list(set(genre_list))
genre_list.sort()

cur = sql_con.cursor()
sql = 'INSERT INTO Genre (GenreName) VALUES(%s);' # here I expect genre from genre_list to be inserted @ %s
for genre in genre_list:
    cur.execute(sql, genre)
sql_con.commit()

```
<p>Result:</p>
```Traceback (most recent call last):
  File "/Users/.../IngestData.py", line 76, in <module>
    cur.execute(sql, t)
IndexError: string index out of range
```

Body:
I try to read a column of a .csv file into a database with psycopg2.
The data from the column in the .csv comes in form:
<other_col>   genres
<...>       Rock|Pop|Metallic Doom Rock|...

I first read these values row-wise and split "|", them and append everything to one list where I remove duplicates with set.
My input file needed a little formatting and have to be unique, thus I transformed the values into a list(set(data))).

When for-looping over said list to build SQL statements that should implant the values, I get "IndexError: string index out of range" and I don't understand why, since I read elements from a list and not a single string. Can someone give me a hint, where I fail?

test = csv_to_dict("artists.csv", "\t")    #this is a predefined function, that just reads csv.dictReader and the csv-file is tab-separated.

genre_list =[]
for row in test:
    genres = (row['genres'])
    genres = (genres.split(sep="|"))    # this is to "clean" and generate list with unique genres
    for p in genres:
        genre_list.append(p.title())
genre_list = list(set(genre_list))
genre_list.sort()

cur = sql_con.cursor()
sql = 'INSERT INTO Genre (GenreName) VALUES(%s);' # here I expect genre from genre_list to be inserted @ %s
for genre in genre_list:
    cur.execute(sql, genre)
sql_con.commit()

Result:

Traceback (most recent call last):
  File "/Users/.../IngestData.py", line 76, in <module>
    cur.execute(sql, t)
IndexError: string index out of range