问:
Why does this test code fail (It works in the application) - using testing-library/react-hooks
I'm having trouble writing test code for this application.  Specifically, the code works in the app - it works exactly the way I want it to.  But with all the crazy mocks and abstractions in the codebase I have to work with, for some reason the tests never seem to pass.

Here is the code I'm hoping to test:

// useLandAccessHistory.ts
import { RequestState, RootState, useAppDispatch, useAppSelector } from '../../../../../store';
import { fetchLandAccessHistory } from '../../../../../extension/LandAccess/module/thunks';
import { LAND_ACCESS_SLICE_NAME } from '../../../../../extension/LandAccess/module/constants';
import { models } from '@h2know-how/moata-land-management-sdk';
import { useEffect, useMemo } from 'react';

const landAccessHistoryTableSelector = (state: RootState) => {
  const landAccess = state[LAND_ACCESS_SLICE_NAME];
  const byTitleId = (titleId: number): models.LandAccessHistory[] | undefined =>
    landAccess.landAccessHistories[titleId];
  const { status, error } = landAccess.apiStatus.fetchLandAccessHistory;
  return { status, error, byTitleId };
};

export const useLandAccessHistory = ({
  projectId,
  titleId,
}: {
  projectId: number;
  titleId: number;
}): { historyData?: models.LandAccessHistory[] } & RequestState => {
  const dispatch = useAppDispatch();

  const { status, error, byTitleId } = useAppSelector(landAccessHistoryTableSelector);

  useEffect(() => {
    const req = dispatch(
      fetchLandAccessHistory({
        projectId,
        titleId,
      })
    );
    return req.abort;
  }, [dispatch, projectId, titleId]);

  const historyData = useMemo(() => byTitleId(titleId), [byTitleId, titleId]);

  return { historyData, status, error };
};
```
<p>And here is the test suite that is failing.</p>
<pre class="lang-js prettyprint-override"><code>// useLandAccessHistory.spec.ts
import React from 'react';
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
import { renderHook } from '@testing-library/react-hooks';
import { waitFor } from '@testing-library/react';
import { useLocation } from 'react-router-dom';

import { useLandAccessHistory } from './useLandAccessHistory';
import { useAppDispatch, useAppSelector } from '../../../../../store';
import { landAccessSlice } from '../../../../../extension/LandAccess/module/landAccess';
import { LAND_ACCESS_SLICE_NAME } from '../../../../../extension/LandAccess/module/constants';
import { useUrlParams, useUrlSearchParams } from '../../../../../utils/hooks';
import { mockLandAccessHistories } from '../../../../../extension/LandAccess/test-helpers/factories';
import { landAccessAPI } from '../../../../../extension/LandAccess/api/landAccessAPI';

const mockHistories = mockLandAccessHistories({ projectId: 123, titleId: 345 }, 2);

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useLocation: jest.fn(),
}));
jest.mock('../../../../../store');
jest.mock('../../../../../utils/hooks', () => ({
  ...jest.requireActual('../../../../../utils/hooks'),
  useUrlParams: jest.fn(),
  useUrlSearchParams: jest.fn(),
}));
jest.mock('../../../../../extension/LandAccess/api/landAccessAPI', () => ({
  getLandAccessHistory: jest.fn(() => Promise.resolve(mockHistories)),
}));

describe('useLandAccessHistory', () => {
  let dispatch: jest.Mock;
  let abort: jest.Mock;
  let store: any;
  let wrapper: any;

  beforeEach(() => {
    (useLocation as jest.Mock).mockReturnValue({ pathname: '/route/123' });
    store = configureStore({
      reducer: { [LAND_ACCESS_SLICE_NAME]: landAccessSlice.reducer },
      middleware: (getDefaultMiddleware) => getDefaultMiddleware(),
    });

    dispatch = jest.fn((...params) => store.dispatch(...params));
    abort = jest.fn();
    dispatch.mockReturnValue({ abort });

    wrapper = ({ children }) => <Provider store={store}>{children}</Provider>;

    (useUrlParams as jest.Mock).mockReturnValue({ projectId: 123 });
    (useUrlSearchParams as jest.Mock).mockReturnValue({ feature_id: 345 });

    (useAppDispatch as jest.Mock).mockReturnValue(dispatch);
    (useAppSelector as jest.Mock).mockImplementation((selectorFunction) => selectorFunction(store.getState()));
  });

  it('fetches the land access history', async () => {
    const { result, rerender } = renderHook(() => useLandAccessHistory({ projectId: 123, titleId: 345 }), { wrapper });
    await waitFor(() => {
      expect(dispatch).toHaveBeenCalled(); // this line runs.
    });
    rerender();
    await waitFor(() => {
      expect(store.getState().landAccessHistories).toEqual(mockHistories); // the store does not contain the data
      expect(result.current).toEqual({ error: null, status: 'fulfilled', historyData: mockHistories }); // the status is idle and history data is undefined
    });
  });
});
</code>```

Here's what I've tried so far: so far as I can tell, dispatch runs, but it doesn't seem to actually call the mocked (or real) API function.  It could be that dispatch has been called but has not yet resolved, but then wouldn't await waitFor and rerender() help solve that problem?

Body:
I'm having trouble writing test code for this application.  Specifically, the code works in the app - it works exactly the way I want it to.  But with all the crazy mocks and abstractions in the codebase I have to work with, for some reason the tests never seem to pass.

Here is the code I'm hoping to test:

// useLandAccessHistory.ts
import { RequestState, RootState, useAppDispatch, useAppSelector } from '../../../../../store';
import { fetchLandAccessHistory } from '../../../../../extension/LandAccess/module/thunks';
import { LAND_ACCESS_SLICE_NAME } from '../../../../../extension/LandAccess/module/constants';
import { models } from '@h2know-how/moata-land-management-sdk';
import { useEffect, useMemo } from 'react';

const landAccessHistoryTableSelector = (state: RootState) => {
  const landAccess = state[LAND_ACCESS_SLICE_NAME];
  const byTitleId = (titleId: number): models.LandAccessHistory[] | undefined =>
    landAccess.landAccessHistories[titleId];
  const { status, error } = landAccess.apiStatus.fetchLandAccessHistory;
  return { status, error, byTitleId };
};

export const useLandAccessHistory = ({
  projectId,
  titleId,
}: {
  projectId: number;
  titleId: number;
}): { historyData?: models.LandAccessHistory[] } & RequestState => {
  const dispatch = useAppDispatch();

  const { status, error, byTitleId } = useAppSelector(landAccessHistoryTableSelector);

  useEffect(() => {
    const req = dispatch(
      fetchLandAccessHistory({
        projectId,
        titleId,
      })
    );
    return req.abort;
  }, [dispatch, projectId, titleId]);

  const historyData = useMemo(() => byTitleId(titleId), [byTitleId, titleId]);

  return { historyData, status, error };
};

And here is the test suite that is failing.

// useLandAccessHistory.spec.ts
import React from 'react';
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
import { renderHook } from '@testing-library/react-hooks';
import { waitFor } from '@testing-library/react';
import { useLocation } from 'react-router-dom';

import { useLandAccessHistory } from './useLandAccessHistory';
import { useAppDispatch, useAppSelector } from '../../../../../store';
import { landAccessSlice } from '../../../../../extension/LandAccess/module/landAccess';
import { LAND_ACCESS_SLICE_NAME } from '../../../../../extension/LandAccess/module/constants';
import { useUrlParams, useUrlSearchParams } from '../../../../../utils/hooks';
import { mockLandAccessHistories } from '../../../../../extension/LandAccess/test-helpers/factories';
import { landAccessAPI } from '../../../../../extension/LandAccess/api/landAccessAPI';

const mockHistories = mockLandAccessHistories({ projectId: 123, titleId: 345 }, 2);

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useLocation: jest.fn(),
}));
jest.mock('../../../../../store');
jest.mock('../../../../../utils/hooks', () => ({
  ...jest.requireActual('../../../../../utils/hooks'),
  useUrlParams: jest.fn(),
  useUrlSearchParams: jest.fn(),
}));
jest.mock('../../../../../extension/LandAccess/api/landAccessAPI', () => ({
  getLandAccessHistory: jest.fn(() => Promise.resolve(mockHistories)),
}));

describe('useLandAccessHistory', () => {
  let dispatch: jest.Mock;
  let abort: jest.Mock;
  let store: any;
  let wrapper: any;

  beforeEach(() => {
    (useLocation as jest.Mock).mockReturnValue({ pathname: '/route/123' });
    store = configureStore({
      reducer: { [LAND_ACCESS_SLICE_NAME]: landAccessSlice.reducer },
      middleware: (getDefaultMiddleware) => getDefaultMiddleware(),
    });

    dispatch = jest.fn((...params) => store.dispatch(...params));
    abort = jest.fn();
    dispatch.mockReturnValue({ abort });

    wrapper = ({ children }) => <Provider store={store}>{children}</Provider>;

    (useUrlParams as jest.Mock).mockReturnValue({ projectId: 123 });
    (useUrlSearchParams as jest.Mock).mockReturnValue({ feature_id: 345 });

    (useAppDispatch as jest.Mock).mockReturnValue(dispatch);
    (useAppSelector as jest.Mock).mockImplementation((selectorFunction) => selectorFunction(store.getState()));
  });

  it('fetches the land access history', async () => {
    const { result, rerender } = renderHook(() => useLandAccessHistory({ projectId: 123, titleId: 345 }), { wrapper });
    await waitFor(() => {
      expect(dispatch).toHaveBeenCalled(); // this line runs.
    });
    rerender();
    await waitFor(() => {
      expect(store.getState().landAccessHistories).toEqual(mockHistories); // the store does not contain the data
      expect(result.current).toEqual({ error: null, status: 'fulfilled', historyData: mockHistories }); // the status is idle and history data is undefined
    });
  });
});

Here's what I've tried so far: so far as I can tell, dispatch runs, but it doesn't seem to actually call the mocked (or real) API function.  It could be that dispatch has been called but has not yet resolved, but then wouldn't await waitFor and rerender() help solve that problem?


来源: stackexchange

问:
What is the System.Text.Json alternative to XmlElementAttribute("Emp", GetType(Employee))
I have a class as below with the property of type object. Earlier I used to assign class dynamically to object property Item as below using XmlElementAttribute.

