问:
React: Select component not updating inside a dynamic form
I am attempting to create a dynamic form in which there are 2 text fields and one dropdown select. These fields can be added by clicking the "Add More.." button. The remove button removes a particular field set. After an npm start the code shows all elements normally, add, remove and input fields work as intended. However, the problem starts when the select is used. On selecting something, the app crashes and gives a white screen with the errors [tag:"formFields.map is not a function"] and [tag:"Consider adding an error boundary to your tree to customize error handling behavior."] I would appreciate any help that can resolve this. :)

P.S. I am learning react through building projects rather than the conventional method of sitting through hours of tutorials and figuring things out. I am grateful to any help that is offered to me.

```<code>import { useState } from "react";

function FoodPreferences(){

  const [formFields, setFormFields] = useState([
    { name: '', age: '', food: '' }
  ])
  const [foodState, setFoodState] = useState("dumpling");
  const handleFormChange = (event, index) => {
    let data = [...formFields];
    data[index][event.target.name] = event.target.value;
    setFormFields(data);
  }
  const handleSelectChange = (event, index) => {
    const selectedFood = event.target.value
    setFormFields(selectedFood)
  }
  const submit = (e) => {
    e.preventDefault();
    console.log(formFields, foodState)
  }

  const addFields = () => {
    let object = {
      name: '',
      age: '',
      food: ''
    }

    setFormFields([...formFields, object])
  }

  const removeFields = (index) => {
    let data = [...formFields];
    data.splice(index, 1)
    setFormFields(data)
  }

  return (
    <div className="App">
      <form onSubmit={submit}>
        {formFields.map((form, index) => {
          return (
            <div key={index}>
              <input
                name='name'
                placeholder='Name'
                onChange={event => handleFormChange(event, index)}
                value={form.name}
              />
              <input
                name='age'
                placeholder='Age'
                onChange={event => handleFormChange(event, index)}
                value={form.age}
              />
              <select
                className="custom-select"
                value={form.food}
                onChange={event => handleSelectChange(event,index)}
              >
                <option value="steak">Steak</option>
                <option value="sandwich">Sandwich</option>
                <option value="dumpling">Dumpling</option>
              </select>

              <button onClick={() => removeFields(index)}>Remove</button>
            </div>
          )
        })}
      </form>
      <button onClick={addFields}>Add More..</button>
      <br />
      <button onClick={submit}>Submit</button>
    </div>
  );
}
export default FoodPreferences;
</code>```

I have tried using the select component alone without looping it and it worked fine. The errors pop up when select component is placed under a map() for dynamic inputs (Adding or Removing Fields). I know that the error is either in the onChange part of my code for the select component or the handleSelectChange

```<code>
import React, {useState} from 'react';
function FoodChoice() {
const \[foodState, setFoodState\] = useState("dumpling");

    return (
      <div className="container p-5">
        <select
          className="custom-select"
          value={foodState}
          onChange={(e) => {
            const selectedFood = e.target.value;
            setFoodState(selectedFood);
          }}
        >
          <option value="steak">Steak</option>
          <option value="sandwich">Sandwich</option>
          <option value="dumpling">Dumpling</option>
        </select>
        {foodState}
      </div>
    );

}

export default FoodChoice;
</code>```

Body:
I am attempting to create a dynamic form in which there are 2 text fields and one dropdown select. These fields can be added by clicking the "Add More.." button. The remove button removes a particular field set. After an npm start the code shows all elements normally, add, remove and input fields work as intended. However, the problem starts when the select is used. On selecting something, the app crashes and gives a white screen with the errors [tag:"formFields.map is not a function"] and [tag:"Consider adding an error boundary to your tree to customize error handling behavior."] I would appreciate any help that can resolve this. :)

P.S. I am learning react through building projects rather than the conventional method of sitting through hours of tutorials and figuring things out. I am grateful to any help that is offered to me.

import { useState } from "react";

function FoodPreferences(){

  const [formFields, setFormFields] = useState([
    { name: '', age: '', food: '' }
  ])
  const [foodState, setFoodState] = useState("dumpling");
  const handleFormChange = (event, index) => {
    let data = [...formFields];
    data[index][event.target.name] = event.target.value;
    setFormFields(data);
  }
  const handleSelectChange = (event, index) => {
    const selectedFood = event.target.value
    setFormFields(selectedFood)
  }
  const submit = (e) => {
    e.preventDefault();
    console.log(formFields, foodState)
  }

  const addFields = () => {
    let object = {
      name: '',
      age: '',
      food: ''
    }

    setFormFields([...formFields, object])
  }

  const removeFields = (index) => {
    let data = [...formFields];
    data.splice(index, 1)
    setFormFields(data)
  }

  return (

      <form onSubmit={submit}>
        {formFields.map((form, index) => {
          return (

              <input
                name='name'
                placeholder='Name'
                onChange={event => handleFormChange(event, index)}
                value={form.name}
              />
              <input
                name='age'
                placeholder='Age'
                onChange={event => handleFormChange(event, index)}
                value={form.age}
              />
              <select
                className="custom-select"
                value={form.food}
                onChange={event => handleSelectChange(event,index)}
              >
                <option value="steak">Steak</option>
                <option value="sandwich">Sandwich</option>
                <option value="dumpling">Dumpling</option>
              </select>

              <button onClick={() => removeFields(index)}>Remove</button>

          )
        })}
      </form>
      <button onClick={addFields}>Add More..</button>

      <button onClick={submit}>Submit</button>

  );
}
export default FoodPreferences;

I have tried using the select component alone without looping it and it worked fine. The errors pop up when select component is placed under a map() for dynamic inputs (Adding or Removing Fields). I know that the error is either in the onChange part of my code for the select component or the handleSelectChange

import React, {useState} from 'react';
function FoodChoice() {
const \[foodState, setFoodState\] = useState("dumpling");

    return (

        <select
          className="custom-select"
          value={foodState}
          onChange={(e) => {
            const selectedFood = e.target.value;
            setFoodState(selectedFood);
          }}
        >
          <option value="steak">Steak</option>
          <option value="sandwich">Sandwich</option>
          <option value="dumpling">Dumpling</option>
        </select>
        {foodState}

    );

}

export default FoodChoice;


来源: stackexchange

问:
Django forms useless div tag
I am getting one problem while using django forms. Actually When I am using RadioSelect widget it is giving unnecessary div tags. Means each radio button is separated with individual div tag. And I don't want that. Please help   Image of Div tags for each label

How can I get those label and input tag i.e Radio Buttons in single div tag not these many

index.html
forms.py

ContentLicense: CC BY-SA 4.0

Title: Django forms useless div tag


问:
Spring Data JPA Query: Insert List Of Values
I have a List<Integer> ids and a Integer singleId. Is there a way to make INSERT INTO TABLE VALUES() for a lot of values using spring data JPA @Query()?
I need something like:

```<code>INSERT INTO TABLE
    VALUES(ids[0], singleId),
    VALUES(ids[1], singleId),
    VALUES(ids[2], singleId),
    ...
</code>```

Body:
I have a List<Integer> ids and a Integer singleId. Is there a way to make INSERT INTO TABLE VALUES() for a lot of values using spring data JPA @Query()?
I need something like:

INSERT INTO TABLE
    VALUES(ids[0], singleId),
    VALUES(ids[1], singleId),
    VALUES(ids[2], singleId),
    ...


问:
How do I stub a dependency within Cypress/Sinon without actually importing the file?
Within my Cypress tests I would like to use the endpoints that I generate from our swagger documentation. However, these endpoints use a custom Axios client, that uses Redux and a ton of other dependencies. I can mock this client, but only by using:

```<code>import * as CustomAxios from "libs/custom";

cy.stub(CustomAxios, "customAxios");
</code>```

However, within this file "custom.ts", I have the following code:

```<code>export const customAxios = createCustomAxiosClient()
</code>```

It seems I cannot mock this file, without importing the file, and calling this method (which creates errors). Does anyone have an idea how I can mock this customAxios client without having the createCustomAxiosClient() method being called (which I cannot remove).

I tried reading the documentation and other questions, but I could not find any answers to my specific case.

Body:
Within my Cypress tests I would like to use the endpoints that I generate from our swagger documentation. However, these endpoints use a custom Axios client, that uses Redux and a ton of other dependencies. I can mock this client, but only by using:

import * as CustomAxios from "libs/custom";

cy.stub(CustomAxios, "customAxios");

However, within this file "custom.ts", I have the following code:

export const customAxios = createCustomAxiosClient()

It seems I cannot mock this file, without importing the file, and calling this method (which creates errors). Does anyone have an idea how I can mock this customAxios client without having the createCustomAxiosClient() method being called (which I cannot remove).

I tried reading the documentation and other questions, but I could not find any answers to my specific case.


问:
Is there a short $BUILD_ID in Cloud Build?
I'd like to use the build ID in a step in Cloud Build.

I'm looking at variables available at https://cloud.google.com/build/docs/configuring-builds/substitute-variable-values but I'm not seeing anything other than $BUILD_ID that I can use but that takes up 36 characters.

Is there a short version I'm missing?  There's a SHORT_SHA for the Git SHA for each commit.       So I thought there might be one for the build ID.


问:
anyone help i not able to trigger buy and sell alert in plotting trendline
plotting the two trend lines

need buy and sell alert or strategy buy or strategy sell, if candle closes above trend line buy and if candle closes below trendline sell

color_high1 = slope_high1 * time<0 ? color.red : na

color_low1  = slope_low1  * time>0 ? color.lime : na

```<code>plot(tlmod ? high_point1 : na, color=color_high1, offset=-l1/2, linewidth=2)
plot(tlmod ? low_point1  : na, color=color_low1, offset=-l1/2, linewidth=2)

if  crossover(close,high_point1 )
    strategy.entry('My Long Entry Id', strategy.long)
    alert(tostring(LicenseID)+',buy,' + syminfo.ticker + ',sl=' + tostring(high_point1) + ',risk=' + tostring(riskvalue),alert.freq_all)

if  crossunder(close,low_point1)
    strategy.entry('My Short Entry Id', strategy.short)
    alert(tostring(LicenseID)+',sell,' + syminfo.ticker + ',sl=' + tostring(low_point1) + ',risk=' + tostring(riskvalue),alert.freq_all)
</code>```

Body:
plotting the two trend lines

need buy and sell alert or strategy buy or strategy sell, if candle closes above trend line buy and if candle closes below trendline sell

color_high1 = slope_high1 * time<0 ? color.red : na

color_low1  = slope_low1  * time>0 ? color.lime : na

plot(tlmod ? high_point1 : na, color=color_high1, offset=-l1/2, linewidth=2)
plot(tlmod ? low_point1  : na, color=color_low1, offset=-l1/2, linewidth=2)

