问:
Docker build command not running for several commands in React scripts (in package.json)
I encountered a problem in building Docker for the stage environment, the problem is that I want a command to be executed before building the project, then the build is done. I will put the codes to guide you better.

package.json:

```<code>"scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "build:staging": "env-cmd -f ./.env.staging npm run sitemap && react-scripts build",
        "build:production": "env-cmd -f ./.env.production react-scripts build",
        "sitemap": "babel-node ./src/utils/SitemapBuilder.js"
    },
</code>```

Normally, there is no problem, and the stage build (npm run build:staging) command works correctly in localhost, but when I want to build the project by docker, it is fielded.

This problem is solved, if there is no command npm run sitemap && before react-scripts build. But because I need to execute this command before building, I am looking for a solution.

.babelrc file:

```<code>{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
  }
</code>```

Docker file:

```<code>FROM node:14.18.2-alpine AS builder

WORKDIR /

ENV NODE_OPTIONS=--max_old_space_size=4096

ENV NODE_ENV=staging

ENV REACT_APP_ENV=staging

COPY . .

ADD deploy/stage/app.env .env

RUN yarn install --staging && yarn build:staging

FROM nginx:stable-alpine

ADD deploy/stage/nginx.conf /etc/nginx/conf.d/default.conf

COPY --from=builder /build /usr/share/nginx/html
</code>```

After docker build:

```<code>#10 332.5 > babel-node ./src/utils/SitemapBuilder.js
#10 332.5
#10 335.3 /node_modules/babel-core/lib/transformation/file/options/option-manager.js:328
#10 335.3         throw e;
#10 335.3         ^
#10 335.3
#10 335.3 Error: Requires Babel "^7.0.0-0", but was loaded with "6.26.3". If you are sure you have a compatible version of @babel/core, it is likely that something in your build process is loading the wrong version. Inspect the stack trace of this error to look for the first entry that doesn't mention "@babel/core" or "babel-core" to see what is calling Babel. (While processing preset: "/node_modules/@babel/preset-env/lib/index.js")
#10 335.3     at throwVersionError (/node_modules/@babel/helper-plugin-utils/src/index.ts:128:11)
#10 335.3     at Object.assertVersion (/node_modules/@babel/helper-plugin-utils/src/index.ts:24:5)
#10 335.3     at /node_modules/@babel/preset-env/src/index.ts:291:7
#10 335.3     at /node_modules/@babel/helper-plugin-utils/src/index.ts:64:12
#10 335.3     at /node_modules/babel-core/lib/transformation/file/options/option-manager.js:317:46
#10 335.3     at Array.map (<anonymous>)
#10 335.3     at OptionManager.resolvePresets (/node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
#10 335.3     at OptionManager.mergePresets (/node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
#10 335.3     at OptionManager.mergeOptions (/node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
#10 335.3     at OptionManager.init (/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
#10 335.3     at compile (/node_modules/babel-register/lib/node.js:103:45)
#10 335.3     at loader (/node_modules/babel-register/lib/node.js:144:14)
#10 335.3     at Object.require.extensions.<computed> [as .js] (/node_modules/babel-register/lib/node.js:154:7)
#10 335.3     at Module.load (internal/modules/cjs/loader.js:950:32)
#10 335.3     at Function.Module._load (internal/modules/cjs/loader.js:790:12)
#10 335.3     at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
#10 335.3     at Object.<anonymous> (/node_modules/babel-cli/lib/_babel-node.js:154:22)
#10 335.3     at Module._compile (internal/modules/cjs/loader.js:1085:14)
#10 335.3     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
#10 335.3     at Module.load (internal/modules/cjs/loader.js:950:32)
#10 335.3     at Function.Module._load (internal/modules/cjs/loader.js:790:12)
#10 335.3     at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
#10 335.3     at internal/main/run_main_module.js:17:47 {
#10 335.3   code: 'BABEL_VERSION_UNSUPPORTED',
#10 335.3   version: '6.26.3',
#10 335.3   range: '^7.0.0-0'
#10 335.3 }
#10 335.4 npm ERR! code ELIFECYCLE
#10 335.4 npm ERR! errno 1
#10 335.4 npm ERR! app@0.2.4 sitemap: `babel-node ./src/utils/SitemapBuilder.js`
#10 335.4 npm ERR! Exit status 1
#10 335.4 npm ERR!
#10 335.4 npm ERR! Failed at the app@0.2.4 sitemap script.
#10 335.4 npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
#10 335.4
#10 335.4 npm ERR! A complete log of this run can be found in:
#10 335.4 npm ERR!     /root/.npm/_logs/2022-12-28T20_08_43_024Z-debug.log
#10 335.5 error Command failed with exit code 1.
#10 335.5 info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

Also, I use React, Docker, Nginx, and Jenkins.

If anyone has information, please help.

Body:
I encountered a problem in building Docker for the stage environment, the problem is that I want a command to be executed before building the project, then the build is done. I will put the codes to guide you better.

package.json:

"scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "build:staging": "env-cmd -f ./.env.staging npm run sitemap && react-scripts build",
        "build:production": "env-cmd -f ./.env.production react-scripts build",
        "sitemap": "babel-node ./src/utils/SitemapBuilder.js"
    },

Normally, there is no problem, and the stage build (npm run build:staging) command works correctly in localhost, but when I want to build the project by docker, it is fielded.

This problem is solved, if there is no command npm run sitemap && before react-scripts build. But because I need to execute this command before building, I am looking for a solution.

.babelrc file:

{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
  }

Docker file:

FROM node:14.18.2-alpine AS builder

WORKDIR /

ENV NODE_OPTIONS=--max_old_space_size=4096

ENV NODE_ENV=staging

ENV REACT_APP_ENV=staging

COPY . .

ADD deploy/stage/app.env .env

RUN yarn install --staging && yarn build:staging

FROM nginx:stable-alpine

ADD deploy/stage/nginx.conf /etc/nginx/conf.d/default.conf

COPY --from=builder /build /usr/share/nginx/html

After docker build:

#10 332.5 > babel-node ./src/utils/SitemapBuilder.js
#10 332.5
#10 335.3 /node_modules/babel-core/lib/transformation/file/options/option-manager.js:328
#10 335.3         throw e;
#10 335.3         ^
#10 335.3
#10 335.3 Error: Requires Babel "^7.0.0-0", but was loaded with "6.26.3". If you are sure you have a compatible version of @babel/core, it is likely that something in your build process is loading the wrong version. Inspect the stack trace of this error to look for the first entry that doesn't mention "@babel/core" or "babel-core" to see what is calling Babel. (While processing preset: "/node_modules/@babel/preset-env/lib/index.js")
#10 335.3     at throwVersionError (/node_modules/@babel/helper-plugin-utils/src/index.ts:128:11)
#10 335.3     at Object.assertVersion (/node_modules/@babel/helper-plugin-utils/src/index.ts:24:5)
#10 335.3     at /node_modules/@babel/preset-env/src/index.ts:291:7
#10 335.3     at /node_modules/@babel/helper-plugin-utils/src/index.ts:64:12
#10 335.3     at /node_modules/babel-core/lib/transformation/file/options/option-manager.js:317:46
#10 335.3     at Array.map (<anonymous>)
#10 335.3     at OptionManager.resolvePresets (/node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
#10 335.3     at OptionManager.mergePresets (/node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
#10 335.3     at OptionManager.mergeOptions (/node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
#10 335.3     at OptionManager.init (/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
#10 335.3     at compile (/node_modules/babel-register/lib/node.js:103:45)
#10 335.3     at loader (/node_modules/babel-register/lib/node.js:144:14)
#10 335.3     at Object.require.extensions.<computed> [as .js] (/node_modules/babel-register/lib/node.js:154:7)
#10 335.3     at Module.load (internal/modules/cjs/loader.js:950:32)
#10 335.3     at Function.Module._load (internal/modules/cjs/loader.js:790:12)
#10 335.3     at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
#10 335.3     at Object.<anonymous> (/node_modules/babel-cli/lib/_babel-node.js:154:22)
#10 335.3     at Module._compile (internal/modules/cjs/loader.js:1085:14)
#10 335.3     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
#10 335.3     at Module.load (internal/modules/cjs/loader.js:950:32)
#10 335.3     at Function.Module._load (internal/modules/cjs/loader.js:790:12)
#10 335.3     at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
#10 335.3     at internal/main/run_main_module.js:17:47 {
#10 335.3   code: 'BABEL_VERSION_UNSUPPORTED',
#10 335.3   version: '6.26.3',
#10 335.3   range: '^7.0.0-0'
#10 335.3 }
#10 335.4 npm ERR! code ELIFECYCLE
#10 335.4 npm ERR! errno 1
#10 335.4 npm ERR! app@0.2.4 sitemap: `babel-node ./src/utils/SitemapBuilder.js`
#10 335.4 npm ERR! Exit status 1
#10 335.4 npm ERR!
#10 335.4 npm ERR! Failed at the app@0.2.4 sitemap script.
#10 335.4 npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
#10 335.4
#10 335.4 npm ERR! A complete log of this run can be found in:
#10 335.4 npm ERR!     /root/.npm/_logs/2022-12-28T20_08_43_024Z-debug.log
#10 335.5 error Command failed with exit code 1.
#10 335.5 info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Also, I use React, Docker, Nginx, and Jenkins.

If anyone has information, please help.


来源: stackexchange

问:
The python-Docker container exits two second after running even with docker run -dit command
I wanted to test a custome kubernetes scheduler from here with Dockerfile:

```<code>FROM python:3.7
RUN pip install kubernetes
COPY scheduler.py /scheduler.py
CMD python /scheduler.py
</code>```

Once the image and container were created by:

```<code>docker build -t app .
docker container run -d -it --name my-scheduler app:latest
</code>```

Immediately the container went to Exited status.
Firstly I assumed that the process inside the container has ended because it hasn't run in kubernetes cluster yet.
So I craeted deployment.yaml and run:

```<code>kubectl create -f deployment.yaml
</code>```

and then checked:

```<code>kubectl get po -A
</code>```

and as you can see pod is not ready:

```<code>NAMESPACE     NAME                               READY   STATUS         RESTARTS      AGE