```<code>   [Serializable]

   public class Employee
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }
    }

    [Serializable]
    public class Department
    {
        public int DepartmentID { get; set; }
        public string DepartmentName { get; set; }
    }

    [Serializable]
    public class ParentClass
    {
        public string Location { get; set; }

        [System.Xml.Serialization.XmlElementAttribute("Emp", GetType(Employee)), System.Xml.Serialization.XmlElementAttribute("Dept", GetType(Department))]
        public object Item { get; set; }
    }

</code>```

Here is XML data containing property Emp, then automatically Employee class get assigned to the Item property of  ParentClass.

I want to have similar functionality with System.Text.Json.

Is there any alternative for XmlElementAttribute("Emp", GetType(Employee)) in json like  below

```<code>  [System.Text.Json.JsonPropertyName["Emp", GetType(Employee))]]
</code>```

I have JSON input below

```<code>{
"Location": "Chicago",
"Emp": {
    "EmployeeID":123,
    "EmployeeName":"Peter"
}
}

</code>```

Here since my JSON property name is Emp, I want to assign the Employee type dynamically to the object Item property of ParentClass.

```<code>{

"Location": "NJ",
"Dept": {
    "DepartmentID":567,
    "DepartmentName":"IT"
}
}
</code>```

Similarly, if I have JSON data as above, I want to assign Department type to the object property Item of ParentClass.

Kindly suggest any solution for this.

When I googled, I'm able to find only below

```<code>    [JsonPropertyName("Wind")]

</code>```

But I want to bind type dynamically similar to  XmlElementAttribute("Emp", GetType(Employee))

ContentLicense: CC BY-SA 4.0

Body:
I have a class as below with the property of type object. Earlier I used to assign class dynamically to object property Item as below using XmlElementAttribute.

   [Serializable]

   public class Employee
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }
    }

    [Serializable]
    public class Department
    {
        public int DepartmentID { get; set; }
        public string DepartmentName { get; set; }
    }

    [Serializable]
    public class ParentClass
    {
        public string Location { get; set; }

        [System.Xml.Serialization.XmlElementAttribute("Emp", GetType(Employee)), System.Xml.Serialization.XmlElementAttribute("Dept", GetType(Department))]
        public object Item { get; set; }
    }

Here is XML data containing property Emp, then automatically Employee class get assigned to the Item property of  ParentClass.

I want to have similar functionality with System.Text.Json.

Is there any alternative for XmlElementAttribute("Emp", GetType(Employee)) in json like  below

  [System.Text.Json.JsonPropertyName["Emp", GetType(Employee))]]

I have JSON input below

{
"Location": "Chicago",
"Emp": {
    "EmployeeID":123,
    "EmployeeName":"Peter"
}
}

Here since my JSON property name is Emp, I want to assign the Employee type dynamically to the object Item property of ParentClass.

{

"Location": "NJ",
"Dept": {
    "DepartmentID":567,
    "DepartmentName":"IT"
}
}

Similarly, if I have JSON data as above, I want to assign Department type to the object property Item of ParentClass.

Kindly suggest any solution for this.

When I googled, I'm able to find only below

    [JsonPropertyName("Wind")]

But I want to bind type dynamically similar to  XmlElementAttribute("Emp", GetType(Employee))


问:
How to return mysql data from custom js funtion in node.js
here is my function in egallery.js

```<code>var conn = require('./conn.js');

function getAllUrls () {
    console.log('sdfsadfsaf');
    var result;
    conn.connect();

    conn.query('Select * from ray_url', function(err, rows, fields) {

        if (err) throw err;
        result = rows;
        //console.log(err);
        //console.log(rows);
        return rows;
    });

    conn.end();

}

module.exports = {
    getAllUrls
};
</code>```

in app.js, the console output is undefined.

```<code>let app = require('express')();
var egallery = require('./models/egallery.js');
rows = egallery.getAllUrls();
console.log(rows); //undefined
app.set('view engine', 'ejs');
app.get('/e', function (req, res) {
    //res.send("Hello, welcome to our app")
    console.log(rows);
    res.render('pages/index', {rows : rows});
})

// about page
app.get('/e/about', function(req, res) {
    res.render('pages/about');
});
app.listen(3000,'0.0.0.0')
</code>```

-------------------update changed to use async & promise---------------

egallery.js

```<code>var conn = require('./conn.js');
conn.connect();

function getAllUrls () {

    return new Promise((resolve, reject) => {
        conn.query(
            "Select * from ray_url",
            (err, result) => {
                return err ? reject(err) : resolve(result)
            }
        )
    })
}
conn.end();
module.exports = {
    getAllUrls
};
</code>```

app.js

```<code>let app = require('express')();
var egallery = require('./models/egallery.js');

app.set('view engine', 'ejs');
app.get('/e', async  (req, res) => {

    rows = await egallery.getAllUrls();
    console.log(rows);

    res.render('pages/index', {rows : rows});
})

// about page
app.get('/e/about', function(req, res) {
    res.render('pages/about');
});
app.listen(3000,'0.0.0.0')
</code>```

------------error------------

```<code>    const err = new Error(
                ^

Error: Can't add new command when connection is in closed state
    at Connection._addCommandClosedState (/home/opc/docker/src/html/e/node_modules/mysql2/lib/connection.js:148:17)
    at Connection.query (/home/opc/docker/src/html/e/node_modules/mysql2/lib/connection.js:546:17)
    at /home/opc/docker/src/html/e/models/egallery.js:7:14
    at new Promise (<anonymous>)
    at Object.getAllUrls (/home/opc/docker/src/html/e/models/egallery.js:6:12)
    at /home/opc/docker/src/html/e/app.js:7:27
    at Layer.handle [as handle_request] (/home/opc/docker/src/html/e/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/opc/docker/src/html/e/node_modules/express/lib/router/route.js:144:13)
    at Route.dispatch (/home/opc/docker/src/html/e/node_modules/express/lib/router/route.js:114:3)
    at Layer.handle [as handle_request] (/home/opc/docker/src/html/e/node_modules/express/lib/router/layer.js:95:5) {
  fatal: true
}

Node.js v18.9.1
</code>```

Body:
here is my function in egallery.js

var conn = require('./conn.js');

function getAllUrls () {
    console.log('sdfsadfsaf');
    var result;
    conn.connect();

    conn.query('Select * from ray_url', function(err, rows, fields) {

        if (err) throw err;
        result = rows;
        //console.log(err);
        //console.log(rows);
        return rows;
    });

    conn.end();

}

module.exports = {
    getAllUrls
};

in app.js, the console output is undefined.

let app = require('express')();
var egallery = require('./models/egallery.js');
rows = egallery.getAllUrls();
console.log(rows); //undefined
app.set('view engine', 'ejs');
app.get('/e', function (req, res) {
    //res.send("Hello, welcome to our app")
    console.log(rows);
    res.render('pages/index', {rows : rows});
})

// about page
app.get('/e/about', function(req, res) {
    res.render('pages/about');
});
app.listen(3000,'0.0.0.0')

-------------------update changed to use async & promise---------------

egallery.js

var conn = require('./conn.js');
conn.connect();

function getAllUrls () {

    return new Promise((resolve, reject) => {
        conn.query(
            "Select * from ray_url",
            (err, result) => {
                return err ? reject(err) : resolve(result)
            }
        )
    })
}
conn.end();
module.exports = {
    getAllUrls
};

app.js

let app = require('express')();
var egallery = require('./models/egallery.js');

app.set('view engine', 'ejs');
app.get('/e', async  (req, res) => {

    rows = await egallery.getAllUrls();
    console.log(rows);

    res.render('pages/index', {rows : rows});
})

// about page
app.get('/e/about', function(req, res) {
    res.render('pages/about');
});
app.listen(3000,'0.0.0.0')