if  crossover(close,high_point1 )
    strategy.entry('My Long Entry Id', strategy.long)
    alert(tostring(LicenseID)+',buy,' + syminfo.ticker + ',sl=' + tostring(high_point1) + ',risk=' + tostring(riskvalue),alert.freq_all)

if  crossunder(close,low_point1)
    strategy.entry('My Short Entry Id', strategy.short)
    alert(tostring(LicenseID)+',sell,' + syminfo.ticker + ',sl=' + tostring(low_point1) + ',risk=' + tostring(riskvalue),alert.freq_all)


问:
Using wget downloading data from FTP server
I trying to download data from FTP server using wget. I am using the following command

wget -r ftp://aftp.cmdl.noaa.gov/data/radiation/surfrad/

```<code>C:\Users\Shoaib ch>wget -r ftp://aftp.cmdl.noaa.gov/data/radiation/surfrad/
--12:14:37--  ftp://aftp.cmdl.noaa.gov/data/radiation/surfrad/
           => `aftp.cmdl.noaa.gov/data/radiation/surfrad/.listing'
Connecting to aftp.cmdl.noaa.gov:21... connected!
Logging in as anonymous ... Logged in!
==> SYST ... done.    ==> PWD ... done.
==> TYPE I ... done.  ==> CWD /data/radiation/surfrad ... done.
==> PORT ...
Invalid PORT.
Retrying.
</code>```

Can Anyone help me with this issue

Body:
I trying to download data from FTP server using wget. I am using the following command

wget -r ftp://aftp.cmdl.noaa.gov/data/radiation/surfrad/

C:\Users\Shoaib ch>wget -r ftp://aftp.cmdl.noaa.gov/data/radiation/surfrad/
--12:14:37--  ftp://aftp.cmdl.noaa.gov/data/radiation/surfrad/
           => `aftp.cmdl.noaa.gov/data/radiation/surfrad/.listing'
Connecting to aftp.cmdl.noaa.gov:21... connected!
Logging in as anonymous ... Logged in!
==> SYST ... done.    ==> PWD ... done.
==> TYPE I ... done.  ==> CWD /data/radiation/surfrad ... done.
==> PORT ...
Invalid PORT.
Retrying.

Can Anyone help me with this issue


问:
from utils.character_cnn import CharacterMapper, CharacterIndexer
I get an issue when I try to import from utils.character_cnn, I get error module utils.character_cnn what should I install to get the module

I tried installing utils module but I still in counter the same error, please assist


问:
error No cached version of androidx.exifinterface:exifinterface:1.3.3 android studio
I want to run the Android Studio project, but the following error is given :

error :
`Caused by:org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all files for configuration ':app:debugRuntimeClasspath'.

No cached version of androidx.exifinterface:exifinterface:1.3.3 available for offline mode.
Disable Gradle 'offline mode' and sync project`


问:
How to display same picturebox to other forms visual studio c# winforms
I have FormAct1:

and FormMain:

I can't make the picture to be inserted, via user input from FormAct1 and display it in FormMain

Here is my code

```<code>public static PictureBox usi;

private void ChooseImage_Click(object sender, EventArgs e)
{
    try
    {
        // openfiledialog filter
        if (open.ShowDialog() == DialogResult.OK)
        {
        }

        usi = pictureBox1;
    }
    catch
    {
    }
}
</code>```

I tried searching for similar problems, but to no avail.

What I need to see is that the same picture should appear in FormMain.

Body:
I have FormAct1:

and FormMain:

I can't make the picture to be inserted, via user input from FormAct1 and display it in FormMain

Here is my code

public static PictureBox usi;

private void ChooseImage_Click(object sender, EventArgs e)
{
    try
    {
        // openfiledialog filter
        if (open.ShowDialog() == DialogResult.OK)
        {
        }

        usi = pictureBox1;
    }
    catch
    {
    }
}

I tried searching for similar problems, but to no avail.

What I need to see is that the same picture should appear in FormMain.


问:
Select all pods running on a K8s node for Cilium Policy
I am trying to use Cilium Egress Gateway Policy in my K8s cluster. I want to apply policy on all pods scheduled on Node X. How can I do that?

Using the podSelector field, I can pick pods which matchLabels. Theer is also a special label io.kubernetes.pod.namespace to select pods in a namespace. But I don't know how to filter for the pod's scheduled node (spec.nodeName).

Another possible solution is that I write a daemon set, which will get all pods on the node, and then call api-server to add a label for nodeName. But I need guidance how to write such daemon set, or if it's even secure to have the api-server credentials on the node.


问:
TypeScript, how to iterate an object, and create a new mapped type/object with multiple keys
So I have some source data:

```<code>const response = [{
    "date": 10/12/2022,
    "type": 1001
},
{
    "date": 11/12/2022,
    "type": 1001
},
{
    "date": 11/12/2022,
    "type": 1001
},
{
    "date": 13/12/2022,
    "type": 1002
}]
</code>```

I want to iterate this array, and create a new object (defined as a TypeScript type) calculating counts of the unique index of 'date' + 'type'. I am struggling to do this in an elegant way, I can do it using pure Javascript but its messy.

The output would look something like this:

```<code>[
{
  1001 : [
    {
      "10/12/2022" : 1
    },
    {
      "11/12/2022" : 2
    }
  ]
},
{
  1002 : [
    {
      "13/12/2022" : 1
    }
  ]
}
]
</code>```

And the output would be defined by a TypeScript type where I could access values by going 1001["11/12/2022"] and get a result of 2.

I'm unsure how to do this and define my TypeScript response object.

I tried defining my new response like so:

```<code>export type DataCounts = {
    [date: string]: number
}

export type Statistic = {
    [type: number]: DataCounts;
}
</code>```

And then tried various ways to iterate the original data using reduce or for loops, using Object.keys etc to check for the existence of an object to increment counts by, but keep getting stuck on the 2nd dimension, i.e. type then date.

Body:
So I have some source data:

const response = [{
    "date": 10/12/2022,
    "type": 1001
},
{
    "date": 11/12/2022,
    "type": 1001
},
{
    "date": 11/12/2022,
    "type": 1001
},
{
    "date": 13/12/2022,
    "type": 1002
}]

I want to iterate this array, and create a new object (defined as a TypeScript type) calculating counts of the unique index of 'date' + 'type'. I am struggling to do this in an elegant way, I can do it using pure Javascript but its messy.

The output would look something like this:

[
{
  1001 : [
    {
      "10/12/2022" : 1
    },
    {
      "11/12/2022" : 2
    }
  ]
},
{
  1002 : [
    {
      "13/12/2022" : 1
    }
  ]
}
]

And the output would be defined by a TypeScript type where I could access values by going 1001["11/12/2022"] and get a result of 2.

I'm unsure how to do this and define my TypeScript response object.

I tried defining my new response like so:

export type DataCounts = {
    [date: string]: number
}

export type Statistic = {
    [type: number]: DataCounts;
}

And then tried various ways to iterate the original data using reduce or for loops, using Object.keys etc to check for the existence of an object to increment counts by, but keep getting stuck on the 2nd dimension, i.e. type then date.


问:
DB Migration from Azure SQL VM to AWS RDS Postgres with Babelfish enabled
We are migrating an Application from Azure to AWS. We have requirement to migrate a sql server database which exists Azure VM to AWS RDS postgres with Babelfish enabled, we need this to be done near real time or with very limited downtime. We were contemplating to use AWS DMS service, but to do that, we need Azure VM to be exposed to Public, and as we know it is very risky. Would you please help me with your experiences and are aware of how this can be done in a very secure and efficient way and the various options we have. Thank you.</p>


问:
Runtime.UserCodeSyntaxError: SyntaxError: Invalid or unexpected token when running a lambda function trying to query data from rds
I have a lambda function querying all rows from table accounts

```<code>const pool = require("../db");
'use strict';

function getAllUsers (event, context, callback) {
  context.callbackWaitsForEmptyEventLoop = false;
  try {
    pool.query('SELECT * FROM accounts;').then((r) => {
      callback(null, {
        statusCode: 200,
        body: JSON.stringify(r.rows)
      })
    }).catch((e) => callback(null, {
      statusCode: 500,
      body: e.toString()
    }))
  } catch (e) {
    console.log(e)
  }
};
</code>```

serverless.yaml file:

```<code>plugins:
  - serverless-offline

service: node-serverless
app: server-app

provider:
  name: aws
  runtime: nodejs16.x
  memorySize: 128
  timeout: 5

functions:

  getAllUsers:
    handler: handler.getAllUsers
    events:
      - http:
          path: /users
          method: get
          cors: true

</code>```

But I am running into an error:

```<code>GET /dev/users (λ: getAllUsers)
✖ Unhandled exception in handler 'getAllUsers'.
✖ Runtime.UserCodeSyntaxError: SyntaxError: Invalid or unexpected token
</code>```

(502 error)

same error when deployed and running offline...
I am using node-pg to pool from my db.

Body:
I have a lambda function querying all rows from table accounts

const pool = require("../db");
'use strict';

function getAllUsers (event, context, callback) {
  context.callbackWaitsForEmptyEventLoop = false;
  try {
    pool.query('SELECT * FROM accounts;').then((r) => {
      callback(null, {
        statusCode: 200,
        body: JSON.stringify(r.rows)
      })
    }).catch((e) => callback(null, {
      statusCode: 500,
      body: e.toString()
    }))
  } catch (e) {
    console.log(e)
  }
};

serverless.yaml file:

plugins:
  - serverless-offline

service: node-serverless
app: server-app

provider:
  name: aws
  runtime: nodejs16.x
  memorySize: 128
  timeout: 5

functions:

  getAllUsers:
    handler: handler.getAllUsers
    events:
      - http:
          path: /users
          method: get
          cors: true

But I am running into an error:

GET /dev/users (λ: getAllUsers)
✖ Unhandled exception in handler 'getAllUsers'.
✖ Runtime.UserCodeSyntaxError: SyntaxError: Invalid or unexpected token

(502 error)

same error when deployed and running offline...
I am using node-pg to pool from my db.


问:
TWO MySQL freeradius
I have two mysql

No problem with login

but

I have a problem with the accounting part.

how do i make the accounting successful login go to the correct sql

authorize { sql1, sql2 }

accounting {i need help here }

Title: TWO MySQL freeradius


问:
Fixing imports in my custom reactjs component library
I have followed a simple tutorial at https://www.bayanbennett.com/posts/making-a-ui-library-with-react-and-typescript/.

Thanks to this tutorial, I have managed to create my custom component library, pack it and publish it to my nexus repository.

If I add it as dependency to my other project, imports seem not to work correctly.

Here is the structure of the component library

index.ts in my form folder looks like this:

```<code>export { default as JmfFormAutocomplete } from "./JmfFormAutocomplete";
export { default as JmfFormAutocompleteMultiple } from "./JmfFormAutocompleteMultiple";
export { default as JmfFormCheckbox } from "./JmfFormCheckbox";
export { default as JmfFormSelect } from "./JmfFormSelect";
export { default as JmfFormSwitch } from "./JmfFormSwitch";
export { default as JmfFormTextField } from "./JmfFormTextField";

export type { JmfFormAutocompleteProps } from "./JmfFormAutocomplete.types";
export type { JmfFormCheckboxProps } from "./JmfFormCheckbox.types";
export type { JmfFormSelectProps } from "./JmfFormSelect.types";
export type { JmfFormSwitchProps } from "./JmfFormSwitch.types";
export type { JmfFormTextFieldProps } from "./JmfFormTextField.types";
export type { ReactHookFormCommonPropsTypes } from "./ReactHookFormCommonProps.types";
</code>```

Errors in my project, where I am using this component library, are:

```<code>ERROR in ./node_modules/java-multima-framework/src/components/form/index.ts 8:7

Module parse failed: Unexpected token (8:7)
File was processed with these loaders:
 * ./node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
| export { default as JmfFormTextField } from "./JmfFormTextField";
|
> export type { JmfFormAutocompleteProps } from "./JmfFormAutocomplete.types";
| export type { JmfFormCheckboxProps } from "./JmfFormCheckbox.types";
| export type { JmfFormSelectProps } from "./JmfFormSelect.types";
</code>```

component library other files:

tsconfig.json

```<code>{
  "extends": "@tsconfig/recommended/tsconfig.json",
  "compilerOptions": {
    "jsx": "preserve",
    "resolveJsonModule": true
  },
  "include": ["src/**/*"]
}
</code>```

package.json

```<code>{
  "name": "java-multima-framework",
  "version": "0.1.0",
  "author": "Adam Ostrožlík",
  "main": "src/index.ts",
  "files": [
    "src/**/*"
  ],
  "directories": {
    "src": "src"
  },
  "publishConfig": {
    "registry": "http://lnx-nexusrep.mm.int/repository/npm-releases/"
  },
  "scripts": {
    "prepare": "cd .. && husky install frontend/.husky",
    "storybook": "start-storybook -p 6006 -s ./public",
    "build-storybook": "build-storybook -s ./public",
    "openapi-taxguru": "openapi -i openapi/jmf-openapi.json -o src/backend --exportCore false --exportServices false"
  },
  "lint-staged": {
    "*/**/*.{js,ts,jsx,tsx,x1}": "eslint --fix",
    "*/**/*.{js,ts,jsx,tsx,x2}": "prettier --write -u"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ],
    "overrides": [
      {
        "files": [
          "**/*.stories.*"
        ],
        "rules": {
          "import/no-anonymous-default-export": "off"
        }
      },
      {
        "files": [
          "**/*.stories.*"
        ],
        "rules": {
          "import/no-anonymous-default-export": "off"
        }
      }
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/preset-react": "^7.18.6",
    "@storybook/addon-actions": "^6.5.13",
    "@storybook/addon-essentials": "^6.5.13",
    "@storybook/addon-interactions": "^6.5.13",
    "@storybook/addon-links": "^6.5.13",
    "@storybook/builder-webpack5": "^6.5.13",
    "@storybook/manager-webpack5": "^6.5.13",
    "@storybook/node-logger": "^6.5.13",
    "@storybook/preset-create-react-app": "^4.1.2",
    "@storybook/react": "^6.5.13",
    "@storybook/testing-library": "^0.0.13",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "@tsconfig/recommended": "^1.0.1",
    "@types/jest": "^29.2.3",
    "@typescript-eslint/eslint-plugin": "^5.44.0",
    "@typescript-eslint/parser": "^5.44.0",
    "babel-plugin-named-exports-order": "^0.0.2",
    "eslint": "^8.28.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-config-standard": "^17.0.0",
    "eslint-import-resolver-typescript": "^3.5.2",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-n": "^15.3.0",
    "eslint-plugin-promise": "^6.1.1",
    "eslint-plugin-react": "^7.31.10",
    "eslint-plugin-storybook": "^0.6.7",
    "husky": "^8.0.2",
    "lint-staged": "^13.0.3",
    "openapi-typescript-codegen": "^0.23.0",
    "prettier": "2.7.1",
    "react-scripts": "5.0.1",
    "tsconfig-paths-webpack-plugin": "^4.0.0",
    "web-vitals": "^2.1.4",
    "webpack": "^5.75.0"
  },
  "dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@hookform/resolvers": "^2.9.10",
    "@mui/icons-material": "^5.10.16",
    "@mui/material": "^5.10.17",
    "@types/node": "^18.11.12",
    "@types/react": "^18.0.25",
    "@types/react-dom": "^18.0.9",
    "axios": "^1.2.0",
    "i18next": "^22.0.6",
    "material-react-table": "^1.4.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-hook-form": "^7.39.1",
    "react-i18next": "^12.0.0",
    "react-jwt": "^1.1.7",
    "react-router-dom": "^6.4.2",
    "typescript": "^4.9.3",
    "yup": "^0.32.11"
  }
}

</code>```

I have tried packiging with rollup but it is overkill for me. I just need this library for one environment.
It seems that compiler is having problems only with exporting props.

I am expecting this to work seamlessly as the tutorial describes.

Body:
I have followed a simple tutorial at https://www.bayanbennett.com/posts/making-a-ui-library-with-react-and-typescript/.

Thanks to this tutorial, I have managed to create my custom component library, pack it and publish it to my nexus repository.

If I add it as dependency to my other project, imports seem not to work correctly.

Here is the structure of the component library

index.ts in my form folder looks like this:

export { default as JmfFormAutocomplete } from "./JmfFormAutocomplete";
export { default as JmfFormAutocompleteMultiple } from "./JmfFormAutocompleteMultiple";
export { default as JmfFormCheckbox } from "./JmfFormCheckbox";
export { default as JmfFormSelect } from "./JmfFormSelect";
export { default as JmfFormSwitch } from "./JmfFormSwitch";
export { default as JmfFormTextField } from "./JmfFormTextField";

export type { JmfFormAutocompleteProps } from "./JmfFormAutocomplete.types";
export type { JmfFormCheckboxProps } from "./JmfFormCheckbox.types";
export type { JmfFormSelectProps } from "./JmfFormSelect.types";
export type { JmfFormSwitchProps } from "./JmfFormSwitch.types";
export type { JmfFormTextFieldProps } from "./JmfFormTextField.types";
export type { ReactHookFormCommonPropsTypes } from "./ReactHookFormCommonProps.types";

Errors in my project, where I am using this component library, are:

ERROR in ./node_modules/java-multima-framework/src/components/form/index.ts 8:7

Module parse failed: Unexpected token (8:7)
File was processed with these loaders:
 * ./node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
| export { default as JmfFormTextField } from "./JmfFormTextField";
|
> export type { JmfFormAutocompleteProps } from "./JmfFormAutocomplete.types";
| export type { JmfFormCheckboxProps } from "./JmfFormCheckbox.types";
| export type { JmfFormSelectProps } from "./JmfFormSelect.types";

component library other files:

tsconfig.json

{
  "extends": "@tsconfig/recommended/tsconfig.json",
  "compilerOptions": {
    "jsx": "preserve",
    "resolveJsonModule": true
  },
  "include": ["src/**/*"]
}

package.json

{
  "name": "java-multima-framework",
  "version": "0.1.0",
  "author": "Adam Ostrožlík",
  "main": "src/index.ts",
  "files": [
    "src/**/*"
  ],
  "directories": {
    "src": "src"
  },
  "publishConfig": {
    "registry": "http://lnx-nexusrep.mm.int/repository/npm-releases/"
  },
  "scripts": {
    "prepare": "cd .. && husky install frontend/.husky",
    "storybook": "start-storybook -p 6006 -s ./public",
    "build-storybook": "build-storybook -s ./public",
    "openapi-taxguru": "openapi -i openapi/jmf-openapi.json -o src/backend --exportCore false --exportServices false"
  },
  "lint-staged": {
    "*/**/*.{js,ts,jsx,tsx,x1}": "eslint --fix",
    "*/**/*.{js,ts,jsx,tsx,x2}": "prettier --write -u"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ],
    "overrides": [
      {
        "files": [
          "**/*.stories.*"
        ],
        "rules": {
          "import/no-anonymous-default-export": "off"
        }
      },
      {
        "files": [
          "**/*.stories.*"
        ],
        "rules": {
          "import/no-anonymous-default-export": "off"
        }
      }
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/preset-react": "^7.18.6",
    "@storybook/addon-actions": "^6.5.13",
    "@storybook/addon-essentials": "^6.5.13",
    "@storybook/addon-interactions": "^6.5.13",
    "@storybook/addon-links": "^6.5.13",
    "@storybook/builder-webpack5": "^6.5.13",
    "@storybook/manager-webpack5": "^6.5.13",
    "@storybook/node-logger": "^6.5.13",
    "@storybook/preset-create-react-app": "^4.1.2",
    "@storybook/react": "^6.5.13",
    "@storybook/testing-library": "^0.0.13",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "@tsconfig/recommended": "^1.0.1",
    "@types/jest": "^29.2.3",
    "@typescript-eslint/eslint-plugin": "^5.44.0",
    "@typescript-eslint/parser": "^5.44.0",
    "babel-plugin-named-exports-order": "^0.0.2",
    "eslint": "^8.28.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-config-standard": "^17.0.0",
    "eslint-import-resolver-typescript": "^3.5.2",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-n": "^15.3.0",
    "eslint-plugin-promise": "^6.1.1",
    "eslint-plugin-react": "^7.31.10",
    "eslint-plugin-storybook": "^0.6.7",
    "husky": "^8.0.2",
    "lint-staged": "^13.0.3",
    "openapi-typescript-codegen": "^0.23.0",
    "prettier": "2.7.1",
    "react-scripts": "5.0.1",
    "tsconfig-paths-webpack-plugin": "^4.0.0",
    "web-vitals": "^2.1.4",
    "webpack": "^5.75.0"
  },
  "dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@hookform/resolvers": "^2.9.10",
    "@mui/icons-material": "^5.10.16",
    "@mui/material": "^5.10.17",
    "@types/node": "^18.11.12",
    "@types/react": "^18.0.25",
    "@types/react-dom": "^18.0.9",
    "axios": "^1.2.0",
    "i18next": "^22.0.6",
    "material-react-table": "^1.4.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-hook-form": "^7.39.1",
    "react-i18next": "^12.0.0",
    "react-jwt": "^1.1.7",
    "react-router-dom": "^6.4.2",
    "typescript": "^4.9.3",
    "yup": "^0.32.11"
  }
}