kube-system   etcd-minikube                      1/1     Running        0             119s
kube-system   kube-apiserver-minikube            1/1     Running        0             119s
kube-system   kube-controller-manager-minikube   1/1     Running        0             119s
kube-system   kube-proxy-8c7l5                   1/1     Running        0             107s
kube-system   kube-scheduler-minikube            1/1     Running        0             119s
kube-system   my-scheduler-5f964589d7-pgg74      0/1     ErrImagePull   0             6s
kube-system   storage-provisioner                1/1     Running        1 (85s ago)   116s
</code>```

I know there are many similar questions and answers in stackoverflow which I tried some of them which were not helpful for this case.

ContentLicense: CC BY-SA 4.0

Body:
I wanted to test a custome kubernetes scheduler from here with Dockerfile:

FROM python:3.7
RUN pip install kubernetes
COPY scheduler.py /scheduler.py
CMD python /scheduler.py

Once the image and container were created by:

docker build -t app .
docker container run -d -it --name my-scheduler app:latest

Immediately the container went to Exited status.
Firstly I assumed that the process inside the container has ended because it hasn't run in kubernetes cluster yet.
So I craeted deployment.yaml and run:

kubectl create -f deployment.yaml

and then checked:

kubectl get po -A

and as you can see pod is not ready:

NAMESPACE     NAME                               READY   STATUS         RESTARTS      AGE

kube-system   etcd-minikube                      1/1     Running        0             119s
kube-system   kube-apiserver-minikube            1/1     Running        0             119s
kube-system   kube-controller-manager-minikube   1/1     Running        0             119s
kube-system   kube-proxy-8c7l5                   1/1     Running        0             107s
kube-system   kube-scheduler-minikube            1/1     Running        0             119s
kube-system   my-scheduler-5f964589d7-pgg74      0/1     ErrImagePull   0             6s
kube-system   storage-provisioner                1/1     Running        1 (85s ago)   116s

I know there are many similar questions and answers in stackoverflow which I tried some of them which were not helpful for this case.


问:
Error handling in getstaticpaths/getstaicprops
im creating a dynamic page on nextjs using getstaticpaths and props and graphql
but im having an issue when handling errors.
If the Api request fails
it shows this on the screen

Error: request to https://api-eu-west-2.hygraph.com/n2/cl9xdiogb0pw01tbhwj57e4y/master failed, reason: getaddrinfo ENOTFOUND api-eu-west-1.hygraph.com

is there anyway i can display a custom error message or maybe redirect to another page if the api request fails ?

This is my code

```<code>const Api = new GraphQLClient("https://api-eu-west-2.hygraph.com/v2/cl9xdiogb0p9w01tbhwj5774y/master");

    const GETPOST = gql`
    query($title: String){
    posts(where: {title : $title}) {
        id
        title
        body
        date
        coverpic {
          id
          url
        }
        tag
      }
    }
    `
const Titlelist = gql`
{
  posts{
    title
  }
}`

export async function getStaticPaths(){

  const {posts} = await Api.request(Titlelist)

  return{
    paths: posts.map((post) => ({params: {title :post.title}})),
    fallback: true,
  }
}
    export async function getStaticProps({params}){

      const title = params.title
      const {data, notFound} = await Api.request(GETPOST, {title})

      const dataa = data
      return{
        props:{
          dataa,
        },
        revalidate: 10,
      }
    }

export default function Readoo({dataa}){
return(
  <main>
    {dataa.posts.map(thu => {
      return(
        <Reading title ={thu.title} date={thu.date} coverpic={thu.coverpic.url} body={thu.body} tag={thu.tag}/>
      )
    })}
    </main>
  )
}
</code>```

Body:
im creating a dynamic page on nextjs using getstaticpaths and props and graphql
but im having an issue when handling errors.
If the Api request fails
it shows this on the screen

Error: request to https://api-eu-west-2.hygraph.com/n2/cl9xdiogb0pw01tbhwj57e4y/master failed, reason: getaddrinfo ENOTFOUND api-eu-west-1.hygraph.com

is there anyway i can display a custom error message or maybe redirect to another page if the api request fails ?

This is my code

const Api = new GraphQLClient("https://api-eu-west-2.hygraph.com/v2/cl9xdiogb0p9w01tbhwj5774y/master");

    const GETPOST = gql`
    query($title: String){
    posts(where: {title : $title}) {
        id
        title
        body
        date
        coverpic {
          id
          url
        }
        tag
      }
    }
    `
const Titlelist = gql`
{
  posts{
    title
  }
}`

export async function getStaticPaths(){

  const {posts} = await Api.request(Titlelist)

  return{
    paths: posts.map((post) => ({params: {title :post.title}})),
    fallback: true,
  }
}
    export async function getStaticProps({params}){

      const title = params.title
      const {data, notFound} = await Api.request(GETPOST, {title})

      const dataa = data
      return{
        props:{
          dataa,
        },
        revalidate: 10,
      }
    }

export default function Readoo({dataa}){
return(

    {dataa.posts.map(thu => {
      return(
        <Reading title ={thu.title} date={thu.date} coverpic={thu.coverpic.url} body={thu.body} tag={thu.tag}/>
      )
    })}

  )
}


问:
Foreach with structuredClone run into RangeError
```<code>const result: Model[] = [];
array.forEach((element) => {
  if (condition1)
    result.push(structuredClone(element));

  if (condition2)
    result.push(structuredClone(element));
});
</code>```

The object is nested:

```<code>export interface Model extends Dto {
  indentation?: number;
  previous?: Model;
  next?: Model;
}

export interface Dto {
  ...
  children?: Array<Dto>;
  contentChunks?: Array<ContentChunk>;
  id?: number;
  ...
}
</code>```

If the size of array is small i works. But on big arrays it runs into

ERROR RangeError: Maximum call stack size exceeded

Suggestions to improve appreciated.

Update:

on changing structuredClone to JSON.parse(JSON.stringify

```<code>ERROR TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Object'
|     property 'next' -> object with constructor 'Object'
--- property 'previous' closes the circle
</code>```

Body:
const result: Model[] = [];
array.forEach((element) => {
  if (condition1)
    result.push(structuredClone(element));

  if (condition2)
    result.push(structuredClone(element));
});

The object is nested:

export interface Model extends Dto {
  indentation?: number;
  previous?: Model;
  next?: Model;
}

export interface Dto {
  ...
  children?: Array<Dto>;
  contentChunks?: Array<ContentChunk>;
  id?: number;
  ...
}

If the size of array is small i works. But on big arrays it runs into

ERROR RangeError: Maximum call stack size exceeded

Suggestions to improve appreciated.

Update:

on changing structuredClone to JSON.parse(JSON.stringify

ERROR TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Object'
|     property 'next' -> object with constructor 'Object'
--- property 'previous' closes the circle


问:
async method doesn't execute all the way through
I have a method that adds some data to my database, it worked fine a while ago but now it has just stopped working.
I found out with debugging that my async method gets called but then just stops in the middle and the Answers are never getting added:

```<code> private async Task CreateNewQuestion()
{
    if (newQuestion.QuestionType is null)
    {
        noType = true;
        return;
    }
    else if (Answers.Count == 0)
    {
        noAnswer = true;
        return;
    }
    else if (newQuestion.QuestionType is not null)
    {
        List<Question> questioncount = new List<Question>();
        questioncount = await questionRepo.GetQuestionByQuizId(QuizId);
        _order = questioncount.Count + 1;
        newQuestion.QuestionOrderId = _order;
        newQuestion.AnswerType = _answerType;
        newQuestion.QuestionUrl = _questionUrlConverted;
        await questionRepo.AddQuestionWithAnswers(newQuestion, Answers); <-- THIS IS WHERE THE METHOD GETS CALLED
        noType = false;
        questions = await questionRepo.GetQuestionByQuizId(QuizId);
        var quiz = quizRepo.GetQuizById(QuizId);

        Navigation.NavigateTo($"/Quiz/AddQuestionWithId/{QuizId}", true);
    }

}
</code>```

and here is the method:

```<code>public async Task AddQuestionWithAnswers(Question newQuestion, List<Answer> answers)
    {
        if(newQuestion is not null && answers.Count > 0)
        {

            _context.Questions.Add(newQuestion);
            await _context.SaveChangesAsync(); <-- THIS IS WHERE IT JUST STOPS TO EXECUTE

            var answerQuestionItem = await GetQuestionById(newQuestion.QuestionId);
            if(answerQuestionItem is not null)
            {
                foreach(var answer in answers)
                {
                    answer.Question = answerQuestionItem;
                    _context.Answers.Add(answer);
                    await _context.SaveChangesAsync();
                }
            }
        }
    }
</code>```

It also doesn't even go back to the method that called the method, just to my razor component and nothing happens.
Any ideas how I can fix this?

Body:
I have a method that adds some data to my database, it worked fine a while ago but now it has just stopped working.
I found out with debugging that my async method gets called but then just stops in the middle and the Answers are never getting added:

 private async Task CreateNewQuestion()
{
    if (newQuestion.QuestionType is null)
    {
        noType = true;
        return;
    }
    else if (Answers.Count == 0)
    {
        noAnswer = true;
        return;
    }
    else if (newQuestion.QuestionType is not null)
    {
        List<Question> questioncount = new List<Question>();
        questioncount = await questionRepo.GetQuestionByQuizId(QuizId);
        _order = questioncount.Count + 1;
        newQuestion.QuestionOrderId = _order;
        newQuestion.AnswerType = _answerType;
        newQuestion.QuestionUrl = _questionUrlConverted;
        await questionRepo.AddQuestionWithAnswers(newQuestion, Answers); <-- THIS IS WHERE THE METHOD GETS CALLED
        noType = false;
        questions = await questionRepo.GetQuestionByQuizId(QuizId);
        var quiz = quizRepo.GetQuizById(QuizId);

        Navigation.NavigateTo($"/Quiz/AddQuestionWithId/{QuizId}", true);
    }

}

and here is the method:

public async Task AddQuestionWithAnswers(Question newQuestion, List<Answer> answers)
    {
        if(newQuestion is not null && answers.Count > 0)
        {

            _context.Questions.Add(newQuestion);
            await _context.SaveChangesAsync(); <-- THIS IS WHERE IT JUST STOPS TO EXECUTE

            var answerQuestionItem = await GetQuestionById(newQuestion.QuestionId);
            if(answerQuestionItem is not null)
            {
                foreach(var answer in answers)
                {
                    answer.Question = answerQuestionItem;
                    _context.Answers.Add(answer);
                    await _context.SaveChangesAsync();
                }
            }
        }
    }

It also doesn't even go back to the method that called the method, just to my razor component and nothing happens.
Any ideas how I can fix this?


问:
Is there a way to check how many open watch() connections are there?
I created a web-app that utilizes db.collection.watch() to observe database changes.

However, after a few weeks, the app becomes sluggish and I have to fix it by restarting the backend - which hints at some memory leaks.

My fear is that my db.collection.watch() calls are not being properly closed, so it would be helpfull if I could see how many are actually open at any given time.

Is there a mongo command that can provide this information?


问:
Auth0 and WebView - React native
I am trying to use Auth0 and a Webview but without having to login on the webview in React native.

I use the package react-native-auth0, and react-native-webview.

I can retrieve the access token from Auth0, but haven't figured out how to authorize the webview session. I have been able to use react-native-inappbrowser-reborn, which use by default using the same place it retrieves the token. But I would want the web browser to be displayed inside a view/tab.

I would like any solution where the "browser" is viewed inside a View/Tab and authorized from the auth0 login.

Title: Auth0 and WebView - React native


问:
Python ignores the "or" operator
As you can see in the following, my intention was to close the program once the user types either "x" or "X" and to ask again (loop) if not. Confusingly, the whole program closes anyway once I type anything but "x" or "X".

```<code>import sys

while True:
    userAnswer = input("press x or X to exit")

    if userAnswer == "x" or "X":
        sys.exit()