------------error------------

    const err = new Error(
                ^

Error: Can't add new command when connection is in closed state
    at Connection._addCommandClosedState (/home/opc/docker/src/html/e/node_modules/mysql2/lib/connection.js:148:17)
    at Connection.query (/home/opc/docker/src/html/e/node_modules/mysql2/lib/connection.js:546:17)
    at /home/opc/docker/src/html/e/models/egallery.js:7:14
    at new Promise (<anonymous>)
    at Object.getAllUrls (/home/opc/docker/src/html/e/models/egallery.js:6:12)
    at /home/opc/docker/src/html/e/app.js:7:27
    at Layer.handle [as handle_request] (/home/opc/docker/src/html/e/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/opc/docker/src/html/e/node_modules/express/lib/router/route.js:144:13)
    at Route.dispatch (/home/opc/docker/src/html/e/node_modules/express/lib/router/route.js:114:3)
    at Layer.handle [as handle_request] (/home/opc/docker/src/html/e/node_modules/express/lib/router/layer.js:95:5) {
  fatal: true
}

Node.js v18.9.1


问:
Yarn install is not working, terminal looks: There appears to be trouble with your network connection. Retrying
I have a problem with yarn install on the server. Before I tried simply yarn install and it did not work. After I tried yarn install --network -timeout=30000 and the same result. It got stuck here. How can i solve it? Also my internet connection is very good.

[3/5] Fetching packages...


问:
Form required fields not working when disabling submit for a few seconds
I have a submit form that needs to be disabled for a few seconds because some users are clicking more than one time since it takes a while to load, sending the request more than once.

Searching on here I have found the next code:

```<code>function disableSubmit(){
submit.value = 'Sending...';
document.getElementById("submit").disabled = true;
setTimeout(
    function(){
        document.getElementById("submit").disabled = false;
        submit.value = 'Send';
    },
    5000);
}

const submit = document.getElementById("submit");
submit.addEventListener("click", disableSubmit);
</code>```

I have made some additions to also change the text. The thing is that by doing this you can click the submit button without completing the fields (name, email... etc). The normal behavior is that it will throw an alert telling you need to complete this fields if they are empty, but after my personalized function the required fields are not required anymore. Any ideas? I guess it needs to take the submit normal functioning first and then my personalized function. How can I achieve this goal? Thanks

Body:
I have a submit form that needs to be disabled for a few seconds because some users are clicking more than one time since it takes a while to load, sending the request more than once.

Searching on here I have found the next code:

function disableSubmit(){
submit.value = 'Sending...';
document.getElementById("submit").disabled = true;
setTimeout(
    function(){
        document.getElementById("submit").disabled = false;
        submit.value = 'Send';
    },
    5000);
}

const submit = document.getElementById("submit");
submit.addEventListener("click", disableSubmit);

I have made some additions to also change the text. The thing is that by doing this you can click the submit button without completing the fields (name, email... etc). The normal behavior is that it will throw an alert telling you need to complete this fields if they are empty, but after my personalized function the required fields are not required anymore. Any ideas? I guess it needs to take the submit normal functioning first and then my personalized function. How can I achieve this goal? Thanks


问:
ERROR: Error processing tar file(exit status 1): write /media/tv/mytv/24.avi: no space left on device
Im obtaining this error in docker-compose up -d command execution. My docker-compose.yml looks like this:

```<code>version: '3'

services:
  plex:
    container_name: plex
    build: .
    network_mode: host
    environment:
      - PUID=1000
      - PGID=1000
      - VERSION=docker
    volumes:
      - /home/pi/docker/Plex/media/config:/config
      - /home/pi/docker/Plex/media/tv:/tv
      - /home/pi/docker/Plex/media/movies:/movies
    restart: unless-stopped
</code>```

and my Dockerfile:

```<code>FROM lscr.io/linuxserver/plex:latest
</code>```

My docker system is clean. I have executed docker system prune --all --volumes --force so I havent no cache, no images, no volumes, etc... to delete.

It seems to me that when building the image, docker tries to copy all the library multimedia contents of my folders somehow and that's why it appears that it has no space, but it is something that is beyond my knowledge.

In addition, with this image something happens to me that does not happen to me with the others, and that is that it takes a loooong time to build. The other images are built immediately.

Any help or recommendation?

Thanks in advance.

Body:
Im obtaining this error in docker-compose up -d command execution. My docker-compose.yml looks like this:

version: '3'

services:
  plex:
    container_name: plex
    build: .
    network_mode: host
    environment:
      - PUID=1000
      - PGID=1000
      - VERSION=docker
    volumes:
      - /home/pi/docker/Plex/media/config:/config
      - /home/pi/docker/Plex/media/tv:/tv
      - /home/pi/docker/Plex/media/movies:/movies
    restart: unless-stopped

and my Dockerfile:

FROM lscr.io/linuxserver/plex:latest

My docker system is clean. I have executed docker system prune --all --volumes --force so I havent no cache, no images, no volumes, etc... to delete.

It seems to me that when building the image, docker tries to copy all the library multimedia contents of my folders somehow and that's why it appears that it has no space, but it is something that is beyond my knowledge.

In addition, with this image something happens to me that does not happen to me with the others, and that is that it takes a loooong time to build. The other images are built immediately.

Any help or recommendation?

Thanks in advance.


问:
How to map in JPA a field that can hold a foreign key to on of two tables?
I have the following DB tables: Teacher and Student. They contain a few common fields I would like to hold in my java code in a Person class, which will be the parent class of my Teacher and Student entities. I also have an Event table, that contains an organizer field. The organizer field contains the id of either a Teacher or a Student.

The question is, can this be mapped in a way that the event contains a Person type as organizer? If not, what other options do I have?

Of course, there are plenty of solutions that require me to query the organizer separately from the event, I would like to avoid that.


问:
Airflow exception when using SparkSubmitOperator env_vars not supported in standalone-cluster
My infrastructure, as following:

Spark cluster

Airflow cluster

both in the same cloud (OpenShift), but different namespaces.

Airflow UI/Admin/Connections/spark content:

```<code>Connection ID: spark
Connection Type: spark
Description: blank
Host: spark://master
Port: 7077
Extras: {"queue": "root.default", "master": "spark://master:7077", "deploy-mode": "cluster", "spark_binary": "/usr/local/spark/bin/spark-submit", "namespace": "default"}
</code>```

Airflow DAG file content:

```<code>
spark_submit_local = SparkSubmitOperator(
    application ='/opt/airflow/dags/repo/dags/airflow-pyspark-app.py' ,
    conn_id= 'spark',
    spark_binary='spark-submit',
    task_id= 'spark_submit_task',
    name='airflow-pyspark-test',
    verbose=True,
    dag=dag
)
</code>```

When running via the Airflow UI, the following Airflow Exception is being thrown:

```<code>airflow.exceptions.AirflowException: SparkSubmitHook env_vars is not supported in standalone-cluster mode.
</code>```

There are a few AIRFLOW_CTX environment variables loaded at the start:

```<code>[2022-12-07, 12:50:32 UTC] {taskinstance.py:1590} INFO - Exporting the following env vars:
AIRFLOW_CTX_DAG_OWNER=airflow
AIRFLOW_CTX_DAG_ID=airflow-pyspark-test
AIRFLOW_CTX_TASK_ID=spark_submit_task
AIRFLOW_CTX_EXECUTION_DATE=2022-12-07T12:50:29.450280+00:00
AIRFLOW_CTX_TRY_NUMBER=1
AIRFLOW_CTX_DAG_RUN_ID=manual__2022-12-07T12:50:29.450280+00:00
AIRFLOW_CTX_UID=5d5607d2-0396-51eb-abb2-ab7d3bd96f49
</code>```

My questions are:

How to resolve this issue when trying to make Airflow DAG to run a file containing SparkSubmitOperator (to the cluster)?

If I remove the environment variables loaded at start (e.g. AIRLFOW_CTX_*) will it break Airflow? Or should I expect that to resolve the issue?

Is there anything else I can do to make it work with environment variables? (There are some other env variables I want to pass for spark-submit, for reporting to another service.)

Body:
My infrastructure, as following:

Spark cluster

Airflow cluster

both in the same cloud (OpenShift), but different namespaces.

Airflow UI/Admin/Connections/spark content:

Connection ID: spark
Connection Type: spark
Description: blank
Host: spark://master
Port: 7077
Extras: {"queue": "root.default", "master": "spark://master:7077", "deploy-mode": "cluster", "spark_binary": "/usr/local/spark/bin/spark-submit", "namespace": "default"}

Airflow DAG file content:

spark_submit_local = SparkSubmitOperator(
    application ='/opt/airflow/dags/repo/dags/airflow-pyspark-app.py' ,
    conn_id= 'spark',
    spark_binary='spark-submit',
    task_id= 'spark_submit_task',
    name='airflow-pyspark-test',
    verbose=True,
    dag=dag
)

When running via the Airflow UI, the following Airflow Exception is being thrown:

airflow.exceptions.AirflowException: SparkSubmitHook env_vars is not supported in standalone-cluster mode.

There are a few AIRFLOW_CTX environment variables loaded at the start:

[2022-12-07, 12:50:32 UTC] {taskinstance.py:1590} INFO - Exporting the following env vars:
AIRFLOW_CTX_DAG_OWNER=airflow
AIRFLOW_CTX_DAG_ID=airflow-pyspark-test
AIRFLOW_CTX_TASK_ID=spark_submit_task
AIRFLOW_CTX_EXECUTION_DATE=2022-12-07T12:50:29.450280+00:00
AIRFLOW_CTX_TRY_NUMBER=1
AIRFLOW_CTX_DAG_RUN_ID=manual__2022-12-07T12:50:29.450280+00:00
AIRFLOW_CTX_UID=5d5607d2-0396-51eb-abb2-ab7d3bd96f49

My questions are:

How to resolve this issue when trying to make Airflow DAG to run a file containing SparkSubmitOperator (to the cluster)?

If I remove the environment variables loaded at start (e.g. AIRLFOW_CTX_*) will it break Airflow? Or should I expect that to resolve the issue?

Is there anything else I can do to make it work with environment variables? (There are some other env variables I want to pass for spark-submit, for reporting to another service.)


问:
gcloud identity groups memberships list command not working in github actions
I am trying to list members of google group with follow command, however same command is working when run from cloud sdk on my local machine

C:\Program Files (x86)\Google\Cloud SDK>gcloud   --project=projectID identity groups memberships list --group-email="groupemail"

When above command is ran from github actions, it throws following error

ERROR: (gcloud.identity.groups.memberships.list) Invalid value for [--group-email]: There is no such a group associated with the specified argument:'groupemail mentioned in command'

Need suggestion on this behavior.

I am trying to list members of google group with follow command, however same command is working when run from cloud sdk on my local machine

C:\Program Files (x86)\Google\Cloud SDK>gcloud   --project=projectID identity groups memberships list --group-email="groupemail"

When above command is ran from github actions, it throws following error

ERROR: (gcloud.identity.groups.memberships.list) Invalid value for [--group-email]: There is no such a group associated with the specified argument:'groupemail mentioned in command'

Need suggestion on this behavior.


问:
How to truncate Materialize CSS chip text while still showing Close Icon?

        Big text that keeps overflowing out of the div chip
        close

        Test
        close

    <input class="input" placeholder="Type & Press Enter">

```

Tried ellipsis text overflow, but that truncates the close icon  too. What can be done to truncate the text alone. This is materialise chips, so can only use CSS to manipulate these properties.

Body:
        Big text that keeps overflowing out of the div chip
        close

        Test
        close

    <input class="input" placeholder="Type & Press Enter">

Tried ellipsis text overflow, but that truncates the close icon  too. What can be done to truncate the text alone. This is materialise chips, so can only use CSS to manipulate these properties.


问:
Setting up notifications for a Flutter PWA
Trying to set up Firebase Cloud Messaging for a Flutter PWA but I don't know how to show the notifications. The PWA installs on a mobile phone just like a native app from the browser, so I would like to have mobile notifications. When app is closed tapping on the notification would open it and so on. Not looking for showDialog or anything like that.

I set up a firebase-messaging-sw.js file in the web directory

```<code>importScripts("https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js");

firebase.initializeApp({
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
});

const messaging = firebase.messaging();

messaging.onBackgroundMessage((message) => {
    console.log("onBackgroundMessage", message);
});

</code>```

And imported it in index.html

```<code><body>
  <script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function (ev) {

        _flutter.loader.loadEntrypoint({
          serviceWorker: {
            serviceWorkerVersion: serviceWorkerVersion,
          }
        }).then(function (engineInitializer) {
          return engineInitializer.initializeEngine();
        }).then(function (appRunner) {
          return appRunner.runApp();
        });

        navigator.serviceWorker.register('firebase-messaging-sw.js');
        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
      });
    }
  </script>
</body>
</code>```

I also have these in the main.dart file

```<code>    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Got a message whilst in the foreground!');
      print('Message data: ${message.data}');

      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification}');
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('A new onMessageOpenedApp event was published!');
    });