I have tried packiging with rollup but it is overkill for me. I just need this library for one environment.
It seems that compiler is having problems only with exporting props.

I am expecting this to work seamlessly as the tutorial describes.


问:
How to style react native for multiple different devices and operating systems
I am relatively new to react native and am not looking for actual code however I am wondering the best way to implement layouts/ styling of a page so that it looks the same proportion wise across multiple different devices and operating systems. For example iPhone X through to 13 have different size screens and then if you include the new Samsung's, Google Pixels and Huawei phones there is a lot of different sizes of screens.
I can create different styles by detecting what device is being used and getting the logical resolution from that however I am wondering if there is a better way than just doing this for 10 different phone sizes. For example in the picture you can see the front wheel of the car is on the edge of the blue box which gives it an almost 3D effect.[] To get this effect across 2 different devices I have to change the absolute positioning of the car for both devices however the more screen sizes/ devices I want it to look the same on the more code it is and it seems like I am using a long winded/ redundant method.

Another alternative I have thought about is just turning that section into an image and using it as a background image however I am not sure how that will affect performance.

Any thoughts?


问:
Swagger (SpringDoc) UI requests throught gateway
It seems that when we use Swagger (SpringDoc) UI for the gateway, when a request is sent through it, the request is made directly to the service and not through the gateway. For example, in this example (linked from SpringDoc documentation), the swagger ui address is 158.101.191.70 while the request is being made to 172.17.0.9.

Isn't an important point of using swagger to let API users know what APIs we have and be able to test them? Thus, shouldn't the requests be made through the gateway and not directly? Maybe, they don't even have access to the services directly. Is there a solution?


问:
Uncaught TypeError: Cannot set properties of undefined (setting 'right')
My code is:

```<code>let stars = document.getElementsByClassName('stars');
        let moon = document.getElementsByClassName('moon');
        let mountains_behind = document.getElementsByClassName('mountains_behind');
        let text = document.getElementsByClassName('text');
        let btn = document.getElementsByClassName('btn');
        let mountains_front = document.getElementsByClassName('mountains_front');

        window.addEventListener('scroll', function(){
            let value = window.scrollY;
            stars.style.left = value * 0.25 + 'px';
        })
</code>```

And I get the following error: Uncaught TypeError: Cannot set properties of undefined (setting 'left')
How should I exactly define this property?

I tried to change the property or search how should I define one but didn't get the answer I really needed

Body:
My code is:

let stars = document.getElementsByClassName('stars');
        let moon = document.getElementsByClassName('moon');
        let mountains_behind = document.getElementsByClassName('mountains_behind');
        let text = document.getElementsByClassName('text');
        let btn = document.getElementsByClassName('btn');
        let mountains_front = document.getElementsByClassName('mountains_front');

        window.addEventListener('scroll', function(){
            let value = window.scrollY;
            stars.style.left = value * 0.25 + 'px';
        })

And I get the following error: Uncaught TypeError: Cannot set properties of undefined (setting 'left')
How should I exactly define this property?

I tried to change the property or search how should I define one but didn't get the answer I really needed


问:
VS2022 swagger document generation on build
I am trying in VS2022 using .net 7 to auto build an open-api (swagger) specification, that I want to wire later in connected services. My problem is that the file is not being created.

This is my swagger configuration:

```<code>public static void ConfigureSwagger(this WebApplicationBuilder builder)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        var appSettings = builder.Configuration.GetObjectFromConfigSection<AppSettings>("AppSettings");

        builder.Services.AddSwaggerGen(x =>
        {
            x.SwaggerDoc(appSettings.SwaggerPublicGroupAPI, new OpenApiInfo { Title = "aov.org public API", Version = appSettings.SwaggerPublicGroupAPI });
            x.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["action"]}");

            // This code allow you to use XML-comments
            string xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            if (File.Exists(xmlPath))
            {
                x.IncludeXmlComments(xmlPath);
            }

            x.AddSecurityDefinition
            (
                "Bearer",
                new OpenApiSecurityScheme
                {
                    In = ParameterLocation.Header,
                    Description = "Please enter token into the field",
                    Name = "Authorization",
                    Type = SecuritySchemeType.ApiKey
                }
            );
        });
    }

    public static void ConfigureSwagger(this WebApplication webApp)
    {
        if (webApp is null)
            return;

        var appSettings = webApp.Configuration.GetObjectFromConfigSection<AppSettings>("AppSettings");

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        webApp.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        webApp.UseSwaggerUI(x =>
        {
            x.SwaggerEndpoint($"/swagger/{appSettings.SwaggerPublicGroupAPI}/swagger.json", "aov.org public API");
        });
    }
</code>```

The appSettings are coming from appSettings.json and have the following entries:

```<code>  "AppSettings": {
    "SwaggerPublicGroupAPI": "public",
    "VersionAPI": "1.0"
  }
</code>```

In the WebAPI project I added the following lines:

```<code><Target Name="OpenAPI" AfterTargets="Build" Condition="$(Configuration)=='Debug'">
        <Exec Command="echo Generating OprnAPI." />
        <Exec Command="dotnet swagger tofile --output ./_open-api.json $(OutputPath)$(AssemblyName).dll public"
              ContinueOnError="true" />
    </Target>
</code>```

The project builds, but in the output window am getting a strange error:

```<code>Unhandled exception. System.AggregateException: One or more errors occurred. (The ConnectionString property has not been initialized.)
1> ---> System.InvalidOperationException: The ConnectionString property has not been initialized.
1>   at Microsoft.Data.SqlClient.SqlConnection.PermissionDemand()
1>   at Microsoft.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
1>   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
1>   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
1>   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
1>   at Microsoft.Data.SqlClient.SqlConnection.InternalOpenAsync(CancellationToken cancellationToken)
1>--- End of stack trace from previous location ---
1>   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
1>   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
1>   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
1>   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass20_0.<<ExistsAsync>b__0>d.MoveNext()
1>--- End of stack trace from previous location ---
1>   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass20_0.<<ExistsAsync>b__0>d.MoveNext()
1>--- End of stack trace from previous location ---
1>   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.<>c__DisplayClass30_0`2.<<ExecuteAsync>b__0>d.MoveNext()
1>--- End of stack trace from previous location ---
1>   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementationAsync[TState,TResult](Func`4 operation, Func`4 verifySucceeded, TState state, CancellationToken cancellationToken)
1>   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementationAsync[TState,TResult](Func`4 operation, Func`4 verifySucceeded, TState state, CancellationToken cancellationToken)
1>   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
1>   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.ExistsAsync(CancellationToken cancellationToken)
1>   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.MigrateAsync(String targetMigration, CancellationToken cancellationToken)
1>   at Program.<Main>$(String[] args) in C:\temp\amazonsofvolleyball\Backend.WebAPI\Program.cs:line 83
1>   at Program.<Main>(String[] args)
1>   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
1>   at System.Reflection.MethodInvoker.Invoke(Object obj, IntPtr* args, BindingFlags invokeAttr)
1>   --- End of inner exception stack trace ---
1>   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
1>   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
1>   at System.Threading.Tasks.Task.Wait()
1>   at Swashbuckle.AspNetCore.Cli.HostingApplication.GetServiceProvider(Assembly assembly) in C:\projects\ahoy\src\Swashbuckle.AspNetCore.Cli\HostingApplication.cs:line 81
1>   at Swashbuckle.AspNetCore.Cli.Program.GetServiceProvider(Assembly startupAssembly) in C:\projects\ahoy\src\Swashbuckle.AspNetCore.Cli\Program.cs:line 152
1>   at Swashbuckle.AspNetCore.Cli.Program.<>c.<Main>b__0_4(IDictionary`2 namedArgs) in C:\projects\ahoy\src\Swashbuckle.AspNetCore.Cli\Program.cs:line 82
1>   at Swashbuckle.AspNetCore.Cli.CommandRunner.Run(IEnumerable`1 args) in C:\projects\ahoy\src\Swashbuckle.AspNetCore.Cli\CommandRunner.cs:line 68
1>   at Swashbuckle.AspNetCore.Cli.CommandRunner.Run(IEnumerable`1 args) in C:\projects\ahoy\src\Swashbuckle.AspNetCore.Cli\CommandRunner.cs:line 59
1>   at Swashbuckle.AspNetCore.Cli.Program.Main(String[] args) in C:\projects\ahoy\src\Swashbuckle.AspNetCore.Cli\Program.cs:line 121
1>C:\temp\amazonsofvolleyball\Backend.WebAPI\Backend.WebAPI.csproj(5,3): warning MSB3073: The command "dotnet swagger tofile --output ./_open-api.json bin\Debug\net7.0\Backend.WebAPI.dll public" exited with code -532462766.
</code>```

Any ideas?
thnx

Body:
I am trying in VS2022 using .net 7 to auto build an open-api (swagger) specification, that I want to wire later in connected services. My problem is that the file is not being created.

This is my swagger configuration:

public static void ConfigureSwagger(this WebApplicationBuilder builder)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        var appSettings = builder.Configuration.GetObjectFromConfigSection<AppSettings>("AppSettings");

        builder.Services.AddSwaggerGen(x =>
        {
            x.SwaggerDoc(appSettings.SwaggerPublicGroupAPI, new OpenApiInfo { Title = "aov.org public API", Version = appSettings.SwaggerPublicGroupAPI });
            x.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["action"]}");

            // This code allow you to use XML-comments
            string xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            if (File.Exists(xmlPath))
            {
                x.IncludeXmlComments(xmlPath);
            }

            x.AddSecurityDefinition
            (
                "Bearer",
                new OpenApiSecurityScheme
                {
                    In = ParameterLocation.Header,
                    Description = "Please enter token into the field",
                    Name = "Authorization",
                    Type = SecuritySchemeType.ApiKey
                }
            );
        });
    }

    public static void ConfigureSwagger(this WebApplication webApp)
    {
        if (webApp is null)
            return;

        var appSettings = webApp.Configuration.GetObjectFromConfigSection<AppSettings>("AppSettings");

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        webApp.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        webApp.UseSwaggerUI(x =>
        {
            x.SwaggerEndpoint($"/swagger/{appSettings.SwaggerPublicGroupAPI}/swagger.json", "aov.org public API");
        });
    }

The appSettings are coming from appSettings.json and have the following entries:

  "AppSettings": {
    "SwaggerPublicGroupAPI": "public",
    "VersionAPI": "1.0"
  }

In the WebAPI project I added the following lines:

<Target Name="OpenAPI" AfterTargets="Build" Condition="$(Configuration)=='Debug'">
        <Exec Command="echo Generating OprnAPI." />
        <Exec Command="dotnet swagger tofile --output ./_open-api.json $(OutputPath)$(AssemblyName).dll public"
              ContinueOnError="true" />
    </Target>

