问:
How to have 3 nodes for Apache Nifi cluster in Kubernetes?
I am using external zookeeper and I have applied this yaml in order to have Nifi in cluster mode in Kubernetes (see below)

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: nifi
  labels:
    name: nifi
    app: nifi
  annotations:
    app.kubernetes.io/name: nifi
    app.kubernetes.io/part-of: nifi
spec:
  revisionHistoryLimit: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: nifi
  template:
    metadata:
      labels:
        app: nifi
    spec:
      automountServiceAccountToken: false
      enableServiceLinks: false
      restartPolicy: Always
      securityContext:
        runAsGroup: 1000
        runAsUser: 1000
        runAsNonRoot: true
        seccompProfile:
          type: RuntimeDefault
      containers:
      - name: nifi
        image: XXX
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 8080
          name: nifi
        - containerPort: 8082
          name: cluster
        env:
        - name: "NIFI_SENSITIVE_PROPS_KEY"
          value: "XXX"
        - name: ALLOW_ANONYMOUS_LOGIN
          value: "no"
        - name: SINGLE_USER_CREDENTIALS_USERNAME
          value: XXX
        - name: SINGLE_USER_CREDENTIALS_PASSWORD
          value: XXX
        - name: NIFI_WEB_HTTP_HOST
          value: "0.0.0.0"
        - name: NIFI_WEB_HTTP_PORT
          value: "8080"
        # - name: NIFI_WEB_PROXY_HOST
        #   value: 0.0.0.0:8080
        # - name: HOSTNAME
        #   value: "nifi1"
        - name: NIFI_ANALYTICS_PREDICT_ENABLED
          value: "true"
        - name: NIFI_ELECTION_MAX_CANDIDATES
          value: "2"
        - name: NIFI_ELECTION_MAX_WAIT
          value: "1 min"
        - name: NIFI_CLUSTER_IS_NODE
          value: "true"
        - name: NIFI_JVM_HEAP_INIT
          value: "3g"
        - name: NIFI_JVM_HEAP_MAX
          value: "4g"
        - name: NIFI_CLUSTER_NODE_CONNECTION_TIMEOUT
          value: "2 min"
        - name: NIFI_CLUSTER_PROTOCOL_CONNECTION_HANDSHAKE_TIMEOUT
          value: "2 min"
        - name: NIFI_CLUSTER_NODE_PROTOCOL_MAX_THREADS
          value: "15"
        - name: NIFI_CLUSTER_NODE_PROTOCOL_PORT
          value: "8082"
        - name: NIFI_CLUSTER_NODE_READ_TIMEOUT
          value: "15"
        - name: NIFI_ZK_CONNECT_STRING
          value: "zookeeper:2181"
        - name: NIFI_CLUSTER_NODE_ADDRESS
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: HOSTNAME
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        livenessProbe:
          exec:
            command:
              - pgrep
              - java
          initialDelaySeconds: 60
          periodSeconds: 30
          timeoutSeconds: 10
          failureThreshold: 3
          successThreshold: 1
        readinessProbe:
          exec:
            command:
              - pgrep
              - java
          initialDelaySeconds: 180
          periodSeconds: 30
          timeoutSeconds: 10
          failureThreshold: 3
          successThreshold: 1
        resources:
          requests:
            cpu: 400m
            memory: 1Gi
          limits:
            cpu: 500m
            memory: 2Gi
        securityContext:
          allowPrivilegeEscalation: false
          privileged: false
          capabilities:
            drop:
              - ALL