</code>```

I'm able to get the fcmToken and save it to Firestore ... and when I send a test notification I see the print messages from the above listener ... but don't know how to create the notification. I am only interested in the mobile notification, no in-app notification is required. Just the top bar notification.

Body:
Trying to set up Firebase Cloud Messaging for a Flutter PWA but I don't know how to show the notifications. The PWA installs on a mobile phone just like a native app from the browser, so I would like to have mobile notifications. When app is closed tapping on the notification would open it and so on. Not looking for showDialog or anything like that.

I set up a firebase-messaging-sw.js file in the web directory

importScripts("https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js");

firebase.initializeApp({
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
});

const messaging = firebase.messaging();

messaging.onBackgroundMessage((message) => {
    console.log("onBackgroundMessage", message);
});

And imported it in index.html

I also have these in the main.dart file

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Got a message whilst in the foreground!');
      print('Message data: ${message.data}');

      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification}');
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('A new onMessageOpenedApp event was published!');
    });

I'm able to get the fcmToken and save it to Firestore ... and when I send a test notification I see the print messages from the above listener ... but don't know how to create the notification. I am only interested in the mobile notification, no in-app notification is required. Just the top bar notification.


问:
After saving file using openpyxl i lost computing formulas
I have some formulas in my excel file and I need to put to this file data using python. I use openpyxl because i think this library is the most appropriate. The problem is when I wrote this file using openpyxl and I want to open this file again formulas which are inside doesn't compute and when I use Data Only mode I see "NaN" value, without this mode I see string with this formula.
How can I read value of this formula?

I tried to use other libraries but It still doesn't working.

```<code>dec1 = pd.read_excel(path).iloc[26, 10]

str_dat2 = datetime.now()
exe_app = xw.App(visible=False)
xlwb = xw.Book(path)
xlwb.sheets['HURT'].range("C17").value = 'BASE_Q-1-23'
xlwb.sheets['HURT'].range("E17").value = 0.25
xlwb.sheets['HURT'].range("F17").value = 1500
xlwb.save(path)
xlwb.close()
exe_app.quit()
stp_dat3 = datetime.now()-str_dat2
dec3 = pd.read_excel(path).iloc[26, 10]

str_dat1 = datetime.now()
wb = load_workbook(filename=path, read_only=False, keep_vba=True)
ws = wb['HURT']
ws['C17'] = 'BASE_Q-1-23'
ws['E17'] = 0.25
ws['F17'] = 1500
wb.save(path)
stp_dat2 = datetime.now()-str_dat1
dec2 = pd.read_excel(path).iloc[26, 10]

</code>```
```<code>Before changing file (value): NIE
Before changing file (formula): =IF(J22=100%,IF(AND($F$15<>"",J27>0),"TAK","NIE"),"NIE")

After changing file (openpyxl): nan it lasted: 0:00:00.166674
After changing file (xlwings): TAK it lasted: 0:00:02.496538
</code>```

Body:
I have some formulas in my excel file and I need to put to this file data using python. I use openpyxl because i think this library is the most appropriate. The problem is when I wrote this file using openpyxl and I want to open this file again formulas which are inside doesn't compute and when I use Data Only mode I see "NaN" value, without this mode I see string with this formula.
How can I read value of this formula?

I tried to use other libraries but It still doesn't working.

dec1 = pd.read_excel(path).iloc[26, 10]

str_dat2 = datetime.now()
exe_app = xw.App(visible=False)
xlwb = xw.Book(path)
xlwb.sheets['HURT'].range("C17").value = 'BASE_Q-1-23'
xlwb.sheets['HURT'].range("E17").value = 0.25
xlwb.sheets['HURT'].range("F17").value = 1500
xlwb.save(path)
xlwb.close()
exe_app.quit()
stp_dat3 = datetime.now()-str_dat2
dec3 = pd.read_excel(path).iloc[26, 10]

str_dat1 = datetime.now()
wb = load_workbook(filename=path, read_only=False, keep_vba=True)
ws = wb['HURT']
ws['C17'] = 'BASE_Q-1-23'
ws['E17'] = 0.25
ws['F17'] = 1500
wb.save(path)
stp_dat2 = datetime.now()-str_dat1
dec2 = pd.read_excel(path).iloc[26, 10]

Before changing file (value): NIE
Before changing file (formula): =IF(J22=100%,IF(AND($F$15<>"",J27>0),"TAK","NIE"),"NIE")

After changing file (openpyxl): nan it lasted: 0:00:00.166674
After changing file (xlwings): TAK it lasted: 0:00:02.496538


问:
Find class origin within IntelliJ Idea
I would like to find the library specification for a class opened in the editor. I have a Maven project which is quite big with a lot of modules. When I navigate to a class which is referenced from the source code I can see a module origin in the title bar of Intellij Idea like this "HttpServlet [Maven: org.apache..."

However I am not able to see where exactly this Maven library is included from, I can guess this example above as part of an Web Service and I can think of where it is nested in, but this is a hard process sometimes especially if it is a nested include somewhere...

Title: Find class origin within IntelliJ Idea


问:
Selenium, how to get network request response data?
Is there a way to access chrome Network's request and response api calls data using selenium 3?

I saw few responses based on selenium 4 Chrome dev tools, but I doubt it would be of any help.


问:
Use readline.question after getting a raw key
I'm trying to do the following two things sequentially in a Node.js app:

Get an arbitrary key as user input. (could be a character pressed, or any other key like arrow up/down...)

I'd like to ask the user for an arbitrary text input.

Each step works but if I chain them, the key entered first is always appended to the second input. Additionally the question is written to the console twice.

Here's the full code sample:

```<code>// sample.js

const readline = require("readline")

// Read a raw key from stdin as Promise
const getKey = () => new Promise((res) => {
    process.stdin.setRawMode(true)

    process.stdin.once('keypress', (str, key) => {
        process.stdin.setRawMode(false)
        res(key)
    });
})

// Just promisify the "question" method
const getText = (interface, str) =>
    new Promise(res => interface.question(str, res))

const main = async () => {

    readline.emitKeypressEvents(process.stdin);

    const interface = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    console.log("Press a key!")
    const key = await getKey()
    console.log(`\nYou pressed key "${key.name}"`)

    const name = await getText(interface, "What's your name?\n")
    console.log(`Your name is "${name}"`)
}

main()
</code>```

And here's a sample CLI session screencast:

The expected behavior would be that those inputs don't interfere with eachother. Does anyone have a solution for this problem?

My assumtion was that the character from the first input is still unconsumed inside the stdin stream. But attempts to force to consume it were not successfull.

Body:
I'm trying to do the following two things sequentially in a Node.js app:

Get an arbitrary key as user input. (could be a character pressed, or any other key like arrow up/down...)

I'd like to ask the user for an arbitrary text input.

Each step works but if I chain them, the key entered first is always appended to the second input. Additionally the question is written to the console twice.

Here's the full code sample:

// sample.js

const readline = require("readline")

// Read a raw key from stdin as Promise
const getKey = () => new Promise((res) => {
    process.stdin.setRawMode(true)

    process.stdin.once('keypress', (str, key) => {
        process.stdin.setRawMode(false)
        res(key)
    });
})

// Just promisify the "question" method
const getText = (interface, str) =>
    new Promise(res => interface.question(str, res))

const main = async () => {

    readline.emitKeypressEvents(process.stdin);

    const interface = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    console.log("Press a key!")
    const key = await getKey()
    console.log(`\nYou pressed key "${key.name}"`)

    const name = await getText(interface, "What's your name?\n")
    console.log(`Your name is "${name}"`)
}

main()

And here's a sample CLI session screencast:

The expected behavior would be that those inputs don't interfere with eachother. Does anyone have a solution for this problem?

My assumtion was that the character from the first input is still unconsumed inside the stdin stream. But attempts to force to consume it were not successfull.


问:
Android Studio Composite Build
we have an android app and an android library. Now I want to rework some stuff in the lib and want the app to be also reworked (e.g. rename method etc.)

I found gradle composite builds. I was not able to use the little + button (link gradle project) in the gradle toolbar, as it is in IntelliJ. But I could make it work by using the

```<code>includeBuild ../android-lib
</code>```

directive in settings.gradle

I also tried to add the dependency in the root build.gradle as follows:

```<code>tasks.register('run') {
    dependsOn gradle.includedBuild('../android-lib').task(':app:run')
}
</code>```

The Lib is added in my projects/android tree and is also visible in gradle toolbar.
BUT it is not found in "show usages". Also, changes in the libary do not cause any compile errors in the root app.

I know this feature from eclipse ("workspace resultution"). Can't really believe that it is so hard to achieve in android studio?

Edit: found this old question, but at that time, the conposite build was just added and android studio was still eclipse-based: Android Studio nested composite build - plugin com.android.library not found

Edit2: Also tried to define the depencendy replacement:

```<code>//settings.gradle
includeBuild('../android-library') {
    dependencySubstitution {
        substitute module('de.example.android-lib:android-lib') with project(':android-lib')
    }
}
</code>```

Edit3:
File -> New -> Import Module ... does also not work. This copies the files from the library's git into the app's repom which I definitely don't want.

Title: Android Studio Composite Build

Body:
we have an android app and an android library. Now I want to rework some stuff in the lib and want the app to be also reworked (e.g. rename method etc.)

I found gradle composite builds. I was not able to use the little + button (link gradle project) in the gradle toolbar, as it is in IntelliJ. But I could make it work by using the

includeBuild ../android-lib

directive in settings.gradle

I also tried to add the dependency in the root build.gradle as follows:

tasks.register('run') {
    dependsOn gradle.includedBuild('../android-lib').task(':app:run')
}

The Lib is added in my projects/android tree and is also visible in gradle toolbar.
BUT it is not found in "show usages". Also, changes in the libary do not cause any compile errors in the root app.

I know this feature from eclipse ("workspace resultution"). Can't really believe that it is so hard to achieve in android studio?

Edit: found this old question, but at that time, the conposite build was just added and android studio was still eclipse-based: Android Studio nested composite build - plugin com.android.library not found

Edit2: Also tried to define the depencendy replacement:

//settings.gradle
includeBuild('../android-library') {
    dependencySubstitution {
        substitute module('de.example.android-lib:android-lib') with project(':android-lib')
    }
}

Edit3:
File -> New -> Import Module ... does also not work. This copies the files from the library's git into the app's repom which I definitely don't want.


问:
How can i create a new folder and copy specific types of files in it , in my CI/CD pipeline
I am running a CI/CD pipeline on gitlab and in deployement I want to create a new folder which will copy whole directory structure but only .pyc files in it

This is my deploy job code

```<code>
deploy-job:      # This job runs in the deploy stage.
  stage: deploy  # It only runs when *both* jobs in the test stage complete successfully.
  environment: production
  script:
    - mkdir trial
    - find . -name '*.pyc' -exec cp --parents \{\} ~/trial \;
    - echo "files successfully delivered."