The project builds, but in the output window am getting a strange error:

Unhandled exception. System.AggregateException: One or more errors occurred. (The ConnectionString property has not been initialized.)
1> ---> System.InvalidOperationException: The ConnectionString property has not been initialized.
1>   at Microsoft.Data.SqlClient.SqlConnection.PermissionDemand()
1>   at Microsoft.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
1>   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
1>   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
1>   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
1>   at Microsoft.Data.SqlClient.SqlConnection.InternalOpenAsync(CancellationToken cancellationToken)
1>--- End of stack trace from previous location ---
1>   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
1>   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
1>   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
1>   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass20_0.<<ExistsAsync>b__0>d.MoveNext()
1>--- End of stack trace from previous location ---
1>   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass20_0.<<ExistsAsync>b__0>d.MoveNext()
1>--- End of stack trace from previous location ---
1>   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.<>c__DisplayClass30_0`2.<<ExecuteAsync>b__0>d.MoveNext()
1>--- End of stack trace from previous location ---
1>   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementationAsync[TState,TResult](Func`4 operation, Func`4 verifySucceeded, TState state, CancellationToken cancellationToken)
1>   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementationAsync[TState,TResult](Func`4 operation, Func`4 verifySucceeded, TState state, CancellationToken cancellationToken)
1>   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
1>   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.ExistsAsync(CancellationToken cancellationToken)
1>   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.MigrateAsync(String targetMigration, CancellationToken cancellationToken)
1>   at Program.$(String[] args) in C:\temp\amazonsofvolleyball\Backend.WebAPI\Program.cs:line 83
1>   at Program.(String[] args)
1>   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
1>   at System.Reflection.MethodInvoker.Invoke(Object obj, IntPtr* args, BindingFlags invokeAttr)
1>   --- End of inner exception stack trace ---
1>   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
1>   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
1>   at System.Threading.Tasks.Task.Wait()
1>   at Swashbuckle.AspNetCore.Cli.HostingApplication.GetServiceProvider(Assembly assembly) in C:\projects\ahoy\src\Swashbuckle.AspNetCore.Cli\HostingApplication.cs:line 81
1>   at Swashbuckle.AspNetCore.Cli.Program.GetServiceProvider(Assembly startupAssembly) in C:\projects\ahoy\src\Swashbuckle.AspNetCore.Cli\Program.cs:line 152
1>   at Swashbuckle.AspNetCore.Cli.Program.<>c.b__0_4(IDictionary`2 namedArgs) in C:\projects\ahoy\src\Swashbuckle.AspNetCore.Cli\Program.cs:line 82
1>   at Swashbuckle.AspNetCore.Cli.CommandRunner.Run(IEnumerable`1 args) in C:\projects\ahoy\src\Swashbuckle.AspNetCore.Cli\CommandRunner.cs:line 68
1>   at Swashbuckle.AspNetCore.Cli.CommandRunner.Run(IEnumerable`1 args) in C:\projects\ahoy\src\Swashbuckle.AspNetCore.Cli\CommandRunner.cs:line 59
1>   at Swashbuckle.AspNetCore.Cli.Program.Main(String[] args) in C:\projects\ahoy\src\Swashbuckle.AspNetCore.Cli\Program.cs:line 121
1>C:\temp\amazonsofvolleyball\Backend.WebAPI\Backend.WebAPI.csproj(5,3): warning MSB3073: The command "dotnet swagger tofile --output ./_open-api.json bin\Debug\net7.0\Backend.WebAPI.dll public" exited with code -532462766.

Any ideas?
thnx


问:
I cannot understand how Anonymous Inner Class Fields work
```<code>public class MyFile {

    public static void main(String[] arga) {
           Outer out = new Outer();
           System.out.println(out.a.n);
    }
}

class Outer{
    Object a =  new Object(){
        public int n = 42;
        public String toString() {
            return "hi + " + n;
        }
    };
    {
        System.out.println(a.n);
    }
}
</code>```

In this code why is n not accessible anywhere?

I tried to access n as a normal member variable but i cant seem to resolve it anywhere.

Body:
public class MyFile {

    public static void main(String[] arga) {
           Outer out = new Outer();
           System.out.println(out.a.n);
    }
}

class Outer{
    Object a =  new Object(){
        public int n = 42;
        public String toString() {
            return "hi + " + n;
        }
    };
    {
        System.out.println(a.n);
    }
}

In this code why is n not accessible anywhere?

I tried to access n as a normal member variable but i cant seem to resolve it anywhere.


问:
This is related to npm not being able to find a file. npm
how to fix this error

npm ERR! code ENOENT
npm ERR! syscall spawn bash
npm ERR! path G:\Users\sidra
npm ERR! errno -4058
npm ERR! enoent spawn bash ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!

i am trying to run command npx cli-calculator


问:
Signals2 disconnects slot automatically?
Code below is a test program, emulating some events processing. Full code snippets is here. There are 3 threads for event producer, for event distributor like event bus, what handles system event too, and for a certain game, what handles significant events.

And I have stdout printer in event bus, what method pass into every event as a callback. The event bus thread:

```<code>class EventBus : public std::enable_shared_from_this<EventBus>
{
    using handlers = boost::signals2::signal<void(std::shared_ptr<EventBase>)>;
private:
    std::atomic<double> m_GameTicks;

    std::thread m_Worker;
    std::mutex m_Locker;
    std::condition_variable m_NewEvent;
    bool m_Suspend;
    std::queue<std::shared_ptr<EventBase>> m_EventStorage;

    std::unordered_map<std::type_index, handlers> m_Subscribers;
    std::shared_ptr<IPrinter> m_InfoPrinter;
public:
    EventBus()
    {
        m_Worker = std::thread([this]() /// Firing event
        {
            while (true)
            {
                std::shared_ptr<EventBase> event;
                {
                    std::unique_lock guard(m_Locker);
                    m_NewEvent.wait(
                        guard,
                        [this]{ return m_Suspend || !m_EventStorage.empty(); });
                    if (m_Suspend && m_EventStorage.empty())
                    {
                        break;
                    }

                    event = std::move(m_EventStorage.front());
                    m_EventStorage.pop();
                }

                auto raw_event = event.get();
                try
                {
                    m_Subscribers[typeid(*raw_event)](event);
                }
                catch (std::exception& ex)
                {
                    std::cerr << ex.what() << std::endl;
                    std::exit(EXIT_FAILURE);
                }
            }
        });
    }

    ~EventBus()
    {
        m_Worker.join();
    }

    AddEvent(std::shared_ptr<EventBase>&& event)
    {
        event->SetPrintingCallback(
            [/*ptr = shared_from_this()*/ this](auto&& message)
            {
                return m_InfoPrinter->SafetyPrint(
                    m_GameTicks,
                    std::forward<decltype(message)>(message));
            });
        {
            std::lock_guard guard(m_Locker);
            m_EventStorage.push(std::move(event));
        }
        m_NewEvent.notify_one();
    }

    template <typename TEvent, typename TSubscriber> // TODO add enable_if
    void Subscribe(const std::shared_ptr<TSubscriber>& subscriber)
    {
        m_Subscribers[typeid(TEvent)].connect(
            [subscriber](std::shared_ptr<EventBase> event)
            {
                subscriber->ProcessEvent(std::static_pointer_cast<TEvent>(event));
            });
    }

    template <typename TEvent, typename TFunc>
    void Subscribe(const TFunc& subscriber_callback)
    {
        m_Subscribers[typeid(TEvent)].connect(
            [subscriber_callback](std::shared_ptr<EventBase> event)
            {
                subscriber_callback(std::static_pointer_cast<TEvent>(event));
            });
    }

    template <typename TEvent>
    void SubscribeSelf()
    {
        m_Subscribers[typeid(TEvent)].connect(
            [this](std::shared_ptr<EventBase> event)
            {
                ProcessEvent(std::static_pointer_cast<TEvent>(event));
            });
    }
};
</code>```

There is SIGSEGV at this variant sometimes of AddEvent, but if I pass shared_form_this, it will be called either never, or sometimes, processed one or two events. But I don't why does it happen, and the first, and the second variant?

I try to debug and I see that boost.signal2 disconnects handlers at the second variant with shared_from_this passing.

The game thread:

```<code>class GameMap : public std::enable_shared_from_this<GameMap>
{
public:
    GameMap(const MapPoint& map_size, const Key<GameMapFactory>&)
        : m_MapSize(map_size)
        , m_Work(std::make_unique<dummy_game_work_type>(m_GameContext.get_executor()))
    {
        m_GameThread = std::thread([this] ()
        {
            m_GameContext.run();
        });
    }

    ~GameMap()
    {
        m_Work.reset(); // need transfer this to processing finish event?
        m_GameThread.join();
    }
};
</code>```

GameMap handles events into ProcessEvent method, does some validation and post it handlers via boost::asio::post for further processing.

The main thread:

```<code>int main(int ac, char **av)
{
    std::shared_ptr<GameMap> map;
    std::shared_ptr<EventBus> bus = std::make_shared<EventBus (std::make_shared<StdOutPrinter>());

    bus->Subscribe<MapCreationEvent>(
        [&map, &bus](auto&& event) // todo check about references in capture list
        {
            map = GameMapFactory{}.CreateMap(std::forward<decltype(event)>(event));
            bus->Subscribe<MarchEvent>(map);
            // todo think about replace this to Game Map Factory
        });
    bus->Subscribe<SpawnCreatureEvent>(
        [](auto&& event)
        {
            CreatureFactory{}.CreateCreature(std::forward<decltype(event)>(event));
        });
    //    bus->Subscribe<WaitEvent>(bus); // todo it doesn't work too
    //    bus->Subscribe<WaitEvent>( // todo why it doesn't work subscription to self slot??
    //        [bus](auto&& event)
    //        {
    //            bus->ProcessEvent(std::forward<decltype(event)>(event));
    //        });
    bus->SubscribeSelf<WaitEvent>();
    bus->SubscribeSelf<FinishEvent>();

    // todo test producer
    std::vector<std::shared_ptr<EventBase>> events = {
        std::make_shared<MapCreationEvent>(MapPoint(40, 40)),
        std::make_shared<SpawnCreatureEvent>(1, MapPoint(40, 40), 50),
        std::make_shared<SpawnCreatureEvent>(2, MapPoint(30, 40), 100),
        std::make_shared<SpawnCreatureEvent>(3, MapPoint(10, 20), 70),
        std::make_shared<SpawnCreatureEvent>(4, MapPoint(40, 30), 90),
        std::make_shared<MarchEvent>(1, MapPoint(40, 30)),
        std::make_shared<MarchEvent>(2, MapPoint(20, 20)),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<MarchEvent>(4, MapPoint(20, 20)),
        std::make_shared<FinishEvent>(),
    };

    for (auto& ev : events)
    {
        bus->AddEvent(std::move(ev));
    }
}
</code>```