</code>```

I have one node in my Nifi cluster and node adress is : 0.0.0.0:8080

I would like to have 3 nodes and I think having 0.0.0.0:8080 for nodes is not good.
I don't know how to deploy the 3 nodes in Kubernetes and with different node address.

How should I do it and modify my yaml ?

Body:
I am using external zookeeper and I have applied this yaml in order to have Nifi in cluster mode in Kubernetes (see below)

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nifi
  labels:
    name: nifi
    app: nifi
  annotations:
    app.kubernetes.io/name: nifi
    app.kubernetes.io/part-of: nifi
spec:
  revisionHistoryLimit: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: nifi
  template:
    metadata:
      labels:
        app: nifi
    spec:
      automountServiceAccountToken: false
      enableServiceLinks: false
      restartPolicy: Always
      securityContext:
        runAsGroup: 1000
        runAsUser: 1000
        runAsNonRoot: true
        seccompProfile:
          type: RuntimeDefault
      containers:
      - name: nifi
        image: XXX
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 8080
          name: nifi
        - containerPort: 8082
          name: cluster
        env:
        - name: "NIFI_SENSITIVE_PROPS_KEY"
          value: "XXX"
        - name: ALLOW_ANONYMOUS_LOGIN
          value: "no"
        - name: SINGLE_USER_CREDENTIALS_USERNAME
          value: XXX
        - name: SINGLE_USER_CREDENTIALS_PASSWORD
          value: XXX
        - name: NIFI_WEB_HTTP_HOST
          value: "0.0.0.0"
        - name: NIFI_WEB_HTTP_PORT
          value: "8080"
        # - name: NIFI_WEB_PROXY_HOST
        #   value: 0.0.0.0:8080
        # - name: HOSTNAME
        #   value: "nifi1"
        - name: NIFI_ANALYTICS_PREDICT_ENABLED
          value: "true"
        - name: NIFI_ELECTION_MAX_CANDIDATES
          value: "2"
        - name: NIFI_ELECTION_MAX_WAIT
          value: "1 min"
        - name: NIFI_CLUSTER_IS_NODE
          value: "true"
        - name: NIFI_JVM_HEAP_INIT
          value: "3g"
        - name: NIFI_JVM_HEAP_MAX
          value: "4g"
        - name: NIFI_CLUSTER_NODE_CONNECTION_TIMEOUT
          value: "2 min"
        - name: NIFI_CLUSTER_PROTOCOL_CONNECTION_HANDSHAKE_TIMEOUT
          value: "2 min"
        - name: NIFI_CLUSTER_NODE_PROTOCOL_MAX_THREADS
          value: "15"
        - name: NIFI_CLUSTER_NODE_PROTOCOL_PORT
          value: "8082"
        - name: NIFI_CLUSTER_NODE_READ_TIMEOUT
          value: "15"
        - name: NIFI_ZK_CONNECT_STRING
          value: "zookeeper:2181"
        - name: NIFI_CLUSTER_NODE_ADDRESS
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: HOSTNAME
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        livenessProbe:
          exec:
            command:
              - pgrep
              - java
          initialDelaySeconds: 60
          periodSeconds: 30
          timeoutSeconds: 10
          failureThreshold: 3
          successThreshold: 1
        readinessProbe:
          exec:
            command:
              - pgrep
              - java
          initialDelaySeconds: 180
          periodSeconds: 30
          timeoutSeconds: 10
          failureThreshold: 3
          successThreshold: 1
        resources:
          requests:
            cpu: 400m
            memory: 1Gi
          limits:
            cpu: 500m
            memory: 2Gi
        securityContext:
          allowPrivilegeEscalation: false
          privileged: false
          capabilities:
            drop:
              - ALL

I have one node in my Nifi cluster and node adress is : 0.0.0.0:8080

I would like to have 3 nodes and I think having 0.0.0.0:8080 for nodes is not good.
I don't know how to deploy the 3 nodes in Kubernetes and with different node address.

How should I do it and modify my yaml ?


来源: stackexchange

问:
FormatException (FormatException: Trying to read from 02:38 at position 6)
can anybody help me with my problem ? , i have this problem when i entering the time and choose the daily repeat the error was "FormatException (FormatException: Trying to read   from 02:38 at position 6)"

the error come from here

```<code> if (task.repeat == 'Daily') {
        DateTime date = DateFormat.jm().parse(task.startTime.toString());
        var myTime = DateFormat('HH:mm').format(date);
        notifyHelper.scheduledNotification(
            int.parse(myTime.toString().split(':')[0]),
            int.parse(myTime.toString().split(':')[1]),
            task);
</code>```

please help me with my problem

ContentLicense: CC BY-SA 4.0

Body:
can anybody help me with my problem ? , i have this problem when i entering the time and choose the daily repeat the error was "FormatException (FormatException: Trying to read   from 02:38 at position 6)"

the error come from here

 if (task.repeat == 'Daily') {
        DateTime date = DateFormat.jm().parse(task.startTime.toString());
        var myTime = DateFormat('HH:mm').format(date);
        notifyHelper.scheduledNotification(
            int.parse(myTime.toString().split(':')[0]),
            int.parse(myTime.toString().split(':')[1]),
            task);

please help me with my problem


问:
Layout template for interactive view (Border with inner Grid)
I am working on UI and would like to know what is the best practice for building a dashboard like a view with boxes for an interactive dashboard. Currently my view is looking like this:

```<code>  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="*" />
      <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <Border Margin="10,10,10,10" Grid.Row="0" Grid.Column="0" StrokeShape="RoundRectangle 10,10,10,10"
            Stroke="Transparent" BackgroundColor="#3F0071">
      <Label Text="{Binding TotalMessages}" FontSize="30" HorizontalTextAlignment="Center"
             VerticalTextAlignment="Center"></Label>
    </Border>

    ...

    </Grid>
</code>```

However currently I am missing a text (Label) inside each Box (Border). Is it better to create inner Grid for that with two Rows or use VerticalStacklayout? Is there some way to create a template for layout to utilize it then later in all of the boxes? Should it be ContentPage with BindableProperties? I mean Border with inner Stacklayout or Grid with Label?

EDIT:

I have also noticed an issue. In box on the left I am using VerticalStackLayout and in box on the right Grid. Can somebody describe why so? First chart is not visible and second one inside the Grid works fine? I have heard that Grid is using more resources and better to use Stacklayouts whenever possible? Here is my code:

```<code> <Border Margin="10,10,10,10" Grid.Row="2" Grid.ColumnSpan="2" Grid.Column="0"
            StrokeShape="RoundRectangle 10,10,10,10" Stroke="Transparent" BackgroundColor="#3F0071">
      <VerticalStackLayout Spacing="10">
        <Label Text="Split 1" Padding="20,10,0,0" FontAttributes="Bold"></Label>
        <lvc:PieChart Series="{Binding SplitChart}" BackgroundColor="Transparent" LegendPosition="Right"/>
      </VerticalStackLayout>
    </Border>

    <Border Margin="10,10,10,10" Grid.Row="2" Grid.ColumnSpan="2" Grid.Column="2"
            StrokeShape="RoundRectangle 10,10,10,10" Stroke="Transparent" BackgroundColor="#3F0071">
      <Grid>
        <Grid.RowDefinitions>
          <RowDefinition Height="40" />
          <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Label Grid.Row="0" Text="Split 2" Padding="20,10,0,0" FontAttributes="Bold"></Label>
        <Chart/>
      </Grid>
    </Border>
</code>```

EDIT 2:

I have also noticed that setting height explicitly helps. Just trying to figure out where height should be attached in order to be set dynamically and not to some fixed value.

```<code><Border Margin="10,10,10,10" Grid.Row="2" Grid.ColumnSpan="2" Grid.Column="0"
        StrokeShape="RoundRectangle 10,10,10,10" Stroke="Transparent" BackgroundColor="#3F0071">
  <VerticalStackLayout Spacing="10">
    <Label Text="Split 1" Padding="15,10,0,0" FontAttributes="Bold"></Label>
    <lvc:PieChart Series="{Binding SplitChart}" BackgroundColor="Transparent" HeightRequest="200"
              TooltipBackground="Transparent" LegendPosition="Right"/>
  </VerticalStackLayout>
</Border>
</code>```

Body:
I am working on UI and would like to know what is the best practice for building a dashboard like a view with boxes for an interactive dashboard. Currently my view is looking like this:

  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="*" />
      <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="*" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <Border Margin="10,10,10,10" Grid.Row="0" Grid.Column="0" StrokeShape="RoundRectangle 10,10,10,10"
            Stroke="Transparent" BackgroundColor="#3F0071">

    </Border>

    ...

    </Grid>

However currently I am missing a text (Label) inside each Box (Border). Is it better to create inner Grid for that with two Rows or use VerticalStacklayout? Is there some way to create a template for layout to utilize it then later in all of the boxes? Should it be ContentPage with BindableProperties? I mean Border with inner Stacklayout or Grid with Label?

EDIT:

I have also noticed an issue. In box on the left I am using VerticalStackLayout and in box on the right Grid. Can somebody describe why so? First chart is not visible and second one inside the Grid works fine? I have heard that Grid is using more resources and better to use Stacklayouts whenever possible? Here is my code:

 <Border Margin="10,10,10,10" Grid.Row="2" Grid.ColumnSpan="2" Grid.Column="0"
            StrokeShape="RoundRectangle 10,10,10,10" Stroke="Transparent" BackgroundColor="#3F0071">
      <VerticalStackLayout Spacing="10">

        <lvc:PieChart Series="{Binding SplitChart}" BackgroundColor="Transparent" LegendPosition="Right"/>
      </VerticalStackLayout>
    </Border>

    <Border Margin="10,10,10,10" Grid.Row="2" Grid.ColumnSpan="2" Grid.Column="2"
            StrokeShape="RoundRectangle 10,10,10,10" Stroke="Transparent" BackgroundColor="#3F0071">
      <Grid>
        <Grid.RowDefinitions>
          <RowDefinition Height="40" />
          <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Chart/>
      </Grid>
    </Border>

EDIT 2:

I have also noticed that setting height explicitly helps. Just trying to figure out where height should be attached in order to be set dynamically and not to some fixed value.

<Border Margin="10,10,10,10" Grid.Row="2" Grid.ColumnSpan="2" Grid.Column="0"
        StrokeShape="RoundRectangle 10,10,10,10" Stroke="Transparent" BackgroundColor="#3F0071">
  <VerticalStackLayout Spacing="10">

    <lvc:PieChart Series="{Binding SplitChart}" BackgroundColor="Transparent" HeightRequest="200"
              TooltipBackground="Transparent" LegendPosition="Right"/>
  </VerticalStackLayout>
</Border>


问:
Airflow : How to start a DAG run before the end of its date_interval / end time
In Airflow, is it possible to make a DAG run start before the end of its date_interval / end time ?

Let's take for instance a DAG that runs with schedule daily. A DAG run is thus triggered daily at midnight. Suppose now that the data the DAG is supposed to process is made available every day around 10am. Airflow doesn't know that and will be waiting uselessly until midnight to process that piece of data.

For DAG with given date_interval, is there an easy way to trigger it before the end of its date_interval if we know in advance that it will be able to process its job sooner ?


问:
Nodejs Serverless API is Corrupting PDF
I have a Nodejs API that returns a PDF file in the response. It returns the PDF as binary data. On my frontend, I use a package called React-PDF which takes the PDF endpoint url and fetches the data to display. This worked completely fine up until the point where I decided to switch to the serverless framework (including serverless-offline).

Now after switching to serverless, when the PDF is fetched by my frontend, it fails to load and logs a warning to the console Warning: Indexing all PDF objects. I have used the tool vbindiff to compare the same PDF file downloaded from the normal Nodejs Express API with the one downloaded from the API using serverless-framework and I saw that both files are the same length, but the one downloaded from the serverless API has different contents in some places.

I have found a few similar questions that talk about problems with serverless and binary data, to which I added their recommended configuration to the serverless.yml file that is supposed to allow binary data, but this changed nothing to the result.

Here is the configuration that was recommended to be added to allow binary data through the API gateway

```<code>provider:
    apiGateway:
        binaryMediaTypes:
          - "*/*"
</code>```

Here is my full serverless.yml file

```<code>service: flightchecklists-backend
frameworkVersion: "3"
provider:
  name: aws
  runtime: nodejs12.x
  memorySize: 1024
  timeout: 30
  region: ${opt:region}

  # To allow binary pdf responses.
  apiGateway:
    binaryMediaTypes:
      - "*/*"
functions:
  handler:
    handler: server.handler
    events:
      - http:
          path: /
          method: ANY
          cors: true
      - http:
          path: /{proxy+}
          method: ANY
          cors: true
plugins:
  - serverless-offline
custom:
  serverless-offline:
    noPrependStageInUrl: true
    httpPort: 3000

</code>```

Here is my server.js file

```<code>"use strict";

require("dotenv").config();
require("log-aws-lambda")();
const express = require("express");
const serverless = require("serverless-http");
const bodyParser = require("body-parser");
const path = require("path");
const cors = require("cors");
const app = express();

const checklists = require("./routes/checklists");
const checkout = require("./routes/checkout");
const customerPortal = require("./routes/customerPortal");
const paymentUsers = require("./routes/paymentUsers");
const webhook = require("./routes/webhook");
const subscriptions = require("./routes/subscriptions");
const orders = require("./routes/orders");
const isAdmin = require("./routes/isAdmin");
const blockExternalRequests = require("./middleware/blockExternalRequests");
const namedLogger = require("./utils/logger");

const logger = new namedLogger("server.js");
const port = 3000;

// Cors
app.use(cors());

// Webhook route (Needs to be before bodyparser)
app.use("/webhook", webhook);

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// View engine
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.use(
  "/static",
  blockExternalRequests,
  express.static(path.join(__dirname, "public"))
);

// Routes
app.use("/checklists", checklists);
app.use("/create-checkout-session", checkout);
app.use("/create-portal-session", customerPortal);
app.use("/paymentusers", paymentUsers);
app.use("/subscriptions", subscriptions);
app.use("/orders", orders);
app.use("/isadmin", isAdmin);

// Comment when using serverless.
app.listen(port, () => {
  logger.info(`Server started on port ${port}...`);
});

// Export for tests
// module.exports = app;

// Uncomment for serverless.
// module.exports.handler = serverless(app);

</code>```

I am not sure what to do at this point. It is clear that my API is working fine without serverless, but I would like to use the serverless framework. I am wondering if maybe this has something to do with the serverless-offline package I am using, but I could not find any documentation about binary data for that package. I would appreciate any help I can get. If there is other information I have failed to provide, let me know and I can post it. Thank you.

EDIT:
Upon request I have uploaded both PDFs, the first being the one which was downloaded correctly through the Nodejs API, and the second being the one downloaded through serverless framework and resulting in the file being corrupted.

The PDFs can be downloaded from the following page. Hopefully this is allowed.

https://ufile.io/f/t3ga1

Title: Nodejs Serverless API is Corrupting PDF

Body:
I have a Nodejs API that returns a PDF file in the response. It returns the PDF as binary data. On my frontend, I use a package called React-PDF which takes the PDF endpoint url and fetches the data to display. This worked completely fine up until the point where I decided to switch to the serverless framework (including serverless-offline).

Now after switching to serverless, when the PDF is fetched by my frontend, it fails to load and logs a warning to the console Warning: Indexing all PDF objects. I have used the tool vbindiff to compare the same PDF file downloaded from the normal Nodejs Express API with the one downloaded from the API using serverless-framework and I saw that both files are the same length, but the one downloaded from the serverless API has different contents in some places.

I have found a few similar questions that talk about problems with serverless and binary data, to which I added their recommended configuration to the serverless.yml file that is supposed to allow binary data, but this changed nothing to the result.

Here is the configuration that was recommended to be added to allow binary data through the API gateway

provider:
    apiGateway:
        binaryMediaTypes:
          - "*/*"

Here is my full serverless.yml file

service: flightchecklists-backend
frameworkVersion: "3"
provider:
  name: aws
  runtime: nodejs12.x
  memorySize: 1024
  timeout: 30
  region: ${opt:region}

  # To allow binary pdf responses.
  apiGateway:
    binaryMediaTypes:
      - "*/*"
functions:
  handler:
    handler: server.handler
    events:
      - http:
          path: /
          method: ANY
          cors: true
      - http:
          path: /{proxy+}
          method: ANY
          cors: true
plugins:
  - serverless-offline
custom:
  serverless-offline:
    noPrependStageInUrl: true
    httpPort: 3000

Here is my server.js file

"use strict";

require("dotenv").config();
require("log-aws-lambda")();
const express = require("express");
const serverless = require("serverless-http");
const bodyParser = require("body-parser");
const path = require("path");
const cors = require("cors");
const app = express();

const checklists = require("./routes/checklists");
const checkout = require("./routes/checkout");
const customerPortal = require("./routes/customerPortal");
const paymentUsers = require("./routes/paymentUsers");
const webhook = require("./routes/webhook");
const subscriptions = require("./routes/subscriptions");
const orders = require("./routes/orders");
const isAdmin = require("./routes/isAdmin");
const blockExternalRequests = require("./middleware/blockExternalRequests");
const namedLogger = require("./utils/logger");

const logger = new namedLogger("server.js");
const port = 3000;

// Cors
app.use(cors());

// Webhook route (Needs to be before bodyparser)
app.use("/webhook", webhook);

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// View engine
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.use(
  "/static",
  blockExternalRequests,
  express.static(path.join(__dirname, "public"))
);

// Routes
app.use("/checklists", checklists);
app.use("/create-checkout-session", checkout);
app.use("/create-portal-session", customerPortal);
app.use("/paymentusers", paymentUsers);
app.use("/subscriptions", subscriptions);
app.use("/orders", orders);
app.use("/isadmin", isAdmin);

// Comment when using serverless.
app.listen(port, () => {
  logger.info(`Server started on port ${port}...`);
});

// Export for tests
// module.exports = app;

// Uncomment for serverless.
// module.exports.handler = serverless(app);

I am not sure what to do at this point. It is clear that my API is working fine without serverless, but I would like to use the serverless framework. I am wondering if maybe this has something to do with the serverless-offline package I am using, but I could not find any documentation about binary data for that package. I would appreciate any help I can get. If there is other information I have failed to provide, let me know and I can post it. Thank you.

EDIT:
Upon request I have uploaded both PDFs, the first being the one which was downloaded correctly through the Nodejs API, and the second being the one downloaded through serverless framework and resulting in the file being corrupted.

The PDFs can be downloaded from the following page. Hopefully this is allowed.

https://ufile.io/f/t3ga1


问:
Update and computed do not work to change the chart
I need to make reactive changed component, when the date changes, it is pushed into the Chart and the component will update. I've done it with two methods, but none of them works. One of them is computed, the other is chartInstance.update(). The computer triggers when changes occur, which can be checked through the console log, update also works without errors, there are changes in data, but nothing happens, what's wrong?

<template>

      <Line ref="Graph" id="Chart" :data="ChartData" :options="options" :plugins="plugins" />

</template>


问:
How can I display a default value within a slash command's argument?
Using discord.py, I'm trying to first query a database for some values that are displayed to the user as the default value within a slash command's argument (essentially allowing them to edit values).

Simplifying the problem: the slash command, would be

```<code>/update [Age]
</code>```

But I'd like to default the value for [Age] with a value queried from a database. The problem is how to query the database at the time the command is issued. For reference, this is contained in a cog.

```<code>import discord
from discord.ext import commands
from discord import app_commands

class Age(commands.Cog):
    def __init__(self, client: commands.Bot):
        self.client = client
        print("age.py LOADED!")

    @app_commands.command(
        name="age",
        description="Update your Age")

    #HERE IS WHERE I'D LIKE TO SHOW A DEFAULT NUMBER BASED ON A DB QUERY
    async def age(self, interaction: discord.Interaction,age: int):
        data = self.client.db
        data.reconnect()
        cursor = data.cursor()

        qry = (
            f"update users set age= {age} where d_uid = %s and d_gid = %s"
        )
        val = (str(interaction.user.id), str(interaction.guild_id))

        try:
          cursor.execute(qry,val)
          data.commit()
        except:
          await interaction.response.send_message(
            f'ERROR! Something went wrong. Sorry about that. The Botmaster has been notified.'
          )
        else:
          await interaction.response.send_message(
            f'Age to {age}!'
          )
        finally:
          cursor.close()

async def setup(client: commands.Bot) -> None:
    await client.add_cog(Age(client))
</code>```

Is this even possible?

Not sure how I can query the data before the command renders the arguments to the user, along with a default.

Body:
Using discord.py, I'm trying to first query a database for some values that are displayed to the user as the default value within a slash command's argument (essentially allowing them to edit values).

Simplifying the problem: the slash command, would be

/update [Age]

But I'd like to default the value for [Age] with a value queried from a database. The problem is how to query the database at the time the command is issued. For reference, this is contained in a cog.

import discord
from discord.ext import commands
from discord import app_commands

class Age(commands.Cog):
    def __init__(self, client: commands.Bot):
        self.client = client
        print("age.py LOADED!")

    @app_commands.command(
        name="age",
        description="Update your Age")

    #HERE IS WHERE I'D LIKE TO SHOW A DEFAULT NUMBER BASED ON A DB QUERY
    async def age(self, interaction: discord.Interaction,age: int):
        data = self.client.db
        data.reconnect()
        cursor = data.cursor()

        qry = (
            f"update users set age= {age} where d_uid = %s and d_gid = %s"
        )
        val = (str(interaction.user.id), str(interaction.guild_id))

        try:
          cursor.execute(qry,val)
          data.commit()
        except:
          await interaction.response.send_message(
            f'ERROR! Something went wrong. Sorry about that. The Botmaster has been notified.'
          )
        else:
          await interaction.response.send_message(
            f'Age to {age}!'
          )
        finally:
          cursor.close()

async def setup(client: commands.Bot) -> None:
    await client.add_cog(Age(client))

Is this even possible?

Not sure how I can query the data before the command renders the arguments to the user, along with a default.


问:
Access to register of unclocked peripheral at 0x40000000 cause BUS_FAULT [U2_CM3CORE]
I'm working with STM32F103C6, HCSR-04 Ultrasonic sensor and LCD display.
I simulate that in Proteus Professional 8, when I activate Timer 2 in STM32, there are big problems with frequency, frequency of LCD display = 250kHz, frequency of STM32 = 36MHz. In this state, program will eject this message "Access to register of unclocked peripheral at 0x40000000 cause BUS_FAULT [U2_CM3CORE]" more than 1000 times, and then program will crash.

If I increase frequency of STM32 in Proteus then LCD display shows nothing. Does anyone has idea how to fix this problem.

```<code>/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "lcd_txt.h"
#include "stdio.h"

#include "HCSR04.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#define HCSR04_SENSOR1 8
uint16_t TRIG_Ticks = 0;
uint16_t LCD_Ticks = 0;
float Distance = 0.0;
char TEXT[16] = {0};
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define usTIM   TIM1

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
I2C_HandleTypeDef hi2c1;

TIM_HandleTypeDef htim2;

UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_I2C1_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_TIM2_Init(void);
/* USER CODE BEGIN PFP */
void usDelay(uint32_t uSec);

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
    uint32_t numTicks = 0;

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C1_Init();
  MX_USART2_UART_Init();
  MX_TIM2_Init();
  /* USER CODE BEGIN 2 */
    lcd_init();
    lcd_puts(1,0, (int8_t*)"test");
  /* USER CODE END 2 */
    HCSR04_Init(HCSR04_SENSOR1, &htim2);
    lcd_puts(0,0, (int8_t*)"test");

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
        Distance = HCSR04_Read(HCSR04_SENSOR1);
    sprintf(TEXT, "Dist= %.2f cm", Distance);
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
    HCSR04_TMR_IC_ISR(htim);
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef* htim)
{
    HCSR04_TMR_OVF_ISR(htim);
}