</code>```

It would be great if someone could explain this to me. Thanks

Title: Python ignores the "or" operator

Body:
As you can see in the following, my intention was to close the program once the user types either "x" or "X" and to ask again (loop) if not. Confusingly, the whole program closes anyway once I type anything but "x" or "X".

import sys

while True:
    userAnswer = input("press x or X to exit")

    if userAnswer == "x" or "X":
        sys.exit()

It would be great if someone could explain this to me. Thanks


问:
Values in variables get flushed after function gets called in python
I have created a function to fetch data from Database & use it inside the code. Inside that DBRead() function the values were able to printed, but unable to use in next sequence, it throws not defined error or empty values if defined at top.

I'm trying to fetch data from sqlite DB and use those data inside the code. The code fetches time and audio location (importantly) and play that audio at a scheduled time using scheduler. Trying to simplify the job function to only 1 (as there are lot of schedules needed up to 20). Currently stuck with this data flush error.
Eg:

```<code>print(audiofile)
print(jobid)
</code>```

These gets printed inside the DBRead() and not after that inside the code. Throws #Empty or undefined error

Here is the full code below

```<code>import glob
import schedule
import time
import sqlite3
import pygame
from pygame import mixer #calling for pygame mixer to play audio files

pygame.mixer.init()
curr_daytype = 'Regular'
audiofile = ''
log_id = ''
daytype = ''
jobid = ''
#==========================================FUNCTIONS===========================================#
def DBRead():

    global conn, cursor
    conn = sqlite3.connect('pythontut.db')
    cursor = conn.cursor()
    #cursor.execute("SELECT * FROM `anno` ORDER BY `daytype` ASC") #Return All Data in Asc
    #cursor.execute("SELECT * FROM anno WHERE daytype = 'Regular'") #Return Daytype if Regular

    sql = "SELECT * FROM anno WHERE daytype ='"
    fetch_daytype = curr_daytype
    sql = sql + fetch_daytype + "'"
    cursor.execute(sql)
    fetch = cursor.fetchall()

    #print(fetch)
    for data in fetch:
        #tree.insert('', 'end', values=(data[0], data[1], data[2], data[3]))
        log_id = data[0]
        daytype = data[1]
        rec_time = data[2]
        audiofile = data[3]
        #print("Successfully read the data from database")
        print(log_id,daytype,rec_time,audiofile)

    cursor.close()
    conn.close()
    jobid = log_id
    print(audiofile)
    print(jobid)

"""
The fetch from cursor.fetchall returns this

[(41, '180MIN_Exam', '00:03:00 AM', 'audio\\8-start.mp3'), (40, '90MIN_Exam', '00:00:00 AM', ''),
(42, 'Saturday', '00:03:00 PM', 'audio\\8-start.mp3'), (43, 'Saturday', '00:03:00 PM', 'audio\\8-start.mp3')]

[(ID, 'Day Type', 'TIME', 'audio\\location.mp3'), (ID, 'Day Type', 'TIME', 'audio\\location.mp3')]

"""
def job1():
    print("file1.wav Playing...")
    mixer.music.load("1-start.mp3")
    #mixer.music.set_volume(0.9)
    mixer.music.play(1)

def job2():
    print("file2.wav Playing...")
    mixer.music.load("1-end.mp3")
    #mixer.music.set_volume(0.9)
    mixer.music.play(1)

def job3():
    print("2-start.mp3 Playing...")
    mixer.music.load("7-end.mp3")
    #mixer.music.set_volume(0.9)
    mixer.music.play(1)

def job4():
    print("2-end.mp3 Playing...")
    mixer.music.load("8-start.mp3")
    #mixer.music.set_volume(0.9)
    mixer.music.play(1)

#==========================================SIMPLIFIED FUNCTION====================================#

def job_to_play(jobid):
    #print("Day Type:" + daytype + "Time: " + rec_time + "," + jobid + " is Playing " + audiofile)
    print(jobid)

def curr_job():
    #DBRead()
    print('Current Job')
    print(log_id)
    curr_audiofile = "'" + audiofile + "'"
    print(curr_audiofile)
    mixer.music.load(curr_audiofile)
    #mixer.music.set_volume(0.9)
    mixer.music.play(1)

#============================================VARIABLES=============================================#

# relative path to search all text files (list)
audiolist = glob.glob("audio/*.mp3")
print(audiolist)

DBRead()
print(daytype) #Empty or undefined error
print(audiofile) #Empty or undefined error
print(jobid) #Empty or undefined error
if curr_daytype == "Regular":
    #schedule.every().day.at("14:31").do(jobid)
    #job_to_play(jobid)
    print(jobid)
    schedule.every().day.at("17:07").do(curr_job)

#==============================================TEST CODES================================================#
#Run job every day at specific HH:MM
schedule.every().day.at("12:45").do(job1)
schedule.every().day.at("13:07").do(job2)
schedule.every().day.at("14:31").do(job3)
schedule.every().day.at("14:31").do(job4)

#schedule.every().day.at("11:24").do(job1)
#schedule.every().day.at("11:25").do(job3)
#schedule.every().day.at("11:26").do(job2)
#schedule.every(1).minutes.do(job1)

"""
# Run job every day at specific HH:MM:SS
schedule.every().day.at("10:30:42").do(job)

# Run job on a specific day of the week
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
schedule.every().minute.at(":17").do(job)

# Run job every 3 second/minute/hour/day/week,
# Starting 3 second/minute/hour/day/week from now
schedule.every(3).seconds.do(job)
schedule.every(3).minutes.do(job)
schedule.every(3).hours.do(job)
schedule.every(3).days.do(job)
schedule.every(3).weeks.do(job)

# Run job every minute at the 23rd second
schedule.every().minute.at(":23").do(job)

# Run job every hour at the 42rd minute
schedule.every().hour.at(":42").do(job)

# Run jobs every 5th hour, 20 minutes and 30 seconds in.
# If current time is 02:00, first execution is at 06:20:30
schedule.every(5).hours.at("20:30").do(job)
"""

while True:
    schedule.run_pending()
    time.sleep(1)