I caught similar problem here. If I subscribe bus to handling Wait and Finish events via Subscribe, I will get the similar behaviour I wrote above: signals2 disconnect all my slots and stop the program. Why?

Could somebody help me with disconnecting and sigsegv?

I tried to change passing this to shared_from_this but I got only other error

Body:
Code below is a test program, emulating some events processing. Full code snippets is here. There are 3 threads for event producer, for event distributor like event bus, what handles system event too, and for a certain game, what handles significant events.

And I have stdout printer in event bus, what method pass into every event as a callback. The event bus thread:

class EventBus : public std::enable_shared_from_this<EventBus>
{
    using handlers = boost::signals2::signal<void(std::shared_ptr<EventBase>)>;
private:
    std::atomic<double> m_GameTicks;

    std::thread m_Worker;
    std::mutex m_Locker;
    std::condition_variable m_NewEvent;
    bool m_Suspend;
    std::queue<std::shared_ptr<EventBase>> m_EventStorage;

    std::unordered_map<std::type_index, handlers> m_Subscribers;
    std::shared_ptr<IPrinter> m_InfoPrinter;
public:
    EventBus()
    {
        m_Worker = std::thread([this]() /// Firing event
        {
            while (true)
            {
                std::shared_ptr<EventBase> event;
                {
                    std::unique_lock guard(m_Locker);
                    m_NewEvent.wait(
                        guard,
                        [this]{ return m_Suspend || !m_EventStorage.empty(); });
                    if (m_Suspend && m_EventStorage.empty())
                    {
                        break;
                    }

                    event = std::move(m_EventStorage.front());
                    m_EventStorage.pop();
                }

                auto raw_event = event.get();
                try
                {
                    m_Subscribers[typeid(*raw_event)](event);
                }
                catch (std::exception& ex)
                {
                    std::cerr << ex.what() << std::endl;
                    std::exit(EXIT_FAILURE);
                }
            }
        });
    }

    ~EventBus()
    {
        m_Worker.join();
    }

    AddEvent(std::shared_ptr<EventBase>&& event)
    {
        event->SetPrintingCallback(
            [/*ptr = shared_from_this()*/ this](auto&& message)
            {
                return m_InfoPrinter->SafetyPrint(
                    m_GameTicks,
                    std::forward<decltype(message)>(message));
            });
        {
            std::lock_guard guard(m_Locker);
            m_EventStorage.push(std::move(event));
        }
        m_NewEvent.notify_one();
    }

    template <typename TEvent, typename TSubscriber> // TODO add enable_if
    void Subscribe(const std::shared_ptr<TSubscriber>& subscriber)
    {
        m_Subscribers[typeid(TEvent)].connect(
            [subscriber](std::shared_ptr<EventBase> event)
            {
                subscriber->ProcessEvent(std::static_pointer_cast<TEvent>(event));
            });
    }

    template <typename TEvent, typename TFunc>
    void Subscribe(const TFunc& subscriber_callback)
    {
        m_Subscribers[typeid(TEvent)].connect(
            [subscriber_callback](std::shared_ptr<EventBase> event)
            {
                subscriber_callback(std::static_pointer_cast<TEvent>(event));
            });
    }

    template <typename TEvent>
    void SubscribeSelf()
    {
        m_Subscribers[typeid(TEvent)].connect(
            [this](std::shared_ptr<EventBase> event)
            {
                ProcessEvent(std::static_pointer_cast<TEvent>(event));
            });
    }
};

There is SIGSEGV at this variant sometimes of AddEvent, but if I pass shared_form_this, it will be called either never, or sometimes, processed one or two events. But I don't why does it happen, and the first, and the second variant?

I try to debug and I see that boost.signal2 disconnects handlers at the second variant with shared_from_this passing.

The game thread:

class GameMap : public std::enable_shared_from_this<GameMap>
{
public:
    GameMap(const MapPoint& map_size, const Key<GameMapFactory>&)
        : m_MapSize(map_size)
        , m_Work(std::make_unique<dummy_game_work_type>(m_GameContext.get_executor()))
    {
        m_GameThread = std::thread([this] ()
        {
            m_GameContext.run();
        });
    }

    ~GameMap()
    {
        m_Work.reset(); // need transfer this to processing finish event?
        m_GameThread.join();
    }
};

GameMap handles events into ProcessEvent method, does some validation and post it handlers via boost::asio::post for further processing.

The main thread:

int main(int ac, char **av)
{
    std::shared_ptr<GameMap> map;
    std::shared_ptr<EventBus> bus = std::make_shared<EventBus (std::make_shared<StdOutPrinter>());

    bus->Subscribe<MapCreationEvent>(
        [&map, &bus](auto&& event) // todo check about references in capture list
        {
            map = GameMapFactory{}.CreateMap(std::forward<decltype(event)>(event));
            bus->Subscribe<MarchEvent>(map);
            // todo think about replace this to Game Map Factory
        });
    bus->Subscribe<SpawnCreatureEvent>(
        [](auto&& event)
        {
            CreatureFactory{}.CreateCreature(std::forward<decltype(event)>(event));
        });
    //    bus->Subscribe<WaitEvent>(bus); // todo it doesn't work too
    //    bus->Subscribe<WaitEvent>( // todo why it doesn't work subscription to self slot??
    //        [bus](auto&& event)
    //        {
    //            bus->ProcessEvent(std::forward<decltype(event)>(event));
    //        });
    bus->SubscribeSelf<WaitEvent>();
    bus->SubscribeSelf<FinishEvent>();

    // todo test producer
    std::vector<std::shared_ptr<EventBase>> events = {
        std::make_shared<MapCreationEvent>(MapPoint(40, 40)),
        std::make_shared<SpawnCreatureEvent>(1, MapPoint(40, 40), 50),
        std::make_shared<SpawnCreatureEvent>(2, MapPoint(30, 40), 100),
        std::make_shared<SpawnCreatureEvent>(3, MapPoint(10, 20), 70),
        std::make_shared<SpawnCreatureEvent>(4, MapPoint(40, 30), 90),
        std::make_shared<MarchEvent>(1, MapPoint(40, 30)),
        std::make_shared<MarchEvent>(2, MapPoint(20, 20)),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<WaitEvent>(1),
        std::make_shared<MarchEvent>(4, MapPoint(20, 20)),
        std::make_shared<FinishEvent>(),
    };

    for (auto& ev : events)
    {
        bus->AddEvent(std::move(ev));
    }
}

I caught similar problem here. If I subscribe bus to handling Wait and Finish events via Subscribe, I will get the similar behaviour I wrote above: signals2 disconnect all my slots and stop the program. Why?

Could somebody help me with disconnecting and sigsegv?

I tried to change passing this to shared_from_this but I got only other error


问:
Printing Average of Marks In an Array
The provided code stub will read in a dictionary containing key/value pairs of name:[marks] for a list of students. Print the average of the marks array for the student name provided, showing 2 places after the decimal.

I tried to find the average of the marks array for the student name provided, but after finding the average I could not limit it up to 2 decimal places.

Title: Printing Average of Marks In an Array


问:
Multi Agents in OpenAi gym?
We are planning to do a multi-agents in a openai gym super mario, is it possible to have multiple agents in one level? to see what agent will accomplish (with the mixture of genetic algorithm and deep q learning) and for the levels using level scene stitching is it possible to do that in openai gym?

Answer and we want to know if its possible to have multiple agents in one level in the game to simulate it.

Title: Multi Agents in OpenAi gym?


问:
Observing time difference between Oracle and SQL Server during data migration
We are moving data from Oracle on one Geography to an SQL Server database in another Geography. We are noticing that the time related columns for different objects are different in the two geographies. They are differing by 2 hours.

At source: 2022/05/13 12:01:00
At target: 2022/05/13 10:01:00

I am using this SQL to extract the data at source Oracle database

```<code>select distinct item.pitem_id || '~'
                || TO_CHAR(paoItem.PCREATION_DATE, 'dd-Mon-YYYY HH24:MI') || '~'
                || puItemOwner.puser_id || '~'
                || pgItem.pname || '~'
                || puItemLMU.puser_id || '~'
                || TO_CHAR(paoItem.PLAST_MOD_DATE, 'dd-Mon-YYYY HH24:MI')

-- Item Information
from infodba.PITEM item
inner join infodba.PPOM_APPLICATION_OBJECT paoItem on paoItem.puid = item.puid
inner join infodba.PPOM_GROUP pgItem on pgItem.puid = paoItem.ROWNING_GROUPU
inner join infodba.PPOM_USER puItemOwner on puItemOwner.puid = paoItem.ROWNING_USERU
inner join infodba.PPOM_USER puItemLMU on puItemLMU.puid = paoItem.RLAST_MOD_USERU

where item.pitem_id in '3204-001-0613-C';
</code>```

This query is giving me the correct result itself - 2022/05/13 12:01:00. But when I import this data into the target system, the date is getting update to 2022-05-13 10:01:00.000.

I am assuming that this time difference of 2 hours is because of the probable Geography time difference. If so, what can I do to ensure that the data gets persisted correctly.

Please share me some idea on which options or where to look for this sort of issue.

Thanks,
Pavan.

Body:
We are moving data from Oracle on one Geography to an SQL Server database in another Geography. We are noticing that the time related columns for different objects are different in the two geographies. They are differing by 2 hours.

At source: 2022/05/13 12:01:00
At target: 2022/05/13 10:01:00

I am using this SQL to extract the data at source Oracle database

select distinct item.pitem_id || '~'
                || TO_CHAR(paoItem.PCREATION_DATE, 'dd-Mon-YYYY HH24:MI') || '~'
                || puItemOwner.puser_id || '~'
                || pgItem.pname || '~'
                || puItemLMU.puser_id || '~'
                || TO_CHAR(paoItem.PLAST_MOD_DATE, 'dd-Mon-YYYY HH24:MI')

-- Item Information
from infodba.PITEM item
inner join infodba.PPOM_APPLICATION_OBJECT paoItem on paoItem.puid = item.puid
inner join infodba.PPOM_GROUP pgItem on pgItem.puid = paoItem.ROWNING_GROUPU
inner join infodba.PPOM_USER puItemOwner on puItemOwner.puid = paoItem.ROWNING_USERU
inner join infodba.PPOM_USER puItemLMU on puItemLMU.puid = paoItem.RLAST_MOD_USERU

where item.pitem_id in '3204-001-0613-C';

This query is giving me the correct result itself - 2022/05/13 12:01:00. But when I import this data into the target system, the date is getting update to 2022-05-13 10:01:00.000.

I am assuming that this time difference of 2 hours is because of the probable Geography time difference. If so, what can I do to ensure that the data gets persisted correctly.