void SysTick_CallBack(void)
{
    TRIG_Ticks++;
    LCD_Ticks++;
    if(TRIG_Ticks >= 15) // Each 15msec
    {
        HCSR04_Trigger(HCSR04_SENSOR1);
        TRIG_Ticks = 0;
    }
    if(LCD_Ticks >= 200) // Each 200msec
    {
        lcd_clear();
        lcd_puts(0,0, (int8_t*)TEXT);
        LCD_Ticks = 0;
    }
}
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief I2C1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_I2C1_Init(void)
{

  /* USER CODE BEGIN I2C1_Init 0 */

  /* USER CODE END I2C1_Init 0 */

  /* USER CODE BEGIN I2C1_Init 1 */

  /* USER CODE END I2C1_Init 1 */
  hi2c1.Instance = I2C1;
  hi2c1.Init.ClockSpeed = 100000;
  hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
  hi2c1.Init.OwnAddress1 = 0;
  hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
  hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
  hi2c1.Init.OwnAddress2 = 0;
  hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
  hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
  if (HAL_I2C_Init(&hi2c1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN I2C1_Init 2 */

  /* USER CODE END I2C1_Init 2 */

}

/**
  * @brief TIM2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM2_Init(void)
{

  /* USER CODE BEGIN TIM2_Init 0 */

  /* USER CODE END TIM2_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};
  TIM_IC_InitTypeDef sConfigIC = {0};

  /* USER CODE BEGIN TIM2_Init 1 */

  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 0;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 0;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_TIM_IC_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_RISING;
  sConfigIC.ICSelection = TIM_ICSELECTION_DIRECTTI;
  sConfigIC.ICPrescaler = TIM_ICPSC_DIV1;
  sConfigIC.ICFilter = 0;
  if (HAL_TIM_IC_ConfigChannel(&htim2, &sConfigIC, TIM_CHANNEL_1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM2_Init 2 */

  /* USER CODE END TIM2_Init 2 */

}

/**
  * @brief USART2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, GPIO_PIN_10|GPIO_PIN_11|GPIO_PIN_12|GPIO_PIN_13
                          |GPIO_PIN_14|GPIO_PIN_15, GPIO_PIN_RESET);

  /*Configure GPIO pins : PB10 PB11 PB12 PB13
                           PB14 PB15 */
  GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_11|GPIO_PIN_12|GPIO_PIN_13
                          |GPIO_PIN_14|GPIO_PIN_15;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */
void usDelay(uint32_t uSec)
{
    if(uSec < 2) uSec = 2;
    usTIM->ARR = uSec - 1;  /*sets the value in the auto-reload register*/
    usTIM->EGR = 1;             /*Re-initialises the timer*/
    usTIM->SR &= ~1;        //Resets the flag
    usTIM->CR1 |= 1;        //Enables the counter
    while((usTIM->SR&0x0001) != 1);
    usTIM->SR &= ~(0x0001);
}
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
</code>```

Body:
I'm working with STM32F103C6, HCSR-04 Ultrasonic sensor and LCD display.
I simulate that in Proteus Professional 8, when I activate Timer 2 in STM32, there are big problems with frequency, frequency of LCD display = 250kHz, frequency of STM32 = 36MHz. In this state, program will eject this message "Access to register of unclocked peripheral at 0x40000000 cause BUS_FAULT [U2_CM3CORE]" more than 1000 times, and then program will crash.

If I increase frequency of STM32 in Proteus then LCD display shows nothing. Does anyone has idea how to fix this problem.

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "lcd_txt.h"
#include "stdio.h"

#include "HCSR04.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#define HCSR04_SENSOR1 8
uint16_t TRIG_Ticks = 0;
uint16_t LCD_Ticks = 0;
float Distance = 0.0;
char TEXT[16] = {0};
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define usTIM   TIM1

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
I2C_HandleTypeDef hi2c1;

TIM_HandleTypeDef htim2;

UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_I2C1_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_TIM2_Init(void);
/* USER CODE BEGIN PFP */
void usDelay(uint32_t uSec);

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
    uint32_t numTicks = 0;

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C1_Init();
  MX_USART2_UART_Init();
  MX_TIM2_Init();
  /* USER CODE BEGIN 2 */
    lcd_init();
    lcd_puts(1,0, (int8_t*)"test");
  /* USER CODE END 2 */
    HCSR04_Init(HCSR04_SENSOR1, &htim2);
    lcd_puts(0,0, (int8_t*)"test");

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
        Distance = HCSR04_Read(HCSR04_SENSOR1);
    sprintf(TEXT, "Dist= %.2f cm", Distance);
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
    HCSR04_TMR_IC_ISR(htim);
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef* htim)
{
    HCSR04_TMR_OVF_ISR(htim);
}

void SysTick_CallBack(void)
{
    TRIG_Ticks++;
    LCD_Ticks++;
    if(TRIG_Ticks >= 15) // Each 15msec
    {
        HCSR04_Trigger(HCSR04_SENSOR1);
        TRIG_Ticks = 0;
    }
    if(LCD_Ticks >= 200) // Each 200msec
    {
        lcd_clear();
        lcd_puts(0,0, (int8_t*)TEXT);
        LCD_Ticks = 0;
    }
}
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief I2C1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_I2C1_Init(void)
{

  /* USER CODE BEGIN I2C1_Init 0 */

  /* USER CODE END I2C1_Init 0 */

  /* USER CODE BEGIN I2C1_Init 1 */

  /* USER CODE END I2C1_Init 1 */
  hi2c1.Instance = I2C1;
  hi2c1.Init.ClockSpeed = 100000;
  hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
  hi2c1.Init.OwnAddress1 = 0;
  hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
  hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
  hi2c1.Init.OwnAddress2 = 0;
  hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
  hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
  if (HAL_I2C_Init(&hi2c1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN I2C1_Init 2 */

  /* USER CODE END I2C1_Init 2 */

}

/**
  * @brief TIM2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM2_Init(void)
{

  /* USER CODE BEGIN TIM2_Init 0 */

  /* USER CODE END TIM2_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};
  TIM_IC_InitTypeDef sConfigIC = {0};

  /* USER CODE BEGIN TIM2_Init 1 */

  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 0;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 0;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_TIM_IC_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_RISING;
  sConfigIC.ICSelection = TIM_ICSELECTION_DIRECTTI;
  sConfigIC.ICPrescaler = TIM_ICPSC_DIV1;
  sConfigIC.ICFilter = 0;
  if (HAL_TIM_IC_ConfigChannel(&htim2, &sConfigIC, TIM_CHANNEL_1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM2_Init 2 */

  /* USER CODE END TIM2_Init 2 */

}

/**
  * @brief USART2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, GPIO_PIN_10|GPIO_PIN_11|GPIO_PIN_12|GPIO_PIN_13
                          |GPIO_PIN_14|GPIO_PIN_15, GPIO_PIN_RESET);

  /*Configure GPIO pins : PB10 PB11 PB12 PB13
                           PB14 PB15 */
  GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_11|GPIO_PIN_12|GPIO_PIN_13
                          |GPIO_PIN_14|GPIO_PIN_15;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */
void usDelay(uint32_t uSec)
{
    if(uSec < 2) uSec = 2;
    usTIM->ARR = uSec - 1;  /*sets the value in the auto-reload register*/
    usTIM->EGR = 1;             /*Re-initialises the timer*/
    usTIM->SR &= ~1;        //Resets the flag
    usTIM->CR1 |= 1;        //Enables the counter
    while((usTIM->SR&0x0001) != 1);
    usTIM->SR &= ~(0x0001);
}
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */


问:
pytorch lightning: validation with torchmetric extremely slow
I recently tried to implement a DeepLabV3 training pipeline using pytorch lightning. I wanted to use the build-in torchmetrics.JaccardIndex as my evaluation metric. My LightningModule  looks like this:

import torchmetrics
from pytorch_lightning import LightningModule
from torchvision.models.segmentation.deeplabv3 import deeplabv3_resnet50

class DeepLabV3LightningModule(LightningModule):
    def __init__(self):
        self.model = deeplabv3_resnet50(
            num_classes=38,
            aux_loss=False
        )
        self.loss = nn.CrossEntropyLoss(ignore_index=255, reduction="mean")
        self.iou_metric = torchmetrics.JaccardIndex(
            task="multiclass",
            threshold=0.5,
            num_classes=38,
            average="macro",
        )

    def training_step(self, batch, batch_idx):
        imgs, masks = batch
        out = self.model(imgs)
        preds = out["out"]
        loss = self.loss(preds, masks)
        return loss

    def validation_step(self, batch, batch_idx):
        imgs, masks = batch
        out = self.model(imgs)
        preds = out["out"]
        loss = self.loss(preds, masks)
        preds = torch.softmax(preds, dim=1)
        pred_labels = torch.argmax(preds, dim=1)

        # measure runtime of metric update
        start = timer()
        self.iou_metric.update(pred_labels, masks)
        elapsed = timer() - start
        return elapsed

    def validation_epoch_end(self, outputs):
        avg_runtime = round(mean(outputs), 4)
        print(f"GPU {self.local_rank}: {avg_runtime} seconds")

```
<p>When using this validation procedure, it is extremely slow. On average, the update step of the metric takes 23.4 seconds. However, the first 3 updates are very fast (<1 second), then they become slow.</p>
<p>I tried to reproduce this behavior in a MWE:</p>
<pre class="lang-py prettyprint-override"><code>from timeit import default_timer as timer
from statistics import mean
import torchmetrics
import torch

num_classes = 38

iou_metric = torchmetrics.JaccardIndex(
    task="multiclass",
    threshold=0.5,
    num_classes=num_classes,
    average="macro"
).to("cuda")

# dummy labels in shape [b, h, w]
label_mask = torch.randint(low=0, high=num_classes-1, size=(8, 480, 640), device="cuda")

# dummy predicted labels in shape [b, h, w]
pred_mask = torch.randint(low=0, high=num_classes-1, size=(8, 480, 640), device="cuda")

runtime_hist = []
for i in range(100):
    start = timer()
    iou_metric.update(label_mask, pred_mask)
    elapsed = timer() - start
    runtime_hist.append(elapsed)

avg_runtime = round(mean(runtime_hist), 2)
print(avg_runtime)
</code>```

Here I get an average update duration of 0.03 seconds, so I do not encounter the extremely slow update as in my LightningModule above. Can someone help me with an explanation for that?

Here some training information for my pytorch-lightning training pipeline:

OS: Ubuntu 20.04.4

CUDA 11.3

DDP training strategy

GPUs: 4x V100

batch size: 8

image size (width x height): 640 x 480

number of workers in dataloader: 8

My package versions:

pytorch lightning: 1.8.4.post0 (installed via pip)

torch: 1.13.0

torchvision: 0.14.0

torchmetrics: 0.11.0

numpy: 11.23.5

Thanks so much!
Lukas

Body:
I recently tried to implement a DeepLabV3 training pipeline using pytorch lightning. I wanted to use the build-in torchmetrics.JaccardIndex as my evaluation metric. My LightningModule  looks like this:

import torchmetrics
from pytorch_lightning import LightningModule
from torchvision.models.segmentation.deeplabv3 import deeplabv3_resnet50

class DeepLabV3LightningModule(LightningModule):
    def __init__(self):
        self.model = deeplabv3_resnet50(
            num_classes=38,
            aux_loss=False
        )
        self.loss = nn.CrossEntropyLoss(ignore_index=255, reduction="mean")
        self.iou_metric = torchmetrics.JaccardIndex(
            task="multiclass",
            threshold=0.5,
            num_classes=38,
            average="macro",
        )

    def training_step(self, batch, batch_idx):
        imgs, masks = batch
        out = self.model(imgs)
        preds = out["out"]
        loss = self.loss(preds, masks)
        return loss

    def validation_step(self, batch, batch_idx):
        imgs, masks = batch
        out = self.model(imgs)
        preds = out["out"]
        loss = self.loss(preds, masks)
        preds = torch.softmax(preds, dim=1)
        pred_labels = torch.argmax(preds, dim=1)

        # measure runtime of metric update
        start = timer()
        self.iou_metric.update(pred_labels, masks)
        elapsed = timer() - start
        return elapsed

    def validation_epoch_end(self, outputs):
        avg_runtime = round(mean(outputs), 4)
        print(f"GPU {self.local_rank}: {avg_runtime} seconds")

When using this validation procedure, it is extremely slow. On average, the update step of the metric takes 23.4 seconds. However, the first 3 updates are very fast (<1 second), then they become slow.

I tried to reproduce this behavior in a MWE:

from timeit import default_timer as timer
from statistics import mean
import torchmetrics
import torch

num_classes = 38

iou_metric = torchmetrics.JaccardIndex(
    task="multiclass",
    threshold=0.5,
    num_classes=num_classes,
    average="macro"
).to("cuda")

# dummy labels in shape [b, h, w]
label_mask = torch.randint(low=0, high=num_classes-1, size=(8, 480, 640), device="cuda")

# dummy predicted labels in shape [b, h, w]
pred_mask = torch.randint(low=0, high=num_classes-1, size=(8, 480, 640), device="cuda")

runtime_hist = []
for i in range(100):
    start = timer()
    iou_metric.update(label_mask, pred_mask)
    elapsed = timer() - start
    runtime_hist.append(elapsed)

avg_runtime = round(mean(runtime_hist), 2)
print(avg_runtime)

Here I get an average update duration of 0.03 seconds, so I do not encounter the extremely slow update as in my LightningModule above. Can someone help me with an explanation for that?

Here some training information for my pytorch-lightning training pipeline:

OS: Ubuntu 20.04.4

CUDA 11.3

DDP training strategy

GPUs: 4x V100

batch size: 8

image size (width x height): 640 x 480

number of workers in dataloader: 8

My package versions:

pytorch lightning: 1.8.4.post0 (installed via pip)

torch: 1.13.0

torchvision: 0.14.0

torchmetrics: 0.11.0

numpy: 11.23.5

Thanks so much!
Lukas


问:
driving nema14 with circuitpython on a esp32 s2 with A4988
I am trying to drive a stepper motor with circuitpython 7.3.3 on a esp32 s2 with a A4988 stepper motor driver board. I have been fiddling for a while now.  Since adafruit does not carry the A4988 boards there is no example code to start from on there pages, so I ended up trying to modify a piece of micropython code from TechToTinker.

https://techtotinker.blogspot.com/2021/05/036-micropython-technotes-stepper-motor.html%5B/url%5D

Unfortunately I can't seem to make the most basics of code to work and get the stepper to move.

```<code>import time
import board
from digitalio import DigitalInOut, Direction, Pull

dir_1 = DigitalInOut(board.IO1)
dir_1.direction = Direction.OUTPUT
step_1 = DigitalInOut(board.IO2)
step_1.direction = Direction.OUTPUT

def rotate(angle=0, rotation='cw'):
    if rotation == 'cw':
        dir_1.value(0)
        for i in range(0, 200, 1):
            step_1.value(1)  # one step
            time.sleep(0.5)
            step_1.value(0)
            time.sleep(0.5)
    if rotation == 'ccw':
        dir_1.value(1)
        for i in range(200-1, -1, -1):
            step_1.value(1)
            time.sleep(0.5)
            step_1.value(0)
            time.sleep(0.5)
</code>```

With the following lines of codes I should be able to test the stepper using the REPL:

```<code>rotate(360, 'cw')
rotate(360, 'ccw')
</code>```

I checked the above code with mu and corrected all the found (style) error's, still when I run it I get the following error.

Traceback (most recent call last): File "<stdin>", line 1, in
<module> NameError: name 'rotate' is not defined.

A google search gave me an ansers like:

It looks like a variable named 'python' is used which is not present at the given scope during execution[/quote],
Unfortunately I can't do much with that, as far as I understand I am not doing that, so if I am, I have no idea how I am doing that, additionally I thought to have defined 'rotate'.

I tried the following to get some use out of the stepper:

I searched the adafruit site for relevant example code.

I searched the adafruit forum for similar issues but found only topics on arduino boards.

I searched the net for similar pieces of ciruit/micropython code to use with the A4988 board.

I finally tried to write, modify code myself, from relevant code from whichI tried to solve all errors.

I googled the final additional error but did not understand what I found.

Body:
I am trying to drive a stepper motor with circuitpython 7.3.3 on a esp32 s2 with a A4988 stepper motor driver board. I have been fiddling for a while now.  Since adafruit does not carry the A4988 boards there is no example code to start from on there pages, so I ended up trying to modify a piece of micropython code from TechToTinker.

https://techtotinker.blogspot.com/2021/05/036-micropython-technotes-stepper-motor.html%5B/url%5D

Unfortunately I can't seem to make the most basics of code to work and get the stepper to move.

import time
import board
from digitalio import DigitalInOut, Direction, Pull

dir_1 = DigitalInOut(board.IO1)
dir_1.direction = Direction.OUTPUT
step_1 = DigitalInOut(board.IO2)
step_1.direction = Direction.OUTPUT

def rotate(angle=0, rotation='cw'):
    if rotation == 'cw':
        dir_1.value(0)
        for i in range(0, 200, 1):
            step_1.value(1)  # one step
            time.sleep(0.5)
            step_1.value(0)
            time.sleep(0.5)
    if rotation == 'ccw':
        dir_1.value(1)
        for i in range(200-1, -1, -1):
            step_1.value(1)
            time.sleep(0.5)
            step_1.value(0)
            time.sleep(0.5)

With the following lines of codes I should be able to test the stepper using the REPL:

rotate(360, 'cw')
rotate(360, 'ccw')

I checked the above code with mu and corrected all the found (style) error's, still when I run it I get the following error.

Traceback (most recent call last): File "<stdin>", line 1, in
<module> NameError: name 'rotate' is not defined.

A google search gave me an ansers like:

It looks like a variable named 'python' is used which is not present at the given scope during execution[/quote],
Unfortunately I can't do much with that, as far as I understand I am not doing that, so if I am, I have no idea how I am doing that, additionally I thought to have defined 'rotate'.

I tried the following to get some use out of the stepper:

I searched the adafruit site for relevant example code.

I searched the adafruit forum for similar issues but found only topics on arduino boards.

I searched the net for similar pieces of ciruit/micropython code to use with the A4988 board.

I finally tried to write, modify code myself, from relevant code from whichI tried to solve all errors.

I googled the final additional error but did not understand what I found.


问:
Material ui datetimepicker
Is it possible to remove weekends from the calendar using the datetimepicker component with material ui. If not any ideas on how to remove them? this is my code for now.</p>
```<code>    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <DateTimePicker
        renderInput={(props) => <TextField {...props} />}
        label="Make an appointment"
        value={value}
        ampm={false}
        disablePast={true}
        maxDate={maxDate}
        minTime={dayjs(new Date(0, 0, 0, 11))}
        maxTime={dayjs(new Date(0, 0, 0, 19))}
        onChange={(newValue) => {
          setValue(newValue);
        }}
      />
    </LocalizationProvider>
</code>```

Title: Material ui datetimepicker

Body:
Is it possible to remove weekends from the calendar using the datetimepicker component with material ui. If not any ideas on how to remove them? this is my code for now.

    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <DateTimePicker
        renderInput={(props) => <TextField {...props} />}
        label="Make an appointment"
        value={value}
        ampm={false}
        disablePast={true}
        maxDate={maxDate}
        minTime={dayjs(new Date(0, 0, 0, 11))}
        maxTime={dayjs(new Date(0, 0, 0, 19))}
        onChange={(newValue) => {
          setValue(newValue);
        }}
      />
    </LocalizationProvider>


问:
Why does "vite build --watch" see changes on .vue files?
i have created a new Laravel 9, Inertia, Vue3 project.
From the "old" laravel i know the "npm run hot"-script ("hot": "mix watch --hot").

Due to Laravel 9 runs with Vite, you should use the "vite build --watch" script to continuously compiling your code.

This works pretty fine except the .vue files. I have created a "Demo.vue"-Site and when i making changes there, nothing "recompiles" or is changing in the browser. Only when I change other files, the browser view changes to new vue-file.

I already have tried to change the "watch" settings in the vite.config.js, without further success.

Now I have rollback these changes and my vite.config.js looks like this

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';
import FullReload from 'vite-plugin-full-reload';

export default defineConfig({
    plugins: [
        FullReload(),
        vue(),
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
    ],
});
```

Do i have to configure anything else in the vite config or somewhere else?

Body:
i have created a new Laravel 9, Inertia, Vue3 project.
From the "old" laravel i know the "npm run hot"-script ("hot": "mix watch --hot").

Due to Laravel 9 runs with Vite, you should use the "vite build --watch" script to continuously compiling your code.

This works pretty fine except the .vue files. I have created a "Demo.vue"-Site and when i making changes there, nothing "recompiles" or is changing in the browser. Only when I change other files, the browser view changes to new vue-file.

I already have tried to change the "watch" settings in the vite.config.js, without further success.

Now I have rollback these changes and my vite.config.js looks like this

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';
import FullReload from 'vite-plugin-full-reload';

export default defineConfig({
    plugins: [
        FullReload(),
        vue(),
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
    ],
});

Do i have to configure anything else in the vite config or somewhere else?


问:
Reading data from a file and create pojo using DeserializationSchema
I am Junit testing my flink code where I am reading message from Kafka and using class X extends DeserializationSchema to convert into a POJO . For junit testing I am reading from a file that would return a DataStream <String> but now I want to convert into DataStream<Y> by using the same class X to deserialize the message . Can someone help me how can this be done?

```<code>Class X extends DeserializationSchema <Y> {

  ObjectMapper om = ......

  @Override
  public void open(InitializationContext context){
    //some flink metric intialization
  }

  @Override
  public Y deserialize(byte[] inputData) {
    // some custom logic that I really interested in testing
  }
}

KafkaSourceBuilder<Y> sourceBuilder = KafkaSource.<Y>builder()
                    .setTopics(inputTopic)
                    .setGroupId(kafkaInputGroupId)
                    .setProperties(kafkaInputParameters)
                    .setStartingOffsets(getOffset(jobConfig, inputTopic))
                    .setValueOnlyDeserializer(new X());
</code>```

I tried the below

```<code>DataStream<String> text =
                    env.readTextFile("src/test/resources/mobile_integration_test.txt");

            text.map(new MapFunction<String, Y>() {
                @Override
                public Y map(String value) throws Exception {
                    return new X().deserialize(value.getBytes());
                }
            }).print();
</code>```

but this gives me NPE beause of the metric being initialized in the open method (explained above).

Any better ways to do this?

Body:
I am Junit testing my flink code where I am reading message from Kafka and using class X extends DeserializationSchema to convert into a POJO . For junit testing I am reading from a file that would return a DataStream <String> but now I want to convert into DataStream<Y> by using the same class X to deserialize the message . Can someone help me how can this be done?

Class X extends DeserializationSchema <Y> {

  ObjectMapper om = ......

  @Override
  public void open(InitializationContext context){
    //some flink metric intialization
  }

  @Override
  public Y deserialize(byte[] inputData) {
    // some custom logic that I really interested in testing
  }
}

KafkaSourceBuilder<Y> sourceBuilder = KafkaSource.<Y>builder()
                    .setTopics(inputTopic)
                    .setGroupId(kafkaInputGroupId)
                    .setProperties(kafkaInputParameters)
                    .setStartingOffsets(getOffset(jobConfig, inputTopic))
                    .setValueOnlyDeserializer(new X());

I tried the below

DataStream<String> text =
                    env.readTextFile("src/test/resources/mobile_integration_test.txt");

            text.map(new MapFunction<String, Y>() {
                @Override
                public Y map(String value) throws Exception {
                    return new X().deserialize(value.getBytes());
                }
            }).print();

but this gives me NPE beause of the metric being initialized in the open method (explained above).

Any better ways to do this?


问:
Why is ref.current not getting set when running tests using react testing-library
```<code>test('test-1', async () => {
  const Comp = () => {
    const r = React.useRef(null);
    React.useEffect(() => {
      if (r.current) {
        console.log(r.current);
      }
    });
    return <div ref={r}> Hello </div>;
  };
  render(<Comp />);
});
</code>```

In the above code r.current is null and never gets set to HtmlDivElement Why is that?
I am using react-testing-library with jest version 27

I tried updatign to latest version of react-testing library but still did not see the issue getting resolved.

Body:
test('test-1', async () => {
  const Comp = () => {
    const r = React.useRef(null);
    React.useEffect(() => {
      if (r.current) {
        console.log(r.current);
      }
    });
    return
 Hello
;
  };
  render(<Comp />);
});

In the above code r.current is null and never gets set to HtmlDivElement Why is that?
I am using react-testing-library with jest version 27

I tried updatign to latest version of react-testing library but still did not see the issue getting resolved.


问:
How to add fake ClaimsIdentity for testing Asp .Net Core Web API?
I'm trying to add some tests for my API. I want to test if for user with bad role Forbidden status code is returned. So far to add fake ClaimsIdentity I were replacing default implementation of IPolicyEvaluator with this one:

```<code>public class FakePolicyEvaluator : IPolicyEvaluator
{
    public ClaimsIdentity? ClaimsIdentity { get; set; }

    public Task<AuthenticateResult> AuthenticateAsync(AuthorizationPolicy policy, HttpContext context)
    {
        var claimsPrincipal = new ClaimsPrincipal();

        if (ClaimsIdentity != null)
        {
            claimsPrincipal.AddIdentity(ClaimsIdentity);
        }

        var ticket = new AuthenticationTicket(claimsPrincipal, "test");
        var result = AuthenticateResult.Success(ticket);

        return Task.FromResult(result);
    }

    public Task<PolicyAuthorizationResult> AuthorizeAsync(AuthorizationPolicy policy, AuthenticateResult authenticationResult, HttpContext context, object? resource)
    {
        var result = PolicyAuthorizationResult.Success();

        return Task.FromResult(result);
    }
}
</code>```

So with this class I could customize ClaimsIdentity by proprty. I am using such attribute

```<code>[Authorize(Roles="SomeAllowedRole")]
</code>```

which I mark my controller method with. Now it does not work, I guess it's becuase I return AuthenticationResult.Seccess(). Is there any other way to add fake ClaimsIdentity? I were thinking about injecting an original implementation of IPolicyEvaluator to my FakePolicyEvaluator and do something like this:

```<code>public class FakePolicyEvaluator : IPolicyEvaluator
{
    private readonly PolicyEvaluator _realPolicyEvaluator;

    public FakePolicyEvaluator(PolicyEvaluator realPolicyEvaluator)
    {
        _realPolicyEvaluator = realPolicyEvaluator;
    }

    public ClaimsIdentity? ClaimsIdentity { get; set; }

    public Task<AuthenticateResult> AuthenticateAsync(AuthorizationPolicy policy, HttpContext context)
    {
        var claimsPrincipal = new ClaimsPrincipal();

        if (ClaimsIdentity != null)
        {
            claimsPrincipal.AddIdentity(ClaimsIdentity);
        }

        context.User = claimsPrincipal;
        return _realPolicyEvaluator.AuthenticateAsync(policy, context);
    }

    public Task<PolicyAuthorizationResult> AuthorizeAsync(AuthorizationPolicy policy, AuthenticateResult authenticationResult, HttpContext context, object? resource)
    {
        return _realPolicyEvaluator.AuthorizeAsync(policy, authenticationResult, context, resource);
    }
}
</code>```

But I dont't know how can I register this in my service collection (or create an instance of PolicyEvaluator). Any ideas?

Body:
I'm trying to add some tests for my API. I want to test if for user with bad role Forbidden status code is returned. So far to add fake ClaimsIdentity I were replacing default implementation of IPolicyEvaluator with this one:

public class FakePolicyEvaluator : IPolicyEvaluator
{
    public ClaimsIdentity? ClaimsIdentity { get; set; }

    public Task<AuthenticateResult> AuthenticateAsync(AuthorizationPolicy policy, HttpContext context)
    {
        var claimsPrincipal = new ClaimsPrincipal();

        if (ClaimsIdentity != null)
        {
            claimsPrincipal.AddIdentity(ClaimsIdentity);
        }

        var ticket = new AuthenticationTicket(claimsPrincipal, "test");
        var result = AuthenticateResult.Success(ticket);

        return Task.FromResult(result);
    }

    public Task<PolicyAuthorizationResult> AuthorizeAsync(AuthorizationPolicy policy, AuthenticateResult authenticationResult, HttpContext context, object? resource)
    {
        var result = PolicyAuthorizationResult.Success();

        return Task.FromResult(result);
    }
}

So with this class I could customize ClaimsIdentity by proprty. I am using such attribute

[Authorize(Roles="SomeAllowedRole")]

which I mark my controller method with. Now it does not work, I guess it's becuase I return AuthenticationResult.Seccess(). Is there any other way to add fake ClaimsIdentity? I were thinking about injecting an original implementation of IPolicyEvaluator to my FakePolicyEvaluator and do something like this:

public class FakePolicyEvaluator : IPolicyEvaluator
{
    private readonly PolicyEvaluator _realPolicyEvaluator;

    public FakePolicyEvaluator(PolicyEvaluator realPolicyEvaluator)
    {
        _realPolicyEvaluator = realPolicyEvaluator;
    }

    public ClaimsIdentity? ClaimsIdentity { get; set; }

    public Task<AuthenticateResult> AuthenticateAsync(AuthorizationPolicy policy, HttpContext context)
    {
        var claimsPrincipal = new ClaimsPrincipal();

        if (ClaimsIdentity != null)
        {
            claimsPrincipal.AddIdentity(ClaimsIdentity);
        }

        context.User = claimsPrincipal;
        return _realPolicyEvaluator.AuthenticateAsync(policy, context);
    }

    public Task<PolicyAuthorizationResult> AuthorizeAsync(AuthorizationPolicy policy, AuthenticateResult authenticationResult, HttpContext context, object? resource)
    {
        return _realPolicyEvaluator.AuthorizeAsync(policy, authenticationResult, context, resource);
    }
}

But I dont't know how can I register this in my service collection (or create an instance of PolicyEvaluator). Any ideas?


问:
Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead BUT i'm not using numpy here
I get this error in the training loop for this neural network:

class YourModel(torch.nn.Module):
    def __init__(self):
        super(YourModel, self).__init__()
        self.fc1 = nn.Linear(50, 128)
        self.sigmoid = nn.Sigmoid()
        self.fc2 = nn.Linear(128, 1)

    def forward(self, x1, x2):
        x = torch.cat((x1, x2), dim=1)

        out = self.fc1(x)
        out = self.sigmoid(out)
        out = self.fc2(out)
        return out

model = YourModel().to(device)

optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
loss_fn = nn.BCELoss()
```
<p>My dataloader contains 3 datasets, 1 with 25 features for 8000 documents, other with 25 features of 8000 queries and the last one with the relation between both (0 or 1). So that's why I'm using a neural network for binary classification. (However if you know an alternative neural network I'm open to options)</p>
<p>My <code>batch_size</code> is 1 right now and here is my training loop:</p>
<pre class="lang-py prettyprint-override"><code>def train(dataloader, model, loss_fn, optimizer):
    model.train()
    train_loss = 0
    num_batches = len(dataloader)
    all_pred = []
    all_real = []
    for batch, i in enumerate(train_dataloader): #access to each batch
      i_1 = i[0]
      i_2 = i[1]
      y = i[2].float().view(1, 1) #find relevance
      #y = torch.clamp(y, min=0, max=1)
      #x = np.hstack((i_1, i_2))
      #x = torch.Tensor(x)
      #x = torch.clamp(x, min=0, max=1)

      # Zero the gradients
      optimizer.zero_grad()

      # Forward pass
      y_pred = model(i_1, i_2).float()
      y_pred = torch.clamp(y_pred, min=0, max=1)
      loss = loss_fn(y_pred, y)

      # Backward pass
      loss.backward()

      # Update the parameters
      optimizer.step()

      train_loss += loss.item() #sum the loss

      all_pred.append(y_pred)
      all_real.append(y)
      if batch > 0 and batch%1000 == 0:
        print(f"Partial loss: {train_loss/batch}, F1: {f1_score(all_real, all_pred)}")
    train_loss /= num_batches
    print(f"Total loss: {train_loss}") #print loss of every epoch
    return train_loss
</code>```

I'm getting this error: "Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead." but as far as I know I'm not calling numpy on any tensors. And if I use the detach method then I get the an error saying that the loss can not be computed because the tensor of 0 doesn't need grad. So it is pretty much a loop.

Body:
I get this error in the training loop for this neural network:

class YourModel(torch.nn.Module):
    def __init__(self):
        super(YourModel, self).__init__()
        self.fc1 = nn.Linear(50, 128)
        self.sigmoid = nn.Sigmoid()
        self.fc2 = nn.Linear(128, 1)

    def forward(self, x1, x2):
        x = torch.cat((x1, x2), dim=1)

        out = self.fc1(x)
        out = self.sigmoid(out)
        out = self.fc2(out)
        return out

model = YourModel().to(device)

optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
loss_fn = nn.BCELoss()

My dataloader contains 3 datasets, 1 with 25 features for 8000 documents, other with 25 features of 8000 queries and the last one with the relation between both (0 or 1). So that's why I'm using a neural network for binary classification. (However if you know an alternative neural network I'm open to options)

My batch_size is 1 right now and here is my training loop:

def train(dataloader, model, loss_fn, optimizer):
    model.train()
    train_loss = 0
    num_batches = len(dataloader)
    all_pred = []
    all_real = []
    for batch, i in enumerate(train_dataloader): #access to each batch
      i_1 = i[0]
      i_2 = i[1]
      y = i[2].float().view(1, 1) #find relevance
      #y = torch.clamp(y, min=0, max=1)
      #x = np.hstack((i_1, i_2))
      #x = torch.Tensor(x)
      #x = torch.clamp(x, min=0, max=1)

      # Zero the gradients
      optimizer.zero_grad()

      # Forward pass
      y_pred = model(i_1, i_2).float()
      y_pred = torch.clamp(y_pred, min=0, max=1)
      loss = loss_fn(y_pred, y)

      # Backward pass
      loss.backward()

      # Update the parameters
      optimizer.step()

      train_loss += loss.item() #sum the loss

      all_pred.append(y_pred)
      all_real.append(y)
      if batch > 0 and batch%1000 == 0:
        print(f"Partial loss: {train_loss/batch}, F1: {f1_score(all_real, all_pred)}")
    train_loss /= num_batches
    print(f"Total loss: {train_loss}") #print loss of every epoch
    return train_loss

I'm getting this error: "Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead." but as far as I know I'm not calling numpy on any tensors. And if I use the detach method then I get the an error saying that the loss can not be computed because the tensor of 0 doesn't need grad. So it is pretty much a loop.


问:
How can I let a Docker image run inside a container, so it awaits for commands?
I have a problem with my Docker Container.
My backend image stops running after it has finished installing dependencies.
While my app is running there will be some querys to the backend, but because it is stopped this doesn't work.

My Dockerfile for the backend

Is there a command I need to add so it runs in the background and listens for querys?

I tried using node as a base image but than it doesnt know R.


问:
Where comes the error "DLL load failed while importing _greenlet"?
i tried using the reddit video maker.

```<code>https://github.com/elebumm/RedditVideoMakerBot
</code>```

After following the complete documentation and fixing some errors I´m getting an error I can`t fix.

Could you help me ?

```<code>https://pastebin.com/3e4H2rkR
</code>```

Tried starting main.py

Did not start due to error I dont understand.

Body:
i tried using the reddit video maker.

https://github.com/elebumm/RedditVideoMakerBot

After following the complete documentation and fixing some errors I´m getting an error I can`t fix.

Could you help me ?

https://pastebin.com/3e4H2rkR

Tried starting main.py

Did not start due to error I dont understand.


问:
Python Mail program issue
I'm trying to send emails to mails in a .txt file. but mails doesnt delivered after first mail. I get the following error :

550 5.7.1 [209.85.220.41] This message is not RFC 5322 compliant, the
issue is: duplicate headers. To reduce the amount of spam sent to
Gmail, this message has been blocked. Please review RFC 5322
specifications for more information.
gv45-20020a1709072bed00b007b284329e31sor3288924ejc.70 - gsmtp

mails.txt lines is like:

```<code>Name,Surname,name@gmail.com
</code>```

Thats my code :

```<code>import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import sys

mesaj = MIMEMultipart()

with open("mails.txt","r",encoding="utf-8") as file:
    mailler=file.readlines()

for i in mailler:
    try:
        kisi=i.split(",")
        kisi[1].strip("\n")
        mesaj["From"]="MY MAİL HERE"
        mesaj["To"]=kisi[1]
        mesaj["Subject"]="SMTP Toplu Mail Denemesi"
        yazı=kisi[0]+"Bu Maili Görmezden Gelin"
        icerik=MIMEText(yazı,"plain")
        mesaj.attach(icerik)
        mail=smtplib.SMTP("smtp.gmail.com",587)
        mail.ehlo()
        mail.starttls()
        mail.login("my mail",
                   "my mail app password here")
        mail.sendmail(mesaj["From"],mesaj["To"],mesaj.as_string())
        print(kisi[0]," Adlı Kişiye Mail Başarıyla Gönderildi")
        mail.close()
    except:
        sys.stderr.write("Mail Gönderilemedi.")
        sys.stderr.flush()
</code>```

I cant send more than 1 mail.

Title: Python Mail program issue

Body:
I'm trying to send emails to mails in a .txt file. but mails doesnt delivered after first mail. I get the following error :

550 5.7.1 [209.85.220.41] This message is not RFC 5322 compliant, the
issue is: duplicate headers. To reduce the amount of spam sent to
Gmail, this message has been blocked. Please review RFC 5322
specifications for more information.
gv45-20020a1709072bed00b007b284329e31sor3288924ejc.70 - gsmtp

mails.txt lines is like:

Name,Surname,name@gmail.com

Thats my code :

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import sys

mesaj = MIMEMultipart()

with open("mails.txt","r",encoding="utf-8") as file:
    mailler=file.readlines()

for i in mailler:
    try:
        kisi=i.split(",")
        kisi[1].strip("\n")
        mesaj["From"]="MY MAİL HERE"
        mesaj["To"]=kisi[1]
        mesaj["Subject"]="SMTP Toplu Mail Denemesi"
        yazı=kisi[0]+"Bu Maili Görmezden Gelin"
        icerik=MIMEText(yazı,"plain")
        mesaj.attach(icerik)
        mail=smtplib.SMTP("smtp.gmail.com",587)
        mail.ehlo()
        mail.starttls()
        mail.login("my mail",
                   "my mail app password here")
        mail.sendmail(mesaj["From"],mesaj["To"],mesaj.as_string())
        print(kisi[0]," Adlı Kişiye Mail Başarıyla Gönderildi")
        mail.close()
    except:
        sys.stderr.write("Mail Gönderilemedi.")
        sys.stderr.flush()

I cant send more than 1 mail.


问:
Within a nested array, can I create an array of the keys at each index?

Goal: For each key, assign every value to an array.

Use case: I have to be able to search using all possible values simultaneously. As seen at the bottom, a possible key:value search would be:

```<code>"LocationNumber": [1,2,3,4]}
</code>```

The problem: Object SettingOptions is a nested array.

This is how I log each key within a given index:

```<code>//Defines array 'keysArray'
const keysArray = [];

pm.test("array of SettingsOptions[0] keys", () => {
    arrayOfObject = responseDataLocal.Products[0].ConfigurationModel.SettingOptions[0]; //object 'SettingOptions[0]' calls 1st settingoption

    //For each property in array, add the property to 'keysArray'
    for (var property in arrayOfObject) {
        keysArray.push(property)
    }

    console.log(keysArray)
});
</code>```

Response:

```<code>(11) ["LocationNumber", …]
0: "LocationNumber"
1: "StoneCount"
2. ....
....
9: "Shape"
10: ...
</code>```

To create an array of values from a given property:

```<code>pm.test("array of SettingsOptions objects", () => {
    arrayOfObject = responseDataLocal.Products[0].ConfigurationModel.SettingOptions;
    let arrayLocationNumber = arrayOfObject.map(a => a.LocationNumber);

//    console.log(Object.values(arrayLocationNumber));
});
</code>```

Response:

```<code>[1, 2, 3, 4]
</code>```

What I'm looking for:

There is a lot of variation in the data I'm pulling from. So I need to be able to automagically pull values to be able to reference them in subsequent requests. An acceptable response could look something like:

```<code>0.{"LocationNumber": [1,2,3,4]}
</code>```
```<code>1....
</code>```
```<code>2.......
</code>```
```<code>3.{"Shape": ["Center","Halo","Accent 1","Accent 2"]}
</code>```

Body:
Goal: For each key, assign every value to an array.

Use case: I have to be able to search using all possible values simultaneously. As seen at the bottom, a possible key:value search would be:

"LocationNumber": [1,2,3,4]}

The problem: Object SettingOptions is a nested array.

This is how I log each key within a given index:

//Defines array 'keysArray'
const keysArray = [];

pm.test("array of SettingsOptions[0] keys", () => {
    arrayOfObject = responseDataLocal.Products[0].ConfigurationModel.SettingOptions[0]; //object 'SettingOptions[0]' calls 1st settingoption

    //For each property in array, add the property to 'keysArray'
    for (var property in arrayOfObject) {
        keysArray.push(property)
    }

    console.log(keysArray)
});

Response:

(11) ["LocationNumber", …]
0: "LocationNumber"
1: "StoneCount"
2. ....
....
9: "Shape"
10: ...

To create an array of values from a given property:

pm.test("array of SettingsOptions objects", () => {
    arrayOfObject = responseDataLocal.Products[0].ConfigurationModel.SettingOptions;
    let arrayLocationNumber = arrayOfObject.map(a => a.LocationNumber);

//    console.log(Object.values(arrayLocationNumber));
});

Response:

[1, 2, 3, 4]

What I'm looking for:

There is a lot of variation in the data I'm pulling from. So I need to be able to automagically pull values to be able to reference them in subsequent requests. An acceptable response could look something like:

0.{"LocationNumber": [1,2,3,4]}

1....

2.......

3.{"Shape": ["Center","Halo","Accent 1","Accent 2"]}


问:
Angular not re-rendering Prism when input changes
I am trying to write an Angular wrapper for Prism. When the component first loads the code displays and is highlighted properly. However, whenever the @Input() code changes, nothing happens. The old code still displays in the same code wrapper when I was expecting it to change.

Stackblitz

Click the JSON button

Click the HTML button

Refresh the page

Click the HTML button

Click the JSON button

As seen, they both output on the fist click but not subsequent clicks.

@Component({
  selector: 'ui-prism',
  templateUrl: './prism.component.html',
  styleUrls: ['./prism.component.scss'],
})
export class PrismComponent implements AfterViewInit, OnChanges {
  protected lang = 'language-text';
  protected outCode: Observable<string> = new Observable();

  @Input() lineNumbers = true;
  @Input() set language(value: string) {
    this.lang = `language-${value.replace(/\./, '')}`;
  }
  @Input() set code(val: string | Observable<string>) {
    this.outCode = typeof val === 'string' ? of(val) : val;
  }

  @ViewChild('codeBlock')
  codeBlock!: ElementRef<HTMLPreElement>;

  ngAfterViewInit() {
    this.highlight();
  }

  ngOnChanges(changes: SimpleChanges) {
    this.highlight();
  }

  private highlight() {
    if (this.codeBlock) {
      Prism.highlightElement(this.codeBlock.nativeElement);
    }
  }
}
```
<p><strong>./prism.component.html</strong></p>
<pre class="lang-html prettyprint-override"><code><pre
  [ngClass]="{ 'line-numbers': lineNumbers }"
  class="w-full"
><code #codeBlock [ngClass]="lang">{{ outCode | async }}</code>```
```
<p>I am using it like this:</p>
<pre class="lang-html prettyprint-override"><code><ng-container *ngTemplateOutlet="file.isText ? text : null; context: { $implicit: file }"></ng-container>

<ng-template #text let-file>
  <!-- fileContent returns an Observable<string> -->
  <ui-prism [language]="file.extension" [code]="file | fileContent"></ui-prism>
</ng-template>
</code>```

Body:
I am trying to write an Angular wrapper for Prism. When the component first loads the code displays and is highlighted properly. However, whenever the @Input() code changes, nothing happens. The old code still displays in the same code wrapper when I was expecting it to change.

Stackblitz

Click the JSON button

Click the HTML button

Refresh the page

Click the HTML button

Click the JSON button

As seen, they both output on the fist click but not subsequent clicks.

@Component({
  selector: 'ui-prism',
  templateUrl: './prism.component.html',
  styleUrls: ['./prism.component.scss'],
})
export class PrismComponent implements AfterViewInit, OnChanges {
  protected lang = 'language-text';
  protected outCode: Observable<string> = new Observable();

  @Input() lineNumbers = true;
  @Input() set language(value: string) {
    this.lang = `language-${value.replace(/\./, '')}`;
  }
  @Input() set code(val: string | Observable<string>) {
    this.outCode = typeof val === 'string' ? of(val) : val;
  }

  @ViewChild('codeBlock')
  codeBlock!: ElementRef<HTMLPreElement>;

  ngAfterViewInit() {
    this.highlight();
  }

  ngOnChanges(changes: SimpleChanges) {
    this.highlight();
  }

  private highlight() {
    if (this.codeBlock) {
      Prism.highlightElement(this.codeBlock.nativeElement);
    }
  }
}

./prism.component.html

{{ outCode | async }}

I am using it like this:

<ng-container *ngTemplateOutlet="file.isText ? text : null; context: { $implicit: file }"></ng-container>

<ng-template #text let-file>

  <ui-prism [language]="file.extension" [code]="file | fileContent"></ui-prism>
</ng-template>


问:
Restrict SortableJS Elements Clone + Nesting Problem
I am looking to allow only certain elements to be nested inside others and I did not managed to do so.

Example: Application element can contain only Container elements. Container only Queries, and Queries different types of Components.

Codepen - Code

HTML:

```<code><div class="container">

        <div id="cloning" class="row">
            <div id="example3Left" class="list-group col">
                <div class="list-group-item nested-sortable" name="container">Container</div>
                <div class="list-group-item nested-1 nested-sortable" name="query">Query</div>
                <div class="list-group-item nested-2" name="component text">Component Text</div>
                <div class="list-group-item nested-2" name="component bool">Component Bool</div>
            </div>
            <div class="list-group col">
                <div id="example3Right" class="list-group-item tinted nested-sortable" name="application">Application
                </div>
            </div>
            <div style="padding: 0" class="col-12">
            </div>
        </div>

</div>
</code>```

JAVASCRIPT:

```<code><script>
        createNesting();

        var example3LeftSortable = new Sortable(example3Left, {
            group: {
                name: 'shared',
                pull: 'clone',
                put: false
            },
            animation: 150,
            onEnd: function (/**Event*/evt, /**Event*/originalEvent) {
                createNesting();
            }
        });

        var example3RightSortable = new Sortable(example3Right, {
            group: {
                name: 'shared',
                pull: false
            },
            animation: 150,
            sort: false
        });

        function createNesting() {
        // Nested demo
        const container = document.querySelector("#example3Right");
        var nestedSortables = [].slice.call(container.querySelectorAll('.nested-sortable'));
        // Loop through each nested sortable element
        for (var i = 0; i < nestedSortables.length; i++) {
            new Sortable(nestedSortables[i], {
                group: {
                    name: 'shared',
                    pull: false
                },
                animation: 150,
                sort: false,
                fallbackOnBody: true,
                swapThreshold: 0.50
            });
            }
        }
</script>
</code>```

Body:
I am looking to allow only certain elements to be nested inside others and I did not managed to do so.

Example: Application element can contain only Container elements. Container only Queries, and Queries different types of Components.

Codepen - Code

HTML:

Container

Query

Component Text

Component Bool

Application

JAVASCRIPT:


问:
SAML Identity Provider's Metadata Expiration
I am building multiple providers based SSO using SAML, I want to cache the metadata from all IDPs which I download from the their respective metadata URLs dynamically. The SAML specs says about "validUntil" and "cacheDuration" as optional details that IDP can include in its metadata XML. I checked none of the IDPs metadata XML includes these details in entity descriptor.

On what basis should I invalidate the cache, what expiration should I use to re-download the metadata.

I am using Ping, AD, Auth0 & Okta. And I could not find in IDPs docs as well, Thanks in advance.


问:
In-app purchase without login/registration system
I need to integrate in-app purchase to an app. It's an app with static content. It can help  user prepare for the fishing license exam. So users can go through all the questions for free, but they can try some sample exams only when they are premium. The app is totally offline and without login/registration system.

Since the users will probably use the app just before passing the exam and they need probably between 1 and 3 months to prepare, it does not make sense to offer an auto-renewable subscription. So my idea is to offer three option:

Unlock premium feature for 1 month. (non auto-renewable subscription
??)

Unlock premium feature for 3 months. (non auto-renewable
subscription ??)

Get a lifetime access. ( non-consumable in-app ??)

So my question is:

Assuming that the first two options will be done via non auto-renewable subscription (let me know if you have another idea). Will it be a problem that my app does not have any registration or login system? Maybe somehow identify the user (if it's really needed? to use the app in the different device with the same AppleID) by just his AppleID (I know that I don't have access to this but maybe StoreKit have this possibility) using StoreKit. And do you see any flaw or technical issue that I can face in my proposed in-app purchase strategy


问:
truffle run verify SomeContractName --network bscTestnet not working
I followed the instructions:
https://docs.bnbchain.org/docs/truffle-new/

Could already deploy the SmartContract and migrate to bscTestnet, but verifying with the plugin truffle-pluging-verify is not working. I get the following error message:

TypeError: (intermediate value).hostname.split(...).at is not a function
at getApiKey (/home/hakikat/SoupTokenterm/node_modules/truffle-plugin-verify/dist/util.js:141:58)
at /home/hakikat/SoupTokenterm/node_modules/truffle-plugin-verify/dist/verify.js:92:41
at Generator.next ()
at fulfilled (/home/hakikat/SoupTokenterm/node_modules/truffle-plugin-verify/dist/verify.js:5:58)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
Truffle v5.5.21 (core: 5.5.21)
Node v12.22.9

I don't know what is the problem here. Can please someone help. I installed all modules.