</code>```

Body:
I have created a function to fetch data from Database & use it inside the code. Inside that DBRead() function the values were able to printed, but unable to use in next sequence, it throws not defined error or empty values if defined at top.

I'm trying to fetch data from sqlite DB and use those data inside the code. The code fetches time and audio location (importantly) and play that audio at a scheduled time using scheduler. Trying to simplify the job function to only 1 (as there are lot of schedules needed up to 20). Currently stuck with this data flush error.
Eg:

print(audiofile)
print(jobid)

These gets printed inside the DBRead() and not after that inside the code. Throws #Empty or undefined error

Here is the full code below

import glob
import schedule
import time
import sqlite3
import pygame
from pygame import mixer #calling for pygame mixer to play audio files

pygame.mixer.init()
curr_daytype = 'Regular'
audiofile = ''
log_id = ''
daytype = ''
jobid = ''
#==========================================FUNCTIONS===========================================#
def DBRead():

    global conn, cursor
    conn = sqlite3.connect('pythontut.db')
    cursor = conn.cursor()
    #cursor.execute("SELECT * FROM `anno` ORDER BY `daytype` ASC") #Return All Data in Asc
    #cursor.execute("SELECT * FROM anno WHERE daytype = 'Regular'") #Return Daytype if Regular

    sql = "SELECT * FROM anno WHERE daytype ='"
    fetch_daytype = curr_daytype
    sql = sql + fetch_daytype + "'"
    cursor.execute(sql)
    fetch = cursor.fetchall()

    #print(fetch)
    for data in fetch:
        #tree.insert('', 'end', values=(data[0], data[1], data[2], data[3]))
        log_id = data[0]
        daytype = data[1]
        rec_time = data[2]
        audiofile = data[3]
        #print("Successfully read the data from database")
        print(log_id,daytype,rec_time,audiofile)

    cursor.close()
    conn.close()
    jobid = log_id
    print(audiofile)
    print(jobid)

"""
The fetch from cursor.fetchall returns this

[(41, '180MIN_Exam', '00:03:00 AM', 'audio\\8-start.mp3'), (40, '90MIN_Exam', '00:00:00 AM', ''),
(42, 'Saturday', '00:03:00 PM', 'audio\\8-start.mp3'), (43, 'Saturday', '00:03:00 PM', 'audio\\8-start.mp3')]

[(ID, 'Day Type', 'TIME', 'audio\\location.mp3'), (ID, 'Day Type', 'TIME', 'audio\\location.mp3')]

"""
def job1():
    print("file1.wav Playing...")
    mixer.music.load("1-start.mp3")
    #mixer.music.set_volume(0.9)
    mixer.music.play(1)

def job2():
    print("file2.wav Playing...")
    mixer.music.load("1-end.mp3")
    #mixer.music.set_volume(0.9)
    mixer.music.play(1)

def job3():
    print("2-start.mp3 Playing...")
    mixer.music.load("7-end.mp3")
    #mixer.music.set_volume(0.9)
    mixer.music.play(1)

def job4():
    print("2-end.mp3 Playing...")
    mixer.music.load("8-start.mp3")
    #mixer.music.set_volume(0.9)
    mixer.music.play(1)

#==========================================SIMPLIFIED FUNCTION====================================#

def job_to_play(jobid):
    #print("Day Type:" + daytype + "Time: " + rec_time + "," + jobid + " is Playing " + audiofile)
    print(jobid)

def curr_job():
    #DBRead()
    print('Current Job')
    print(log_id)
    curr_audiofile = "'" + audiofile + "'"
    print(curr_audiofile)
    mixer.music.load(curr_audiofile)
    #mixer.music.set_volume(0.9)
    mixer.music.play(1)

#============================================VARIABLES=============================================#

# relative path to search all text files (list)
audiolist = glob.glob("audio/*.mp3")
print(audiolist)

DBRead()
print(daytype) #Empty or undefined error
print(audiofile) #Empty or undefined error
print(jobid) #Empty or undefined error
if curr_daytype == "Regular":
    #schedule.every().day.at("14:31").do(jobid)
    #job_to_play(jobid)
    print(jobid)
    schedule.every().day.at("17:07").do(curr_job)

#==============================================TEST CODES================================================#
#Run job every day at specific HH:MM
schedule.every().day.at("12:45").do(job1)
schedule.every().day.at("13:07").do(job2)
schedule.every().day.at("14:31").do(job3)
schedule.every().day.at("14:31").do(job4)

#schedule.every().day.at("11:24").do(job1)
#schedule.every().day.at("11:25").do(job3)
#schedule.every().day.at("11:26").do(job2)
#schedule.every(1).minutes.do(job1)

"""
# Run job every day at specific HH:MM:SS
schedule.every().day.at("10:30:42").do(job)

# Run job on a specific day of the week
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
schedule.every().minute.at(":17").do(job)

# Run job every 3 second/minute/hour/day/week,
# Starting 3 second/minute/hour/day/week from now
schedule.every(3).seconds.do(job)
schedule.every(3).minutes.do(job)
schedule.every(3).hours.do(job)
schedule.every(3).days.do(job)
schedule.every(3).weeks.do(job)

# Run job every minute at the 23rd second
schedule.every().minute.at(":23").do(job)

# Run job every hour at the 42rd minute
schedule.every().hour.at(":42").do(job)

# Run jobs every 5th hour, 20 minutes and 30 seconds in.
# If current time is 02:00, first execution is at 06:20:30
schedule.every(5).hours.at("20:30").do(job)
"""

while True:
    schedule.run_pending()
    time.sleep(1)


问:
MsalModule does not have a module def (ɵmod property)
```<code>MsalModule does not have a module def (ɵmod property)

      36 | describe('AppComponent', () => {
      37 |   beforeEach(waitForAsync(() => {
    > 38 |     TestBed.configureTestingModule({

</code>```

I am executing ng test command . I have tried

```<code>import 'jest-preset-angular/setup-jest';
</code>```

but same error

Body:
MsalModule does not have a module def (ɵmod property)

      36 | describe('AppComponent', () => {
      37 |   beforeEach(waitForAsync(() => {
    > 38 |     TestBed.configureTestingModule({

I am executing ng test command . I have tried

import 'jest-preset-angular/setup-jest';

but same error


问:
Entity creation issue in the symfony 4.4
When, i am trying to make entity. then getting issue like

In DoctrineHelper.php line 314:
Warning: Invalid argument supplied for foreach()
make:entity [-a|--api-resource] [-b|--broadcast] [--regenerate] [--overwrite] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--]  []

In DoctrineHelper.php line 314:
Warning: Invalid argument supplied for foreach()
make:entity [-a|--api-resource] [-b|--broadcast] [--regenerate] [--overwrite] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--]  []


问:
I have jsp code in which i want show all the notes which are added by user and every user have diff notes and Nid is auto_in how i can show all notes
How i can user array list in my jsp file so can view all the notes which are added by particular user.

```<code><%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>

<%
                if(request.getParameter("dr1")!=null)
                {

                try
                {
                DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
                String url="jdbc:mysql://localhost:3306/e_notes_app";
                String un="root";
                String pw="abc123";
                Connection con=DriverManager.getConnection(url,un,pw);
                String sql="delete from posts where Nid=?";
                PreparedStatement pst=con.prepareStatement(sql);
                pst.setInt(1,Integer.parseInt(request.getParameter("dr1")));
                pst.executeUpdate();
                con.close();
                }
                catch(SQLException e)
                {
                    out.println("issue :"+e);
                }
                }
            %>

<!DOCTYPE html>
<html>
<head>
<title>View Notes</title>
<style>
</style>
<%@include file="allcss.jsp" %>
</head>
<body style="background-color: #f3e5f5">

<%@include file="navbar.jsp" %>
<br>
<div class="container">
<h1 class="text-center" style="color:#6a1b9a;"><b><i class="fa fa-file-text" aria-hidden="true"></i> All Notes</b></h1>

<%

                try
                {
                DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
                String url="jdbc:mysql://localhost:3306/e_notes_app";
                String un="root";
                String pw="password";
                Connection con=DriverManager.getConnection(url,un,pw);
                String sql="select * from posts where uid=?";
                String sql1="select * from user where uid=?";
                PreparedStatement pst=con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
                pst.setString(1,uid);
                PreparedStatement pst1=con.prepareStatement(sql1);
                pst1.setString(1,uid);

                ResultSet rs=pst.executeQuery();
                ResultSet rs1=pst1.executeQuery();
                while(rs.next())
                {
                    int Nid=rs.getInt(1);
                    String Ntitle=rs.getString(2);
                    String Ntext=rs.getString(3);
                    Timestamp date=rs.getTimestamp(4);

                while(rs1.next())
                {
                    String uname=rs1.getString(1);
                    String uemail=rs1.getString(3);
                    String pw1=rs1.getString(4);

%>
<div class="row">
    <div class="col-md-12">
        <div class="card mt-3">
            <img alt="" src="mobile-devices-2017981_1280.png" class="card-img-top mt-2 mx-auto" style="max-width:100px;">

            <div class="card-body p-4">
            <h6 class="card-title" style="color:#28a745;"><b>Note Id: <%= Nid %></b></h6>
            <h6 class="card-title" style="color:#28a745;"><b>Note Title :<%= Ntitle %></b></h6>
            <p style="color:#28a745;"><b>Note :</b><br><%= Ntext %></p>
            <b class="text-success">Published By: <%= uname %> </b><br>
            <b class="text-primary"></b>
            </p>

            <p>
            <b class="text-success">Published Date: <%= date %></b><br>
            <b class="text-success"></b>
            </p>

            <div class="container text-center mt-2">
                <a href="?dr1=<%=Nid%>" class="btn btn-danger" name="dr1" id="dr1" onclick="return confirm('Are you want delete? Sure??')" >Delete</a>
                <a href="edit.jsp" class="btn btn-primary" name="ed1" id="ed1">Edit</a>
            </div>
            </div>
        </div>
    </div>
</div>
</div>
<%
                }
                }
                    con.close();
                }
                catch(SQLException e)
                {
                    out.println("Issue"+e);
                }
%>
</body>
</html>
</code>```

I want to add array list in this code so all notes of particular user are visisble. and i have 2 tables in my database one is user where user info is stored and other is posts where each notes info is stored which is added by that particular user.

Body:
How i can user array list in my jsp file so can view all the notes which are added by particular user.

<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>

<%
                if(request.getParameter("dr1")!=null)
                {

                try
                {
                DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
                String url="jdbc:mysql://localhost:3306/e_notes_app";
                String un="root";
                String pw="abc123";
                Connection con=DriverManager.getConnection(url,un,pw);
                String sql="delete from posts where Nid=?";
                PreparedStatement pst=con.prepareStatement(sql);
                pst.setInt(1,Integer.parseInt(request.getParameter("dr1")));
                pst.executeUpdate();
                con.close();
                }
                catch(SQLException e)
                {
                    out.println("issue :"+e);
                }
                }
            %>

<!DOCTYPE html>

<title>View Notes</title>

<%@include file="allcss.jsp" %>

<%@include file="navbar.jsp" %>

 All Notes

<%

                try
                {
                DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
                String url="jdbc:mysql://localhost:3306/e_notes_app";
                String un="root";
                String pw="password";
                Connection con=DriverManager.getConnection(url,un,pw);
                String sql="select * from posts where uid=?";
                String sql1="select * from user where uid=?";
                PreparedStatement pst=con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
                pst.setString(1,uid);
                PreparedStatement pst1=con.prepareStatement(sql1);
                pst1.setString(1,uid);

                ResultSet rs=pst.executeQuery();
                ResultSet rs1=pst1.executeQuery();
                while(rs.next())
                {
                    int Nid=rs.getInt(1);
                    String Ntitle=rs.getString(2);
                    String Ntext=rs.getString(3);
                    Timestamp date=rs.getTimestamp(4);

                while(rs1.next())
                {
                    String uname=rs1.getString(1);
                    String uemail=rs1.getString(3);
                    String pw1=rs1.getString(4);

%>

Note Id: <%= Nid %>

Note Title :<%= Ntitle %>

Note :
<%= Ntext %>

            Published By: <%= uname %>

            Published Date: <%= date %>

                <a href="?dr1=<%=Nid%>" class="btn btn-danger" name="dr1" id="dr1" onclick="return confirm('Are you want delete? Sure??')" >Delete
                Edit

<%
                }
                }
                    con.close();
                }
                catch(SQLException e)
                {
                    out.println("Issue"+e);
                }
%>

I want to add array list in this code so all notes of particular user are visisble. and i have 2 tables in my database one is user where user info is stored and other is posts where each notes info is stored which is added by that particular user.


问:
How to include unit tests from outside Angular project after upgrade to v15?
Since Angular v15 the require.context function from test.ts configuration file was removed.

I was using require.context to make tests outside Angular project visible to Karma. Now this was removed:

```<code>const contextGlobal = require.context('../../../folderOutsideProject/', true, /\.spec\.ts$/);
contextGlobal.keys().map(contextGlobal);
</code>```

How I can include tests from outside Angular project? (v15)

I tried creating a symlink between outsideFolder and project folder. It's not working.

EDIT:
from what I see in the source code, during the webpack compilation phase it is only included the projectSourceRoot path: https://github.com/angular/angular-cli/blob/dbcea96274122db128099967fec3d1ecceafe1ab/packages/angular_devkit/build_angular/src/builders/karma/find-tests-plugin.ts#L69

Body:
Since Angular v15 the require.context function from test.ts configuration file was removed.

I was using require.context to make tests outside Angular project visible to Karma. Now this was removed:

const contextGlobal = require.context('../../../folderOutsideProject/', true, /\.spec\.ts$/);
contextGlobal.keys().map(contextGlobal);

How I can include tests from outside Angular project? (v15)

I tried creating a symlink between outsideFolder and project folder. It's not working.

EDIT:
from what I see in the source code, during the webpack compilation phase it is only included the projectSourceRoot path: https://github.com/angular/angular-cli/blob/dbcea96274122db128099967fec3d1ecceafe1ab/packages/angular_devkit/build_angular/src/builders/karma/find-tests-plugin.ts#L69


问:
Tool to manage release and deployments
We are using GitHub actions for for building and deploying our products. We did migrate over from Azure DevOps, but we still have some projects there.

We are now faced with some difficulties. In DevOps, there is the Release feature. https://learn.microsoft.com/en-us/azure/devops/pipelines/release/releases?view=azure-devops

We use it to see the current rollout of a product, which version is in a certain stage, and release approvals that some of our clients use to approve release to production.

We have yet to find a similar functionality in GitHub.

What do you guys use to handle this? We have looked into other solutions just for release management, but haven’t found any. Services like http://Harness.io looks interesting, but it seems to include all the things that GitHub action is used for as well.

We deploy our products to own servers, Vercel, Firebase, Kubernetes etc.

Having a single tool to create and approve release would be a huge help for us.

Any suggestions, ideas or comments on this?

Thanks!

We Have tried GitHub actions, Caprover, Vercel, Firebase and Azure DevOps.
All tools offer similar things, but nothing useful for managing releases.

Title: Tool to manage release and deployments


问:
How to disable the security-constraint in runtime in java web application
We are using form based authentication in our application and we need to disable security-constraint in runtime in our java web application.

As of now we configured the security constraints in web.xml. The requirement is for the same url patterns we need to enable or disable the security contraints in run time.

We are expecting to enable or disable the security constraint in runtime.


问:
The connection to the server localhost:8080 was refused. Did you specify the right host?
While installing kubectl on Ubuntu 22.04 i got this error message. Is there any solutions for this problem please !!

I tried to reinstall it


问:
Not getting output when passing react state in array.slice method by intializing the react state. Working when passing hard coded integer values
```<code> Not getting output  when passing react state in array.slice method by intializing the react state. Working when passing hard coded integer values

>! const [pageStartIndex, setPageStartIndex] = useState(0)
>! const [pageEndingIndex, setPageEndingIndex] = useState(10)
>!
>! useEffect(() => {
>! function fetchData() {
>! Axios.get("")
>!         .then(function (response) {
>! setCurrentRecords(tableData.slice(pageStartIndex, pageEndingIndex))
>! WORKING WHEN PASSING INTEGER HARDCODED VALUES 0,10
>!         })
>!     }
>! fetchData()
>! [])
</code>```

I AM TRYING TO SET THE currentData state but not able to set the state

Body:
 Not getting output  when passing react state in array.slice method by intializing the react state. Working when passing hard coded integer values

>! const [pageStartIndex, setPageStartIndex] = useState(0)
>! const [pageEndingIndex, setPageEndingIndex] = useState(10)
>!
>! useEffect(() => {
>! function fetchData() {
>! Axios.get("")
>!         .then(function (response) {
>! setCurrentRecords(tableData.slice(pageStartIndex, pageEndingIndex))
>! WORKING WHEN PASSING INTEGER HARDCODED VALUES 0,10
>!         })
>!     }
>! fetchData()
>! [])

I AM TRYING TO SET THE currentData state but not able to set the state


问:
How to properly cycle the use of work items two times in a robot
My robot is made under the producer-consumer model, on the consumer robot side previously I had one cycle (as how normally a consumer robot works) which takes a series of files listed under the work item json file created on the producer robot on the first step, these files are uploaded onto a website, and then checks the status of that same file under a table of the website, the entire workflow is like this:

```<code>*** Tasks ***
Consumes file data work items
    Open DT webpage
    For Each Input Work Item    Process work items
    Close Browser
</code>```

But now I have to split the cycle into two:

one cycle takes only the uploading task, then after all the files are finished, a new second cycle should do the check of each file status, but after I configured the robot like this:

```<code>*** Tasks ***
Consumes file data work items
    Open DT webpage
    For Each Input Work Item    First cycle
    For Each Input Work Item    Second cycle
    Close Browser
</code>```

I noticed when I use the 'For Each Input Work Item' on the second cycle, it just got ignored and doesn't execute the listed keywords (just shows it as PASS and doesn't do any keyword order), but if I leave the 'second cycle' task alone, it does all of them, but obviously, doesn't make a cycle for all the work items, so the question is:

How I can load the work items as a FOR cycle without calling the 'For Each Input Work Item' function?

Body:
My robot is made under the producer-consumer model, on the consumer robot side previously I had one cycle (as how normally a consumer robot works) which takes a series of files listed under the work item json file created on the producer robot on the first step, these files are uploaded onto a website, and then checks the status of that same file under a table of the website, the entire workflow is like this:

*** Tasks ***
Consumes file data work items
    Open DT webpage
    For Each Input Work Item    Process work items
    Close Browser

But now I have to split the cycle into two:

one cycle takes only the uploading task, then after all the files are finished, a new second cycle should do the check of each file status, but after I configured the robot like this:

*** Tasks ***
Consumes file data work items
    Open DT webpage
    For Each Input Work Item    First cycle
    For Each Input Work Item    Second cycle
    Close Browser

I noticed when I use the 'For Each Input Work Item' on the second cycle, it just got ignored and doesn't execute the listed keywords (just shows it as PASS and doesn't do any keyword order), but if I leave the 'second cycle' task alone, it does all of them, but obviously, doesn't make a cycle for all the work items, so the question is:

How I can load the work items as a FOR cycle without calling the 'For Each Input Work Item' function?


问:
How to use grep to find Em dashes with a character right before or after and no spaces?
I am trying to clean up a bunch of writing that has Em Dashes, and want them formatted as "word - word". But in the text there are a lot of occurrences where it is "word-word". What is a good way in grep to do a search-and-replace that will identify if there is no spaces before and after the Em Dash and insert them?</p>


问:
How can I find the coordinates of the tangent to the arc - JavaScript
I need to find the point of intersection of the tangent to the arc with the frame containing the circle. For this purpose, I create a line tangent to the arc starting at the beginning of the arc and ending 200 away from it. I managed to mark the intersection point correctly. However, the coordinates of the ends of the tangent line are indistinct.

My question is:

How to correctly determine the coordinates of the end of the tangent to the arc? All arc data is known.

p1x,p1y- arc start coordinates
cx,cy- coordinate of the center of the arc

```<code>
function TangentToArc(p1x, p1y, cx, cy) {
    vx = cx - p1x;
    vy = cy - p1y;

    norm = Math.sqrt((vx * vx) + (vy * vy))
    p2x = p1x + (vy * 1000 / norm),
    p2y = p1y + (vx * 1000 / norm);
    let B = { x: p2x, y: p2y };
    return B
}

</code>```

Body:
I need to find the point of intersection of the tangent to the arc with the frame containing the circle. For this purpose, I create a line tangent to the arc starting at the beginning of the arc and ending 200 away from it. I managed to mark the intersection point correctly. However, the coordinates of the ends of the tangent line are indistinct.

My question is:

How to correctly determine the coordinates of the end of the tangent to the arc? All arc data is known.

p1x,p1y- arc start coordinates
cx,cy- coordinate of the center of the arc

function TangentToArc(p1x, p1y, cx, cy) {
    vx = cx - p1x;
    vy = cy - p1y;

    norm = Math.sqrt((vx * vx) + (vy * vy))
    p2x = p1x + (vy * 1000 / norm),
    p2y = p1y + (vx * 1000 / norm);
    let B = { x: p2x, y: p2y };
    return B
}


问:
Current request is not a multipart request in Angular
I have an issue in angular. I can't upload an excel file through my angular but it is working on my backend through POSTMAN. In angular it shows that "Current request is not a multipart request". Anybody who know please tell me a solution.

This is my frontend code( Ts code)

```<code>selectFile(event){
    this.file=event.target.files[0];
    console.log(this.file);
  }
  uploadExcel() {
    console.log("inside");
    let formData = new FormData();
    // data.append('file', input.files[0])
    formData.append('file',this.file[0]);
    this.http.post('http://localhost:8802/va2-interbanking-service/interbanking/upload',formData).subscribe(
      (Response)=>{});
}
</code>```

I want a solution for this error

Body:
I have an issue in angular. I can't upload an excel file through my angular but it is working on my backend through POSTMAN. In angular it shows that "Current request is not a multipart request". Anybody who know please tell me a solution.

This is my frontend code( Ts code)

selectFile(event){
    this.file=event.target.files[0];
    console.log(this.file);
  }
  uploadExcel() {
    console.log("inside");
    let formData = new FormData();
    // data.append('file', input.files[0])
    formData.append('file',this.file[0]);
    this.http.post('http://localhost:8802/va2-interbanking-service/interbanking/upload',formData).subscribe(
      (Response)=>{});
}

I want a solution for this error


问:
Slow loading Django Admin change/add
The Loading time is too much for this particular model in admin panel.I know it is because I have too many values in Foreign Fields (field with 20k+ records each) which takes too much time to load on client side. Is there a way to optimise this? below is my code and screenshot of loadtime,

Loading Time

Models:

```<code>class Alert(BaseModelCompleteUserTimestamps):
    type = models.ForeignKey(to=AlertType, on_delete=models.CASCADE, verbose_name="Type")
    device = models.ForeignKey(Device, on_delete=models.CASCADE, related_name="alert_device")
    device_event = models.ForeignKey("dm_detection.VIDSDetection",
                                     on_delete=models.CASCADE, null=True, blank=True, related_name="device_event")
    anpr_event = models.ForeignKey("dm_detection.VSDSDetection",
                                   on_delete=models.CASCADE, null=True, blank=True, related_name="anpr_event")
    ecb_event = models.ForeignKey("dm_detection.ECBDetection",
                                   on_delete=models.CASCADE, null=True, blank=True, related_name="ecb_event")
    hr_only = models.IntegerField(null=True, blank=True)

    # acknowledged
    is_acknowledged = models.BooleanField(default=False, verbose_name="Acknowledged")
    acknowledged_at = models.DateTimeField(blank=True, null=True)
    acknowledged_by = models.ForeignKey(to=User, on_delete=models.CASCADE, null=True, blank=True,
                                        related_name="alert_acknowledged_by")
    # resolved
    is_resolved = models.BooleanField(default=False, verbose_name="Resolved")
    resolved_at = models.DateTimeField(blank=True, null=True)
    resolved_by = models.ForeignKey(to=User, on_delete=models.CASCADE, null=True, blank=True,

    status = models.ForeignKey(to=TicketStatus, on_delete=models.DO_NOTHING, default=1)
</code>```

Admin.py

```<code>@admin.register(Alert)
class AlertModelAdmin(BaseModelCompleteUserTimestampsAdmin):
    form = AlertEditForm
    fields = ('type',
              'device',
              'device_event',
              'status', 'hr_only',
              'is_acknowledged', 'acknowledged_at', 'acknowledged_by',
              'is_resolved', 'resolved_at', 'resolved_by', 'anpr_event',
              'created_at',
              'updated_at', 'OD_vehicle_number'
              )
</code>```

Forms.py

```<code>class AlertEditForm(forms.ModelForm):
    status = forms.ModelChoiceField(queryset=TicketStatus.objects.filter(is_for_alert=True))
    device_event = forms.ModelChoiceField(queryset=VIDSDetection.objects.all())
    anpr_event = forms.ModelChoiceField(queryset=VSDSDetection.objects.all())
    acknowledged_by = forms.ModelChoiceField(queryset=User.objects.all())
    resolved_by = forms.ModelChoiceField(queryset=User.objects.all())

    class Meta:
        model = Alert
        fields = '__all__'
</code>```

Title: Slow loading Django Admin change/add

Body:
The Loading time is too much for this particular model in admin panel.I know it is because I have too many values in Foreign Fields (field with 20k+ records each) which takes too much time to load on client side. Is there a way to optimise this? below is my code and screenshot of loadtime,

Loading Time

Models:

class Alert(BaseModelCompleteUserTimestamps):
    type = models.ForeignKey(to=AlertType, on_delete=models.CASCADE, verbose_name="Type")
    device = models.ForeignKey(Device, on_delete=models.CASCADE, related_name="alert_device")
    device_event = models.ForeignKey("dm_detection.VIDSDetection",
                                     on_delete=models.CASCADE, null=True, blank=True, related_name="device_event")
    anpr_event = models.ForeignKey("dm_detection.VSDSDetection",
                                   on_delete=models.CASCADE, null=True, blank=True, related_name="anpr_event")
    ecb_event = models.ForeignKey("dm_detection.ECBDetection",
                                   on_delete=models.CASCADE, null=True, blank=True, related_name="ecb_event")
    hr_only = models.IntegerField(null=True, blank=True)

    # acknowledged
    is_acknowledged = models.BooleanField(default=False, verbose_name="Acknowledged")
    acknowledged_at = models.DateTimeField(blank=True, null=True)
    acknowledged_by = models.ForeignKey(to=User, on_delete=models.CASCADE, null=True, blank=True,
                                        related_name="alert_acknowledged_by")
    # resolved
    is_resolved = models.BooleanField(default=False, verbose_name="Resolved")
    resolved_at = models.DateTimeField(blank=True, null=True)
    resolved_by = models.ForeignKey(to=User, on_delete=models.CASCADE, null=True, blank=True,

    status = models.ForeignKey(to=TicketStatus, on_delete=models.DO_NOTHING, default=1)

Admin.py

@admin.register(Alert)
class AlertModelAdmin(BaseModelCompleteUserTimestampsAdmin):
    form = AlertEditForm
    fields = ('type',
              'device',
              'device_event',
              'status', 'hr_only',
              'is_acknowledged', 'acknowledged_at', 'acknowledged_by',
              'is_resolved', 'resolved_at', 'resolved_by', 'anpr_event',
              'created_at',
              'updated_at', 'OD_vehicle_number'
              )

Forms.py

class AlertEditForm(forms.ModelForm):
    status = forms.ModelChoiceField(queryset=TicketStatus.objects.filter(is_for_alert=True))
    device_event = forms.ModelChoiceField(queryset=VIDSDetection.objects.all())
    anpr_event = forms.ModelChoiceField(queryset=VSDSDetection.objects.all())
    acknowledged_by = forms.ModelChoiceField(queryset=User.objects.all())
    resolved_by = forms.ModelChoiceField(queryset=User.objects.all())

    class Meta:
        model = Alert
        fields = '__all__'


问:
Why is rust-mongodb library slow compared to c++ version?
I've  loaded this airbnb dataset into a local mongodb(version 4.4.17) database called sample_db and collection called barcelona_cal. There are 6175334 records in the collection.

I created a small experiment to compare rust, c++ and python performances. The code for each langugage will simply get a cursor for the collection and iterate over it, increment a counter and note the time taken.

here's the python code:

```<code>import pymongo
from bson.raw_bson import RawBSONDocument

db = "sample_db"
collection = "barcelona_cal"

def get_docs(db, collection, document_class=RawBSONDocument):
    url = "mongodb://localhost:27017"
    client = pymongo.MongoClient(url, document_class=document_class)
    coll = client.get_database(db).get_collection(collection)

    count = 0
    for doc in coll.find({}):
        count += 1

    print('Doc count: ', count)

def main():
    get_docs(db, collection, dict)

if __name__ == "__main__":
    main()

</code>```

running this code using time python3 test.py returns the following times:

```<code>real    0m32.784s
user    0m28.076s
sys     0m1.888s
</code>```

considering most of the time is spent in decoding the bson into python objects, I ran it again with the the default argument document_class=RawBSONDocument. It gave the following times:

```<code>real    0m12.132s
user    0m8.113s
sys     0m1.266s
</code>```

Now, I repeated the same experiment with c++ with the following code:

```<code>#include <iostream>
#include <mongocxx/client.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/instance.hpp>
#include <bsoncxx/types.hpp>

void mongo_connection_test(){
    mongocxx::instance instance{};
    mongocxx::client client{mongocxx::uri{}};
    mongocxx::database database = client["sample_db"];
    mongocxx::collection collection = database["barcelona_cal"];

    mongocxx::cursor cursor = collection.find({});

    bsoncxx::document::element el;
    uint32_t count = 0;

    for(auto doc: cursor) {
        count += 1;
    }
    std::cout << "Leads: " << count << std::endl;
}

int main(){
    mongo_connection_test();
}
</code>```

This resulted in the following times:

```<code>real    0m3.347s
user    0m0.388s
sys     0m1.004s
</code>```

Now, coming to the rust code. On rustc 1.65, with latest mongodb crate version 2.3.1, this is the equivalent code:

```<code>use std::io::Read;
use mongodb::{sync::Client, options::ClientOptions, bson::doc, bson::Document};

fn cursor_iterate()-> mongodb::error::Result<()>{
    // setup
    let mongo_url = "mongodb://localhost:27017";
    let db_name = "sample_db";
    let collection_name = "barcelona_cal";

    let client = Client::with_uri_str(mongo_url)?;
    let database = client.database(db_name);
    let collection = database.collection::<Document>(collection_name);
    let mut cursor = collection.find(None, None)?;

    let mut count = 0;
    for result in cursor {
        count += 1;
    }

    println!("Doc count:  {}", count);
    Ok(())
}

fn main() {
    cursor_iterate();
}
</code>```

The code was built with cargo build --release and ran with time cargo run --release. I got the following times

```<code>real    0m18.727s
user    0m15.541s
sys     0m0.790s
</code>```

I've run every version multiple times and got identical results. so all these numbers can be considered representative.

Edit: I've run the rust binary separately like time target/release/bbson and that made very little, if no difference cos I did the build and run steps separately.

So the question is why is the mongodb rust library so much slower than c++? One interesting thing that I noticed, which may explain this partly is that in the system monitor (ubuntu 22.04), the Network part shows that the tranfer rate is no higher than 64MB/s. Meanwhile for c++ it goes up to 600MB/s. I see similar thing when running the python with dict and that explains the slow bson decoding in python, so is the deserializer that slow in rust too?

Body:
I've  loaded this airbnb dataset into a local mongodb(version 4.4.17) database called sample_db and collection called barcelona_cal. There are 6175334 records in the collection.

I created a small experiment to compare rust, c++ and python performances. The code for each langugage will simply get a cursor for the collection and iterate over it, increment a counter and note the time taken.

here's the python code:

import pymongo
from bson.raw_bson import RawBSONDocument

db = "sample_db"
collection = "barcelona_cal"

def get_docs(db, collection, document_class=RawBSONDocument):
    url = "mongodb://localhost:27017"
    client = pymongo.MongoClient(url, document_class=document_class)
    coll = client.get_database(db).get_collection(collection)

    count = 0
    for doc in coll.find({}):
        count += 1

    print('Doc count: ', count)

def main():
    get_docs(db, collection, dict)

if __name__ == "__main__":
    main()

running this code using time python3 test.py returns the following times:

real    0m32.784s
user    0m28.076s
sys     0m1.888s

considering most of the time is spent in decoding the bson into python objects, I ran it again with the the default argument document_class=RawBSONDocument. It gave the following times:

real    0m12.132s
user    0m8.113s
sys     0m1.266s

Now, I repeated the same experiment with c++ with the following code:

#include <iostream>
#include <mongocxx/client.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/instance.hpp>
#include <bsoncxx/types.hpp>

void mongo_connection_test(){
    mongocxx::instance instance{};
    mongocxx::client client{mongocxx::uri{}};
    mongocxx::database database = client["sample_db"];
    mongocxx::collection collection = database["barcelona_cal"];

    mongocxx::cursor cursor = collection.find({});

    bsoncxx::document::element el;
    uint32_t count = 0;

    for(auto doc: cursor) {
        count += 1;
    }
    std::cout << "Leads: " << count << std::endl;
}

int main(){
    mongo_connection_test();
}

This resulted in the following times:

real    0m3.347s
user    0m0.388s
sys     0m1.004s

Now, coming to the rust code. On rustc 1.65, with latest mongodb crate version 2.3.1, this is the equivalent code:

use std::io::Read;
use mongodb::{sync::Client, options::ClientOptions, bson::doc, bson::Document};

fn cursor_iterate()-> mongodb::error::Result<()>{
    // setup
    let mongo_url = "mongodb://localhost:27017";
    let db_name = "sample_db";
    let collection_name = "barcelona_cal";

    let client = Client::with_uri_str(mongo_url)?;
    let database = client.database(db_name);
    let collection = database.collection::<Document>(collection_name);
    let mut cursor = collection.find(None, None)?;

    let mut count = 0;
    for result in cursor {
        count += 1;
    }

    println!("Doc count:  {}", count);
    Ok(())
}

fn main() {
    cursor_iterate();
}

The code was built with cargo build --release and ran with time cargo run --release. I got the following times

real    0m18.727s
user    0m15.541s
sys     0m0.790s

I've run every version multiple times and got identical results. so all these numbers can be considered representative.

Edit: I've run the rust binary separately like time target/release/bbson and that made very little, if no difference cos I did the build and run steps separately.

So the question is why is the mongodb rust library so much slower than c++? One interesting thing that I noticed, which may explain this partly is that in the system monitor (ubuntu 22.04), the Network part shows that the tranfer rate is no higher than 64MB/s. Meanwhile for c++ it goes up to 600MB/s. I see similar thing when running the python with dict and that explains the slow bson decoding in python, so is the deserializer that slow in rust too?


问:
How to use an interface where one module implements the functionality and another is calling it for the result in Kotlin
How can I define and implement an interface where one Module is using it for the implementation (lets say the View layer) and another Module is calling it to get the result from the defined implementation (say the Backend Layer)?

I want to keep seperation of concerns so that the Backend layer does not care about how it is implemented, yet the View Layer must always have an implementation even if there are different implementations of this module.

Say the interface is the following:

```<code>interface AreaProcessing{
/**
 *
 * @param point Pair<Double, Double> the point's <Longitude, Latitude>
 * @param areaPointsList ArrayList<Pair<Double, Double>> as of <Longitude, Latitude>
 * @return Boolean True, if the given point is inside the area, False otherwise.
 */
fun isPointInsideTheArea(
    point: Pair<Double, Double>,
    areaPointsList: ArrayList<Pair<Double, Double>>
): Boolean
</code>```

More specifically, I have a module that is based on the specific implementation of the map engine say GoogleMapModule. I want this module to implement the specific interface and then in the backend to call it without having any knowledge on the map module or the class that is being implemented within. So if I then decide to use another module, say BingMapModule all I have to do is implement the interface ONLY in the new module without affecting the backend. Optionally, if there is no implementation for the specific interface then an exception could be thrown.

I am not sure if this doable with interfaces or with abstract class. That is why I am asking here.

I have read the following post here :
If I call an interface method, will it get the method body from implementation class and execute?

Thanks in advance.

Body:
How can I define and implement an interface where one Module is using it for the implementation (lets say the View layer) and another Module is calling it to get the result from the defined implementation (say the Backend Layer)?

I want to keep seperation of concerns so that the Backend layer does not care about how it is implemented, yet the View Layer must always have an implementation even if there are different implementations of this module.

Say the interface is the following:

interface AreaProcessing{
/**
 *
 * @param point Pair<Double, Double> the point's <Longitude, Latitude>
 * @param areaPointsList ArrayList<Pair<Double, Double>> as of <Longitude, Latitude>
 * @return Boolean True, if the given point is inside the area, False otherwise.
 */
fun isPointInsideTheArea(
    point: Pair<Double, Double>,
    areaPointsList: ArrayList<Pair<Double, Double>>
): Boolean

More specifically, I have a module that is based on the specific implementation of the map engine say GoogleMapModule. I want this module to implement the specific interface and then in the backend to call it without having any knowledge on the map module or the class that is being implemented within. So if I then decide to use another module, say BingMapModule all I have to do is implement the interface ONLY in the new module without affecting the backend. Optionally, if there is no implementation for the specific interface then an exception could be thrown.

I am not sure if this doable with interfaces or with abstract class. That is why I am asking here.

I have read the following post here :
If I call an interface method, will it get the method body from implementation class and execute?

Thanks in advance.


问:
Integrity error thrown even when parent model has values
I am getting this integrity error

```<code>ORA-02091: transaction rolled back ORA-02291: integrity constraint (SYSTEM.MAIN_PAIN_ARTIST_ID_4D007402_F) violated - parent key not found
</code>```

even when parent model contain the values passed to foreign keys in the child table

here are my models

```<code>class Artist(models.Model):
    id = models.PositiveSmallIntegerField(primary_key=True , unique = True)
    name = models.CharField(max_length=200)
    country = models.CharField(max_length=200)
    year_of_birth = models.PositiveSmallIntegerField()
    year_of_death  = models.PositiveSmallIntegerField(null=True)

    def __str__(self) -> str:
        return self.name

class Owner(models.Model):
    id = models.PositiveSmallIntegerField(primary_key=True , unique = True)
    name = models.CharField(max_length=200)
    address = models.CharField(max_length=200)
    city = models.CharField(max_length=10)

    def __str__(self) -> str:
        return self.name

class Painting(models.Model):
    id = models.PositiveSmallIntegerField(primary_key=True , unique = True)
    title =  models.CharField(max_length=200)
    theme = models.CharField(max_length=200)
    rent = models.FloatField()
    owner_id = models.ForeignKey(Owner , on_delete=models.CASCADE , null= False , blank = False)
    artist_id = models.ForeignKey(Artist , on_delete=models.CASCADE , null=False ,blank = False)

    def __str__(self) -> str:
        return self.title
</code>```

Here is my views.py file

```<code>def create_painting(response):
    if response.method == "POST":
        painting_form = createNewPainting(response.POST)
        if painting_form.is_valid():
            i = painting_form.cleaned_data["id"]
            ttl = painting_form.cleaned_data["title"]
            thm = painting_form.cleaned_data["theme"]
            rent = painting_form.cleaned_data["rent"]
            own_id= int(painting_form.cleaned_data["owner_id"])
            art_id= int(painting_form.cleaned_data["artist_id"])
            answers = Painting.objects.filter(id=i)
            if not answers:
                with connection.cursor() as cursor:
                    try:
                        r = cursor.execute(
                            f"INSERT INTO main_painting VALUES ({i} ,'{ttl}' , '{thm}' , {rent} , {own_id} , {art_id});")
                        return HttpResponseRedirect("paintings/%s" %i)
                    except IntegrityError as e:
                        return render(response , "main/error.html" , {"error" : e} )
            else:
                error = "Painting with ID already exists !"
                return render(response , "main/error.html" , {"error" : error} )

        else:
            return render(response , "main/create-painting.html" , {"form" : painting_form})
    else:
        painting_form = createNewPainting()
        return render(response , "main/create-painting.html" , {"form" : painting_form})

def painting_index(response, id):

    painting = Painting.objects.get(id = id)
    return render(response , "main/display_painting_det.html" , {"painting":painting})
</code>```

I am using oracle 21c as database. I have tried type casting cleaned value to integer but it does not work. What could be the error here?

Body:
I am getting this integrity error

ORA-02091: transaction rolled back ORA-02291: integrity constraint (SYSTEM.MAIN_PAIN_ARTIST_ID_4D007402_F) violated - parent key not found

even when parent model contain the values passed to foreign keys in the child table

here are my models

class Artist(models.Model):
    id = models.PositiveSmallIntegerField(primary_key=True , unique = True)
    name = models.CharField(max_length=200)
    country = models.CharField(max_length=200)
    year_of_birth = models.PositiveSmallIntegerField()
    year_of_death  = models.PositiveSmallIntegerField(null=True)

    def __str__(self) -> str:
        return self.name

class Owner(models.Model):
    id = models.PositiveSmallIntegerField(primary_key=True , unique = True)
    name = models.CharField(max_length=200)
    address = models.CharField(max_length=200)
    city = models.CharField(max_length=10)

    def __str__(self) -> str:
        return self.name

class Painting(models.Model):
    id = models.PositiveSmallIntegerField(primary_key=True , unique = True)
    title =  models.CharField(max_length=200)
    theme = models.CharField(max_length=200)
    rent = models.FloatField()
    owner_id = models.ForeignKey(Owner , on_delete=models.CASCADE , null= False , blank = False)
    artist_id = models.ForeignKey(Artist , on_delete=models.CASCADE , null=False ,blank = False)

    def __str__(self) -> str:
        return self.title

Here is my views.py file

def create_painting(response):
    if response.method == "POST":
        painting_form = createNewPainting(response.POST)
        if painting_form.is_valid():
            i = painting_form.cleaned_data["id"]
            ttl = painting_form.cleaned_data["title"]
            thm = painting_form.cleaned_data["theme"]
            rent = painting_form.cleaned_data["rent"]
            own_id= int(painting_form.cleaned_data["owner_id"])
            art_id= int(painting_form.cleaned_data["artist_id"])
            answers = Painting.objects.filter(id=i)
            if not answers:
                with connection.cursor() as cursor:
                    try:
                        r = cursor.execute(
                            f"INSERT INTO main_painting VALUES ({i} ,'{ttl}' , '{thm}' , {rent} , {own_id} , {art_id});")
                        return HttpResponseRedirect("paintings/%s" %i)
                    except IntegrityError as e:
                        return render(response , "main/error.html" , {"error" : e} )
            else:
                error = "Painting with ID already exists !"
                return render(response , "main/error.html" , {"error" : error} )

        else:
            return render(response , "main/create-painting.html" , {"form" : painting_form})
    else:
        painting_form = createNewPainting()
        return render(response , "main/create-painting.html" , {"form" : painting_form})

def painting_index(response, id):

    painting = Painting.objects.get(id = id)
    return render(response , "main/display_painting_det.html" , {"painting":painting})

I am using oracle 21c as database. I have tried type casting cleaned value to integer but it does not work. What could be the error here?


问:
WP Rocket is making my site to get a white page every time i update pictures or text
So i have Wp rocket on my site and i saw that every time i modify a image or a text from my site, the homepage appears white with only the cookie icon visible.... i have to delete cache each time this happens and also i have to check page every time.. This i what support said but no clue.....

I enabled WP Debug while performing the following test:
I made a small edit (added a dot at the beginning of the content) and saved the settings. I visited the page from desktop and from mobile, but it rendered correctly. I repeated the test by reverting the change I made. Still, the page got rendered correctly.

So far I could not reproduce the issue, but I checked the information provided by Sandy. Based on my observations, the issue is not related to WP Rocket, but I will explain to you why you see it when WP Rocket is enabled.

Generally, when a page is rendered in WordPress your theme is rendering the following parts of the code in the exact order for each page:

header.php

template (i.e. the content)

footer.php

When the issue occurs, the template part is missing. Here is how I found it:

Sandy was able to reproduce the issue in the past and shared the code difference between the blank page and the correctly displayed page. You can find it here: https://www.diffchecker.com/AKBv9sVj/

Here is the place where part of the HTML is missing on the "blank" page. And I highlighted the last line of code that is included in both cache files:

Full-screen image: https://i.imgur.com/28DgxpT.png

That last line of code comes from header-adora-framework.php which is included with no issues:

Similarly, the next segment that both pages have in common comes from the footer:

Full-screen image: https://i.imgur.com/wsw4wHk.png

This is where the code in footer-adora-framework.php, and it is also included with no issues:

Full-screen image: https://i.imgur.com/9Nw0QDv.png

Based on this, I can see that the template part is missing. It seems your theme is not rendering the template sometimes.

I checked the debug.log that is available on the server and found the following fatal error that might be related to the issue:

Here is the main part of the error: "The template "/wp-content/themes/project-theme/templates/layout.html.php" cannot be rendered."

If you check the file mentioned in the error, you will find that this is exactly the part that is missing:

Full-screen image: https://i.imgur.com/SpLKbyH.png

The code from /wp-content/themes/project-theme/templates/layout.html.php:

Full-screen image: https://i.imgur.com/7KfMxCR.png

The reason that you see the issue only when WP Rocket is enabled is due to caching. WP Rocket "takes a snapshot" of the page the way it was rendered the first time it was accessed.
If the template did not render the template part when the page was accessed - this is how the page will be cached and you will see the issue persists.

This, however, does not mean that the issue is resolved when you disable WP Rocket.
The issue is happening, but it is not persistent as with caching. Refreshing the page when caching is not present would likely resolve the problem.

You would need to pass this information on to your theme support. Possibly they will have suggestions on how the problem can be resolved.

I try all but nonthing. I hope to fix this with your help


问:
can i use Arrayformula in sumproduct google sheets?
I'm trying to sum the product of three arrays.
All three have the same size (10 rows, 1 col).
The middle array is a text, and I want to lookup the value corresponding to the text in another named table.
So I tried the following formulas:

```<code>=arrayformula(SUMPRODUCT(K12:K21,vlookup(id_tip_art,'Copy of 002F_OF'!def_manop,3,false),R12:R21))
</code>```

or

```<code>=SUMPRODUCT(K12:K21,arrayformula(vlookup(id_tip_art,'Copy of 002F_OF'!def_manop,3,false)),
R12:R21)
</code>```

#parse ERROR.

Any ideas?
Thx

Following formula works and returns the expected array size, but cannot insert it in sumproduct:

```<code>=arrayformula(vlookup(id_tip_art,'Copy of 002F_OF'!def_manop,3,false))
</code>```

Body:
I'm trying to sum the product of three arrays.
All three have the same size (10 rows, 1 col).
The middle array is a text, and I want to lookup the value corresponding to the text in another named table.
So I tried the following formulas:

=arrayformula(SUMPRODUCT(K12:K21,vlookup(id_tip_art,'Copy of 002F_OF'!def_manop,3,false),R12:R21))

or

=SUMPRODUCT(K12:K21,arrayformula(vlookup(id_tip_art,'Copy of 002F_OF'!def_manop,3,false)),
R12:R21)

#parse ERROR.

Any ideas?
Thx

Following formula works and returns the expected array size, but cannot insert it in sumproduct:

=arrayformula(vlookup(id_tip_art,'Copy of 002F_OF'!def_manop,3,false))


问:
"No such file or directory" protoc
The protofiles are located here E:\GolangTr\GRPC\internal\protofiles\chat.proto.

At the command line I enter

protoc --go_out=. --go_opt=paths=source_relative\ --go-grpc_out=. --go-grpc_opt=paths=source_relative \internal/protofiles/chat
.proto
```
<p>I get an error -</p>
<pre class="lang-bash prettyprint-override"><code>No such file or directory.
</code>```

What am I doing wrong?

Studying gRPC in golang

Title: "No such file or directory" protoc

Body:
The protofiles are located here E:\GolangTr\GRPC\internal\protofiles\chat.proto.

At the command line I enter

protoc --go_out=. --go_opt=paths=source_relative\ --go-grpc_out=. --go-grpc_opt=paths=source_relative \internal/protofiles/chat
.proto

I get an error -

No such file or directory.

What am I doing wrong?

Studying gRPC in golang


问:
How do I remove or change the 'Unknown' option from the dropdown of a BooleanField filter created using django_filters?
In my models.py, there's a BooleanField named cash:

```<code>class Realization(models.Model):
    patient=models.ForeignKey(Patient, on_delete=CASCADE)
    patient_type=models.ForeignKey(PatientType, on_delete=CASCADE, default=None)
    cash=models.BooleanField(default=False)
    amount_received=models.DecimalField(max_digits=10, decimal_places=2, default=0)
</code>```

And I'm using this model as a ForeignKey in another model IPDReport:

```<code>class IpdReport(models.Model):
    patient=models.ForeignKey(Patient, on_delete=CASCADE)
    package=models.ForeignKey(Package, on_delete=CASCADE, blank=True, null=True)
    approvedpackage=models.ForeignKey(ApprovedPackage, on_delete=CASCADE, blank=True, null=True)
    ctscan=models.ForeignKey(CTScan, on_delete=CASCADE, blank=True, null=True)
    radiations=models.ForeignKey(Radiations, on_delete=CASCADE, blank=True, null=True)
    discharge=models.ForeignKey(Discharge, on_delete=CASCADE, blank=True, null=True)
    realization=models.ForeignKey(Realization, on_delete=CASCADE, blank=True, null=True)
    lockdata=models.ForeignKey(LockData, on_delete=CASCADE, blank=True, null=True)
</code>```

I wanted to create a filter for the IPDReport data, including Realization's cash field, so I used this way:

```<code>class IpdFilters(django_filters.FilterSet):
    patient__name=django_filters.CharFilter(widget=forms.TextInput(attrs={'class':'form-control'}), lookup_expr='icontains', label='Name')
    ctscan__rt_number=django_filters.CharFilter(widget=forms.TextInput(attrs={'class':'form-control'}), lookup_expr='icontains', label='RT Number')
    package__patient_type__patient_type=django_filters.CharFilter(widget=forms.TextInput(attrs={'class':'form-control'}), lookup_expr='icontains', label='Type of Patient')
    realization__amount_received__gt=django_filters.NumberFilter(widget=forms.NumberInput(attrs={'class':'form-control'}), field_name='realization__amount_received', lookup_expr='gt', label='Min. Amount Received')
    realization__amount_received__lt=django_filters.NumberFilter(widget=forms.NumberInput(attrs={'class':'form-control'}), field_name='realization__amount_received', lookup_expr='lt', label='Max. Amount Received')
    from_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'from_doa', 'class':'form-control'}), field_name='package__date_of_admission', label='From - Date of Admission ', lookup_expr='gte')
    to_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'to_doa', 'class':'form-control'}), field_name='package__date_of_admission', label='To - Date of Admission ', lookup_expr='lte')
    from_date_bill=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'from_bd', 'class':'form-control'}), field_name='realization__billing_month', label='From - Date of Billing ', lookup_expr='gte')
    to_date_bill=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'to_bd', 'class':'form-control'}), field_name='realization__billing_month', label='To - Date of Billing ', lookup_expr='lte')

    class Meta:
        model=IpdReport
        fields={
            'realization__cash':['exact']
        }