Please share me some idea on which options or where to look for this sort of issue.

Thanks,
Pavan.


问:
Firebase Stripe Extension: Need help checking the current user's premium plan
I am working on a membership program and everything works fine until I am trying to check for the stripe role and show them content based if they are a paying member or not.

I need help with this code and here is an example of what I have got.

Can somebody please lead me in the right direction with this. I am using Reac, NEXTJS and firebase.

```<code>let premiumUser = collection(db, `users/currentUser.uid/subscriptions`)
     const q = query(premiumUser, where("status", "==", ["trailing", "active"]))
    onSnapshot(q, async (snapshot) => {
      const doc = snapshot.docs
    })
</code>```

I have tried different youtube tutorials, forums and such forth. I am at a standstill when it comes to this.

Body:
I am working on a membership program and everything works fine until I am trying to check for the stripe role and show them content based if they are a paying member or not.

I need help with this code and here is an example of what I have got.

Can somebody please lead me in the right direction with this. I am using Reac, NEXTJS and firebase.

let premiumUser = collection(db, `users/currentUser.uid/subscriptions`)
     const q = query(premiumUser, where("status", "==", ["trailing", "active"]))
    onSnapshot(q, async (snapshot) => {
      const doc = snapshot.docs
    })

I have tried different youtube tutorials, forums and such forth. I am at a standstill when it comes to this.


问:
How to query a table on timestamp with Sequelize ORM
I would like to query my Table for the value at midnight (00:00:00) everyday.
So The system gets a value every minutes but I want the value at 00:00:00 so I can plot daily sales.

Here is how my code looking so far:

```<code>  const data = await Chart.findAll({
    where: {
      DATEPART(hour, TimeStamp): 0,
      DATEPART(minute, TimeStamp): 0
    },
  });
  res.send(data);
};
</code>```

TimeStamp is the name of the field on SQL table that contain the time stamp.

Body:
I would like to query my Table for the value at midnight (00:00:00) everyday.
So The system gets a value every minutes but I want the value at 00:00:00 so I can plot daily sales.

Here is how my code looking so far:

  const data = await Chart.findAll({
    where: {
      DATEPART(hour, TimeStamp): 0,
      DATEPART(minute, TimeStamp): 0
    },
  });
  res.send(data);
};

TimeStamp is the name of the field on SQL table that contain the time stamp.


问:
CNN deep model using too much RAM
I'm building a CNN for dectection of chest x-ray images with pneumonia, the problem I got is that when training the usage of ram just blows up, I'm using a Kaggle Notebook and the ram usage slowly grows till the 30gb limit and then shuts down, even before printing a single epoch.

I tried passing the data from float64 to float32 but no mayor results, just the rate in which reaches the 30gb limits slows down.

I don't really know where's the problem because I've seen similar codes also trained for the same dataset in Kaggle Notebooks, so I know that the data itself isn't the problem. My image dataset are 5216 images for train and just 16 for validation. Here's the code

image_size = (128,128)

data_train = tf.keras.utils.image_dataset_from_directory(train_path, color_mode ='grayscale', image_size = image_size)
data_train = data_train.map(lambda x, y: (tf.cast(x, tf.float32), y))
data_train_iterator = data_train.as_numpy_iterator()
batch_data_train = data_train_iterator.next()

data_val = tf.keras.utils.image_dataset_from_directory(val_path,color_mode ='grayscale', image_size = image_size)
data_val = data_val.map(lambda x, y: (tf.cast(x, tf.float32), y))
data_val_iterator = data_val.as_numpy_iterator()
batch_data_val = data_val_iterator.next()

data_augmentation = ImageDataGenerator(
    rescale = 1./255,
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2,
    horizontal_flip=True,
    vertical_flip=False,
    zoom_range=0.2,
    fill_mode='nearest'
)

data_aug_train = data_augmentation.flow_from_directory(train_path, target_size=image_size, batch_size=32, class_mode='categorical')

data_aug_val = data_augmentation.flow_from_directory(val_path, target_size=image_size, batch_size=32, class_mode='categorical')