</code>```

Is it possible to create a new directory in my gitlab repository with the given requirements ?

Body:
I am running a CI/CD pipeline on gitlab and in deployement I want to create a new folder which will copy whole directory structure but only .pyc files in it

This is my deploy job code

deploy-job:      # This job runs in the deploy stage.
  stage: deploy  # It only runs when *both* jobs in the test stage complete successfully.
  environment: production
  script:
    - mkdir trial
    - find . -name '*.pyc' -exec cp --parents \{\} ~/trial \;
    - echo "files successfully delivered."

Is it possible to create a new directory in my gitlab repository with the given requirements ?


问:
How to invoke a C# method in JS from an MAUI WebView and vice-versa
I want to call a method in Javascript that invokes C# code in an MAUI WebView and vice-versa, I cannot find any documentation on this.

I have looked at the following issue on github but it did not help me.

How do I do such interop?


问:
How to add counter & Avg Number of results per minute in python
I have this code where I randomly generate mnemonic seeds and get the Eth address.

so I want to stick my counter and Avg Number of results per minute so that after I print. It will show me how many Ether addresses I have generated and if possible it will also show avg number of results I am getting per minute like 100 ether addresses per minute.

(I am using 2 mnemonics because I want to increase it's speed)

It's the first time I am posting an issue here so I hope I am able to convey my issue properly

```<code># import threading
from hdwallet import BIP44HDWallet
from hdwallet.cryptocurrencies import EthereumMainnet
from hdwallet.derivations import BIP44Derivation
from hdwallet.utils import generate_mnemonic
from typing import Optional
from requests import get
import requests

while True:

    #Generate Mnemonic 12 words
    mnemonic1: str = generate_mnemonic(language="english", strength=128)
    mnemonic2: str = generate_mnemonic(language="english", strength=128

    #Generate ETH Address from Mnemonic
    bip44_hdwallet: BIP44HDWallet = BIP44HDWallet(symbol=ETH, account=0, change=False, address=0)
    bip44_hdwallet.from_mnemonic(mnemonic=mnemonic1)
    ETH1_address = bip44_hdwallet.address()

    #Generate ETH Address from Mnemonic
    bip44_hdwallet: BIP44HDWallet = BIP44HDWallet(symbol=ETH, account=0, change=False, address=0)
    bip44_hdwallet.from_mnemonic(mnemonic=mnemonic2)
    ETH2_address = bip44_hdwallet.address()

    print("Mnemonic1 =", (mnemonic1) , "\nMnemonic2 =", (mnemonic2))
    print("ETH1_address =", (ETH1_address) , "\nETH2_address =", (ETH2_address))

-----------------------------------Output I Want ---------------------------------

mnemonic1 = seed .......
Mnemonic2 = seed2 .......
ETH1_address = Eth address .......
ETH2_address = Eth address2 ........

Counter Stick here
Counter = #No of its printing like in above its 2 address
Avg Result/Min = #If possible
</code>```

Body:
I have this code where I randomly generate mnemonic seeds and get the Eth address.

so I want to stick my counter and Avg Number of results per minute so that after I print. It will show me how many Ether addresses I have generated and if possible it will also show avg number of results I am getting per minute like 100 ether addresses per minute.

(I am using 2 mnemonics because I want to increase it's speed)

It's the first time I am posting an issue here so I hope I am able to convey my issue properly

# import threading
from hdwallet import BIP44HDWallet
from hdwallet.cryptocurrencies import EthereumMainnet
from hdwallet.derivations import BIP44Derivation
from hdwallet.utils import generate_mnemonic
from typing import Optional
from requests import get
import requests

while True:

    #Generate Mnemonic 12 words
    mnemonic1: str = generate_mnemonic(language="english", strength=128)
    mnemonic2: str = generate_mnemonic(language="english", strength=128

    #Generate ETH Address from Mnemonic
    bip44_hdwallet: BIP44HDWallet = BIP44HDWallet(symbol=ETH, account=0, change=False, address=0)
    bip44_hdwallet.from_mnemonic(mnemonic=mnemonic1)
    ETH1_address = bip44_hdwallet.address()

    #Generate ETH Address from Mnemonic
    bip44_hdwallet: BIP44HDWallet = BIP44HDWallet(symbol=ETH, account=0, change=False, address=0)
    bip44_hdwallet.from_mnemonic(mnemonic=mnemonic2)
    ETH2_address = bip44_hdwallet.address()

    print("Mnemonic1 =", (mnemonic1) , "\nMnemonic2 =", (mnemonic2))
    print("ETH1_address =", (ETH1_address) , "\nETH2_address =", (ETH2_address))

-----------------------------------Output I Want ---------------------------------

mnemonic1 = seed .......
Mnemonic2 = seed2 .......
ETH1_address = Eth address .......
ETH2_address = Eth address2 ........

Counter Stick here
Counter = #No of its printing like in above its 2 address
Avg Result/Min = #If possible


问:
Trying to inject @Sessionscoped CDI with a null result
i have tried to research information about that topic without any results. And I dont know what im doing wrong.

Im giving my first steps with injection CDI trying through sessionscoped context.

Basically i got a class "products" where i create some instances with description, name, etc. Those products are inserted in a List who belong to the class marked by @SessionScoped annotation and im trying to print that list in a servlet with the inject, but with a null result. Let me paste all the code:

I got an index html with the next links:

```<code><html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Testing</title>
</head>
<body>
    <center><h1> Index </h1>

        <a href="/Project/adding_products"> Adding products </a><br>
        <a href="/Project/products_list"> Products List </a>

    </center>
</body>
</html>
</code>```

Here the class products:

```<code>package com.espina.models;
import jakarta.enterprise.context.SessionScoped;

import java.util.ArrayList;
import java.util.List;

public class Products {

    private String name;
    private String description;
    private int amount;
    private double price;

    public Products() {
    }

    public Products(String name, String description, int amount, double price) {
        this.name= name;
        this.descripction = description;
        this.amount = amount;
        this.price= price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name= name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount= amount;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price= price;
    }
}
</code>```

Here the class with List method, that im adding to @sessionScoped

```<code>package com.espina.models;

import jakarta.enterprise.context.SessionScoped;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@SessionScoped
public class Listing implements Serializable {

    private List<Products> list;

    public Listing(){
        list = new ArrayList<>();
    }

    public List<Products> getList() {
        return list;
    }

    public void setList(Products products) {
        this.list.add(products);
    }
}
</code>```

Here the servlet where i add the products:

```<code>@WebServlet("/adding_products")
public class AddingProducts extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Listing listing= new Listing();

        listing.setList(new Products("Fanta","Energetic drink",5,4.50));
        listing.setList(new Products("ZeroCoke","Coke drink",3,2.50));
        listing.setList(new Products("Water","Drink",1,1.50));

    }

}
</code>```

Here where im trying to inject the class:

```<code>
@WebServlet("/products_list")
public class Productslist extends HttpServlet {
    @Inject
    private Listing listing;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter out = resp.getWriter();
        listing.getList().forEach((n) -> out.println(n));
        out.println("Products listing: ");
        for(Products list: listing.getList()){
            out.println("Name " + list.getName() + " Amount " + list.getAmount() + "   "  + list.getDescription() + "   "  +list.getPrice());
        }

    }
}

</code>```

The foreach is giving nullPointerException

Tried to inject a class by SessionScoped but i got a nullPointerExecption during the process

Body:
i have tried to research information about that topic without any results. And I dont know what im doing wrong.

Im giving my first steps with injection CDI trying through sessionscoped context.

Basically i got a class "products" where i create some instances with description, name, etc. Those products are inserted in a List who belong to the class marked by @SessionScoped annotation and im trying to print that list in a servlet with the inject, but with a null result. Let me paste all the code:

I got an index html with the next links:

    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Testing</title>

 Index

         Adding products

         Products List

Here the class products:

package com.espina.models;
import jakarta.enterprise.context.SessionScoped;

import java.util.ArrayList;
import java.util.List;

public class Products {

    private String name;
    private String description;
    private int amount;
    private double price;

    public Products() {
    }

    public Products(String name, String description, int amount, double price) {
        this.name= name;
        this.descripction = description;
        this.amount = amount;
        this.price= price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name= name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount= amount;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price= price;
    }
}

Here the class with List method, that im adding to @sessionScoped

package com.espina.models;

import jakarta.enterprise.context.SessionScoped;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@SessionScoped
public class Listing implements Serializable {

    private List<Products> list;

    public Listing(){
        list = new ArrayList<>();
    }

    public List<Products> getList() {
        return list;
    }

    public void setList(Products products) {
        this.list.add(products);
    }
}

Here the servlet where i add the products:

@WebServlet("/adding_products")
public class AddingProducts extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Listing listing= new Listing();

        listing.setList(new Products("Fanta","Energetic drink",5,4.50));
        listing.setList(new Products("ZeroCoke","Coke drink",3,2.50));
        listing.setList(new Products("Water","Drink",1,1.50));

    }

}

Here where im trying to inject the class:

@WebServlet("/products_list")
public class Productslist extends HttpServlet {
    @Inject
    private Listing listing;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter out = resp.getWriter();
        listing.getList().forEach((n) -> out.println(n));
        out.println("Products listing: ");
        for(Products list: listing.getList()){
            out.println("Name " + list.getName() + " Amount " + list.getAmount() + "   "  + list.getDescription() + "   "  +list.getPrice());
        }

    }
}

The foreach is giving nullPointerException

Tried to inject a class by SessionScoped but i got a nullPointerExecption during the process


问:
VBA Help Attach PDF to Email
I already have the PDF macro created but id' like to add the option of attaching to an email.

This is my PDF macro that works perfectly.

```<code>Sub PDFActiveSheet()
'www.contextures.com
'for Excel 2010 and later
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
On Error GoTo errHandler

Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
strTime = Format(Now(), "yyyymmdd\_hhmm")

'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
  strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"

'replace spaces and periods in sheet name
strName = wsA.Range("G6").Value & " " & wsA.Range("G11").Value