</code>```

Now on the IPDReport page in my app, the field renders like below:

In the dropdown, the default option shows as Unknown. Is there any way I can change or remove that completely?

Also, how can I add an HTML class attribute to this cash field under Meta class?

Body:
In my models.py, there's a BooleanField named cash:

class Realization(models.Model):
    patient=models.ForeignKey(Patient, on_delete=CASCADE)
    patient_type=models.ForeignKey(PatientType, on_delete=CASCADE, default=None)
    cash=models.BooleanField(default=False)
    amount_received=models.DecimalField(max_digits=10, decimal_places=2, default=0)

And I'm using this model as a ForeignKey in another model IPDReport:

class IpdReport(models.Model):
    patient=models.ForeignKey(Patient, on_delete=CASCADE)
    package=models.ForeignKey(Package, on_delete=CASCADE, blank=True, null=True)
    approvedpackage=models.ForeignKey(ApprovedPackage, on_delete=CASCADE, blank=True, null=True)
    ctscan=models.ForeignKey(CTScan, on_delete=CASCADE, blank=True, null=True)
    radiations=models.ForeignKey(Radiations, on_delete=CASCADE, blank=True, null=True)
    discharge=models.ForeignKey(Discharge, on_delete=CASCADE, blank=True, null=True)
    realization=models.ForeignKey(Realization, on_delete=CASCADE, blank=True, null=True)
    lockdata=models.ForeignKey(LockData, on_delete=CASCADE, blank=True, null=True)

I wanted to create a filter for the IPDReport data, including Realization's cash field, so I used this way:

class IpdFilters(django_filters.FilterSet):
    patient__name=django_filters.CharFilter(widget=forms.TextInput(attrs={'class':'form-control'}), lookup_expr='icontains', label='Name')
    ctscan__rt_number=django_filters.CharFilter(widget=forms.TextInput(attrs={'class':'form-control'}), lookup_expr='icontains', label='RT Number')
    package__patient_type__patient_type=django_filters.CharFilter(widget=forms.TextInput(attrs={'class':'form-control'}), lookup_expr='icontains', label='Type of Patient')
    realization__amount_received__gt=django_filters.NumberFilter(widget=forms.NumberInput(attrs={'class':'form-control'}), field_name='realization__amount_received', lookup_expr='gt', label='Min. Amount Received')
    realization__amount_received__lt=django_filters.NumberFilter(widget=forms.NumberInput(attrs={'class':'form-control'}), field_name='realization__amount_received', lookup_expr='lt', label='Max. Amount Received')
    from_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'from_doa', 'class':'form-control'}), field_name='package__date_of_admission', label='From - Date of Admission ', lookup_expr='gte')
    to_date=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'to_doa', 'class':'form-control'}), field_name='package__date_of_admission', label='To - Date of Admission ', lookup_expr='lte')
    from_date_bill=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'from_bd', 'class':'form-control'}), field_name='realization__billing_month', label='From - Date of Billing ', lookup_expr='gte')
    to_date_bill=django_filters.DateFilter(widget=forms.DateInput(attrs={'id': 'to_bd', 'class':'form-control'}), field_name='realization__billing_month', label='To - Date of Billing ', lookup_expr='lte')

    class Meta:
        model=IpdReport
        fields={
            'realization__cash':['exact']
        }

Now on the IPDReport page in my app, the field renders like below:

In the dropdown, the default option shows as Unknown. Is there any way I can change or remove that completely?

Also, how can I add an HTML class attribute to this cash field under Meta class?


问:
ElasticSearch: analyze (check tokens) spesific filed of the document
Can we analyze the specific field of the document? I found out only a command for analyzing text

GET index_name/_analyze
{
"text": "test your code"
}


问:
Auto drop to frame , debug mode ,eclipse
I'm using Eclipse IDE for Java
Maven Projects
when I'm on debug mode and try to
edit the code and save it, the green
line should go to the first line of the
function (like drop to frame) to see
the change, my problem now when I
edit the code and save it, the green
line do not go back to first line of
the function as before

what settings should I modify?


问:
How to do queuing graphql calls using ApolloClient in next.js?
Ex.

```<code>const clientRef = useRef(initClient());