def pneumonia_model():
    model = Sequential()
    model.add(Conv2D(16, (3, 3), activation='relu', padding="same", input_shape=(128,128,1)))
    model.add(BatchNormalization())
    model.add(Conv2D(16, (3, 3), padding="same", activation='relu'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(32, (3, 3), activation='relu', padding="same", input_shape=(128,128,1)))
    model.add(BatchNormalization())
    model.add(Conv2D(32, (3, 3), padding="same", activation='relu'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(64, (3, 3), activation='relu', padding="same"))
    model.add(BatchNormalization())
    model.add(Conv2D(64, (3, 3), padding="same", activation='relu'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(96, (3, 3), dilation_rate=(2, 2), activation='relu', padding="same"))
    model.add(BatchNormalization())
    model.add(Conv2D(96, (3, 3), padding="valid", activation='relu'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(128, (3, 3), dilation_rate=(2, 2), activation='relu', padding="same"))
    model.add(BatchNormalization())
    model.add(Conv2D(128, (3, 3), padding="valid", activation='relu'))
    model.add(BatchNormalization())
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Flatten())

    model.add(Dense(64, activation='relu'))
    model.add(Dropout(0.4))
    model.add(Dense(2 , activation='softmax'))

    print(model.summary())

    return model

model = pneumonia_model()

model.compile('adam', loss=tf.losses.BinaryCrossentropy(), metrics=['accuracy'])

hist = model.fit(data_aug_train,epochs=20,validation_data = tuple(data_aug_val))`

`

```

Title: CNN deep model using too much RAM


问:
Dropdown sub menu and bullet point alignment
I am trying to create a sub menu option for my website but do not how to. From the references I found online I was able to create a horizontal menu but I want to create a sub menu option for the side menu.

https://www.w3schools.com/howto/howto_css_subnav.asp

I am also having problems with the custom bullet list alignment. The arrow is not in the middle of my text.

My code link:

https://codepen.io/arielkoh/details/QWxPREr

Bullet Code

```<code> ul li {
      color: rgb(12, 179, 220);
      position: relative;
      top: 0px;
    }

    ul li:before {
      content: "\21B3";
      position: absolute;
      top: 0px;
    }

    ul {
      list-style: none;
    }
</code>```

What I tried to do for my sub menu but I am unsure if I doing the right thing.

Navigation Code

```<code><!-- Top Navigation Menu -->
    <div class="topnav">
      <a href="#home" class="active">Ubiquitous Nuisance</a>

      <div id="myLinks">
        <a href="#">07 Prototyping</a>

        <a href="#">06 Experiments</a>

        <a href="#">05 Soundwalks</a>

        <a href="#">04 Class Sessions</a>

        <a href="#">03 Case Studies</a>

        <a href="#">02 Research Topic</a>
        <ul>
          <li><a href="service-grid.html">Old Research Topic</a></li>
          <li><a href="service-list.html">Ubiquitous Nuisance</a></li>
        </ul>

        <a href="#about">01 Readers</a>
      </div>
</code>```

Full Code

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

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <style>
    body {
      font-family: Arial, Helvetica, sans-serif;
    }

    .topnav {
      overflow: hidden;
      position: relative;
    }

    .topnav #myLinks {
      display: none;
      background-color: rgba(212, 219, 206, 50);
      max-width: 500px;
      margin-left: 200px;
    }

    .topnav a {
      color: coral;
      padding: 14px 16px;
      text-decoration: none;
      font-size: 17px;
      display: block;
    }

    .topnav a.icon {
      display: block;
      position: absolute;
      right: 0;
      top: 0;
    }

    .topnav a:hover {
      color: black;
    }

    ul li {
      color: rgb(12, 179, 220);
      position: relative;
      top: 0px;
    }

    ul li:before {
      content: "\21B3";
      position: absolute;
      top: 0px;
    }

    ul {
      list-style: none;
    }
  </style>
</head>

<body>

  <!-- Simulate a smartphone / tablet -->
  <div class="mobile-container">

    <!-- Top Navigation Menu -->
    <div class="topnav">
      <a href="#home" class="active">Ubiquitous Nuisance</a>

      <div id="myLinks">
        <a href="#">07 Prototyping</a>

        <a href="#">06 Experiments</a>

        <a href="#">05 Soundwalks</a>

        <a href="#">04 Class Sessions</a>

        <a href="#">03 Case Studies</a>

        <a href="#">02 Research Topic</a>
        <ul>
          <li><a href="service-grid.html">Old Research Topic</a></li>
          <li><a href="service-list.html">Ubiquitous Nuisance</a></li>
        </ul>

        <a href="#about">01 Readers</a>
      </div>

      <a href="javascript:void(0);" class="icon" onclick="myFunction()">
        <i class="fa fa-bars"></i>
      </a>
    </div>
    <!-- End smartphone / tablet look -->
  </div>

  <script>
    function myFunction() {
  var x = document.getElementById("myLinks");
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}
  </script>

</body>

</html>
</code>```

Body:
I am trying to create a sub menu option for my website but do not how to. From the references I found online I was able to create a horizontal menu but I want to create a sub menu option for the side menu.

https://www.w3schools.com/howto/howto_css_subnav.asp

I am also having problems with the custom bullet list alignment. The arrow is not in the middle of my text.

My code link:

https://codepen.io/arielkoh/details/QWxPREr

Bullet Code

 ul li {
      color: rgb(12, 179, 220);
      position: relative;
      top: 0px;
    }

    ul li:before {
      content: "\21B3";
      position: absolute;
      top: 0px;
    }

    ul {
      list-style: none;
    }

What I tried to do for my sub menu but I am unsure if I doing the right thing.

Navigation Code

      Ubiquitous Nuisance

        07 Prototyping

        06 Experiments

        05 Soundwalks

        04 Class Sessions

        03 Case Studies

        02 Research Topic

Old Research Topic

Ubiquitous Nuisance

        01 Readers

Full Code

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

      Ubiquitous Nuisance

        07 Prototyping

        06 Experiments

        05 Soundwalks

        04 Class Sessions

        03 Case Studies

        02 Research Topic

Old Research Topic

Ubiquitous Nuisance

        01 Readers


问:
React custom Button component "as" prop
I want to add a feature to my Button component wherein I want to add an as prop just like in other component libraries to render different components based on the as value.

Title: React custom Button component "as" prop


问:
how to insert table from excel with specific value into outlook using vbscripting
I am trying to send email using outlook and vbs.

Parse through  excel

take subject, email, name, attachment etc from there.  the based on attachment name, i need to insert table from attachment excel into body of email.

```<code>        set app = CreateObject("Excel.Application")
    ' get current path
        Dim WshShell
        Set WshShell = CreateObject("WScript.Shell")
        strPath    = WshShell.CurrentDirectory
        Set WshShell = Nothing

'converting csv to xlsx
        Set wb = app.Workbooks.Open  (strPath+"\"+"rbo1.csv")
            WB.SaveAs Replace(WB.FullName, ".csv", ".xlsx"), 51
            WB.Close False
            wb.close 0
            set wb =nothing

        Set wb = app.Workbooks.Open  (strPath+"\"+"rbo1.xlsx")
        set sh = wb.Sheets(1)
            row = 2

        set name sh.cells("C" & row)
        set email = sh.Range("L" & row)
        set subject = sh.Range("M" & row)
        set attach = sh.Range("N" & row)
        Set Cur_date = sh.range("A" & row)
        Set Prev_date = sh.range("B" & row)
        Set Prev_Bal = sh.range("G" & row)
        Set Cur_Bal = sh.range("H" & row)

        LastRow = sh.UsedRange.Rows.Count
       For r = row to LastRow
              If App.WorkSheetFunction.CountA(sh.Rows(r)) <> 0 Then
                  SendMessage email, name, subject, TRUE, attach, strPath, Cur_date, Prev_date,_
                Prev_Bal ,    Cur_Bal
            row = row + 1
            name sh.cells("C" & row)
            email = sh.Range("L" & row)
            subject = sh.Range("M" & row)
            attach = sh.Range("N" & row)
            Cur_date = sh.range("A" & row)
            Prev_date = sh.range("B" & row)
           Prev_Bal = sh.range("G" & row)
           Cur_Bal = sh.range("H" & row)
      End if
       Next
       wb.close
     set wb = nothing
     set app = nothing

       Sub SendMessage(EmailAddress, DisplayName, Subject, DisplayMsg, AttachmentPath, strPath, Cur_date, Prev_date, Prev_Bal ,    Cur_Bal)

         ' Create the Outlook session.
         Set objOutlook = CreateObject("Outlook.Application")
             objXl = app.Workbooks.Open(strPath+"\"+AttachmentPath)
        htmlmsg = extracttablehtml(objXl.worksheets(1), objXl.worksheets(1).usedRange)

      ' Create the message.
        Set objOutlookMsg  = objOutlook.CreateItem(0)

     With objOutlookMsg
      ' Add the To recipient(s) to the message.
      Set objOutlookRecip = .Recipients.Add(EmailAddress)
      objOutlookRecip.resolve
      objOutlookRecip.Type = 1

     ' Set the Subject, Body, and Importance of the message.
     .Subject = Subject
     .bodyformat = 3
     .Importance = 2  'High importance
     .HTMLBody = "<table> <br> Dear Sir, <br><br> given under details the change balance+"<br> for any query please call under signed<br><br>" + htmlmsg

     ' Should we display the message before sending?
     If DisplayMsg Then
         .Display
     Else
         .Save
       '  .Send
     End If
       End With

    objXl.close 0
    set objXl = Nothing
    Set objOutlook = Nothing

End Sub

Function extracttablehtml(ws, rng)
 Dim HtmlContent
 Dim i
 Dim j

On Error GoTo 0

HtmlContent = "<table>"

For i = 1 To rng.Rows.Count
    HtmlContent = HtmlContent & "<tr>"
    For j = 1 To rng.Columns.Count
        HtmlContent = HtmlContent & "<td>" & ws.Cells(i, j).Value & "</td>"
    Next
    HtmlContent = HtmlContent & "</tr>"
Next
HtmlContent = HtmlContent & "</table>"

extracttablehtml = HtmlContent

End Function
</code>```

two problems

extracttablehtml is not working as desired please advise whats the problem

now modification i need to do is to choose only rows based on given criteria

thanks in advance

Body:
I am trying to send email using outlook and vbs.

Parse through  excel

take subject, email, name, attachment etc from there.  the based on attachment name, i need to insert table from attachment excel into body of email.

        set app = CreateObject("Excel.Application")
    ' get current path
        Dim WshShell
        Set WshShell = CreateObject("WScript.Shell")
        strPath    = WshShell.CurrentDirectory
        Set WshShell = Nothing

'converting csv to xlsx
        Set wb = app.Workbooks.Open  (strPath+"\"+"rbo1.csv")
            WB.SaveAs Replace(WB.FullName, ".csv", ".xlsx"), 51
            WB.Close False
            wb.close 0
            set wb =nothing

        Set wb = app.Workbooks.Open  (strPath+"\"+"rbo1.xlsx")
        set sh = wb.Sheets(1)
            row = 2

        set name sh.cells("C" & row)
        set email = sh.Range("L" & row)
        set subject = sh.Range("M" & row)
        set attach = sh.Range("N" & row)
        Set Cur_date = sh.range("A" & row)
        Set Prev_date = sh.range("B" & row)
        Set Prev_Bal = sh.range("G" & row)
        Set Cur_Bal = sh.range("H" & row)

        LastRow = sh.UsedRange.Rows.Count
       For r = row to LastRow
              If App.WorkSheetFunction.CountA(sh.Rows(r)) <> 0 Then
                  SendMessage email, name, subject, TRUE, attach, strPath, Cur_date, Prev_date,_
                Prev_Bal ,    Cur_Bal
            row = row + 1
            name sh.cells("C" & row)
            email = sh.Range("L" & row)
            subject = sh.Range("M" & row)
            attach = sh.Range("N" & row)
            Cur_date = sh.range("A" & row)
            Prev_date = sh.range("B" & row)
           Prev_Bal = sh.range("G" & row)
           Cur_Bal = sh.range("H" & row)
      End if
       Next
       wb.close
     set wb = nothing
     set app = nothing

       Sub SendMessage(EmailAddress, DisplayName, Subject, DisplayMsg, AttachmentPath, strPath, Cur_date, Prev_date, Prev_Bal ,    Cur_Bal)

         ' Create the Outlook session.
         Set objOutlook = CreateObject("Outlook.Application")
             objXl = app.Workbooks.Open(strPath+"\"+AttachmentPath)
        htmlmsg = extracttablehtml(objXl.worksheets(1), objXl.worksheets(1).usedRange)

      ' Create the message.
        Set objOutlookMsg  = objOutlook.CreateItem(0)

     With objOutlookMsg
      ' Add the To recipient(s) to the message.
      Set objOutlookRecip = .Recipients.Add(EmailAddress)
      objOutlookRecip.resolve
      objOutlookRecip.Type = 1

     ' Set the Subject, Body, and Importance of the message.
     .Subject = Subject
     .bodyformat = 3
     .Importance = 2  'High importance
     .HTMLBody = "

 Dear Sir,

 given under details the change balance+"
 for any query please call under signed

" + htmlmsg

     ' Should we display the message before sending?
     If DisplayMsg Then
         .Display
     Else
         .Save
       '  .Send
     End If
       End With

    objXl.close 0
    set objXl = Nothing
    Set objOutlook = Nothing

End Sub

Function extracttablehtml(ws, rng)
 Dim HtmlContent
 Dim i
 Dim j

On Error GoTo 0

HtmlContent = "
"

For i = 1 To rng.Rows.Count
    HtmlContent = HtmlContent & "
"
    For j = 1 To rng.Columns.Count
        HtmlContent = HtmlContent & "" & ws.Cells(i, j).Value & "	"
    Next
    HtmlContent = HtmlContent & "
"
Next
HtmlContent = HtmlContent & "
"

extracttablehtml = HtmlContent

End Function

two problems

extracttablehtml is not working as desired please advise whats the problem

now modification i need to do is to choose only rows based on given criteria

thanks in advance


问:
WooCommerce - $checkout is undefined
I am getting an error when I go to the checkout page from cart:

Warning: Undefined variable $checkout in …(path)…\form-checkout.php

Why does this error appear? Where is variable definition location?

I did not find the definition of this variable in other files. Also I searched the answer and found one, but it doesn't work for me.
(Woocommerce location of checkout template

Title: WooCommerce - $checkout is undefined


问:
React rerendersa all inputs on one input state change, killing all performance and making experience laggy
I'm developing some selected products manager and encountered a problem i can't think of solution by myself.  I have main state with all the data from api. It looks like array of

```<code>{
"img_url": "http://localhost/wp-content/uploads/2022/12/g",
"productTitle": "Test",
"productId": "17",
"inputs": [
    {
        "inputTitle": "Text",
        "inputType": "text",
        "inputValue": "Test",
        "id": "133"
    },
    {
        "inputTitle": "SELECT",
        "inputType": "select",
        "inputValues": [
            "1",
            "2",
            "3",
            "4"
        ],
        "inputValue": "3",
        "id": "134"
    }
],
"inputsValues": [
    {
        "inputValue": "Test"
    },
    {
        "inputValue": "3"
    }
],
"orderTitle": "MLF-123",
"unique_id": "1b4b0ad6-b796-4608-bc41-5d6"
}
</code>```

And inputs have onchange that edits the actual values

```<code>onChange={(event) => {
                    const selectedProductsCopy = [...selectedProducts];
                    selectedProductsCopy[selectedProductIndex].inputsValues[
                      inputIndex
                    ].inputValue = event.target.value;
                    setSelectedProducts([...selectedProductsCopy]);
                  }}
</code>```

The problem i'm focusing is website performance, on onchange every render (there can be up to 50) rerenders, and i can't think of solution because i'm still not very experienced with render optimization. All i can add to this is the profiler with rerender data.

If you can help me and need any additional data please comment, ill answer shortly.

Body:
I'm developing some selected products manager and encountered a problem i can't think of solution by myself.  I have main state with all the data from api. It looks like array of

{
"img_url": "http://localhost/wp-content/uploads/2022/12/g",
"productTitle": "Test",
"productId": "17",
"inputs": [
    {
        "inputTitle": "Text",
        "inputType": "text",
        "inputValue": "Test",
        "id": "133"
    },
    {
        "inputTitle": "SELECT",
        "inputType": "select",
        "inputValues": [
            "1",
            "2",
            "3",
            "4"
        ],
        "inputValue": "3",
        "id": "134"
    }
],
"inputsValues": [
    {
        "inputValue": "Test"
    },
    {
        "inputValue": "3"
    }
],
"orderTitle": "MLF-123",
"unique_id": "1b4b0ad6-b796-4608-bc41-5d6"
}

And inputs have onchange that edits the actual values

onChange={(event) => {
                    const selectedProductsCopy = [...selectedProducts];
                    selectedProductsCopy[selectedProductIndex].inputsValues[
                      inputIndex
                    ].inputValue = event.target.value;
                    setSelectedProducts([...selectedProductsCopy]);
                  }}

The problem i'm focusing is website performance, on onchange every render (there can be up to 50) rerenders, and i can't think of solution because i'm still not very experienced with render optimization. All i can add to this is the profiler with rerender data.

If you can help me and need any additional data please comment, ill answer shortly.