'create default name for savng file
strFile = strName
strPathFile = strPath & strFile

'use can enter name and
' select folder for file
myFile = Application.GetSaveAsFilename _
    (InitialFileName:=strPathFile, _
        FileFilter:="PDF Files (*.pdf), *.pdf", _
        Title:="Select Folder and FileName to save")

'export to PDF if a folder was selected
If myFile <> "False" Then
    wsA.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:=myFile, _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False
    'confirmation message with file info
    MsgBox "PDF file has been created: " _
      & vbCrLf _
      & myFile

End If

exitHandler:
    Exit Sub
errHandler:
    MsgBox "Could not create PDF file"
    Resume exitHandler

End Sub
</code>```

I've tried adding the below Macro without success.

 Sub sendPDFsub()

Dim Emailapp As Outlook.Application
Set Emailapp = New Outlook.Application

Dim Emailitem As Outlook.MailItem
Set Emailitem = Emailapp.CreateItem(olMailItem)

Emailitem.To = "Test@gmail.com"
Emailitem.Subject = wsA.Range("G6").Value
Emailitem.HTMLBody = "Hi,
 This is a test."

Emailitem.Attachments.Add

Emailitem.Display

End Sub
```

Title: VBA Help Attach PDF to Email

Body:
I already have the PDF macro created but id' like to add the option of attaching to an email.

This is my PDF macro that works perfectly.

Sub PDFActiveSheet()
'www.contextures.com
'for Excel 2010 and later
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
On Error GoTo errHandler

Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
strTime = Format(Now(), "yyyymmdd\_hhmm")

'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
  strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"

'replace spaces and periods in sheet name
strName = wsA.Range("G6").Value & " " & wsA.Range("G11").Value

'create default name for savng file
strFile = strName
strPathFile = strPath & strFile

'use can enter name and
' select folder for file
myFile = Application.GetSaveAsFilename _
    (InitialFileName:=strPathFile, _
        FileFilter:="PDF Files (*.pdf), *.pdf", _
        Title:="Select Folder and FileName to save")

'export to PDF if a folder was selected
If myFile <> "False" Then
    wsA.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:=myFile, _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False
    'confirmation message with file info
    MsgBox "PDF file has been created: " _
      & vbCrLf _
      & myFile

End If

exitHandler:
    Exit Sub
errHandler:
    MsgBox "Could not create PDF file"
    Resume exitHandler

End Sub

I've tried adding the below Macro without success.

 Sub sendPDFsub()

Dim Emailapp As Outlook.Application
Set Emailapp = New Outlook.Application

Dim Emailitem As Outlook.MailItem
Set Emailitem = Emailapp.CreateItem(olMailItem)

Emailitem.To = "Test@gmail.com"
Emailitem.Subject = wsA.Range("G6").Value
Emailitem.HTMLBody = "Hi,
 This is a test."

Emailitem.Attachments.Add

Emailitem.Display

End Sub


问:
Cannot resolve keyword into field error while using drf model serializer and search_fields within field set?
SerializerClass:

```<code>class VacancySerializer(serializers.ModelSerializer):
    organization_small_name = serializers.CharField(source='organization.short_name', read_only=True)
    class Meta:
        model = Vacancy
        fields = ['organization', 'description', 'specs', 'type', 'publication_date',
                  'is_published', 'withdrawal_data', 'organization_small_name', ]
        read_only_fields = ['publication_date', 'is_published', 'withdrawal_data',]
</code>```

ViewSet:

```<code>class VacancyViewSet(viewsets.ModelViewSet):
      queryset = Vacancy.objects.all()
      serializer_class = VacancySerializer
      filter_backends = [filters.SearchFilter]
      search_fields = ['organization_small_name']
...
</code>```

Model:

```<code>class Vacancy(models.Model):
organization = models.OneToOneField(DictOrganization, on_delete=models.CASCADE, related_name='vacancies')
description = models.TextField('Описание')
specs = models.ManyToManyField(DictSpec, blank=True)
type = models.CharField('Тип', max_length=20, choices=VacancyType.choices(), default=VacancyType.PRACTICE.value)

publication_date = models.DateField('Дата публикации', null=True, blank=True)
is_published = models.BooleanField('Опубликовано', default=False)
withdrawal_data = models.DateField('Дата снятия с публикации', null=True, blank=True)
</code>```

My goal is to make API search by 'organization_small_name' field
that is in VacancySerializer.
Server runs successfully, but as soon as i add ?search parameter, i get next error:

Why it doesn't recognize 'organization_small_name' field, even thought it is decribed in serializer, and how can i fix it?

Body:
SerializerClass:

class VacancySerializer(serializers.ModelSerializer):
    organization_small_name = serializers.CharField(source='organization.short_name', read_only=True)
    class Meta:
        model = Vacancy
        fields = ['organization', 'description', 'specs', 'type', 'publication_date',
                  'is_published', 'withdrawal_data', 'organization_small_name', ]
        read_only_fields = ['publication_date', 'is_published', 'withdrawal_data',]

ViewSet:

class VacancyViewSet(viewsets.ModelViewSet):
      queryset = Vacancy.objects.all()
      serializer_class = VacancySerializer
      filter_backends = [filters.SearchFilter]
      search_fields = ['organization_small_name']
...

Model:

class Vacancy(models.Model):
organization = models.OneToOneField(DictOrganization, on_delete=models.CASCADE, related_name='vacancies')
description = models.TextField('Описание')
specs = models.ManyToManyField(DictSpec, blank=True)
type = models.CharField('Тип', max_length=20, choices=VacancyType.choices(), default=VacancyType.PRACTICE.value)

publication_date = models.DateField('Дата публикации', null=True, blank=True)
is_published = models.BooleanField('Опубликовано', default=False)
withdrawal_data = models.DateField('Дата снятия с публикации', null=True, blank=True)

My goal is to make API search by 'organization_small_name' field
that is in VacancySerializer.
Server runs successfully, but as soon as i add ?search parameter, i get next error:

Why it doesn't recognize 'organization_small_name' field, even thought it is decribed in serializer, and how can i fix it?


问:
How to create @Entity class by using room with Map<>
How to create @Entity class by using room with Map<>

I have such data class:

```<code>data class ListResponse(
    @SerializedName("answer")
    val answer: Map<Int, ItemList>
)

data class ItemList(
    @SerializedName("yes")
    val yes: YesItem,

    @SerializedName("no")
    val no: NoItem
)

data class YesItem(
    @SerializedName("time")
    val timeYes: String,

    @SerializedName("date")
    val dateYes: String
)

data class NoItem(
    @SerializedName("time")
    val timeNo: String,

    @SerializedName("date")
    val dateNo: String
)

</code>```

and I need data base with such strucure:
Primary key must be taken as Int key from Map

Map Int key|timeYes|dateYes|timeNo|dateNo

something like that:

```<code>@Entity(tableName = TABLE_NAME)
data class PromotionListEntity(
    @PrimaryKey
    @SerializedName("id") // I don't know SerializedName for Int value
    val id:  //answer Map Int key

    @SerializedName("timeYes")
    val timeYes: String,

    @SerializedName("dateYes")
    val dateYes: String,

    @SerializedName("timeNo")
    val timeNo: String,

    @SerializedName("dateNo")
    val dateNo: String,

){
    companion object{
        const val TABLE_NAME = "answer_table"
    }
}
</code>```

Body:
How to create @Entity class by using room with Map<>

I have such data class:

data class ListResponse(
    @SerializedName("answer")
    val answer: Map<Int, ItemList>
)

data class ItemList(
    @SerializedName("yes")
    val yes: YesItem,

    @SerializedName("no")
    val no: NoItem
)

data class YesItem(
    @SerializedName("time")
    val timeYes: String,

    @SerializedName("date")
    val dateYes: String
)

data class NoItem(
    @SerializedName("time")
    val timeNo: String,

    @SerializedName("date")
    val dateNo: String
)

and I need data base with such strucure:
Primary key must be taken as Int key from Map

Map Int key|timeYes|dateYes|timeNo|dateNo

something like that:

@Entity(tableName = TABLE_NAME)
data class PromotionListEntity(
    @PrimaryKey
    @SerializedName("id") // I don't know SerializedName for Int value
    val id:  //answer Map Int key

    @SerializedName("timeYes")
    val timeYes: String,

    @SerializedName("dateYes")
    val dateYes: String,

    @SerializedName("timeNo")
    val timeNo: String,

    @SerializedName("dateNo")
    val dateNo: String,

){
    companion object{
        const val TABLE_NAME = "answer_table"
    }
}


问:
What is the equivalent/alternate to RAISE_APPLICATION_ERROR in db2 for iSeries platform?
https://www.ibm.com/docs/en/db2/9.7?topic=plsql-raise-application-error

I'm getting the following exception in java when my plslq function code uses the RAISE_APPLICATION_ERROR to throw an error to the caller

[[SQL0204] RAISE_APPLICATION_ERROR in *LIBL type *N not found.]

Note:
My code works fine in Db2 for Windows(DB2 LUW)

Expecting an alternate way to implement the custom application error handling.


问:
expo: i18nManager.isRTL always return true?
I working on the internationalization of an application, I want to set the app language to the user's device language if the language is (Arabic or French), the problem is when I want to use i18nManager.isRTL always returns true even when user's device language is an LTR language

```<code>const loadI18n = () => {
      console.log("in")
      i18n.init()
        .then(() => {
          console.log(`isRTL ${I18nManager.isRTL} this: ${i18n.isRTL}`)
          const RNDir = I18nManager.isRTL ? 'RTL' : 'LTR'; // this is always true
          // RN doesn't always correctly identify native
          // locale direction, so we force it here.
          if (i18n.dir !== RNDir) {
            const isLocaleRTL = i18n.dir === 'RTL';
            I18nManager.forceRTL(isLocaleRTL);
            // RN won't set the layout direction if we
            // don't restart the app's JavaScript.
            updates.reloadAsync();
          }
          setIsI18nInitialized(true);
        })
        .catch((error: any) => console.warn(error));
    }Ï
</code>```

my i18n config:

```<code>import i18next from 'i18next';
import { I18nManager as RNI18nManager } from 'react-native';
import * as config from './config/i18n';
import languageDetector from './services/language-detector';
import translationLoader from './services/translation-loader';

const i18n: any = {
    init: () => {
        return new Promise((resolve, reject) => {
            i18next
                .use(languageDetector)
                .use(translationLoader)
                .init({
                    compatibilityJSON: 'v3',
                    fallbackLng: config.fallback,
                    ns: config.namespaces,
                    defaultNS: config.defaultNamespace,
                    interpolation: {
                        escapeValue: false,
                        // format(value, format) {
                        //  if (value instanceof Date) {
                        //      return date.format(value, format);
                        //  }
                        // }
                    },
                }, (error) => {
                    if (error) { return reject(error); }
                    // date.init(i18next.language)
                    //  .then(resolve)
                    //  .catch(error => reject(error));
                });
            return resolve(true);
        });
    },
    t: (key: string, options?: any): any => i18next.t(key, options),
    get locale() { return i18next.language; },
    get dir() {
        return i18next.dir().toUpperCase();
    },
    get isRTL() {
        console.log("isRtl: ", RNI18nManager.isRTL, "locale: ", this.locale)
        return RNI18nManager.isRTL;
    },
    select(map: any) {
        const key = this.isRTL ? 'rtl' : 'ltr';
        return map[key];
    }
};
export const t = i18n.t;
export default i18n;
Ï
</code>```

some logs when use device's language French

```<code>isRTL true this: true
lang:  fr
</code>```

some logs when use device's language Arabic

```<code>isRTL true this: true
lang:  ar
</code>```

I want the RTL to be activated when user language is arabic otherways RTL has to be false

Body:
I working on the internationalization of an application, I want to set the app language to the user's device language if the language is (Arabic or French), the problem is when I want to use i18nManager.isRTL always returns true even when user's device language is an LTR language

const loadI18n = () => {
      console.log("in")
      i18n.init()
        .then(() => {
          console.log(`isRTL ${I18nManager.isRTL} this: ${i18n.isRTL}`)
          const RNDir = I18nManager.isRTL ? 'RTL' : 'LTR'; // this is always true
          // RN doesn't always correctly identify native
          // locale direction, so we force it here.
          if (i18n.dir !== RNDir) {
            const isLocaleRTL = i18n.dir === 'RTL';
            I18nManager.forceRTL(isLocaleRTL);
            // RN won't set the layout direction if we
            // don't restart the app's JavaScript.
            updates.reloadAsync();
          }
          setIsI18nInitialized(true);
        })
        .catch((error: any) => console.warn(error));
    }Ï

my i18n config:

import i18next from 'i18next';
import { I18nManager as RNI18nManager } from 'react-native';
import * as config from './config/i18n';
import languageDetector from './services/language-detector';
import translationLoader from './services/translation-loader';

const i18n: any = {
    init: () => {
        return new Promise((resolve, reject) => {
            i18next
                .use(languageDetector)
                .use(translationLoader)
                .init({
                    compatibilityJSON: 'v3',
                    fallbackLng: config.fallback,
                    ns: config.namespaces,
                    defaultNS: config.defaultNamespace,
                    interpolation: {
                        escapeValue: false,
                        // format(value, format) {
                        //  if (value instanceof Date) {
                        //      return date.format(value, format);
                        //  }
                        // }
                    },
                }, (error) => {
                    if (error) { return reject(error); }
                    // date.init(i18next.language)
                    //  .then(resolve)
                    //  .catch(error => reject(error));
                });
            return resolve(true);
        });
    },
    t: (key: string, options?: any): any => i18next.t(key, options),
    get locale() { return i18next.language; },
    get dir() {
        return i18next.dir().toUpperCase();
    },
    get isRTL() {
        console.log("isRtl: ", RNI18nManager.isRTL, "locale: ", this.locale)
        return RNI18nManager.isRTL;
    },
    select(map: any) {
        const key = this.isRTL ? 'rtl' : 'ltr';
        return map[key];
    }
};
export const t = i18n.t;
export default i18n;
Ï

some logs when use device's language French

isRTL true this: true
lang:  fr

some logs when use device's language Arabic

isRTL true this: true
lang:  ar

I want the RTL to be activated when user language is arabic otherways RTL has to be false


问:
Scale x-axis in Grafana to show the seconds tick
I am new to Grafana and using a PostgreSQL data source for getting data and plotting the graph using the query results. I am trying to plot a time series graph where my data points present in the database varies every 10 seconds

Currently, in grafana the x-axis interval is showing 1 min interval tick mark. How do I label the X-axis such that it display 10 seconds tick mark?

Please suggest any available option or process to show seconds tick in X-Axis


问:
Android nested fragment navigation
How in the right way implement nested navigation with Android Navigation component?
For example if we have 2 fragment outer and inner with 2 navigation graph. How i can navigate (get navigation controller) outer fragment from inner in the right way?

Code example from github

Title: Android nested fragment navigation


问:
using Jacob call office "saveas" to pdf very slow
Server Info:
4Core
8G Memory
Office 2016 VL
Windows Server 2012R2

testing file about 50mb size need takes over 800 seconds!

```<code>private static void wordToPdf(String wordFile, String pdfFile, String application) {
        Objects.requireNonNull(wordFile);
        Objects.requireNonNull(pdfFile);
        Objects.requireNonNull(application);

        ActiveXComponent ax = null;
        Dispatch document = null;
        try {
            File outFile = new File(pdfFile);
            // if parent target not exist and create
            if (!outFile.getParentFile().exists()) {
                Files.createDirectories(outFile.getParentFile().toPath());
            }

            //if exists and delete
            if (outFile.exists()) {
                outFile.delete();
            }

            ax = new ActiveXComponent(application);
            ax.setProperty("Visible", new Variant(false));
            ax.setProperty("AutomationSecurity", new Variant(3));

            Dispatch documents = ax.getProperty("Documents").toDispatch();
            document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch();

            Dispatch.call(document, "ExportAsFixedFormat", pdfFile, WORD_FORMAT_PDF);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            if (document != null) {
                Dispatch.call(document, "Close", false);
                document.safeRelease();
            }

            if (ax != null) {
                ax.invoke("Quit", 0);
                ax.safeRelease();
            }
        }
        ComThread.Release();
    }
</code>```

i search document on stackoverflow or google  and  try to solve it,
here is some measure:

upgrade office version

upgrade windows version

expansion server resources（CPU CORE/SSD DISK）

at the beginning i thought it's office problem,now i want know，did anyone can tell me not use as above menthod can make convert speed faster

Body:
Server Info:
4Core
8G Memory
Office 2016 VL
Windows Server 2012R2

testing file about 50mb size need takes over 800 seconds!

private static void wordToPdf(String wordFile, String pdfFile, String application) {
        Objects.requireNonNull(wordFile);
        Objects.requireNonNull(pdfFile);
        Objects.requireNonNull(application);

        ActiveXComponent ax = null;
        Dispatch document = null;
        try {
            File outFile = new File(pdfFile);
            // if parent target not exist and create
            if (!outFile.getParentFile().exists()) {
                Files.createDirectories(outFile.getParentFile().toPath());
            }

            //if exists and delete
            if (outFile.exists()) {
                outFile.delete();
            }

            ax = new ActiveXComponent(application);
            ax.setProperty("Visible", new Variant(false));
            ax.setProperty("AutomationSecurity", new Variant(3));

            Dispatch documents = ax.getProperty("Documents").toDispatch();
            document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch();

            Dispatch.call(document, "ExportAsFixedFormat", pdfFile, WORD_FORMAT_PDF);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            if (document != null) {
                Dispatch.call(document, "Close", false);
                document.safeRelease();
            }

            if (ax != null) {
                ax.invoke("Quit", 0);
                ax.safeRelease();
            }
        }
        ComThread.Release();
    }

i search document on stackoverflow or google  and  try to solve it,
here is some measure:

upgrade office version

upgrade windows version

expansion server resources（CPU CORE/SSD DISK）

at the beginning i thought it's office problem,now i want know，did anyone can tell me not use as above menthod can make convert speed faster


问:
Django. Asynchronous requests are executed in only one async event loop
I'm trying to find out how to use Django 4.0 asynchronous request support.
There is one very strange thing I can't understand: Django (uvicorn or asgi.py) creates only one event loop for two different views, despite the fact that I specified max_workers=8 in uvicorn settings.

This can lead to a case, when we have a lot of views (ex. 100) and in this views there are a lot of CPU-bound logic (ex: conditions, loops, calculations, etc) and a lot of IO-bound logic.
Using async/await we speed up and optimize all IO-bound operations, but our CPU-bound logic is slowing down our event-loop.

Instead of using event-loop for every process (worker), it uses only one loop, while other workers (7) stand still.

I think, it isn't a normal behavior. What do you think?

Check the code below to see more details:

views.py

```<code>import asyncio
import os
import random
import time

from django.http import HttpResponse
from django.utils.decorators import classonlymethod
from django.views import View

class AsyncBaseView(View):
    @classonlymethod
    def as_view(cls, **initkwargs):
        view = super().as_view(**initkwargs)
        view._is_coroutine = asyncio.coroutines._is_coroutine
        return view

class AsyncTestView(AsyncBaseView):
    async def get(self, request, *args, **kwargs):
        r = random.randint(1,4)
        print('Recieved', r)
        print('PID = ', os.getpid())

        # Simulate long code-inside operations (conditions, loops, calculations, ets)
        time.sleep(r)

        # Simulate external API call
        await asyncio.sleep(r)

        return HttpResponse('OK')

class AsyncTestView2(AsyncBaseView):
    async def get(self, request, *args, **kwargs):
        r = random.randint(1,4)
        print('Recieved', r)
        print('PID = ', os.getpid())

        # Simulate long code-inside operations (conditions, loops, calculations, ets)
        time.sleep(r)

        # Simulate external API call
        await asyncio.sleep(r)

        return HttpResponse('OK')
</code>```

urls.py

```<code>from django.urls import path, re_path
from apps.api_v1 import async_views

urlpatterns = [
    # test async
    path('async/', async_views.AsyncTestView.as_view(), name='async'),
    path('async2/', async_views.AsyncTestView2.as_view(), name='async'),
]
</code>```

running server command:

```<code>uvicorn main.asgi:application --host 0.0.0.0 --port 8000 --workers=8 --reload
</code>```

output (client sends GET-request in async mode):