function initClient() {
    const authLink = setContext(async (\_, options) =\> {
        const {
            headers =
                {
‘Accept-Language’: ‘en’ }
        } = options;
        headers.Authorization = Bearer ${token};
        return { headers };
    });

    const client = new ApolloClient({
        link: ${url},
        cache: new InMemoryCache(),
        defaultOptions,
    });
    return client;

}
</code>```

Here is my configuration and here is my query and mutation:

```<code>const handleQuery = async (params) =\> {
    const res = await clientRef.current.query(params);
    const { data, errors } = res;
    if (errors) {
        checkErrorForUnauthenticated(errors);
    }
    return { data };
};

const handleMutation = async (params) =\> {
    const res = await clientRef.current.mutate(params);
    const { data, errors } = res;
    if (errors) {
        checkErrorForUnauthenticated(errors);
    }
    return { data };
};
</code>```

Problem: I have 3 apis on HOC and 5 apis in child component. So when access token expires after 1 API call, I have to call another endpoint to get access token and then want to call remain apis.

But now problem is while doing call for refresh token other apis are fired with old token and got error.

How can I queue the remaining calls while refresh token is being called?

5 apis are calling after 1st api call is access token expire. I'm calling for refreshToken api meanwhile other apis are calling. I want other apis call to be pause and resume after refreshToken.

Body:
Ex.

const clientRef = useRef(initClient());

function initClient() {
    const authLink = setContext(async (\_, options) =\> {
        const {
            headers =
                {
‘Accept-Language’: ‘en’ }
        } = options;
        headers.Authorization = Bearer ${token};
        return { headers };
    });

    const client = new ApolloClient({
        link: ${url},
        cache: new InMemoryCache(),
        defaultOptions,
    });
    return client;

}

Here is my configuration and here is my query and mutation:

const handleQuery = async (params) =\> {
    const res = await clientRef.current.query(params);
    const { data, errors } = res;
    if (errors) {
        checkErrorForUnauthenticated(errors);
    }
    return { data };
};

const handleMutation = async (params) =\> {
    const res = await clientRef.current.mutate(params);
    const { data, errors } = res;
    if (errors) {
        checkErrorForUnauthenticated(errors);
    }
    return { data };
};

Problem: I have 3 apis on HOC and 5 apis in child component. So when access token expires after 1 API call, I have to call another endpoint to get access token and then want to call remain apis.

But now problem is while doing call for refresh token other apis are fired with old token and got error.

How can I queue the remaining calls while refresh token is being called?

5 apis are calling after 1st api call is access token expire. I'm calling for refreshToken api meanwhile other apis are calling. I want other apis call to be pause and resume after refreshToken.


问:
I am trying to read shape file from geopandas library using gpd.read_file() DriverError: not recognized as a supported file format. ERROR
DriverError: '/vsizip//vsimem/3a044273ad394c659206ed9154647032.zip' not recognized as a supported file format.

I am trying to read shape file link  which is on my github using gpd.read_file() but I got this error help me please
DriverError: '/vsizip//vsimem/3a044273ad394c659206ed9154647032.zip' not recognized as a supported file format.

I tried without using zip format as well

```<code>url_shp_file = "https://github.com/Ezeysay16/veridosyalari/blob/main/shapefile/countries.shp?raw=true"
countries_gdf = gpd.read_file(url_shp_file)#Geopandas ile verilen shape dosyasını read_file() fonksiyonu ile okuyabiliriz.

