问:
Create dynamic joins using nodejs
I am creating dynamic joins using NodeJS, I am working on a custom report module user select component just like an above array and I wrote some logic to create dynamic join to fetch data according to requirements. I put my code please guide me what I am doing wrong or what to improve in my code.

Here is my payload

```<code>let dataarray=[
{
TableName: 'Allergies',
ReferencePrimaryKey: [ 'Id' ],
ReferenceForeignKeys: [ 'PatientId', 'UserId', 'VisitId', 'CFModuleId' ]
},
{
TableName: 'Diagnosis',
ReferencePrimaryKey: [ 'Id' ],
ReferenceForeignKeys: [ 'PatientId', 'UserId', 'VisitId', 'CFModuleId' ]
},
{
TableName: 'FamilyHistory',
ReferencePrimaryKey: [ 'Id' ],
ReferenceForeignKeys: [ 'PatientId', 'UserId', 'VisitId', 'CFModuleId' ]
},
{
TableName: 'MedicalHistory',
ReferencePrimaryKey: [ 'Id' ],
ReferenceForeignKeys: [ 'PatientId', 'UserId', 'VisitId', 'CFModuleId' ]
},
{
TableName: 'Medications',
ReferencePrimaryKey: [ 'MedicationId' ],
ReferenceForeignKeys: [ 'PatientId', 'UserId', 'VisitId', 'CFModuleId' ]
},
{
TableName: 'MedicationsDetails',
ReferencePrimaryKey: [ 'MedicationDetailId' ],
ReferenceForeignKeys: [ 'MedicationId' ]
},
{
TableName: 'Patients',
ReferencePrimaryKey: [ 'PatientId' ],
ReferenceForeignKeys: [ 'LanguageId', 'PatientTypeId', 'BloodGroupId' ]
},
{
TableName: 'PatientVisitDetails',
ReferencePrimaryKey: [ 'VisitDetailId' ],
ReferenceForeignKeys: [
  'UnitId',
  'PatientId',
  'DepartmentId',
  'UserId',
  'ClinicId',
  'VisitTypeId',
  'VisitStatusId'
]
},
{
TableName: 'SocialHistory',
ReferencePrimaryKey: [ 'Id' ],
ReferenceForeignKeys: [ 'PatientId', 'UserId', 'VisitId', 'CFModuleId' ]
},
{
TableName: 'SurgicalHistory',
ReferencePrimaryKey: [ 'Id' ],
ReferenceForeignKeys: [ 'PatientId', 'UserId', 'VisitId', 'CFModuleId' ]
},
{
TableName: 'Users',
ReferencePrimaryKey: [ 'UserId' ],
ReferenceForeignKeys: [ '' ]
}
]
</code>```

And here is my code

```<code>let results = [];
let joinedTables = [];

if (dataarray.length > 1) {
  let isFirst = false;
  dataarray.forEach((sourceCom) => {
    let tblIndex = 0;
    dataarray.forEach((secSourceCom) => {
      if (sourceCom.TableName != secSourceCom.TableName) {
        if (
          secSourceCom.ReferenceForeignKeys.includes(
            sourceCom.ReferencePrimaryKey[0]
          )
        ) {
          tblIndex++;
          let tbN = sourceCom.TableName;
          let tbNSecond = secSourceCom.TableName;

          displayFileds = displayFileds.filter(
            (value) => value != "undefined.undefined As undefined_undefined"
          );

          if (!isFirst) {
            results.push({
              sql: `Select * from ${tbN} LEFT JOIN ${tbNSecond} ON ${helper.alternativekeys(
                `${tbN}.${sourceCom.ReferencePrimaryKey[0]}`
              )} = ${helper.alternativekeys(
                `${tbNSecond}.${sourceCom.ReferencePrimaryKey[0]}`
              )}`,
            });
            joinedTables.push(tbN);
            joinedTables.push(tbNSecond);
          } else {

            let foundTableName = tbN;
            if (tblIndex > 1) {
              foundTableName = tbNSecond;
            }
            if (!joinedTables.includes(foundTableName)) {

              results.push({
                sql: `LEFT JOIN ${foundTableName} ON foundTableName.ReferencePrimaryKey[0]=foundTableName.ReferencePrimaryKey[0]`,
              });
              joinedTables.push(foundTableName);
            }
          }
          isFirst = true;
        }
      }
    });
  });
</code>```

Here is my output

```<code>SELECT *
FROM Medications
LEFT JOIN MedicationsDetails ON Medications.MedicationId = MedicationsDetails.MedicationId
LEFT JOIN Patients ON Patients.PatientId = Allergies.PatientId
LEFT JOIN Diagnosis ON Diagnosis.PatientId = Diagnosis.PatientId
LEFT JOIN FamilyHistory ON FamilyHistory.PatientId = FamilyHistory.PatientId
LEFT JOIN MedicalHistory ON MedicalHistory.PatientId = MedicalHistory.PatientId
LEFT JOIN PatientVisitDetails ON PatientVisitDetails.PatientId = PatientVisitDetails.PatientId
LEFT JOIN SocialHistory ON SocialHistory.PatientId = SocialHistory.PatientId
LEFT JOIN SurgicalHistory ON SurgicalHistory.PatientId = SurgicalHistory.PatientId
LEFT JOIN Users ON Users.UserId = Allergies.UserId
</code>```

Which is wrong and I want this output

```<code>SELECT *
FROM Medications
LEFT JOIN MedicationsDetails ON Medications.MedicationId = MedicationsDetails.MedicationId
LEFT JOIN Patients ON Patients.PatientId = Medications.PatientId
LEFT JOIN Allergies ON Allergies.PatientId = Patients.PatientId
LEFT JOIN Diagnosis ON Patients.PatientId = Diagnosis.PatientId
LEFT JOIN FamilyHistory ON Patients.PatientId = FamilyHistory.PatientId
LEFT JOIN MedicalHistory ON Patients.PatientId = MedicalHistory.PatientId
LEFT JOIN PatientVisitDetails ON Patients.PatientId = PatientVisitDetails.PatientId
LEFT JOIN SocialHistory ON Patients.PatientId = SocialHistory.PatientId
LEFT JOIN SurgicalHistory ON Patients.PatientId = SurgicalHistory.PatientId
LEFT JOIN Users ON Users.UserId = PatientVisitDetails.UserId
</code>```

In the above array (dataarray) if I change sorting however give me this output.

Title: Create dynamic joins using nodejs

Body:
I am creating dynamic joins using NodeJS, I am working on a custom report module user select component just like an above array and I wrote some logic to create dynamic join to fetch data according to requirements. I put my code please guide me what I am doing wrong or what to improve in my code.

Here is my payload

let dataarray=[
{
TableName: 'Allergies',
ReferencePrimaryKey: [ 'Id' ],
ReferenceForeignKeys: [ 'PatientId', 'UserId', 'VisitId', 'CFModuleId' ]
},
{
TableName: 'Diagnosis',
ReferencePrimaryKey: [ 'Id' ],
ReferenceForeignKeys: [ 'PatientId', 'UserId', 'VisitId', 'CFModuleId' ]
},
{
TableName: 'FamilyHistory',
ReferencePrimaryKey: [ 'Id' ],
ReferenceForeignKeys: [ 'PatientId', 'UserId', 'VisitId', 'CFModuleId' ]
},
{
TableName: 'MedicalHistory',
ReferencePrimaryKey: [ 'Id' ],
ReferenceForeignKeys: [ 'PatientId', 'UserId', 'VisitId', 'CFModuleId' ]
},
{
TableName: 'Medications',
ReferencePrimaryKey: [ 'MedicationId' ],
ReferenceForeignKeys: [ 'PatientId', 'UserId', 'VisitId', 'CFModuleId' ]
},
{
TableName: 'MedicationsDetails',
ReferencePrimaryKey: [ 'MedicationDetailId' ],
ReferenceForeignKeys: [ 'MedicationId' ]
},
{
TableName: 'Patients',
ReferencePrimaryKey: [ 'PatientId' ],
ReferenceForeignKeys: [ 'LanguageId', 'PatientTypeId', 'BloodGroupId' ]
},
{
TableName: 'PatientVisitDetails',
ReferencePrimaryKey: [ 'VisitDetailId' ],
ReferenceForeignKeys: [
  'UnitId',
  'PatientId',
  'DepartmentId',
  'UserId',
  'ClinicId',
  'VisitTypeId',
  'VisitStatusId'
]
},
{
TableName: 'SocialHistory',
ReferencePrimaryKey: [ 'Id' ],
ReferenceForeignKeys: [ 'PatientId', 'UserId', 'VisitId', 'CFModuleId' ]
},
{
TableName: 'SurgicalHistory',
ReferencePrimaryKey: [ 'Id' ],
ReferenceForeignKeys: [ 'PatientId', 'UserId', 'VisitId', 'CFModuleId' ]
},
{
TableName: 'Users',
ReferencePrimaryKey: [ 'UserId' ],
ReferenceForeignKeys: [ '' ]
}
]

And here is my code

let results = [];
let joinedTables = [];