```<code>nginx | 172.31.0.1 - - [07/Dec/2022:13:13:07 +0000] "GET /api/v1/async2 HTTP/1.1" 301 0 "-" "Python/3.9 aiohttp/3.8.3" "-"
nginx | 172.31.0.1 - - [07/Dec/2022:13:13:07 +0000] "GET /api/v1/async2 HTTP/1.1" 301 0 "-" "Python/3.9 aiohttp/3.8.3" "-"
nginx | 172.31.0.1 - - [07/Dec/2022:13:13:07 +0000] "GET /api/v1/async HTTP/1.1" 301 0 "-" "Python/3.9 aiohttp/3.8.3" "-"
nginx | 172.31.0.1 - - [07/Dec/2022:13:13:07 +0000] "GET /api/v1/async HTTP/1.1" 301 0 "-" "Python/3.9 aiohttp/3.8.3" "-"
web                         | Recieved 1
web                         | PID =  176
web                         | Recieved 3
web                         | PID =  176
web                         | Recieved 2
web                         | PID =  176
web                         | Recieved 1
web                         | PID =  176
</code>```

Look at PID number - all requests are processed by only one worker!

Body:
I'm trying to find out how to use Django 4.0 asynchronous request support.
There is one very strange thing I can't understand: Django (uvicorn or asgi.py) creates only one event loop for two different views, despite the fact that I specified max_workers=8 in uvicorn settings.

This can lead to a case, when we have a lot of views (ex. 100) and in this views there are a lot of CPU-bound logic (ex: conditions, loops, calculations, etc) and a lot of IO-bound logic.
Using async/await we speed up and optimize all IO-bound operations, but our CPU-bound logic is slowing down our event-loop.

Instead of using event-loop for every process (worker), it uses only one loop, while other workers (7) stand still.

I think, it isn't a normal behavior. What do you think?

Check the code below to see more details:

views.py

import asyncio
import os
import random
import time

from django.http import HttpResponse
from django.utils.decorators import classonlymethod
from django.views import View

class AsyncBaseView(View):
    @classonlymethod
    def as_view(cls, **initkwargs):
        view = super().as_view(**initkwargs)
        view._is_coroutine = asyncio.coroutines._is_coroutine
        return view

class AsyncTestView(AsyncBaseView):
    async def get(self, request, *args, **kwargs):
        r = random.randint(1,4)
        print('Recieved', r)
        print('PID = ', os.getpid())

        # Simulate long code-inside operations (conditions, loops, calculations, ets)
        time.sleep(r)

        # Simulate external API call
        await asyncio.sleep(r)

        return HttpResponse('OK')

class AsyncTestView2(AsyncBaseView):
    async def get(self, request, *args, **kwargs):
        r = random.randint(1,4)
        print('Recieved', r)
        print('PID = ', os.getpid())

        # Simulate long code-inside operations (conditions, loops, calculations, ets)
        time.sleep(r)

        # Simulate external API call
        await asyncio.sleep(r)

        return HttpResponse('OK')

urls.py

from django.urls import path, re_path
from apps.api_v1 import async_views

urlpatterns = [
    # test async
    path('async/', async_views.AsyncTestView.as_view(), name='async'),
    path('async2/', async_views.AsyncTestView2.as_view(), name='async'),
]

running server command:

uvicorn main.asgi:application --host 0.0.0.0 --port 8000 --workers=8 --reload

output (client sends GET-request in async mode):

nginx | 172.31.0.1 - - [07/Dec/2022:13:13:07 +0000] "GET /api/v1/async2 HTTP/1.1" 301 0 "-" "Python/3.9 aiohttp/3.8.3" "-"
nginx | 172.31.0.1 - - [07/Dec/2022:13:13:07 +0000] "GET /api/v1/async2 HTTP/1.1" 301 0 "-" "Python/3.9 aiohttp/3.8.3" "-"
nginx | 172.31.0.1 - - [07/Dec/2022:13:13:07 +0000] "GET /api/v1/async HTTP/1.1" 301 0 "-" "Python/3.9 aiohttp/3.8.3" "-"
nginx | 172.31.0.1 - - [07/Dec/2022:13:13:07 +0000] "GET /api/v1/async HTTP/1.1" 301 0 "-" "Python/3.9 aiohttp/3.8.3" "-"
web                         | Recieved 1
web                         | PID =  176
web                         | Recieved 3
web                         | PID =  176
web                         | Recieved 2
web                         | PID =  176
web                         | Recieved 1
web                         | PID =  176

Look at PID number - all requests are processed by only one worker!


问:
Writing a single table in two seperate pages
I want to the user details in two seperate pages but for a single table in SQL. For instance

In SQL a table 'user' with fields

username, name, email, password

I need to get name, email, password in one page when clicked next I want to fill out username in a seperate page. But could not resolve how to do it.

To switch pages in frontend using react

```<code><Router>
      <Routes>
      <Route exact path="/" element={<HomeScreen/>}/>
        <Route exact path="/login" element={!isAuthenticated ? <LoginScreen setAuth={setAuth}/> : <Navigate to='/home'/>}/>
        <Route exact path="/signup" element={!isAuthenticated ? <SignupScreen setAuth={setAuth}/> : <Navigate to='/username'/>}/>
        <Route exact path="/username" element={isSigned? <UsernameScreen setAuth={setAuth}/> : <Navigate to='/home'/>}/>
        <Route exact path="/home" element={isAuthenticated? <LoggedScreen setAuth={setAuth}/> : <Navigate to='/login'/>}/>
        <Route exact path="/explore" element={isAuthenticated? <ExploreScreen/>: <Navigate to='/login'/>}/>
      </Routes>
    </Router>

</code>```

Table Structure in postgres SQL

```<code>CREATE TABLE users(
    user_id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
    username VARCHAR(255) NOT NULL,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL,
    password VARCHAR(255) NOT NULL,
    admin numeric DEFAULT 0
);

</code>```

Body:
I want to the user details in two seperate pages but for a single table in SQL. For instance

In SQL a table 'user' with fields

username, name, email, password

I need to get name, email, password in one page when clicked next I want to fill out username in a seperate page. But could not resolve how to do it.

To switch pages in frontend using react

<Router>
      <Routes>
      <Route exact path="/" element={<HomeScreen/>}/>
        <Route exact path="/login" element={!isAuthenticated ? <LoginScreen setAuth={setAuth}/> : <Navigate to='/home'/>}/>
        <Route exact path="/signup" element={!isAuthenticated ? <SignupScreen setAuth={setAuth}/> : <Navigate to='/username'/>}/>
        <Route exact path="/username" element={isSigned? <UsernameScreen setAuth={setAuth}/> : <Navigate to='/home'/>}/>
        <Route exact path="/home" element={isAuthenticated? <LoggedScreen setAuth={setAuth}/> : <Navigate to='/login'/>}/>
        <Route exact path="/explore" element={isAuthenticated? <ExploreScreen/>: <Navigate to='/login'/>}/>
      </Routes>
    </Router>

Table Structure in postgres SQL

CREATE TABLE users(
    user_id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
    username VARCHAR(255) NOT NULL,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL,
    password VARCHAR(255) NOT NULL,
    admin numeric DEFAULT 0
);


问:
cant run function, because signal only works in main thread of the main interpreter?
I'm trying to build an API using Flask. If the endpoint /register/string:token is retrieved and the token is in a defined list, the function register_user(username) should be executed. This function sends a command to another server using the rcon protocol. However, as soon as the function is called, I get the following error: ValueError: signal only works in main thread of the main interpreter. How can I fix the problem? Or, how can I run the function in the main thread?

My code looks something like this (Note: The script runs fine on Windows):

```<code>from flask import Flask, send_file
from mcrcon import MCRcon as rcon

import configparser

api = Flask(__name__)

# @api.route('/register/<string:token>', methods=['GET'])
def register(token):
    cache = utils.load_cache()
    if token in list(cache['register_tokens'].keys()):
        utils.register_user(username=cache['register_tokens'][token]) # problem!
        del cache['register_tokens'][token]
        utils.update_cache(obj=cache)
        return {'status':'registration successful'}
    else:
        return {'status':'registration failed'}

class utils:
    @staticmethod
    def load_cache(file='../cache.pkl'):
        ...

    @staticmethod
    def update_cache(obj, file='../cache.pkl'):
        ...

    @staticmethod
    def clear_cache():
        ...

    @staticmethod
    def register_user(username):
        with rcon(config['global']['server_ip'], config['global']['server_rcon_secret']) as console:
            r = console.command(...)
            console.disconnect()

if __name__ == '__main__':
    config = configparser.ConfigParser()
    config.read('../config.conf')

    if bool(config['discordbot.py']['enable'])==True:
        api.add_url_rule('/register/<string:token>', 'register', register)

    api.run(host=config['global']['server_ip'], debug=False, use_reloader=False)
</code>```

Body:
I'm trying to build an API using Flask. If the endpoint /register/string:token is retrieved and the token is in a defined list, the function register_user(username) should be executed. This function sends a command to another server using the rcon protocol. However, as soon as the function is called, I get the following error: ValueError: signal only works in main thread of the main interpreter. How can I fix the problem? Or, how can I run the function in the main thread?

My code looks something like this (Note: The script runs fine on Windows):

from flask import Flask, send_file
from mcrcon import MCRcon as rcon

import configparser

api = Flask(__name__)

# @api.route('/register/<string:token>', methods=['GET'])
def register(token):
    cache = utils.load_cache()
    if token in list(cache['register_tokens'].keys()):
        utils.register_user(username=cache['register_tokens'][token]) # problem!
        del cache['register_tokens'][token]
        utils.update_cache(obj=cache)
        return {'status':'registration successful'}
    else:
        return {'status':'registration failed'}

class utils:
    @staticmethod
    def load_cache(file='../cache.pkl'):
        ...

    @staticmethod
    def update_cache(obj, file='../cache.pkl'):
        ...

    @staticmethod
    def clear_cache():
        ...

    @staticmethod
    def register_user(username):
        with rcon(config['global']['server_ip'], config['global']['server_rcon_secret']) as console:
            r = console.command(...)
            console.disconnect()

if __name__ == '__main__':
    config = configparser.ConfigParser()
    config.read('../config.conf')

    if bool(config['discordbot.py']['enable'])==True:
        api.add_url_rule('/register/<string:token>', 'register', register)

    api.run(host=config['global']['server_ip'], debug=False, use_reloader=False)


问:
Contentful CMS GraphQL Playground GraphQL Mutation Return undefined
I am learning GraphQL mutations in react and Contentful CMS. I am trying to add user data into User model. I am getting error below

"Cannot read properties of undefined ( reading 'name')"

In User Content Model, I am having two field firstname and lastname.