</code>```

Body:
DriverError: '/vsizip//vsimem/3a044273ad394c659206ed9154647032.zip' not recognized as a supported file format.

I am trying to read shape file link  which is on my github using gpd.read_file() but I got this error help me please
DriverError: '/vsizip//vsimem/3a044273ad394c659206ed9154647032.zip' not recognized as a supported file format.

I tried without using zip format as well

url_shp_file = "https://github.com/Ezeysay16/veridosyalari/blob/main/shapefile/countries.shp?raw=true"
countries_gdf = gpd.read_file(url_shp_file)#Geopandas ile verilen shape dosyasını read_file() fonksiyonu ile okuyabiliriz.


问:
Error: Unsupported apiGateway.restApiId object
In our project we are using serverless for AWS. After added serverless-domain-manager plugin we are experiencing strange issue - Error: Unsupported apiGateway.restApiId object

```<code>custom:
  customDomain:
    domainName: test.test.com
    stage: ${self:provider.stage}
    basePath: plugin
    certificateName: test.test.com
    createRoute53Record: true
    createRoute53IPv6Record: false
    endpointType: REGIONAL
    securityPolicy: tls_1_2
    apiType: rest
    autoDomain: true
    preserveExternalPathMappings: true

provider:
  name: aws
  region: eu-central-1
  stage: prod
  runtime: nodejs16.x
  logRetentionInDays: 7
  apiGateway:
    restApiId: !Ref EmployeeApiGateway
    restApiRootResourceId:
      Fn::GetAtt:
        - EmployeeApiGateway
        - RootResourceId

</code>```

We try to add domain-manager mapping

Body:
In our project we are using serverless for AWS. After added serverless-domain-manager plugin we are experiencing strange issue - Error: Unsupported apiGateway.restApiId object

custom:
  customDomain:
    domainName: test.test.com
    stage: ${self:provider.stage}
    basePath: plugin
    certificateName: test.test.com
    createRoute53Record: true
    createRoute53IPv6Record: false
    endpointType: REGIONAL
    securityPolicy: tls_1_2
    apiType: rest
    autoDomain: true
    preserveExternalPathMappings: true

provider:
  name: aws
  region: eu-central-1
  stage: prod
  runtime: nodejs16.x
  logRetentionInDays: 7
  apiGateway:
    restApiId: !Ref EmployeeApiGateway
    restApiRootResourceId:
      Fn::GetAtt:
        - EmployeeApiGateway
        - RootResourceId

We try to add domain-manager mapping