if (dataarray.length > 1) {
  let isFirst = false;
  dataarray.forEach((sourceCom) => {
    let tblIndex = 0;
    dataarray.forEach((secSourceCom) => {
      if (sourceCom.TableName != secSourceCom.TableName) {
        if (
          secSourceCom.ReferenceForeignKeys.includes(
            sourceCom.ReferencePrimaryKey[0]
          )
        ) {
          tblIndex++;
          let tbN = sourceCom.TableName;
          let tbNSecond = secSourceCom.TableName;

          displayFileds = displayFileds.filter(
            (value) => value != "undefined.undefined As undefined_undefined"
          );

          if (!isFirst) {
            results.push({
              sql: `Select * from ${tbN} LEFT JOIN ${tbNSecond} ON ${helper.alternativekeys(
                `${tbN}.${sourceCom.ReferencePrimaryKey[0]}`
              )} = ${helper.alternativekeys(
                `${tbNSecond}.${sourceCom.ReferencePrimaryKey[0]}`
              )}`,
            });
            joinedTables.push(tbN);
            joinedTables.push(tbNSecond);
          } else {

            let foundTableName = tbN;
            if (tblIndex > 1) {
              foundTableName = tbNSecond;
            }
            if (!joinedTables.includes(foundTableName)) {

              results.push({
                sql: `LEFT JOIN ${foundTableName} ON foundTableName.ReferencePrimaryKey[0]=foundTableName.ReferencePrimaryKey[0]`,
              });
              joinedTables.push(foundTableName);
            }
          }
          isFirst = true;
        }
      }
    });
  });

Here is my output

SELECT *
FROM Medications
LEFT JOIN MedicationsDetails ON Medications.MedicationId = MedicationsDetails.MedicationId
LEFT JOIN Patients ON Patients.PatientId = Allergies.PatientId
LEFT JOIN Diagnosis ON Diagnosis.PatientId = Diagnosis.PatientId
LEFT JOIN FamilyHistory ON FamilyHistory.PatientId = FamilyHistory.PatientId
LEFT JOIN MedicalHistory ON MedicalHistory.PatientId = MedicalHistory.PatientId
LEFT JOIN PatientVisitDetails ON PatientVisitDetails.PatientId = PatientVisitDetails.PatientId
LEFT JOIN SocialHistory ON SocialHistory.PatientId = SocialHistory.PatientId
LEFT JOIN SurgicalHistory ON SurgicalHistory.PatientId = SurgicalHistory.PatientId
LEFT JOIN Users ON Users.UserId = Allergies.UserId

Which is wrong and I want this output

SELECT *
FROM Medications
LEFT JOIN MedicationsDetails ON Medications.MedicationId = MedicationsDetails.MedicationId
LEFT JOIN Patients ON Patients.PatientId = Medications.PatientId
LEFT JOIN Allergies ON Allergies.PatientId = Patients.PatientId
LEFT JOIN Diagnosis ON Patients.PatientId = Diagnosis.PatientId
LEFT JOIN FamilyHistory ON Patients.PatientId = FamilyHistory.PatientId
LEFT JOIN MedicalHistory ON Patients.PatientId = MedicalHistory.PatientId
LEFT JOIN PatientVisitDetails ON Patients.PatientId = PatientVisitDetails.PatientId
LEFT JOIN SocialHistory ON Patients.PatientId = SocialHistory.PatientId
LEFT JOIN SurgicalHistory ON Patients.PatientId = SurgicalHistory.PatientId
LEFT JOIN Users ON Users.UserId = PatientVisitDetails.UserId

In the above array (dataarray) if I change sorting however give me this output.


来源: stackexchange

问:
is Automatic migration in Typescript Sequelize Postgresql possible from a existing model (in Sequelize ORM Only)
Is there any way of Automatic migration in Typescript sequelize PostgreSQL using sequelize ORM only?
I know in JavaScript we can automatic migration, but in typescript is this possible?
Suppose I have existing models like /models/users.ts, now I need to migrate this model and want to update my database.

I want automatic migrate my existed model (models/users.ts), but I'm not able to find a way, sequelize docs also not mention how can migrate using sequelize ORM in Typescript

ContentLicense: CC BY-SA 4.0


问:
Is it ok to create a redux store within a React component?
I am trying to inject the getAccessToken function to the thunk for later use in action creators (and rtk-query). In redux tutorials I always found the the store is declared as a global constant:

```<code>const store = configureStore(...);
</code>```

But in this case I cannot inject the function to the store because it is outside of a React component. So I have come up with the following snippet:

```<code>const App = () => {
  const { getAccessToken } = useAuth0();
  const store = useMemo(() =>
    return configureStore({
      reducer: rootReducer,
      middleware: (getDefaultMiddleware) => getMiddleware({
        thunk: {
          extraArguemnt: {
            getAccessToken,
          }
        }
      }),
    });
  }, [getAccessToken]);

  return (
    <Provider store={store}>
      ... some components
    </Provider>
  )
}
</code>```

I know how the above code works. But is it how it should work?

Body:
I am trying to inject the getAccessToken function to the thunk for later use in action creators (and rtk-query). In redux tutorials I always found the the store is declared as a global constant:

const store = configureStore(...);

But in this case I cannot inject the function to the store because it is outside of a React component. So I have come up with the following snippet:

const App = () => {
  const { getAccessToken } = useAuth0();
  const store = useMemo(() =>
    return configureStore({
      reducer: rootReducer,
      middleware: (getDefaultMiddleware) => getMiddleware({
        thunk: {
          extraArguemnt: {
            getAccessToken,
          }
        }
      }),
    });
  }, [getAccessToken]);

  return (
    <Provider store={store}>
      ... some components
    </Provider>
  )
}

I know how the above code works. But is it how it should work?


问:
is there a way to format typeorm results for postgresql like in mongo aggregate pipelines?
i have worked with MongoDB and am quite new to postgres and SQL in general. While working in mongodb, i used aggregate pipeline to format my response within the pipeline but i cannot find a way to do so in postgres. I use typeorm to make db queries.
here, i want to reshape the format of response of the typeorm query but cannot find the right method to do so within the query itself. i dont want to use js map, reduce or similar functions to do so.

in my project, i have multiple nested relationships and want all the information from a single query. i have a Floor entity with OneToMany relation with Table, Table has OneToMany relation with OrderItem, while OrderItem has ManyToOne relation with Item.
For example: i tried the following query to get orderitems inside the orders of each table in all floors:

```<code>const wadu = await floorRepository
      .createQueryBuilder("floor")
      .leftJoinAndSelect("floor.tables", "table")
      .leftJoinAndSelect("table.orders", "order")
      .leftJoinAndSelect("order.ordersitems", "orderitem")
      .leftJoinAndSelect("orderitem.item", "item")
      .select([
        "floor.id",
        "floor.name",
        "table.id",
        "table.name",
        "order.id",
        "order.referenceNumber",
        "orderitem.id",
        "item.name",
      ])
      .getMany();
</code>```

i get the following result from this query:

```<code>[
    {
        "id": "3872a671-962c-4e5a-a580-7da21d5c958f",
        "name": "2",
        "tables": [
            {
                "id": "9399258c-ab31-4299-81f1-33b0865d51a1",
                "name": "1",
                "orders": []
            },
            {
                "id": "bfd9c41d-7b0e-49c0-9612-363a4dbaa618",
                "name": "4",
                "orders": []
            },
            {
                "id": "6322cac7-0d82-47b8-b53d-78ddc852af27",
                "name": "2",
                "orders": []
            },
            {
                "id": "26f80bf7-f79b-4968-98b2-5b538a336cf1",
                "name": "3",
                "orders": [
                    {
                        "id": "f71d1e61-5370-4583-96ee-1bccdee4e98a",
                        "referenceNumber": "123",
                        "ordersitems": [
                            {
                                "id": "49ffb8fe-3629-4263-bb35-0f325c9889a1",
                                "item": {
                                    "name": "hrttr334"
                                }
                            }
                        ]
                    },
                    {
                        "id": "e353c8a1-bfa2-4634-86b4-57f7e95aa2ae",
                        "referenceNumber": "123",
                        "ordersitems": [
                            {
                                "id": "191fe3fb-2ba5-4bea-9c21-18fe91f0f442",
                                "item": {
                                    "name": "hrttr334"
                                }
                            }
                        ]
                    }
                ]
            }
        ]
    }
]
</code>```

But for this operation, my desired result is:

```<code>[
    {
        "id": "3872a671-962c-4e5a-a580-7da21d5c958f",
        "name": "2",
        "tables": [
            {
                "id": "9399258c-ab31-4299-81f1-33b0865d51a1",
                "name": "1",
                "orders": []
            },
            {
                "id": "bfd9c41d-7b0e-49c0-9612-363a4dbaa618",
                "name": "4",
                "orders": []
            },
            {
                "id": "6322cac7-0d82-47b8-b53d-78ddc852af27",
                "name": "2",
                "orders": []
            },
            {
                "id": "26f80bf7-f79b-4968-98b2-5b538a336cf1",
                "name": "3",
                "orders": [
                    {
                        "id": "f71d1e61-5370-4583-96ee-1bccdee4e98a",
                        "referenceNumber": "123",
                        "ordersitems": [
                            {
                                "id": "49ffb8fe-3629-4263-bb35-
                                "itemName": "hrttr334" // this is the name of item from the item object in the above output
                            }
                        ]
                    },
                    {
                        "id": "e353c8a1-bfa2-4634-86b4-57f7e95aa2ae",
                        "referenceNumber": "123",
                        "ordersitems": [
                            {
                                "id": "191fe3fb-2ba5-4bea-9c21-18fe91f0f442",
                                "itemName": "hrttr334" // this is the name of item from the item object in the above output
                            }
                        ]
                    }
                ]
            }
        ]
    }
]
</code>```

I am sorry for any inconvenience caused by my lack of knowledge or stupidity. Thank you.

Body:
i have worked with MongoDB and am quite new to postgres and SQL in general. While working in mongodb, i used aggregate pipeline to format my response within the pipeline but i cannot find a way to do so in postgres. I use typeorm to make db queries.
here, i want to reshape the format of response of the typeorm query but cannot find the right method to do so within the query itself. i dont want to use js map, reduce or similar functions to do so.

in my project, i have multiple nested relationships and want all the information from a single query. i have a Floor entity with OneToMany relation with Table, Table has OneToMany relation with OrderItem, while OrderItem has ManyToOne relation with Item.
For example: i tried the following query to get orderitems inside the orders of each table in all floors:

const wadu = await floorRepository
      .createQueryBuilder("floor")
      .leftJoinAndSelect("floor.tables", "table")
      .leftJoinAndSelect("table.orders", "order")
      .leftJoinAndSelect("order.ordersitems", "orderitem")
      .leftJoinAndSelect("orderitem.item", "item")
      .select([
        "floor.id",
        "floor.name",
        "table.id",
        "table.name",
        "order.id",
        "order.referenceNumber",
        "orderitem.id",
        "item.name",
      ])
      .getMany();

i get the following result from this query:

[
    {
        "id": "3872a671-962c-4e5a-a580-7da21d5c958f",
        "name": "2",
        "tables": [
            {
                "id": "9399258c-ab31-4299-81f1-33b0865d51a1",
                "name": "1",
                "orders": []
            },
            {
                "id": "bfd9c41d-7b0e-49c0-9612-363a4dbaa618",
                "name": "4",
                "orders": []
            },
            {
                "id": "6322cac7-0d82-47b8-b53d-78ddc852af27",
                "name": "2",
                "orders": []
            },
            {
                "id": "26f80bf7-f79b-4968-98b2-5b538a336cf1",
                "name": "3",
                "orders": [
                    {
                        "id": "f71d1e61-5370-4583-96ee-1bccdee4e98a",
                        "referenceNumber": "123",
                        "ordersitems": [
                            {
                                "id": "49ffb8fe-3629-4263-bb35-0f325c9889a1",
                                "item": {
                                    "name": "hrttr334"
                                }
                            }
                        ]
                    },
                    {
                        "id": "e353c8a1-bfa2-4634-86b4-57f7e95aa2ae",
                        "referenceNumber": "123",
                        "ordersitems": [
                            {
                                "id": "191fe3fb-2ba5-4bea-9c21-18fe91f0f442",
                                "item": {
                                    "name": "hrttr334"
                                }
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

But for this operation, my desired result is:

[
    {
        "id": "3872a671-962c-4e5a-a580-7da21d5c958f",
        "name": "2",
        "tables": [
            {
                "id": "9399258c-ab31-4299-81f1-33b0865d51a1",
                "name": "1",
                "orders": []
            },
            {
                "id": "bfd9c41d-7b0e-49c0-9612-363a4dbaa618",
                "name": "4",
                "orders": []
            },
            {
                "id": "6322cac7-0d82-47b8-b53d-78ddc852af27",
                "name": "2",
                "orders": []
            },
            {
                "id": "26f80bf7-f79b-4968-98b2-5b538a336cf1",
                "name": "3",
                "orders": [
                    {
                        "id": "f71d1e61-5370-4583-96ee-1bccdee4e98a",
                        "referenceNumber": "123",
                        "ordersitems": [
                            {
                                "id": "49ffb8fe-3629-4263-bb35-
                                "itemName": "hrttr334" // this is the name of item from the item object in the above output
                            }
                        ]
                    },
                    {
                        "id": "e353c8a1-bfa2-4634-86b4-57f7e95aa2ae",
                        "referenceNumber": "123",
                        "ordersitems": [
                            {
                                "id": "191fe3fb-2ba5-4bea-9c21-18fe91f0f442",
                                "itemName": "hrttr334" // this is the name of item from the item object in the above output
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

I am sorry for any inconvenience caused by my lack of knowledge or stupidity. Thank you.


问:
Web queries in google sheets
Is it possible to somehow teach Google Spreadsheet to send and receive web requests (POST, GET)? Maybe this can be done using a script.

I'm far from scripts, that's why I'm turning here.

Title: Web queries in google sheets


问:
Pygame screen disappears when the button is not being clicked
I have created a programme which has a home menu, when the user clicks on engine or multiplayer it should take them to a chess board graphic. However as soon as the mouse is released the chess board graphic disappears and the home menu is shown again. I have attached code below.

There is a variable, numberButton, which is used to see which button has been pressed and display the appropriate screen ie. the chess graphic. I am aware that as soon as the user stops clicking on the button that this variable is set back to zero which is why the main menu shows again however I do not know how to fix. Any suggestions would be appreciated :)

```<code>class button:
    def __init__(self, txt, pos):
        self.txt = txt
        self.pos = pos
        self.button = pygame.rect.Rect((self.pos[0], self.pos[1]), (200,40))

    def draw(self, SCREEN):
        pygame.draw.rect(SCREEN, 'light gray', self.button, 0 ,5)
        pygame.draw.rect(SCREEN, 'dark gray', self.button, 5, 5)
        txt = FONT.render(self.txt , True, 'black')
        SCREEN.blit(txt, (self.pos[0] + 15, self.pos[1] + 7))

    def check_clicked(self):
        if self.button.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
            return True
        else:
            return False

def drawMenu(SCREEN):
    titleText = FONT2.render('CHESS',True,  'black')
    SCREEN.blit(titleText, (70,70))
    knightImage = pygame.transform.scale(pygame.image.load("Images/bK.png"),(200,200))
    SCREEN.blit(knightImage, (300,575))
    numberButton = 0
    #Inizializes all of the buttons and draws them onto the screen
    engineButton = button('Multiplayer', (300, 300))
    engineButton.draw(SCREEN)
    multiplayerButton = button('Engine', (300, 400))
    multiplayerButton.draw(SCREEN)
    exitButton = button('QUIT', (300, 500))
    exitButton.draw(SCREEN)
    #Checks to see if the button has been pressed. Assigns a corresponding number to variable numberButton which can be used later when displaying next screen.
    if engineButton.check_clicked():
        numberButton = 1
    elif multiplayerButton.check_clicked():
        numberButton = 2
    elif exitButton.check_clicked():
        numberButton = 3

    return numberButton

    while RUNNING:

        SCREEN.fill('light blue')
        drawMenu(SCREEN)

        if drawMenu(SCREEN) == 1:
            drawBoard(SCREEN, board)
        elif drawMenu(SCREEN) == 2:
            drawBoard(SCREEN, board)
        elif drawMenu(SCREEN) == 3:
            RUNNING = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                RUNNING = False

</code>```

i did try and use a while loop instead of the if loop to say while numberButton == 1: display the chess graphics, however this just crashed the programme.

Body:
I have created a programme which has a home menu, when the user clicks on engine or multiplayer it should take them to a chess board graphic. However as soon as the mouse is released the chess board graphic disappears and the home menu is shown again. I have attached code below.

There is a variable, numberButton, which is used to see which button has been pressed and display the appropriate screen ie. the chess graphic. I am aware that as soon as the user stops clicking on the button that this variable is set back to zero which is why the main menu shows again however I do not know how to fix. Any suggestions would be appreciated :)

class button:
    def __init__(self, txt, pos):
        self.txt = txt
        self.pos = pos
        self.button = pygame.rect.Rect((self.pos[0], self.pos[1]), (200,40))

    def draw(self, SCREEN):
        pygame.draw.rect(SCREEN, 'light gray', self.button, 0 ,5)
        pygame.draw.rect(SCREEN, 'dark gray', self.button, 5, 5)
        txt = FONT.render(self.txt , True, 'black')
        SCREEN.blit(txt, (self.pos[0] + 15, self.pos[1] + 7))

    def check_clicked(self):
        if self.button.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
            return True
        else:
            return False

def drawMenu(SCREEN):
    titleText = FONT2.render('CHESS',True,  'black')
    SCREEN.blit(titleText, (70,70))
    knightImage = pygame.transform.scale(pygame.image.load("Images/bK.png"),(200,200))
    SCREEN.blit(knightImage, (300,575))
    numberButton = 0
    #Inizializes all of the buttons and draws them onto the screen
    engineButton = button('Multiplayer', (300, 300))
    engineButton.draw(SCREEN)
    multiplayerButton = button('Engine', (300, 400))
    multiplayerButton.draw(SCREEN)
    exitButton = button('QUIT', (300, 500))
    exitButton.draw(SCREEN)
    #Checks to see if the button has been pressed. Assigns a corresponding number to variable numberButton which can be used later when displaying next screen.
    if engineButton.check_clicked():
        numberButton = 1
    elif multiplayerButton.check_clicked():
        numberButton = 2
    elif exitButton.check_clicked():
        numberButton = 3

    return numberButton

    while RUNNING:

        SCREEN.fill('light blue')
        drawMenu(SCREEN)

        if drawMenu(SCREEN) == 1:
            drawBoard(SCREEN, board)
        elif drawMenu(SCREEN) == 2:
            drawBoard(SCREEN, board)
        elif drawMenu(SCREEN) == 3:
            RUNNING = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                RUNNING = False

i did try and use a while loop instead of the if loop to say while numberButton == 1: display the chess graphics, however this just crashed the programme.


问:
AWS Cognito - User record not clearing in Cognito console
I have created a user pool in the AWS Cognito console and I have 2 app clients. I have enabled OAuth 2 signin using one of the app client for IFTTT integration. Later on signed in a user to IFTTT using the app client. I deleted the user from the user pool [admin_delete_user() by boto3] and it cleared the record in the cognito console, but the funny part is that the user signin is still happening in the IFTTT app. When that happen the user record gets recreated in the Cognito console.

No idea what's happening in the background...

I tried executing the [admin_user_global_sign_out() from boto3]. Still no luck


问:
Download all requirements in one go for a cypress project
There are multiple dependencies that we need to download to start with a cypress project eg. Mocha, xpath, file-upload etc. How do we download everything at once?</p>


问:
Resend OTP only after some time (30 or 60 seconds)
I am creating APIs for application, authentication is using phone number and OTPs
I am sending OTP in sms using twilio, but if someone call this API over and over, there will be lots of sms in someones phone
How can i prevent this.

If same issue was in browser, we can use session and cookies, we can store the time when the API was called, and check that time in next API call.
But in mobile application how can i check this.


问:
Construct file path using for loop
I am trying to write a function that reads an array of parquet files as dataframe and concatenate them sequentially as on file

# Get the list of all files and directories
path = "C:**********\\main_data_1"
dir_list = os.listdir(path)
dir_list
Total_df = []
all_ais_msg_df = []
for j in np.arange(1,len(dir_list)+1):
    filename = 'ais_comb_'+ str(j)+ '.parquet'
    j +=1
    Total_df.append(filename)

for i in Total_df:
   ** df = pd.read_parquet('main_data_1/'+ str(i))** # having problem here
    i+=1
    all_ais_msg_df = pd.DataFrame(all_ais_msg_df.append(df))

```

I intend to construct a string like this ------>'main_data_1/ais_comb_1.parquet' while using the i in the second loop to increment ais_comb_1, ais-comb_2 aspect of the string until the last filename in order to get and combine all as a dataframe

The error I get is:

TypeError: can only concatenate str (not "int") to str

I crave a very clear explanation please, I am still a rookie.

Title: Construct file path using for loop

Body:
I am trying to write a function that reads an array of parquet files as dataframe and concatenate them sequentially as on file

# Get the list of all files and directories
path = "C:**********\\main_data_1"
dir_list = os.listdir(path)
dir_list
Total_df = []
all_ais_msg_df = []
for j in np.arange(1,len(dir_list)+1):
    filename = 'ais_comb_'+ str(j)+ '.parquet'
    j +=1
    Total_df.append(filename)

for i in Total_df:
   ** df = pd.read_parquet('main_data_1/'+ str(i))** # having problem here
    i+=1
    all_ais_msg_df = pd.DataFrame(all_ais_msg_df.append(df))

I intend to construct a string like this ------>'main_data_1/ais_comb_1.parquet' while using the i in the second loop to increment ais_comb_1, ais-comb_2 aspect of the string until the last filename in order to get and combine all as a dataframe

The error I get is:

TypeError: can only concatenate str (not "int") to str

I crave a very clear explanation please, I am still a rookie.


问:
Supporting mutilple Windows versions and SHA1/2 certificates for .exe (applications) and .sys (drivers)
Supporting older Windows versions in apps and drivers has become much more difficult due to MS policies/actions and Certificate Authorities (issuers) following them.  At this point it looks like we have to create our own self-signed SHA1 certificate and install that in the Trusted Publishers store on the end-users machine.  Also, cross-signing of drivers for OSes prior to Win10 is expired and no longer available as an option.  That means normal signing will need to be used and both the SHA2 and SHA1 certificate being added to the Trusted Publishers store on the end-user machine.

Catch 22 - while creating a mini certmgr type tool would be easy, there is no way to sign it for SHA1/SHA2 so the OS sees a valid signature before installing the certificates to the store.  Had this utility been created a couple years it could have been signed with the SHA1/SHA2 certificates that worked at that time.  certmgr (SDK 8.1) however is double-signed with SHA1/SHA2...

Now the question I have is if we were to sign the apps with the valid SHA2 EV certificate and the SHA1 self-signed certificate so that the SHA2 EV is "valid" (on Win Vista or later) and the SHA1 is "invalid" (because certificate is not in the store) will that throw off Anti-virus software or Windows itself or are they smart enough to see the SHA2 EV is "valid" so it's valid?

Same with drivers (on OSes prior to win10) (Win10 are signed by MS and while the SHA2 signature is good, the .cat file has no reference to prior OS versions - only Win10/11 are available in the MS portal)?  Although drivers wouldn't be installed prior to installation of the certificate.

The question comes up because we would like to only install the SHA1 certificate to the store on old OSes (Prior to Vista) that may still use SHA1 and leave it off the newer OS versions (meaning it's invalid)?  But we wonder what problems / confusion with other software / Windows could that create?

Comment: Since Windows can simply ignore SHA1, it seems there should have been no reason to prevent the CA's from issuing SHA1 certificates to make it easy to support the old OS.  The same applies to the cross-signing of drivers, new versions of Windows could simply ignore those and only support the MS signed version (like it already does for Win10/11 - this would allow updates to drivers for Win7, etc..).  These changes are what everyone was worried about when all the certificate requirement stuff was being proposed.  They ensured everyone this wouldn't happen...


问:
File provider error to receive pdf from another program
`# Dears, this class works well to receive PDF files from another application on below Android 6, but it gives an error for Android uper 6

```<code>          `                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                public int ExtractImage(Intent intent) {
                    try {
                        String filepath = null;

                        if (intent != null) {

                            String action = intent.getAction();

                            String type = intent.getType();

                            if (Intent.ACTION_VIEW.equals(action) && type.endsWith("pdf")) {

                                Uri file_uri = intent.getData();

                                if (file_uri != null) {

                                    filepath = file_uri.getPath();
                                }

                            } else if (Intent.ACTION_SEND.equals(action) && type.endsWith("pdf")) {

                                Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);

                                if (uri != null) {
                                    filepath = uri.getPath();
                                }

                            }
                        }

                        File file = new File(filepath);

                        PdfRenderer renderer = null;
                        Bitmap bm;

                        try {
                          renderer = new PdfRenderer(ParcelFileDescriptor.open(file,

                          ParcelFileDescriptor.MODE_READ_ONLY));
                        } catch (Exception e) {

                        }

                        assert renderer != null;
                        final int pageCount = renderer.getPageCount();

                        totalPage = pageCount;

                        for (int i = 0; i < pageCount; i++) {

                            PdfRenderer.Page page = renderer.openPage(i);

                            // Create a bitmap and canvas to draw the page into
                            int width = 570;
                            int zarib = 570 / (page.getWidth() + 1);
                            int height = (page.getHeight() * 2) + 1;
                            heightArray.add(i, height);

                            // Create a bitmap and canvas to draw the page into
                            bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

                            // Create canvas to draw into the bitmap
                            Canvas c = new Canvas(bm);

                            // Fill the bitmap with a white background
                            Paint whiteBgnd = new Paint();
                            whiteBgnd.setColor(Color.WHITE);
                            whiteBgnd.setStyle(Paint.Style.FILL);
                            c.drawRect(0, 0, width, height, whiteBgnd);

                            // paint the page into the canvas
                            page.render(bm, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);

                            // Save the bitmap
                            OutputStream outStream = null;
                            try {
                                outStream = new

                           FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()
                           + "/printDo2ta" + i + ".png");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            bm.compress(Bitmap.CompressFormat.PNG, 80, outStream);

                            try {
                                outStream.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            page.close();
                        }

                    } catch (Exception e) {
                        runOnUiThread(() -> Toast.makeText(getBaseContext(),
                                "خطا در پردازش فایل: " + e.getMessage(),
                                Toast.LENGTH_SHORT).show());
                    }

                    return totalPage;
                }
</code>```

I inserted this code in AndroidManifest.xml

```<code>     `<provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="ir.myproject.test.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
     </provider>`
</code>```

`

And I made the class provider_paths.xml

```<code>  `<?xml version="1.0" encoding="utf-8"?>
   <paths>
     <external-path name="external_files" path="."/>
   </paths>`
</code>```

I don't know what else I need to change to make it work on Android 8

please help me`

Body:
`# Dears, this class works well to receive PDF files from another application on below Android 6, but it gives an error for Android uper 6

          `                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                public int ExtractImage(Intent intent) {
                    try {
                        String filepath = null;

                        if (intent != null) {

                            String action = intent.getAction();

                            String type = intent.getType();

                            if (Intent.ACTION_VIEW.equals(action) && type.endsWith("pdf")) {

                                Uri file_uri = intent.getData();

                                if (file_uri != null) {

                                    filepath = file_uri.getPath();
                                }

                            } else if (Intent.ACTION_SEND.equals(action) && type.endsWith("pdf")) {

                                Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);

                                if (uri != null) {
                                    filepath = uri.getPath();
                                }

                            }
                        }

                        File file = new File(filepath);

                        PdfRenderer renderer = null;
                        Bitmap bm;

                        try {
                          renderer = new PdfRenderer(ParcelFileDescriptor.open(file,

                          ParcelFileDescriptor.MODE_READ_ONLY));
                        } catch (Exception e) {

                        }

                        assert renderer != null;
                        final int pageCount = renderer.getPageCount();

                        totalPage = pageCount;

                        for (int i = 0; i < pageCount; i++) {

                            PdfRenderer.Page page = renderer.openPage(i);

                            // Create a bitmap and canvas to draw the page into
                            int width = 570;
                            int zarib = 570 / (page.getWidth() + 1);
                            int height = (page.getHeight() * 2) + 1;
                            heightArray.add(i, height);

                            // Create a bitmap and canvas to draw the page into
                            bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

                            // Create canvas to draw into the bitmap
                            Canvas c = new Canvas(bm);

                            // Fill the bitmap with a white background
                            Paint whiteBgnd = new Paint();
                            whiteBgnd.setColor(Color.WHITE);
                            whiteBgnd.setStyle(Paint.Style.FILL);
                            c.drawRect(0, 0, width, height, whiteBgnd);

                            // paint the page into the canvas
                            page.render(bm, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);

                            // Save the bitmap
                            OutputStream outStream = null;
                            try {
                                outStream = new

                           FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()
                           + "/printDo2ta" + i + ".png");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            bm.compress(Bitmap.CompressFormat.PNG, 80, outStream);

                            try {
                                outStream.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            page.close();
                        }

                    } catch (Exception e) {
                        runOnUiThread(() -> Toast.makeText(getBaseContext(),
                                "خطا در پردازش فایل: " + e.getMessage(),
                                Toast.LENGTH_SHORT).show());
                    }

                    return totalPage;
                }

I inserted this code in AndroidManifest.xml

     `<provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="ir.myproject.test.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
     </provider>`

`

And I made the class provider_paths.xml

  `<?xml version="1.0" encoding="utf-8"?>
   <paths>
     <external-path name="external_files" path="."/>
   </paths>`

I don't know what else I need to change to make it work on Android 8

please help me`


问:
How do you disable gke audit logging from being stored?
I need to disable gke audit logging since they eat up so much storage and money?

I tried to do it through the console and they were aready disabled!

or am i in the wrong place?


问:
How to normalize data which contain positive and negative numbers into 0 and 1 manually (without sklearn.preprocessing.MinMaxScaler package )?
I want to normalize data without using package. I use minmax scaler based on formula. but when i want to normalize data i get error like below.

```<code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

Normalization code :

```<code>minInsole = min(SmartInsole)
maxInsole = max(SmartInsole)
norm_data = (SmartInsole - minInsole) / ( maxInsole - minInsole )
</code>```

Data Shape:

Body:
I want to normalize data without using package. I use minmax scaler based on formula. but when i want to normalize data i get error like below.

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Normalization code :

minInsole = min(SmartInsole)
maxInsole = max(SmartInsole)
norm_data = (SmartInsole - minInsole) / ( maxInsole - minInsole )

Data Shape:


问:
Looking to re-name 1000's of code entries/file paths within a folder automatically
I'm looking for a way to mass-rename many, many lines of code that all end in '.ogg' within a folder. There's more then 4,000 entries so annoying to do one-by-one.

The bigger picture is that I downloaded an open-source game that unfortunately doesn't work because a lot of the sound files are in different directiories, like, "sound/monster, sound/machines, sound/robots", but for SOME REASON literally every .ogg file in the code doesn't contain where the sound file actually is. If the correct path is "sound/machines/lightswitch1.ogg" then the code line is "lightswitch1.ogg" and doesn't work. I am looking for a way to simply rename all the offending files to something like "sound/allsounds/[soundname].ogg", then take every sound file and dump it in the "allsounds" folder. I don't need it to be tidy because I'm the only one using it. Thanks!

Edit: I'm also really ignorant about all things code, so I might've missed some obvious solution.

Edit 2: I tried 'Batch Rename' but it doesn't seem to work for search results (what I'm using to see all the darn filepaths. I think it's only for actual files?).


问:
How assembler programs are executed in a microprocessor trainer kit?
I understand, in microcontrollers assembly language is converted to binary by the assembler. To my understanding, it is a program run on a separate machine. Then the produced machine code is stored on ROM and executed. Is it correct? If so, in the case of a microprocessor trainer kit, who executes the assembler code?</p>


问:
pycharm: cannot start a process, working directory "xxxxxxx" doesn't exist
I update pycharm to 2022.3.1, then my remote depoly failed.
When I run my code get an error: cann't start a process, working directory doesn't exist.

I try to build a new project, a new ssh connect and new map setting, but get the same error. Also I try some solutions searched in stackoverflow:

delete .idea directory and restart pycharm

change the working directory in running config

change the working directory in python console
But not useful for me


问:
Customize Avalara Transaction
I need to update the Avalara commit transaction to have some custom values to be shown.
Is it possible to add a new column in the line items table and the value will be passed to create transaction request?

I have checked the Avalara docs where I have the option to send "Ref1" and "Ref2" values in the request. But we are using that already to pass some other custom values.

Already checked the "TaxDetailsByTaxType" and "parameters" but that is not suitable in our case.

If anyone has an idea about introducing a new column at the line items table it will be more helpful.

Thanks in advance.

Attached screenshot for reference.

Title: Customize Avalara Transaction


问:
Parsing dynamic xml element in grafana
Looking to get parsed xml output from exposed API endpoint which is in below format in Grafana :

```<code><List>
 <item>
  <machine-1>true</machine-1>
  <POOL>ZZZ</POOL>
 </item>
 <item>
  <machine-2>true</machine-2>
  <POOL>YYY</POOL>
 </item>
 <item>
  <machine-3>false</machine-3>
  <POOL>ZZZ</POOL>
 </item>
</LIST>
</code>```

Following along : https://sriramajeyam.com/grafana-infinity-datasource/wiki/xml , installed yesoreyeram-infinity-datasource plugin in Grafana.

Post selecting "infinity-datasource" & column as List.item, not seeing viable option to select above dynamic column name holding machine name.

Kindly suggest way of handling this.

I would like to get machine name & boolean value mapped to that machine

Title: Parsing dynamic xml element in grafana

Body:
Looking to get parsed xml output from exposed API endpoint which is in below format in Grafana :

<List>
 <item>
  <machine-1>true</machine-1>
  <POOL>ZZZ</POOL>
 </item>
 <item>
  <machine-2>true</machine-2>
  <POOL>YYY</POOL>
 </item>
 <item>
  <machine-3>false</machine-3>
  <POOL>ZZZ</POOL>
 </item>
</LIST>

Following along : https://sriramajeyam.com/grafana-infinity-datasource/wiki/xml , installed yesoreyeram-infinity-datasource plugin in Grafana.

Post selecting "infinity-datasource" & column as List.item, not seeing viable option to select above dynamic column name holding machine name.

Kindly suggest way of handling this.

I would like to get machine name & boolean value mapped to that machine


问:
Electron App with Azure AD - without Interactive browser
I am trying to integrate Azure AD authentication with my Electron App (with Angular). I took reference from this link and able to integrate: https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-nodejs-desktop

Issue: It's using getTokenInteractive() method and it's navigating to an external browser. As per my requirement we don't have to navigate to an external browser, it should open the UI inside my electron App where end users can provide their credentials.
Another option if possible we can open the Azure AD url part of my electron App.

I took reference from this link and able to integrate: https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-nodejs-desktop

```<code>async getTokenInteractive(tokenRequest) {
        try {
            const openBrowser = async (url) => {
                await shell.openExternal(url);
            };

            const authResponse = await this.clientApplication.acquireTokenInteractive({
                ...tokenRequest,
                openBrowser,
                successTemplate: '<h1>Successfully signed in!</h1> <p>You can close this window now.</p>',
                errorTemplate: '<h1>Oops! Something went wrong</h1> <p>Check the console for more information.</p>',
            });

            return authResponse;
        } catch (error) {
            throw error;
        }
    }
</code>```

Body:
I am trying to integrate Azure AD authentication with my Electron App (with Angular). I took reference from this link and able to integrate: https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-nodejs-desktop

Issue: It's using getTokenInteractive() method and it's navigating to an external browser. As per my requirement we don't have to navigate to an external browser, it should open the UI inside my electron App where end users can provide their credentials.
Another option if possible we can open the Azure AD url part of my electron App.

I took reference from this link and able to integrate: https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-nodejs-desktop

async getTokenInteractive(tokenRequest) {
        try {
            const openBrowser = async (url) => {
                await shell.openExternal(url);
            };

            const authResponse = await this.clientApplication.acquireTokenInteractive({
                ...tokenRequest,
                openBrowser,
                successTemplate: '
Successfully signed in!

You can close this window now.
',
                errorTemplate: '
Oops! Something went wrong

Check the console for more information.
',
            });

            return authResponse;
        } catch (error) {
            throw error;
        }
    }


问:
The last nested array is lost when an object is created accordingly mongoose model
I'm trying to create an object according to my model in mongoose using a controller, but I'm running into a problem that the last array nesting with prize patterns is not being written. Theoretically it is, but it is empty. I do not understand what the problem is, since I cannot add the necessary value to it even after creating the object through the constructor and after that doing something like: newGame.prizes = prizes;
With this behavior, all other properties within the prize property appear in the object, but the pattern array is empty.

Here is what my model looks like:

```<code>const GameSchema = mongoose.Schema({
  type: String,
  roundId: String,
  userId: String,
  calloutNumbersCount: Number,
  tickets: [
    {
      id: String,
      columns: [[Number]],
    },
  ],
  prizes: [
    {
      id: String,
      name: String,
      nameLocaleKey: String,
      winAmount: Number,
      patterns: [
        {
          type: String,
          count: Number,
        },
      ],
    },
  ],
  ticketPrice: Number,
  boughtTicketIds: [String],
  ended: Boolean,
});
</code>```

Controller:

```<code>function createGame(gameType, userId) {
  const currentGameConfig = config[gameType];
  console.log("Controller");
  currentGameConfig.prizes.map((el) => console.log(el.patterns));
  const roundId = nanoid(LENGTH_OF_ROUND_ID);
  const game = new Game({
    type: currentGameConfig.type,
    roundId,
    userId,
    calloutNumbersCount: currentGameConfig.callout.numbersCount,
    tickets: [
      {
        id: 123, // temp
        columns: [[0]], // temp
      },
    ],
    prizes: currentGameConfig.prizes,
    ticketPrice: currentGameConfig.tickets.price,
    boughtTicketIds: ["1", "2"], // temp
    ended: false,
  });

  return game;
}
</code>```

Place of creation and modification of the object in the route:

```<code>if (!game) {
      const newGame = gameController.createGame(type, userId);
      // newGame.prizes = currentGameConfig.prizes;

      Game.addGame(newGame, (err, game) => {

        if (err) {
          res.json({ success: false, message: err.message });
          throw err;
        }
        return res.json({
          roundId: newGame.roundId,
        });
      });
    }
</code>```

Expected result:

The result:

EDITED

CurrentGameConfig:

```<code>{
  type: 'BINGO_75',
  name: 'Bingo 75',
  nameLocaleKey: 'GAMES.BINGO_75',
  prizes: [
    {
      name: 'Prize 1',
      nameLocaleKey: 'PRIZES.BINGO_75.PRIZE_1',
      winAmount: 10,
      patterns: [Array]
    },
    {
      name: 'Prize 2',
      nameLocaleKey: 'PRIZES.BINGO_75.PRIZE_2',
      winAmount: 10,
      patterns: [Array]
    },
    {
      name: 'Prize 3',
      nameLocaleKey: 'PRIZES.BINGO_75.PRIZE_3',
      winAmount: 10,
      patterns: [Array]
    },
    {
      name: 'Prize 4',
      nameLocaleKey: 'PRIZES.BINGO_75.PRIZE_4',
      winAmount: 10,
      patterns: [Array]
    },
    {
      name: 'Full house',
      nameLocaleKey: 'PRIZES.BINGO_75.PRIZE_5',
      winAmount: 10,
      patterns: [Array]
    }
  ],
  tickets: { price: 10, quantity: 72, grid: { cols: [Object], rows: [Object] } },
  callout: { numbersCount: 25 }
}
</code>```

In node.js patterns look like [Array], but if display each pattern it look like:

```<code>[
{type: 'HORIZONTAL', count: 1},
{type: 'VERTICAL', count: 1},
{type: 'DIAGONAL', count: 1}
]
</code>```

Body:
I'm trying to create an object according to my model in mongoose using a controller, but I'm running into a problem that the last array nesting with prize patterns is not being written. Theoretically it is, but it is empty. I do not understand what the problem is, since I cannot add the necessary value to it even after creating the object through the constructor and after that doing something like: newGame.prizes = prizes;
With this behavior, all other properties within the prize property appear in the object, but the pattern array is empty.

Here is what my model looks like:

const GameSchema = mongoose.Schema({
  type: String,
  roundId: String,
  userId: String,
  calloutNumbersCount: Number,
  tickets: [
    {
      id: String,
      columns: [[Number]],
    },
  ],
  prizes: [
    {
      id: String,
      name: String,
      nameLocaleKey: String,
      winAmount: Number,
      patterns: [
        {
          type: String,
          count: Number,
        },
      ],
    },
  ],
  ticketPrice: Number,
  boughtTicketIds: [String],
  ended: Boolean,
});

Controller:

function createGame(gameType, userId) {
  const currentGameConfig = config[gameType];
  console.log("Controller");
  currentGameConfig.prizes.map((el) => console.log(el.patterns));
  const roundId = nanoid(LENGTH_OF_ROUND_ID);
  const game = new Game({
    type: currentGameConfig.type,
    roundId,
    userId,
    calloutNumbersCount: currentGameConfig.callout.numbersCount,
    tickets: [
      {
        id: 123, // temp
        columns: [[0]], // temp
      },
    ],
    prizes: currentGameConfig.prizes,
    ticketPrice: currentGameConfig.tickets.price,
    boughtTicketIds: ["1", "2"], // temp
    ended: false,
  });

  return game;
}

Place of creation and modification of the object in the route:

if (!game) {
      const newGame = gameController.createGame(type, userId);
      // newGame.prizes = currentGameConfig.prizes;

      Game.addGame(newGame, (err, game) => {

        if (err) {
          res.json({ success: false, message: err.message });
          throw err;
        }
        return res.json({
          roundId: newGame.roundId,
        });
      });
    }

Expected result:

The result:

EDITED

CurrentGameConfig:

{
  type: 'BINGO_75',
  name: 'Bingo 75',
  nameLocaleKey: 'GAMES.BINGO_75',
  prizes: [
    {
      name: 'Prize 1',
      nameLocaleKey: 'PRIZES.BINGO_75.PRIZE_1',
      winAmount: 10,
      patterns: [Array]
    },
    {
      name: 'Prize 2',
      nameLocaleKey: 'PRIZES.BINGO_75.PRIZE_2',
      winAmount: 10,
      patterns: [Array]
    },
    {
      name: 'Prize 3',
      nameLocaleKey: 'PRIZES.BINGO_75.PRIZE_3',
      winAmount: 10,
      patterns: [Array]
    },
    {
      name: 'Prize 4',
      nameLocaleKey: 'PRIZES.BINGO_75.PRIZE_4',
      winAmount: 10,
      patterns: [Array]
    },
    {
      name: 'Full house',
      nameLocaleKey: 'PRIZES.BINGO_75.PRIZE_5',
      winAmount: 10,
      patterns: [Array]
    }
  ],
  tickets: { price: 10, quantity: 72, grid: { cols: [Object], rows: [Object] } },
  callout: { numbersCount: 25 }
}

In node.js patterns look like [Array], but if display each pattern it look like:

[
{type: 'HORIZONTAL', count: 1},
{type: 'VERTICAL', count: 1},
{type: 'DIAGONAL', count: 1}
]


问:
Fullcalendar not showing the correct end date
fullcalendar on adding event

fullcalendar end date is one day before

As you see in the image on adding the event in full calendar the end date is adding correctly to the redux but on fetching that data and displaying it on calendar the end date is displayed one day before.

for ex: If i give the end date  14th-jan its adding correctly to the api but while displaying its showing 13th-jan one day before.

```<code><FullCalendar
            {...rest}
            plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
            events={calendarEvents}
            displayEventTime={false}
            editable={hasFeatureAccess(
              permissionName,
              'updateEvent',
              groupsReferenceData
            )}
            selectable={hasFeatureAccess(
              permissionName,
              'addEvent',
              groupsReferenceData
            )}
            select={
              hasFeatureAccess(
                permissionName,
                'addEvent',
                groupsReferenceData
              )
                ? handleDateSelect
                : undefined
            }
            eventClick={
              hasFeatureAccess(
                permissionName,
                'updateEvent',
                groupsReferenceData
              )
                ? handleEventClick
                : undefined
            }
            initialView='dayGridMonth'
            height='100%'
          />
</code>```

so on fetching the api and displaying the data on full calendar I want the correct date to be displayed.

Body:
fullcalendar on adding event

fullcalendar end date is one day before

As you see in the image on adding the event in full calendar the end date is adding correctly to the redux but on fetching that data and displaying it on calendar the end date is displayed one day before.

for ex: If i give the end date  14th-jan its adding correctly to the api but while displaying its showing 13th-jan one day before.

<FullCalendar
            {...rest}
            plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
            events={calendarEvents}
            displayEventTime={false}
            editable={hasFeatureAccess(
              permissionName,
              'updateEvent',
              groupsReferenceData
            )}
            selectable={hasFeatureAccess(
              permissionName,
              'addEvent',
              groupsReferenceData
            )}
            select={
              hasFeatureAccess(
                permissionName,
                'addEvent',
                groupsReferenceData
              )
                ? handleDateSelect
                : undefined
            }
            eventClick={
              hasFeatureAccess(
                permissionName,
                'updateEvent',
                groupsReferenceData
              )
                ? handleEventClick
                : undefined
            }
            initialView='dayGridMonth'
            height='100%'
          />

so on fetching the api and displaying the data on full calendar I want the correct date to be displayed.


问:
SQL query on default with table names changed
Using FreeRadus 3.0.2 (Docker)

I've modified the table names of SQL on mods-available/sql file as follow:

```<code>    (...)
    acct_table1 = "radius_acct"
    acct_table2 = "radius_acct"

    # Allow for storing data after authentication
    postauth_table = "radius_postauth"

    # Tables containing 'check' items
    authcheck_table = "radius_check"
    groupcheck_table = "radius_groupcheck"

    # Tables containing 'reply' items
    authreply_table = "radius_reply"
    groupreply_table = "radius_groupreply"type here
    (...)
</code>```

Then trying to call a SQL query from the sites-enabled/default file I would use the variable and not hardcoding the string

```<code>post-auth {
    if("%{sql:SELECT COUNT(*) FROM radius_check WHERE username = '%{User-Name}'}" > 0){
        ok
    }
    else {
        reject
    }
</code>```

There is any way to do it? How to access from sites to variables defined on modules?

I've tried to use

```<code>post-auth {
    if("%{sql:SELECT COUNT(*) FROM %{sql:authcheck_table} WHERE username = '%{User-Name}'}" > 0){
        ok
    }
    else {
        reject
    }
</code>```

Body:
Using FreeRadus 3.0.2 (Docker)

I've modified the table names of SQL on mods-available/sql file as follow:

    (...)
    acct_table1 = "radius_acct"
    acct_table2 = "radius_acct"

    # Allow for storing data after authentication
    postauth_table = "radius_postauth"

    # Tables containing 'check' items
    authcheck_table = "radius_check"
    groupcheck_table = "radius_groupcheck"

    # Tables containing 'reply' items
    authreply_table = "radius_reply"
    groupreply_table = "radius_groupreply"type here
    (...)

Then trying to call a SQL query from the sites-enabled/default file I would use the variable and not hardcoding the string

post-auth {
    if("%{sql:SELECT COUNT(*) FROM radius_check WHERE username = '%{User-Name}'}" > 0){
        ok
    }
    else {
        reject
    }

There is any way to do it? How to access from sites to variables defined on modules?

I've tried to use

post-auth {
    if("%{sql:SELECT COUNT(*) FROM %{sql:authcheck_table} WHERE username = '%{User-Name}'}" > 0){
        ok
    }
    else {
        reject
    }


问:
Can not get jaeger trace ID in http middleware
I have an HTTP server and middleware, inside the middleware, I want to get the trace ID from context, but I get only zeros inside handler everything works fine and the trace ID exists

Here is my code sample  https://go.dev/play/p/xKLuxX4SJX9


问:
I Try to export data from Firebase to XLSX using kotlin but whe i run the program nothing happend
I Try to export data from Firebase to XLSX using kotlin but whe i run the program nothing happend no error at my code but i can't find the export file this my code

```<code>val db =  FirebaseDatabase.getInstance().getReference("aktivitas")
        btndownload.setOnClickListener{
            val query_kegiatan = db.orderByChild("aktivitas")

            query_kegiatan.addValueEventListener(object : ValueEventListener{
                override fun onDataChange(snapshot: DataSnapshot) {
                    val workbook = XSSFWorkbook()
                    val sheet = workbook.createSheet("Aktivitas")

                    var rownum = 0
                    for(item in snapshot.children){
                        val row = sheet.createRow(rownum++)
                        row.createCell(0).setCellValue(item.child("bagian").value as String)
                        row.createCell(1).setCellValue(item.child("barang").value as String)
                        row.createCell(2).setCellValue(item.child("jumlah").value as String)
                        row.createCell(3).setCellValue(item.child("keterangan").value as String)

                       val save = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),"aktivitas.xlsx")
                        val fos = FileOutputStream(save)
                        workbook.write(fos)

                    }
                }

                override fun onCancelled(error: DatabaseError) {
                    TODO("Not yet implemented")
                }
            })

        }
</code>```

i try to export data from firebase to xlsx using kotlin using apache.poi library i did't see any error i expecting to export the data to xlsx

Body:
I Try to export data from Firebase to XLSX using kotlin but whe i run the program nothing happend no error at my code but i can't find the export file this my code

val db =  FirebaseDatabase.getInstance().getReference("aktivitas")
        btndownload.setOnClickListener{
            val query_kegiatan = db.orderByChild("aktivitas")

            query_kegiatan.addValueEventListener(object : ValueEventListener{
                override fun onDataChange(snapshot: DataSnapshot) {
                    val workbook = XSSFWorkbook()
                    val sheet = workbook.createSheet("Aktivitas")

                    var rownum = 0
                    for(item in snapshot.children){
                        val row = sheet.createRow(rownum++)
                        row.createCell(0).setCellValue(item.child("bagian").value as String)
                        row.createCell(1).setCellValue(item.child("barang").value as String)
                        row.createCell(2).setCellValue(item.child("jumlah").value as String)
                        row.createCell(3).setCellValue(item.child("keterangan").value as String)

                       val save = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),"aktivitas.xlsx")
                        val fos = FileOutputStream(save)
                        workbook.write(fos)

                    }
                }

                override fun onCancelled(error: DatabaseError) {
                    TODO("Not yet implemented")
                }
            })

        }

i try to export data from firebase to xlsx using kotlin using apache.poi library i did't see any error i expecting to export the data to xlsx


问:
Terraform import not working for GCP crypto keys
I created some crypto-keys manually and now wanted to import them to terraform state so that it's managed by terraform, which I did using following command which completes successfully:

```<code>$ terraform import google_kms_crypto_key.some-key some-gcp-project-id/us/some-keyring/some-key
google_kms_crypto_key.some-key: Refreshing state... [id=projects/some-gcp-project-id/locations/us/keyRings/some-keyring/cryptoKeys/some-key]

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.
</code>```

Even after the import, on doing terraform apply I am still getting resource already exists error:

```<code>Error: Error creating CryptoKey: googleapi: Error 409: CryptoKey projects/some-gcp-project-id/locations/us/keyRings/some-keyring/cryptoKeys/some-key already exists.
</code>```

Since this resource has been imported, I believe I shouldn't be getting this "Error 409". In terrform plan steps, it first destroys the existing key contents and then tries to re-create the key - which leads to error since the key already exists. Since I have already imported the key I do not want terraform to destroy the key. Why is terraform trying to destroy a key which has already been imported?

This is the relevant part of terrform plan output

```<code># google_kms_crypto_key.some-key[1] will be destroyed
  - resource "google_kms_crypto_key" "some-key" {
      - destroy_scheduled_duration    = "86400s" -> null
      - id                            = "projects/some-gcp-project-id/locations/us/keyRings/some-keyring/cryptoKeys/some-key" -> null
      - import_only                   = false -> null
      - key_ring                      = "projects/some-gcp-project-id/locations/us/keyRings/some-keyring" -> null
      - labels                        = {} -> null
      - name                          = "some-key" -> null
      - purpose                       = "ENCRYPT_DECRYPT" -> null
      - rotation_period               = "2592000s" -> null
      - skip_initial_version_creation = false -> null

      - timeouts {}

      - version_template {
          - algorithm        = "GOOGLE_SYMMETRIC_ENCRYPTION" -> null
          - protection_level = "SOFTWARE" -> null
        }
    }

  # google_kms_crypto_key.some-key["some-key"] will be created
  + resource "google_kms_crypto_key" "some-key" {
      + destroy_scheduled_duration = (known after apply)
      + id                         = (known after apply)
      + import_only                = (known after apply)
      + key_ring                   = "projects/some-gcp-project-id/locations/us/keyRings/some-keyring"
      + name                       = "some-key"
      + purpose                    = "ENCRYPT_DECRYPT"
      + rotation_period            = "2592000s"

      + version_template {
          + algorithm        = (known after apply)
          + protection_level = (known after apply)
        }
    }
</code>```

Body:
I created some crypto-keys manually and now wanted to import them to terraform state so that it's managed by terraform, which I did using following command which completes successfully:

$ terraform import google_kms_crypto_key.some-key some-gcp-project-id/us/some-keyring/some-key
google_kms_crypto_key.some-key: Refreshing state... [id=projects/some-gcp-project-id/locations/us/keyRings/some-keyring/cryptoKeys/some-key]

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.

Even after the import, on doing terraform apply I am still getting resource already exists error:

Error: Error creating CryptoKey: googleapi: Error 409: CryptoKey projects/some-gcp-project-id/locations/us/keyRings/some-keyring/cryptoKeys/some-key already exists.

Since this resource has been imported, I believe I shouldn't be getting this "Error 409". In terrform plan steps, it first destroys the existing key contents and then tries to re-create the key - which leads to error since the key already exists. Since I have already imported the key I do not want terraform to destroy the key. Why is terraform trying to destroy a key which has already been imported?

This is the relevant part of terrform plan output

# google_kms_crypto_key.some-key[1] will be destroyed
  - resource "google_kms_crypto_key" "some-key" {
      - destroy_scheduled_duration    = "86400s" -> null
      - id                            = "projects/some-gcp-project-id/locations/us/keyRings/some-keyring/cryptoKeys/some-key" -> null
      - import_only                   = false -> null
      - key_ring                      = "projects/some-gcp-project-id/locations/us/keyRings/some-keyring" -> null
      - labels                        = {} -> null
      - name                          = "some-key" -> null
      - purpose                       = "ENCRYPT_DECRYPT" -> null
      - rotation_period               = "2592000s" -> null
      - skip_initial_version_creation = false -> null

      - timeouts {}

      - version_template {
          - algorithm        = "GOOGLE_SYMMETRIC_ENCRYPTION" -> null
          - protection_level = "SOFTWARE" -> null
        }
    }

  # google_kms_crypto_key.some-key["some-key"] will be created
  + resource "google_kms_crypto_key" "some-key" {
      + destroy_scheduled_duration = (known after apply)
      + id                         = (known after apply)
      + import_only                = (known after apply)
      + key_ring                   = "projects/some-gcp-project-id/locations/us/keyRings/some-keyring"
      + name                       = "some-key"
      + purpose                    = "ENCRYPT_DECRYPT"
      + rotation_period            = "2592000s"

      + version_template {
          + algorithm        = (known after apply)
          + protection_level = (known after apply)
        }
    }


问:
Pass multiple array php data into python for use
I have a multiple array of $dataraw from the code below

```<code>$_SESSION['image'];

$dataraw = $_SESSION['image'];
echo '```';
print_r($dataraw);
echo '```';
</code>```

print_r($dataraw); output looks like this :

```<code>array(2) {
  [0]=>
  array(4) {
    ["FileName"]=>
    string(19) "20221227_202035.jpg"
    ["Model"]=>
    string(8) "SM-A528B"
    ["Longitude"]=>
    float(106.524251)
    ["Latitude"]=>
    float(-6.367665)
  }
  [1]=>
  array(4) {
    ["FileName"]=>
    string(19) "20221227_202157.jpg"
    ["Model"]=>
    string(8) "SM-A528B"
    ["Longitude"]=>
    float(106.9522428)
    ["Latitude"]=>
    float(-6.984758099722223)
  }
}
</code>```

As you can see, its a multiple array of data.
Then i have a button click run python

```<code>$dataraw = $_SESSION['image'];
$datagambar = json_encode($dataraw);
$escaped_json = escapeshellarg($datagambar);

if(isset($_POST['runpython'])){
   echo shell_exec('D:\xampp\htdocs\Klasifikasi_KNN\admin\Klasifikasi.py'.$escaped_json);
    print("success");
    unset($_SESSION['image']);

}
</code>```

This is my python script to call it back

```<code>escaped_json = sys.argv[1]
parsed_data = json.loads(escaped_json)
print (parsed_data[0])
</code>```

How to pass the multiple array of data to python side? and calls it in python? i need the data for python to operate.

parsed_data = json.loads(escaped_json)
Seems give error

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Body:
I have a multiple array of $dataraw from the code below

$_SESSION['image'];

$dataraw = $_SESSION['image'];
echo '
';
print_r($dataraw);
echo '
';

print_r($dataraw); output looks like this :

array(2) {
  [0]=>
  array(4) {
    ["FileName"]=>
    string(19) "20221227_202035.jpg"
    ["Model"]=>
    string(8) "SM-A528B"
    ["Longitude"]=>
    float(106.524251)
    ["Latitude"]=>
    float(-6.367665)
  }
  [1]=>
  array(4) {
    ["FileName"]=>
    string(19) "20221227_202157.jpg"
    ["Model"]=>
    string(8) "SM-A528B"
    ["Longitude"]=>
    float(106.9522428)
    ["Latitude"]=>
    float(-6.984758099722223)
  }
}

As you can see, its a multiple array of data.
Then i have a button click run python

$dataraw = $_SESSION['image'];
$datagambar = json_encode($dataraw);
$escaped_json = escapeshellarg($datagambar);

if(isset($_POST['runpython'])){
   echo shell_exec('D:\xampp\htdocs\Klasifikasi_KNN\admin\Klasifikasi.py'.$escaped_json);
    print("success");
    unset($_SESSION['image']);

}

This is my python script to call it back

escaped_json = sys.argv[1]
parsed_data = json.loads(escaped_json)
print (parsed_data[0])

How to pass the multiple array of data to python side? and calls it in python? i need the data for python to operate.

parsed_data = json.loads(escaped_json)
Seems give error

JSONDecodeError: Expecting value: line 1 column 1 (char 0)


问:
square moving only up and down, Tensorflow
I am trying to learn tensorflow, so far its really simple but something has got me at a stand still. When I run my code, the cube only goes either down or right. I tried changing values and have concluded that the movement is what tensorflow has intended. I really don't know what to do here. I am lost!

the premise of what im trying to do is make an "AI" to learn its environment and go to all of the dots that randomly spawn.

model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(128, input_shape=(2,), activation='relu'),
    tf.keras.layers.Dense(2, activation='softmax')
])

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

EPOCHS = 10

#somewhere in the while loop

inputs = np.array([square_x, square_y])

prediction = model.predict(inputs.reshape(1, 2))
print(prediction) # -> [ [x value, y value] ]
direction = np.argmax(prediction)

square_x += prediction[0][0]
square_y += prediction[0][1]

```
<p>full code:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
import numpy as np
import pygame

pygame.init()

SCREEN_SIZE = (400, 400)
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("TensorFlow Dot Collector")
DOT_COLOR = (0, 0, 255)
SQUARE_COLOR = (255, 0, 0)
DOT_RADIUS = 10
NUM_DOTS = 10
SQUARE_SIZE = 30
square_x = SCREEN_SIZE[0] // 2
square_y = SCREEN_SIZE[1] // 2
game_loop = True
score = 0
speed = 5

dot_positions = np.random.randint(0, SCREEN_SIZE[0], (NUM_DOTS, 2))
old_dotpositions = dot_positions

font = pygame.font.Font(None, 36)

output_data = np.array([0, 1, 0, 1, 0])
input_data = dot_positions[:output_data.shape[0]]

model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(128, input_shape=(2,), activation='tanh'),
    tf.keras.layers.Dense(2, activation='tanh')
])

model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])

num_epochs = 10

model.fit(input_data, output_data, epochs=num_epochs)
while game_loop:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_loop = False
    screen.fill((255, 255, 255))

    for dot_position in dot_positions:
        pygame.draw.circle(screen, DOT_COLOR, dot_position, DOT_RADIUS)

    pygame.draw.rect(screen, SQUARE_COLOR, (square_x - SQUARE_SIZE // 2, square_y - SQUARE_SIZE // 2, SQUARE_SIZE, SQUARE_SIZE))

    inputs = np.array([square_x, square_y])

    prediction = model.predict(inputs.reshape(1, 2))

    direction = np.argmax(prediction)
    print(direction)
    square_x += prediction[0][0] * speed
    square_y += prediction[0][1] * speed
    for dot_position in dot_positions:

        if np.linalg.norm(np.array([square_x, square_y]) - dot_position) < DOT_RADIUS + SQUARE_SIZE // 2:

            score += 5
            dot_positions = np.delete(dot_positions, np.argwhere(np.all(dot_positions == dot_position, axis=1)), axis=0)

    if square_x < 0 or square_y < 0 or square_x > SCREEN_SIZE[0] or square_y > SCREEN_SIZE[1]:
        square_x =200
        square_y = 200
        score -= 10
        model.optimizer.lr.assign(score)
        score = 0
        dot_positions = old_dotpositions

    score_text = font.render(f"Score: {score}", True, (0, 0, 0))

    screen.blit(score_text, (10, 10))
    pygame.display.update()
</code>```

Body:
I am trying to learn tensorflow, so far its really simple but something has got me at a stand still. When I run my code, the cube only goes either down or right. I tried changing values and have concluded that the movement is what tensorflow has intended. I really don't know what to do here. I am lost!

the premise of what im trying to do is make an "AI" to learn its environment and go to all of the dots that randomly spawn.

model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(128, input_shape=(2,), activation='relu'),
    tf.keras.layers.Dense(2, activation='softmax')
])

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

EPOCHS = 10

#somewhere in the while loop

inputs = np.array([square_x, square_y])

prediction = model.predict(inputs.reshape(1, 2))
print(prediction) # -> [ [x value, y value] ]
direction = np.argmax(prediction)

square_x += prediction[0][0]
square_y += prediction[0][1]

full code:

import tensorflow as tf
import numpy as np
import pygame

pygame.init()

SCREEN_SIZE = (400, 400)
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("TensorFlow Dot Collector")
DOT_COLOR = (0, 0, 255)
SQUARE_COLOR = (255, 0, 0)
DOT_RADIUS = 10
NUM_DOTS = 10
SQUARE_SIZE = 30
square_x = SCREEN_SIZE[0] // 2
square_y = SCREEN_SIZE[1] // 2
game_loop = True
score = 0
speed = 5

dot_positions = np.random.randint(0, SCREEN_SIZE[0], (NUM_DOTS, 2))
old_dotpositions = dot_positions

font = pygame.font.Font(None, 36)

output_data = np.array([0, 1, 0, 1, 0])
input_data = dot_positions[:output_data.shape[0]]

model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(128, input_shape=(2,), activation='tanh'),
    tf.keras.layers.Dense(2, activation='tanh')
])

model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])

num_epochs = 10

model.fit(input_data, output_data, epochs=num_epochs)
while game_loop:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_loop = False
    screen.fill((255, 255, 255))

    for dot_position in dot_positions:
        pygame.draw.circle(screen, DOT_COLOR, dot_position, DOT_RADIUS)

    pygame.draw.rect(screen, SQUARE_COLOR, (square_x - SQUARE_SIZE // 2, square_y - SQUARE_SIZE // 2, SQUARE_SIZE, SQUARE_SIZE))

    inputs = np.array([square_x, square_y])

    prediction = model.predict(inputs.reshape(1, 2))

    direction = np.argmax(prediction)
    print(direction)
    square_x += prediction[0][0] * speed
    square_y += prediction[0][1] * speed
    for dot_position in dot_positions:

        if np.linalg.norm(np.array([square_x, square_y]) - dot_position) < DOT_RADIUS + SQUARE_SIZE // 2:

            score += 5
            dot_positions = np.delete(dot_positions, np.argwhere(np.all(dot_positions == dot_position, axis=1)), axis=0)

    if square_x < 0 or square_y < 0 or square_x > SCREEN_SIZE[0] or square_y > SCREEN_SIZE[1]:
        square_x =200
        square_y = 200
        score -= 10
        model.optimizer.lr.assign(score)
        score = 0
        dot_positions = old_dotpositions

    score_text = font.render(f"Score: {score}", True, (0, 0, 0))

    screen.blit(score_text, (10, 10))
    pygame.display.update()


Title: how do i use variables inside a loop?

Body:
I need to run a code in order and use some dates in it.

this is what i tried.

t091="2019-04-01"
t092="2019-04-02"
t093="2019-04-03"
t094="2019-04-04"
t095="2019-04-05"
t096="2019-04-06"
t097="2019-04-07"
t098="2019-04-08"
t099="2019-04-09"

for k in {091..099}; do
echo $t${k}
done

and the output:

091
092
093
094
095
096
097
098
099

I can't run the code without using the dates in order. how can I do it?


问:
Nodejs/Express Maximum Call stack Size Exceeded on Invalid Routes
I run my application with Nodejs/Express in AWS ECS.
However, I am observing an abnormal behavior in Production environment. Whenever I enter an invalid route such as /invalid-route which should result in 404 response I am getting 500 error with RangeError: Maximum call stack size exceeded.

Also, I am not observing this behavior as soon as a deployment or instant refresh and this only happens after the task is run for sometime. However, when I am receiving this error other functionalities are working as expected. I have added the stack trace below for your reference.

```<code>`RangeError: Maximum call stack size exceeded
at getPathname (/app/app/node_modules/express/lib/router/index.js:532:21)
at next (/app/app/node_modules/express/lib/router/index.js:207:16)
at Layer.handle_error (/app/app/node_modules/express/lib/router/layer.js:67:12)
at trim_prefix (/app/app/node_modules/express/lib/router/index.js:321:13)
at /app/app/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/app/app/node_modules/express/lib/router/index.js:341:12)
at next (/app/app/node_modules/express/lib/router/index.js:275:10)
at Layer.handle_error (/app/app/node_modules/express/lib/router/layer.js:67:12)
at trim_prefix (/app/app/node_modules/express/lib/router/index.js:321:13)
at /app/app/node_modules/express/lib/router/index.js:284:7`
</code>```

my nodejs version is 16.14.1 and the express version is 4.17.3

Few questions I am looking for are

Is it possible for the call stack to get accumulated without getting it cleared?

As a remediation is it recommended to increase the call stack size in a case like this?

Body:
I run my application with Nodejs/Express in AWS ECS.
However, I am observing an abnormal behavior in Production environment. Whenever I enter an invalid route such as /invalid-route which should result in 404 response I am getting 500 error with RangeError: Maximum call stack size exceeded.

Also, I am not observing this behavior as soon as a deployment or instant refresh and this only happens after the task is run for sometime. However, when I am receiving this error other functionalities are working as expected. I have added the stack trace below for your reference.

`RangeError: Maximum call stack size exceeded
at getPathname (/app/app/node_modules/express/lib/router/index.js:532:21)
at next (/app/app/node_modules/express/lib/router/index.js:207:16)
at Layer.handle_error (/app/app/node_modules/express/lib/router/layer.js:67:12)
at trim_prefix (/app/app/node_modules/express/lib/router/index.js:321:13)
at /app/app/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/app/app/node_modules/express/lib/router/index.js:341:12)
at next (/app/app/node_modules/express/lib/router/index.js:275:10)
at Layer.handle_error (/app/app/node_modules/express/lib/router/layer.js:67:12)
at trim_prefix (/app/app/node_modules/express/lib/router/index.js:321:13)
at /app/app/node_modules/express/lib/router/index.js:284:7`

my nodejs version is 16.14.1 and the express version is 4.17.3

Few questions I am looking for are

Is it possible for the call stack to get accumulated without getting it cleared?

As a remediation is it recommended to increase the call stack size in a case like this?