问:
Weird Behaviour with Function C++
I have this:

main.cpp

```<code>#include <vector>
#include "Bola.h"

Bola B1();
std::vector <Bola> Ball;
void addBalls();  //this function is the problem

int main()
{
    addBalls(); //Replace

    //Here is where I draw everything

    return 0;
}

void addBalls() {
    Bola nB ();
    Ball.push_back(nB);
    Ball.back().getBall().setPosition(0, 30);  //Not working
}
</code>```

Bola.h

```<code>#include <SFML/Graphics.hpp>

class Bola {
    sf::Texture tBall;
public:
    Bola();
    sf::Sprite getBall();
    ~Bola() {}
private:
    sf::Sprite sBall;
};
</code>```

Bola.cpp

```<code>#include "Bola.h"

Bola::Bola() {
    tBall.loadFromFile("imgs/bola.png");
    sBall.setTexture(tBall);
}
sf::Sprite Bola::getBall() {
    return sBall;
}
</code>```

The vector and the function addBalls() togheter are not working.
If I try to add a new ball using the function it does add a new ball but the sprite does not get rendered.

if I instead add a new ball to the vector using "the same code of the function" addBalls() in the place where I call the function now the sprite gets rendered somehow.

I cant see what´s wrong.

Thanks in advance.

Title: Weird Behaviour with Function C++

Body:
I have this:

main.cpp

#include <vector>
#include "Bola.h"

Bola B1();
std::vector <Bola> Ball;
void addBalls();  //this function is the problem

int main()
{
    addBalls(); //Replace

    //Here is where I draw everything

    return 0;
}

void addBalls() {
    Bola nB ();
    Ball.push_back(nB);
    Ball.back().getBall().setPosition(0, 30);  //Not working
}

Bola.h

#include <SFML/Graphics.hpp>

class Bola {
    sf::Texture tBall;
public:
    Bola();
    sf::Sprite getBall();
    ~Bola() {}
private:
    sf::Sprite sBall;
};

Bola.cpp

#include "Bola.h"

Bola::Bola() {
    tBall.loadFromFile("imgs/bola.png");
    sBall.setTexture(tBall);
}
sf::Sprite Bola::getBall() {
    return sBall;
}

The vector and the function addBalls() togheter are not working.
If I try to add a new ball using the function it does add a new ball but the sprite does not get rendered.

if I instead add a new ball to the vector using "the same code of the function" addBalls() in the place where I call the function now the sprite gets rendered somehow.

I cant see what´s wrong.

Thanks in advance.


来源: stackexchange

问:
error sending header, express comparison code
I wondered. And in general, I need help.

```<code>app.get('/admin', async (req,res) => {
    let tq = await User.findOne({ where: { link: req.params.userId } })
       // if (tq.status === req.originalUrl.split('/')[1])
     //myname(req, res)
       return res.render('/admin')
    // } else {
    //     res.end('w')
    // }
}
</code>```

if I do this, then I will not get mistakes. (spoiler: cors on)
```<code>async function myname(req, res) {
    let tq = await User.findOne({ where: { link: req.params.userId } })
    if (tq.status === req.originalUrl.split('/')[1]) {
        next()
    } else {
        res.end('w')
    }
}
//and I will connect it to the code above (imagine that there are no crutches, a regular render of the page
</code>```

then we get an error of something type: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

what's my problem? Do I have to use conditional operators everywhere?...

ContentLicense: CC BY-SA 4.0

Body:
I wondered. And in general, I need help.

app.get('/admin', async (req,res) => {
    let tq = await User.findOne({ where: { link: req.params.userId } })
       // if (tq.status === req.originalUrl.split('/')[1])
     //myname(req, res)
       return res.render('/admin')
    // } else {
    //     res.end('w')
    // }
}

if I do this, then I will not get mistakes. (spoiler: cors on)

async function myname(req, res) {
    let tq = await User.findOne({ where: { link: req.params.userId } })
    if (tq.status === req.originalUrl.split('/')[1]) {
        next()
    } else {
        res.end('w')
    }
}
//and I will connect it to the code above (imagine that there are no crutches, a regular render of the page

then we get an error of something type: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

what's my problem? Do I have to use conditional operators everywhere?...


问:
Uploading an image into Apache Openwhisk
Currently, I'm running Openwhisk on a Docker standalone container. I've added normal simple JavaScript functions as actions and invoked the same. The input arguments are taken as --param or --param-file for json. The output is always a json file.

Is it possible to upload a simple picture(jpeg, png), do a simple change on it and return the image?

Running a python shell within the javascript file in which the python file uses pillow library to rotate an image for example. This is done because I wanted performance metrics with https://github.com/jthomas/openwhisk-metrics (can be done only with js files).

Serialization has been a very tedious process and highly inefficient.


问:
How can value changes be found using an Influx query?
There is a value in my database that is put into the database several times a second. Sometimes this value will change, but most of the time it will be repeating a value many times. How would I write a query that only returns when the value does not match the previous value, or that can be stated as when it changes.
Ex.
This is how the data might look in the measurement

Time
Value

1
20

2
20

3
20

4
21

5
21

6
22

This is what I want to be returned by the query

Time
Value

1
20

4
21

6
22

I have tried this query, but it is just crashing my influx
select * from (select last(value)-difference(last(value)) as FromValue, last(value) as ToValue from crds where time > 1702582429195.569 group by time(10ms),* fill(none))


问:
Python Code to check the minimum TLS version of the Server
I am trying to build a code to check the TLS version of the servers. We have some servers whose TLS version are using v1.0 as a minimum requirement but those can still negotiate with v1.2.

I am trying to check which are all our servers who still negotiate with v1.0


问:
Get E-commerce products based on past searches
I am building an e-commerce store with django. I want the product page to return products based on the past searches of the user. If user A has always searched for cars and bikes, the product page would return more cars and bikes products more than other products. More like a recommender system

What is the best way to go about this?
Do I save every search users make and run an algorithm to get results for that user or there are better ways to go about this.


问:
How to customize splash screen in pwa?
I have two icons.
Ex:- icon-I , icon-II

I want to customize PWA splash screen. On launching time show icon-II but home screen icon show icon-I

```<code>{
  "manifest_version": 3,
  "name": "Demo School",
  "description": "",
  "version": "1.0",
  "icons": [
              {
                 "src": "images/icon-I-72x72.png",
                 "type" : "image/png",
                 "sizes" : "72x72"
               },
               {
                 "src": "images/icon-I-96x96.png",
                 "type" : "image/png",
                 "sizes" : "96x96"
               },
               {
                 "src": "images/icon-I-128x128.png",
                 "type" : "image/png",
                 "sizes" : "128x128"
               },
               {
                 "src": "images/icon-I-144x144.png",
                 "type" : "image/png",
                 "sizes" : "144x144"
               },
               {
                 "src": "images/icon-I-152x152.png",
                 "type" : "image/png",
                 "sizes" : "152x152"
               },
               {
                 "src": "images/icon-I-192x192.png",
                 "type" : "image/png",
                 "sizes" : "192x192"
               },
               {
                 "src": "images/icon-I-384x384.png",
                 "type" : "image/png",
                 "sizes" : "384x384"
               },
               {
                 "src": "images/icon-I-152x152.png",
                 "type" : "image/png",
                 "sizes" : "512x512"
               }
  ],
  "short_name" : "D.S",
  "start_url" : "./",
  "display" : "standalone",
  "background_color" : "#FFE9D2",
  "theme_color" : "#FFE1C4",
  "orientation" : "portrait-primary"
}
</code>```

In the PWA, on launching page I want to show icon-II

Icon-II on launching

but on home screen icon I want to show icon-I.

Icon-I in
Icon-I

Title: How to customize splash screen in pwa?

Body:
I have two icons.
Ex:- icon-I , icon-II

I want to customize PWA splash screen. On launching time show icon-II but home screen icon show icon-I

{
  "manifest_version": 3,
  "name": "Demo School",
  "description": "",
  "version": "1.0",
  "icons": [
              {
                 "src": "images/icon-I-72x72.png",
                 "type" : "image/png",
                 "sizes" : "72x72"
               },
               {
                 "src": "images/icon-I-96x96.png",
                 "type" : "image/png",
                 "sizes" : "96x96"
               },
               {
                 "src": "images/icon-I-128x128.png",
                 "type" : "image/png",
                 "sizes" : "128x128"
               },
               {
                 "src": "images/icon-I-144x144.png",
                 "type" : "image/png",
                 "sizes" : "144x144"
               },
               {
                 "src": "images/icon-I-152x152.png",
                 "type" : "image/png",
                 "sizes" : "152x152"
               },
               {
                 "src": "images/icon-I-192x192.png",
                 "type" : "image/png",
                 "sizes" : "192x192"
               },
               {
                 "src": "images/icon-I-384x384.png",
                 "type" : "image/png",
                 "sizes" : "384x384"
               },
               {
                 "src": "images/icon-I-152x152.png",
                 "type" : "image/png",
                 "sizes" : "512x512"
               }
  ],
  "short_name" : "D.S",
  "start_url" : "./",
  "display" : "standalone",
  "background_color" : "#FFE9D2",
  "theme_color" : "#FFE1C4",
  "orientation" : "portrait-primary"
}

In the PWA, on launching page I want to show icon-II

Icon-II on launching

but on home screen icon I want to show icon-I.

Icon-I in
Icon-I


问:
Global lists are updating in thread but not showing in simple functions
```<code># importing package
from datasets import load_dataset
from transformers import pipeline
import matplotlib.pyplot as plt
from collections import Counter
from nltk.translate import bleu
from nltk import cluster
import pandas as pd
from threading import Thread
from multiprocessing import Process
from Levenshtein import ratio

global generatedSumamrycosineScore
global generatedSumamryjaccordScore
global originalSummaryLevenshteinScore
global originalSummaryScore
global sum_model
generatedSumamrycosineScore = []
generatedSumamryjaccordScore = []
originalSummaryLevenshteinScore = []
originalSummaryScore = []
sum_model = pipeline('summarization', model='facebook/bart-large-cnn')

def findCosine_Similarity(article, summary):
    counter1 = Counter(article.split())
    counter2 = Counter(summary.split())
    all_items = set(counter1.keys()).union(set(counter2.keys()))
    sim = []
    v1 = [counter1[k] for k in all_items]
    for b in summary.split('. '):
        if b.strip() != '':
            c2 = Counter(b.split())
            v2 = [c2[k] for k in all_items]
        sim.append({'article_line': article, 'summary_line': b,
                    "similarity": cluster.util.cosine_distance(v1, v2)})
    df = pd.DataFrame(sim)
    df_sum = df[abs(df['similarity']) >= 0.75]
    s = '. '.join(df_sum['summary_line'].to_list())

    return bleu([s.split()], article.split())

def jaccard_similarity(art, summary):
    s1 = set(art.split(' '))
    sum = []
    for b in summary.split('. '):
        if b.strip() != '':
            s2 = set(b.split(' '))
        sum.append({'article_line': art, 'summary_line': b, "similarity": float(
            len(s1.intersection(s2)) / len(s1.union(s2)))})
    df = pd.DataFrame(sum)
    df_sum = df[abs(df['similarity']) <= 0.25]
    s = '. '.join(df_sum['summary_line'].to_list())
    return bleu([s.split()], art.split())

def Levenshtein_similarity(art, summary):
    sum = []
    for b in summary.split('. '):
        if b.strip() != '':
            sum.append({'article_line': art, 'summary_line': b,
                        "similarity": ratio(art, b)})
    df = pd.DataFrame(sum)
    df_sum = df[abs(df['similarity']) >= 0.75]
    s = '. '.join(df_sum['summary_line'].to_list())
    return bleu([s.split()], art.split())

def PredictSummary(*art):
    try:
        global generatedSumamrycosineScore
        global generatedSumamryjaccordScore
        global originalSummaryLevenshteinScore
        global originalSummaryScore
        global sum_model
        l1 = art[0]
        summary = sum_model(l1)
        l2 = summary[0]['summary_text']
        generatedSumamrycosineScore.append(findCosine_Similarity(l1, l2))
        generatedSumamryjaccordScore.append(jaccard_similarity(l1, l2))
        originalSummaryLevenshteinScore.append(Levenshtein_similarity(l1, l2))
        originalSummaryScore.append(
            bleu([art[1].split()], l1.split()))

    except:
        pass

def run_process(*art):
    threadlist = []
    print("creating Threads")
    threadlist.append(Thread(target=PredictSummary,
                             args=list(art[0].values())[:2]))
    threadlist.append(Thread(target=PredictSummary,
                             args=list(art[1].values())[:2]))
    for t in threadlist:
        t.start()
    for t in threadlist:
        t.join()
    print("Threads created")

    global generatedSumamrycosineScore
    global generatedSumamryjaccordScore
    global originalSummaryLevenshteinScore
    global originalSummaryScore
    # Printing values here
    print(generatedSumamrycosineScore, generatedSumamryjaccordScore, originalSummaryLevenshteinScore,
          originalSummaryScore)

def plot_graph():
    global generatedSumamrycosineScore
    global generatedSumamryjaccordScore
    global originalSummaryLevenshteinScore
    global originalSummaryScore

    # list values are empty here
    print(generatedSumamrycosineScore, generatedSumamryjaccordScore, originalSummaryLevenshteinScore,
          originalSummaryScore)

    plt.plot(generatedSumamryjaccordScore,
             label="generatedSumamryjaccordScore")
    plt.plot(generatedSumamrycosineScore, label="generatedSumamrycosineScore")
    plt.plot(originalSummaryLevenshteinScore,
             label="originalSummaryLevenshteinScore")
    plt.plot(originalSummaryScore, label="originalSummaryScore")
    plt.legend()
    plt.show()
    plt.savefig("Bleugraph.png", dpi=1000)

if __name__ == '__main__':
    datasets = load_dataset('cnn_dailymail', '3.0.0')

    i = 0
    while i < 1000:
        try:
            print("started", i)
            art = []
            for k in range(0, 30):
                art.append(datasets['test'][i+k])
            processlist = []
            processlist.append(Process(target=run_process, args=art[:10]))
            for t in processlist:
                t.start()

            for t in processlist:
                t.join()
            break
            i += 30
        except:
            continue
    plot_graph()

</code>```

I am creating a process in which i have to create almost 10 threads but currently using 2 thread. In each thread values are calculated and append in eac list. when i print he values in the run_process function where threads are created it prints the values but when i print hem in plot_graph these are null. I have make them global but still this issue occurs.

Body:
# importing package
from datasets import load_dataset
from transformers import pipeline
import matplotlib.pyplot as plt
from collections import Counter
from nltk.translate import bleu
from nltk import cluster
import pandas as pd
from threading import Thread
from multiprocessing import Process
from Levenshtein import ratio

global generatedSumamrycosineScore
global generatedSumamryjaccordScore
global originalSummaryLevenshteinScore
global originalSummaryScore
global sum_model
generatedSumamrycosineScore = []
generatedSumamryjaccordScore = []
originalSummaryLevenshteinScore = []
originalSummaryScore = []
sum_model = pipeline('summarization', model='facebook/bart-large-cnn')

def findCosine_Similarity(article, summary):
    counter1 = Counter(article.split())
    counter2 = Counter(summary.split())
    all_items = set(counter1.keys()).union(set(counter2.keys()))
    sim = []
    v1 = [counter1[k] for k in all_items]
    for b in summary.split('. '):
        if b.strip() != '':
            c2 = Counter(b.split())
            v2 = [c2[k] for k in all_items]
        sim.append({'article_line': article, 'summary_line': b,
                    "similarity": cluster.util.cosine_distance(v1, v2)})
    df = pd.DataFrame(sim)
    df_sum = df[abs(df['similarity']) >= 0.75]
    s = '. '.join(df_sum['summary_line'].to_list())

    return bleu([s.split()], article.split())

def jaccard_similarity(art, summary):
    s1 = set(art.split(' '))
    sum = []
    for b in summary.split('. '):
        if b.strip() != '':
            s2 = set(b.split(' '))
        sum.append({'article_line': art, 'summary_line': b, "similarity": float(
            len(s1.intersection(s2)) / len(s1.union(s2)))})
    df = pd.DataFrame(sum)
    df_sum = df[abs(df['similarity']) <= 0.25]
    s = '. '.join(df_sum['summary_line'].to_list())
    return bleu([s.split()], art.split())

def Levenshtein_similarity(art, summary):
    sum = []
    for b in summary.split('. '):
        if b.strip() != '':
            sum.append({'article_line': art, 'summary_line': b,
                        "similarity": ratio(art, b)})
    df = pd.DataFrame(sum)
    df_sum = df[abs(df['similarity']) >= 0.75]
    s = '. '.join(df_sum['summary_line'].to_list())
    return bleu([s.split()], art.split())

def PredictSummary(*art):
    try:
        global generatedSumamrycosineScore
        global generatedSumamryjaccordScore
        global originalSummaryLevenshteinScore
        global originalSummaryScore
        global sum_model
        l1 = art[0]
        summary = sum_model(l1)
        l2 = summary[0]['summary_text']
        generatedSumamrycosineScore.append(findCosine_Similarity(l1, l2))
        generatedSumamryjaccordScore.append(jaccard_similarity(l1, l2))
        originalSummaryLevenshteinScore.append(Levenshtein_similarity(l1, l2))
        originalSummaryScore.append(
            bleu([art[1].split()], l1.split()))

    except:
        pass

def run_process(*art):
    threadlist = []
    print("creating Threads")
    threadlist.append(Thread(target=PredictSummary,
                             args=list(art[0].values())[:2]))
    threadlist.append(Thread(target=PredictSummary,
                             args=list(art[1].values())[:2]))
    for t in threadlist:
        t.start()
    for t in threadlist:
        t.join()
    print("Threads created")

    global generatedSumamrycosineScore
    global generatedSumamryjaccordScore
    global originalSummaryLevenshteinScore
    global originalSummaryScore
    # Printing values here
    print(generatedSumamrycosineScore, generatedSumamryjaccordScore, originalSummaryLevenshteinScore,
          originalSummaryScore)

def plot_graph():
    global generatedSumamrycosineScore
    global generatedSumamryjaccordScore
    global originalSummaryLevenshteinScore
    global originalSummaryScore

    # list values are empty here
    print(generatedSumamrycosineScore, generatedSumamryjaccordScore, originalSummaryLevenshteinScore,
          originalSummaryScore)

    plt.plot(generatedSumamryjaccordScore,
             label="generatedSumamryjaccordScore")
    plt.plot(generatedSumamrycosineScore, label="generatedSumamrycosineScore")
    plt.plot(originalSummaryLevenshteinScore,
             label="originalSummaryLevenshteinScore")
    plt.plot(originalSummaryScore, label="originalSummaryScore")
    plt.legend()
    plt.show()
    plt.savefig("Bleugraph.png", dpi=1000)

if __name__ == '__main__':
    datasets = load_dataset('cnn_dailymail', '3.0.0')

    i = 0
    while i < 1000:
        try:
            print("started", i)
            art = []
            for k in range(0, 30):
                art.append(datasets['test'][i+k])
            processlist = []
            processlist.append(Process(target=run_process, args=art[:10]))
            for t in processlist:
                t.start()

            for t in processlist:
                t.join()
            break
            i += 30
        except:
            continue
    plot_graph()

I am creating a process in which i have to create almost 10 threads but currently using 2 thread. In each thread values are calculated and append in eac list. when i print he values in the run_process function where threads are created it prints the values but when i print hem in plot_graph these are null. I have make them global but still this issue occurs.


问:
Recharts is not workingReact with typescript with yarn
I have installed recharts by using,
yarn add recharts
yarn add @types/recharts

my Chart.tsx file is:

```<code>import "./chart.scss";
import {
  AreaChart,
  Area,
  XAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from "recharts";

const data = [
  { name: "January", Total: 1200 },
  { name: "February", Total: 2100 },
  { name: "March", Total: 800 },
  { name: "April", Total: 1600 },
  { name: "May", Total: 900 },
  { name: "June", Total: 1700 },
];

const Chart = ({ aspect, title }:any) => {
  return (
    <div className="chart">
      <div className="title">{title}</div>
      <ResponsiveContainer width="100%" aspect={aspect}>
        <AreaChart
          width={730}
          height={250}
          data={data}
          margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
        >
          <defs>
            <linearGradient id="total" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor="#8884d8" stopOpacity={0.8} />
              <stop offset="95%" stopColor="#8884d8" stopOpacity={0} />
            </linearGradient>
          </defs>
          <XAxis dataKey="name" stroke="gray" />
          {/* <CartesianGrid strokeDasharray="3 3" className="chartGrid" /> */}
          <CartesianGrid strokeDasharray="3 3" />
          <Tooltip />
          <Area
            type="monotone"
            dataKey="Total"
            stroke="#8884d8"
            fillOpacity={1}
            fill="url(#total)"
          />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  );
};

export default Chart;

</code>```

But don't know why its giving below error,

```<code>webpack compiled successfully
ERROR in src/views/Dashboard/Chart.tsx:9:8
TS2307: Cannot find module 'recharts' or its corresponding type declarations.
     7 |   Tooltip,
     8 |   ResponsiveContainer,
  >  9 | } from "recharts";
       |        ^^^^^^^^^^
    10 |
    11 | const data = [
    12 |   { name: "January", Total: 1200 },
</code>```

Thanks in advance....

Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum pariatur cumque odit quaerat saepe ratione dolorum excepturi eveniet doloremque quis expedita quasi vero, dignissimos ipsum totam possimus maiores quia debitis illo consectetur soluta in qui? Iure eum beatae ipsam?

Body:
I have installed recharts by using,
yarn add recharts
yarn add @types/recharts

my Chart.tsx file is:

import "./chart.scss";
import {
  AreaChart,
  Area,
  XAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from "recharts";

const data = [
  { name: "January", Total: 1200 },
  { name: "February", Total: 2100 },
  { name: "March", Total: 800 },
  { name: "April", Total: 1600 },
  { name: "May", Total: 900 },
  { name: "June", Total: 1700 },
];

const Chart = ({ aspect, title }:any) => {
  return (

{title}

      <ResponsiveContainer width="100%" aspect={aspect}>
        <AreaChart
          width={730}
          height={250}
          data={data}
          margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
        >
          <defs>
            <linearGradient id="total" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor="#8884d8" stopOpacity={0.8} />
              <stop offset="95%" stopColor="#8884d8" stopOpacity={0} />
            </linearGradient>
          </defs>
          <XAxis dataKey="name" stroke="gray" />
          {/* <CartesianGrid strokeDasharray="3 3" className="chartGrid" /> */}
          <CartesianGrid strokeDasharray="3 3" />
          <Tooltip />
          <Area
            type="monotone"
            dataKey="Total"
            stroke="#8884d8"
            fillOpacity={1}
            fill="url(#total)"
          />
        </AreaChart>
      </ResponsiveContainer>

  );
};

export default Chart;

But don't know why its giving below error,

webpack compiled successfully
ERROR in src/views/Dashboard/Chart.tsx:9:8
TS2307: Cannot find module 'recharts' or its corresponding type declarations.
     7 |   Tooltip,
     8 |   ResponsiveContainer,
  >  9 | } from "recharts";
       |        ^^^^^^^^^^
    10 |
    11 | const data = [
    12 |   { name: "January", Total: 1200 },

Thanks in advance....

Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum pariatur cumque odit quaerat saepe ratione dolorum excepturi eveniet doloremque quis expedita quasi vero, dignissimos ipsum totam possimus maiores quia debitis illo consectetur soluta in qui? Iure eum beatae ipsam?


问:
word-press admin fatal error cannot login
I cannot login word press admin login the following error occurs

"Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 655360 bytes) in /home/ausun888/public_html/gcaahealth.com/wp-content/plugins/sitepress-multilingual-cms/classes/class-wpml-db-chunk.php on line 43"

please help me on this

I tried increasing the memory WP-INCLUDES/ default-constant - to 256M.. but still cannot also tried remnaming the "sitepress-multilingual-cms. nothing helpful


问:
React PWA is not getting added to homescreen
I got all ticks from the lighthouse. I'm running the app locally. Opened IP in chrome android, and clicked on add to the home screen. It said the app was added to the home screen. But I can't find it anywhere.

Note: On Mac, it is added to the home screen and I can see it in apps.


问:
My daemon process in Linux getting stuck randomly
I have a daemon process, which stuck randomly. The /proc/pid/stack shows this:

```<code>[<0>] do_sys_poll+0x486/0x610
[<0>] __x64_sys_poll+0xa9/0x140
[<0>] do_syscall_64+0x59/0xc0
[<0>] entry_SYSCALL_64_after_hwframe+0x61/0xcb
</code>```

strace -cp pid, outputs this:

Does it mean its stuck on do_sys_poll? What do_sys_poll does and how to find why its stuck here?

Body:
I have a daemon process, which stuck randomly. The /proc/pid/stack shows this:

[<0>] do_sys_poll+0x486/0x610
[<0>] __x64_sys_poll+0xa9/0x140
[<0>] do_syscall_64+0x59/0xc0
[<0>] entry_SYSCALL_64_after_hwframe+0x61/0xcb

strace -cp pid, outputs this:

Does it mean its stuck on do_sys_poll? What do_sys_poll does and how to find why its stuck here?


问:
Pass environment variable from gradle to bash script
I want to pass an environment variable from gradle "Exec" task to bash script. In the gradle file the variable is passed like this:

```<code>tasks.register('myTask', Exec) {
    environment('MY_VAR', 'My Value')
    commandLine('./myscript.sh')
}
</code>```

In myscript.sh:

```<code>#!/bin/bash

echo $MY_VAR
</code>```

But I can not get the variable in myscript.sh. I use Gradle 7.3

Body:
I want to pass an environment variable from gradle "Exec" task to bash script. In the gradle file the variable is passed like this:

tasks.register('myTask', Exec) {
    environment('MY_VAR', 'My Value')
    commandLine('./myscript.sh')
}

In myscript.sh:

#!/bin/bash

echo $MY_VAR

But I can not get the variable in myscript.sh. I use Gradle 7.3


问:
Randomize Quiz Answers Order Django
Hi everybody I want to randomize quiz answers in Django
this is models.py

```<code>class Questions(models.Model):
question = models.CharField(max_length=264, unique=True)
point = models.PositiveIntegerField()

def questionanswers(self):
    return self.question_answers.all()

def __str__(self):
    return self.question

class Answers(models.Model):
    question_id = models.ForeignKey(Questions, on_delete=models.CASCADE, related_name='question_answers')
    answer = models.CharField(max_length=20)
    is_true = models.BooleanField()

    def __str__(self):
        return self.answer
</code>```

and this is views.py

```<code>question_list = Questions.objects.all().order_by('?')[:6]
        context['questions'] = question_list

        return context
</code>```

and this is a template

```<code>  {% for answer in question.questionanswers.all %}
        <li class="col-sm-6" style="margin-bottom: 10px"> <button class="btn btn-primary" type="button" id="{{answer.id}}" value="{{answer.id}}">{{answer}}</button> </li>
      {% endfor %}
    </ol>
  </div>
</div>
{% endfor %}
</code>```

Title: Randomize Quiz Answers Order Django

Body:
Hi everybody I want to randomize quiz answers in Django
this is models.py

class Questions(models.Model):
question = models.CharField(max_length=264, unique=True)
point = models.PositiveIntegerField()

def questionanswers(self):
    return self.question_answers.all()

def __str__(self):
    return self.question

class Answers(models.Model):
    question_id = models.ForeignKey(Questions, on_delete=models.CASCADE, related_name='question_answers')
    answer = models.CharField(max_length=20)
    is_true = models.BooleanField()

    def __str__(self):
        return self.answer

and this is views.py

question_list = Questions.objects.all().order_by('?')[:6]
        context['questions'] = question_list

        return context

and this is a template

  {% for answer in question.questionanswers.all %}

 <button class="btn btn-primary" type="button" id="{{answer.id}}" value="{{answer.id}}">{{answer}}</button>

      {% endfor %}

{% endfor %}


问:
i am getting ssl certificate error while installing mailersend
```<code>Could not fetch URL https://pypi.org/simple/mailersend/: There was a problem con
firming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max
 retries exceeded with url: /simple/mailersend/ (Caused by SSLError(SSLCertVerif
icationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: una
ble to get local issuer certificate (_ssl.c:1129)'))) - skipping
ERROR: Could not find a version that satisfies the requirement mailersend (from
versions: none)
ERROR: No matching distribution found for mailersend

</code>```

i try to set ssl_verifiy to false in conda environment but i am unable to resolve the issue.

Body:
Could not fetch URL https://pypi.org/simple/mailersend/: There was a problem con
firming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max
 retries exceeded with url: /simple/mailersend/ (Caused by SSLError(SSLCertVerif
icationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: una
ble to get local issuer certificate (_ssl.c:1129)'))) - skipping
ERROR: Could not find a version that satisfies the requirement mailersend (from
versions: none)
ERROR: No matching distribution found for mailersend

i try to set ssl_verifiy to false in conda environment but i am unable to resolve the issue.


问:
Async and await does not work in sqllite3 in nodejs
I try to Insert query into sqlite database. But the function Does not work correctly.

```<code>
const sqlite3 = require('sqlite3');
const { open } = require('sqlite');

async function main() {
    try {
        sqlite3.verbose();
        const ordersDb = await createDbConnection('./test.db');
        const orderProcessed = await orderAlreadyProcessed(ordersDb, "users");
        console.log('four ');
    } catch (error) {
        console.error(error);
    }
}

async function orderAlreadyProcessed(ordersDb, orderNumberStr) {
    try {
        console.log('two ');
        const query = `INSERT INTO users (first_name , last_name , username , password ) VALUES ('fdlfkld' , 'sfhdfjdk' , 'sdfhsdfhsd' , 'sdffs' )`
        const row = await ordersDb.run(query);
        console.log('three ');
    } catch (error) {
        console.error(error);
        throw error;
    }
}

function createDbConnection(filename) {
    return open({
        filename,
        driver: sqlite3.Database
    });
}

let one = [ 1 , 2, 3 ]

Promise.all(one.map(async()=>{
    await main();
}))

</code>```

enter image description here

i need output like this

```<code>two
three
four
two
three
four
two
three
four
</code>```

Sqlite does not work correctly , i need some help to rid the problem

Body:
I try to Insert query into sqlite database. But the function Does not work correctly.

const sqlite3 = require('sqlite3');
const { open } = require('sqlite');

async function main() {
    try {
        sqlite3.verbose();
        const ordersDb = await createDbConnection('./test.db');
        const orderProcessed = await orderAlreadyProcessed(ordersDb, "users");
        console.log('four ');
    } catch (error) {
        console.error(error);
    }
}

async function orderAlreadyProcessed(ordersDb, orderNumberStr) {
    try {
        console.log('two ');
        const query = `INSERT INTO users (first_name , last_name , username , password ) VALUES ('fdlfkld' , 'sfhdfjdk' , 'sdfhsdfhsd' , 'sdffs' )`
        const row = await ordersDb.run(query);
        console.log('three ');
    } catch (error) {
        console.error(error);
        throw error;
    }
}

function createDbConnection(filename) {
    return open({
        filename,
        driver: sqlite3.Database
    });
}

let one = [ 1 , 2, 3 ]

Promise.all(one.map(async()=>{
    await main();
}))

enter image description here

i need output like this

two
three
four
two
three
four
two
three
four

Sqlite does not work correctly , i need some help to rid the problem


问:
I'm getting android:exported error in merged Manifest
This my problem: I'm getting error in my manifest file but I think I'm set all `android:exported` properly.

enter image description here

Merging Errors: Error: Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details. SpaceWeb.app main manifest (this file)

This my manifest file

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.teamwincc.web">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />
    <uses-permission android:name="android.permission.ACCESS_GPS" />
    <uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.MICROPHONE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature
        android:name="android.hardware.audio.low_latency"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.audio.pro"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.microphone"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.location.gps"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />

    <application
        android:name="com.teamwincc.web.Utilities.MainLanguageApplication"
        android:allowBackup="true"
        android:icon="@drawable/app_icon"
        android:label="@string/your_app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:roundIcon="@drawable/app_icon"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="AllowBackup"
        tools:targetApi="n">
        <activity
            android:name="com.teamwincc.web.Activity.NoInternetConnectionActivity" />
        <activity
            android:name="com.teamwincc.web.Activity.AppIntroActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name="com.teamwincc.web.Activity.Splash"
            android:screenOrientation="portrait"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.teamwincc.web.Activity.WebViewActivity"
            android:hardwareAccelerated="true"
            android:configChanges="orientation|screenSize"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data
                    android:host="https://www.google.com/"
                    android:scheme="https" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="@string/AdMob_app_ID" />
    </application>

</manifest>
</code>```

Body:
This my problem: I'm getting error in my manifest file but I think I'm set all `android:exported` properly.

enter image description here

Merging Errors: Error: Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details. SpaceWeb.app main manifest (this file)

This my manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.teamwincc.web">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />
    <uses-permission android:name="android.permission.ACCESS_GPS" />
    <uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.MICROPHONE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature
        android:name="android.hardware.audio.low_latency"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.audio.pro"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.microphone"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.location.gps"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />

    <application
        android:name="com.teamwincc.web.Utilities.MainLanguageApplication"
        android:allowBackup="true"
        android:icon="@drawable/app_icon"
        android:label="@string/your_app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:roundIcon="@drawable/app_icon"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="AllowBackup"
        tools:targetApi="n">
        <activity
            android:name="com.teamwincc.web.Activity.NoInternetConnectionActivity" />
        <activity
            android:name="com.teamwincc.web.Activity.AppIntroActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name="com.teamwincc.web.Activity.Splash"
            android:screenOrientation="portrait"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.teamwincc.web.Activity.WebViewActivity"
            android:hardwareAccelerated="true"
            android:configChanges="orientation|screenSize"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data
                    android:host="https://www.google.com/"
                    android:scheme="https" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="@string/AdMob_app_ID" />
    </application>

</manifest>


问:
Error in checkMeasures(measures, learner) : object 'fbeta' not found
I am doing an imbalanced classification task, so I want to use f-beta as performance measure. I used the library(mlr) to set measures=fbeta, which follows:

```<code>library(mlr)
#create tasks

## Create combined training data
train_data <- cbind(x_train, y_train)
valid_data <- cbind(x_valid,y_valid)

train_task_data <- rbind(train_data, valid_data)
size <- nrow(train_task_data)
train_ind <- seq_len(nrow(train_data))
validation_ind <- seq.int(max(train_ind) + 1, size)

## Create training task
train_task <- makeClassifTask(data = train_task_data, target = "DEFAULT", positive = 1)

testtask <- makeClassifTask(data = cbind(x_test,y_test),target = "DEFAULT")

#create learner
lrn <- makeLearner("classif.xgboost",predict.type = "response") ##predict.type = "prob"
lrn$par.vals <- list( objective="binary:logistic", eval_metric="logloss", nrounds=100L, eta=0.1)

#set parameter space
params <- makeParamSet( makeDiscreteParam("booster",values = c("gbtree","gblinear")),
                          makeIntegerParam("max_depth",lower = 9L,upper = 10L),
                          makeNumericParam("min_child_weight",lower = 9L,upper = 10L),
                          makeNumericParam("subsample",lower = 0.9,upper = 1),
                          makeNumericParam("colsample_bytree",lower = 0.9,upper = 1))

#search strategy
ctrl <- makeTuneControlRandom(maxit = 10L)

#set parallel backend
library(parallel)
library(parallelMap)
parallelStartSocket(cpus = detectCores())

mytune <- tuneParams(learner = lrn, task = train_task,
                     resampling = makeFixedHoldoutInstance(train_ind, validation_ind, size),
                     measures = fbeta, par.set = params, control = ctrl, show.info = T)

#parameter tuning
#set hyperparameters
lrn_tune <- setHyperPars(lrn,par.vals = mytune$x)

#train model
xgmodel <- train(learner = lrn_tune,task = train_task)

#predict model
xgpred <- predict(xgmodel,testtask)

confusionMatrix(xgpred$data$response,xgpred$data$truth)
</code>```

However, this error is reported:
Error in checkMeasures(measures, learner) : object 'fbeta' not found
Besides, my dataset contains 150,000 instances, but based on the computed confusion matrix, they are less than 150,000.

```<code>> confusionMatrix(xgpred$data$response,xgpred$data$truth)
     [,1]   [,2]
[1,]    0      0
[2,]    0 149887
</code>```

Update: I function to calculate f score is as follows, but I am not sure about it.

```<code>fbeta = makeMeasure(id = "fbeta", minimize = FALSE, best = 1, worst = 0,
                    properties = c("classif", "req.pred", "req.truth"),
                    name = "Fbeta measure",
                    note = "Defined as: (1+beta^2) * tp/ (beta^2 * sum(truth == positive) + sum(response == positive))",
                    fun = function(task, model, pred, feats, extra.args) {
                      beta = 1
                      beta = beta^2
                      truth = pred$data$truth
                      response = pred$data$response
                      positive = pred$task.desc$positive
                      (1+beta) * measureTP(truth, response, positive) /
                        (beta * sum(truth == positive) + sum(response == positive))
                    }
)
</code>```

Body:
I am doing an imbalanced classification task, so I want to use f-beta as performance measure. I used the library(mlr) to set measures=fbeta, which follows:

library(mlr)
#create tasks

## Create combined training data
train_data <- cbind(x_train, y_train)
valid_data <- cbind(x_valid,y_valid)

train_task_data <- rbind(train_data, valid_data)
size <- nrow(train_task_data)
train_ind <- seq_len(nrow(train_data))
validation_ind <- seq.int(max(train_ind) + 1, size)

## Create training task
train_task <- makeClassifTask(data = train_task_data, target = "DEFAULT", positive = 1)

testtask <- makeClassifTask(data = cbind(x_test,y_test),target = "DEFAULT")

#create learner
lrn <- makeLearner("classif.xgboost",predict.type = "response") ##predict.type = "prob"
lrn$par.vals <- list( objective="binary:logistic", eval_metric="logloss", nrounds=100L, eta=0.1)

#set parameter space
params <- makeParamSet( makeDiscreteParam("booster",values = c("gbtree","gblinear")),
                          makeIntegerParam("max_depth",lower = 9L,upper = 10L),
                          makeNumericParam("min_child_weight",lower = 9L,upper = 10L),
                          makeNumericParam("subsample",lower = 0.9,upper = 1),
                          makeNumericParam("colsample_bytree",lower = 0.9,upper = 1))

#search strategy
ctrl <- makeTuneControlRandom(maxit = 10L)

#set parallel backend
library(parallel)
library(parallelMap)
parallelStartSocket(cpus = detectCores())

mytune <- tuneParams(learner = lrn, task = train_task,
                     resampling = makeFixedHoldoutInstance(train_ind, validation_ind, size),
                     measures = fbeta, par.set = params, control = ctrl, show.info = T)

#parameter tuning
#set hyperparameters
lrn_tune <- setHyperPars(lrn,par.vals = mytune$x)

#train model
xgmodel <- train(learner = lrn_tune,task = train_task)

#predict model
xgpred <- predict(xgmodel,testtask)

confusionMatrix(xgpred$data$response,xgpred$data$truth)

However, this error is reported:
Error in checkMeasures(measures, learner) : object 'fbeta' not found
Besides, my dataset contains 150,000 instances, but based on the computed confusion matrix, they are less than 150,000.

> confusionMatrix(xgpred$data$response,xgpred$data$truth)
     [,1]   [,2]
[1,]    0      0
[2,]    0 149887

Update: I function to calculate f score is as follows, but I am not sure about it.

fbeta = makeMeasure(id = "fbeta", minimize = FALSE, best = 1, worst = 0,
                    properties = c("classif", "req.pred", "req.truth"),
                    name = "Fbeta measure",
                    note = "Defined as: (1+beta^2) * tp/ (beta^2 * sum(truth == positive) + sum(response == positive))",
                    fun = function(task, model, pred, feats, extra.args) {
                      beta = 1
                      beta = beta^2
                      truth = pred$data$truth
                      response = pred$data$response
                      positive = pred$task.desc$positive
                      (1+beta) * measureTP(truth, response, positive) /
                        (beta * sum(truth == positive) + sum(response == positive))
                    }
)


问:
Default database is not showing in PgAdmin4 Nor there is any Server

I want to import a database in my pgAdmin 4  but as I installed it there is no default database in that plus there is also no server. First time I am installing this on my PC. Please help me out with the procedure of how to import the database.


问:
How to get data when language changed in react V18.2?
I have problem with fetching data when language changed. I tried a  lot of things that I found from Stack overflow, but unfortunately it just changing the direction and it didn't fetch the data based on language changed.

I fetching data with a custom hook and call it inside my functional component. let me share the code that I write.

Note: I'm using I18nextLng  for translation.

App.js

```<code>import {  RouterProvider } from "react-router-dom";

import Loading from './components/loading';
import routes from './routes/routes';
import { useEffect } from "react";
import i18n from "./utils/i18n";

function App() {
  useEffect(() => {
    let cleanup = true;
    if (cleanup) {
       i18n.on('languageChanged', (local) => {
        let direction = i18n.dir(local);
        document.body.dir = direction;
      })
    }
    return () => {
      cleanup = false;
    };
  }, []);

  return (
    <RouterProvider router={routes} fallbackElement={<Loading />} />
  )
}

export default App;
</code>```

LanguageSwitcher.js

```<code>import { useTranslation } from "react-i18next";

const LanguageSwitcher = () => {
  const { i18n } = useTranslation();
    return (
      <select
        className="form-select-sm rounded-pill text-center"
        aria-label="Default select example"
        value={i18n.language}
        onChange={(e) =>
          i18n.changeLanguage( e.target.value)
        }
      >
        <option value="en">English</option>
        <option value="fa">دری</option>
      </select>
    );
}

export default LanguageSwitcher;
</code>```

Internships.js

```<code>import Image from "react-bootstrap/Image"
import { useFetchWebsiteData } from "../../hooks/website/useFetchWebsiteData";
import Loading from '../../components/loading'
import { useEffect, useState } from "react";
const Internships = () => {
  let lang = localStorage.getItem("i18nextLng")
  const { data, isLoading } = useFetchWebsiteData("getInternship", lang);

    console.log("language changed", language);

    return !isLoading ? (
      <div className="container-fluid news-wrapper">
        <div className="container">
          <div className="row py-5">
            <div className="col-md-12">
              <div className="col-md-8">
                <h4 className="title mb-4">{data?.title}</h4>
                <p className="sub-title">{data?.content}</p>
              </div>
              <div className="col-md-2 text-center">
                <Image
                  src={require("../../images/internships.png")}
                  fluid={true}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    ) : (
      <Loading />
    );
}

export default Internships;
</code>```

useFetchWebsiteData.js  (Custom hook for fetching data)

```<code>import { useState, useEffect } from "react";
import { axiosPublic } from "../../utils/axios";

export const useFetchWebsiteData = (url,lang) => {
  const [data, setData] = useState({});
  const [isLoading, setIsLoading] = useState(true);
  const [isError, setIsError] = useState(false);
//   const lang = localStorage.getItem("i18nextLng");
console.log('lang inside hook', lang)
  useEffect(() => {
    // const controller = new AbortController()

    const fetchData = async () => {
      setIsLoading(true);
      await axiosPublic
        .get(url, {
          headers: { lang: lang === "fa" ? "dr" : "en" },
        //   signal: controller.signal,
        })
        .then((response) => {
          if (response.status === 200) {
            if (lang === "en") {
              setIsLoading(false);
              response.data.data.en.map((d) => {
                let title = d.title;
                let content = d.content;
                return setData({ title: title, content: content });
              });
            }
              if (lang === "fa") {
                  setIsLoading(false);
                console.log("fa intern", response.data.data.dr)
              response.data.data.dr.map((d) => {
                let title = d.title;
                let content = d.content;
                return setData({ title: title, content: content });
              });
              setIsLoading(false);
            }
          } else {
            setIsError(true);
          }
        })
        .catch((error) => {
          setIsLoading(false);
          setIsError(true);
          console.error(error.message);
        });
    };
    fetchData();
    // return () => {
    //   controller.abort()
    // };
  }, [url, lang]);

  return { data, isLoading, isError };
};
</code>```

I really appreciate for your helping.

Body:
I have problem with fetching data when language changed. I tried a  lot of things that I found from Stack overflow, but unfortunately it just changing the direction and it didn't fetch the data based on language changed.

I fetching data with a custom hook and call it inside my functional component. let me share the code that I write.

Note: I'm using I18nextLng  for translation.

App.js

import {  RouterProvider } from "react-router-dom";

import Loading from './components/loading';
import routes from './routes/routes';
import { useEffect } from "react";
import i18n from "./utils/i18n";

function App() {
  useEffect(() => {
    let cleanup = true;
    if (cleanup) {
       i18n.on('languageChanged', (local) => {
        let direction = i18n.dir(local);
        document.body.dir = direction;
      })
    }
    return () => {
      cleanup = false;
    };
  }, []);

  return (
    <RouterProvider router={routes} fallbackElement={<Loading />} />
  )
}

export default App;

LanguageSwitcher.js

import { useTranslation } from "react-i18next";

const LanguageSwitcher = () => {
  const { i18n } = useTranslation();
    return (
      <select
        className="form-select-sm rounded-pill text-center"
        aria-label="Default select example"
        value={i18n.language}
        onChange={(e) =>
          i18n.changeLanguage( e.target.value)
        }
      >
        <option value="en">English</option>
        <option value="fa">دری</option>
      </select>
    );
}

export default LanguageSwitcher;

Internships.js

import Image from "react-bootstrap/Image"
import { useFetchWebsiteData } from "../../hooks/website/useFetchWebsiteData";
import Loading from '../../components/loading'
import { useEffect, useState } from "react";
const Internships = () => {
  let lang = localStorage.getItem("i18nextLng")
  const { data, isLoading } = useFetchWebsiteData("getInternship", lang);

    console.log("language changed", language);

    return !isLoading ? (

{data?.title}

{data?.content}

                <Image
                  src={require("../../images/internships.png")}
                  fluid={true}
                />

    ) : (
      <Loading />
    );
}

export default Internships;

useFetchWebsiteData.js  (Custom hook for fetching data)

import { useState, useEffect } from "react";
import { axiosPublic } from "../../utils/axios";

export const useFetchWebsiteData = (url,lang) => {
  const [data, setData] = useState({});
  const [isLoading, setIsLoading] = useState(true);
  const [isError, setIsError] = useState(false);
//   const lang = localStorage.getItem("i18nextLng");
console.log('lang inside hook', lang)
  useEffect(() => {
    // const controller = new AbortController()

    const fetchData = async () => {
      setIsLoading(true);
      await axiosPublic
        .get(url, {
          headers: { lang: lang === "fa" ? "dr" : "en" },
        //   signal: controller.signal,
        })
        .then((response) => {
          if (response.status === 200) {
            if (lang === "en") {
              setIsLoading(false);
              response.data.data.en.map((d) => {
                let title = d.title;
                let content = d.content;
                return setData({ title: title, content: content });
              });
            }
              if (lang === "fa") {
                  setIsLoading(false);
                console.log("fa intern", response.data.data.dr)
              response.data.data.dr.map((d) => {
                let title = d.title;
                let content = d.content;
                return setData({ title: title, content: content });
              });
              setIsLoading(false);
            }
          } else {
            setIsError(true);
          }
        })
        .catch((error) => {
          setIsLoading(false);
          setIsError(true);
          console.error(error.message);
        });
    };
    fetchData();
    // return () => {
    //   controller.abort()
    // };
  }, [url, lang]);

  return { data, isLoading, isError };
};

I really appreciate for your helping.


问:
How much data normally we use for machine learning prediction?
I know this might seem naive. However, for writing scientific papers how much data we need normally?</p>


问:
Maven modules that require versioning
I created a new project with the org.wildfly.archetype:wildfly-jakartaee-ear-archetype:27.0.0.Final-SNAPSHOT archetype and then added a library module to get the following project structure:

```<code>project
+-->project-ear
+-->project-ejb
+-->project-lib
+-->project-web
</code>```

However, in my project-lib/pom.xml file the dependency for this new library requires a version, where as the EJB and WEB modules do not. Why? And is there a way to configure the project-lib/pom.xml so that the project-ear/pom.xml doesn't require a version on a library that is part of the same project?

Snippet of project/pom.xml

```<code><modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>project</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>project</name>
<modules>
    <module>project-lib</module>
    <module>project-ejb</module>
    <module>project-web</module>
    <module>project-ear</module>
</modules>
</code>```

Snippet of project-ear/pom.xml

```<code><modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.example</groupId>
    <artifactId>project</artifactId>
    <version>1.0-SNAPSHOT</version>
</parent>
<artifactId>project-ear</artifactId>
<packaging>ear</packaging>
<dependencies>
    <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>project-tfl</artifactId>
        <version>${project.version}</version>   <--- Line I wish to remove! -->
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>project-ejb</artifactId>
        <type>ejb</type>
    </dependency>
    <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>project-web</artifactId>
        <type>war</type>
    </dependency>
</dependencies>
</code>```

Snippet of project-lib/pom.xml

```<code><modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.example</groupId>
    <artifactId>project</artifactId>
    <version>1.0-SNAPSHOT</version>
</parent>
<artifactId>project-lib</artifactId>
<packaging>jar</packaging>
<properties>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
    <finalName>${project.artifactId}</finalName>
</build>
</code>```

Title: Maven modules that require versioning

Body:
I created a new project with the org.wildfly.archetype:wildfly-jakartaee-ear-archetype:27.0.0.Final-SNAPSHOT archetype and then added a library module to get the following project structure:

project
+-->project-ear
+-->project-ejb
+-->project-lib
+-->project-web

However, in my project-lib/pom.xml file the dependency for this new library requires a version, where as the EJB and WEB modules do not. Why? And is there a way to configure the project-lib/pom.xml so that the project-ear/pom.xml doesn't require a version on a library that is part of the same project?

Snippet of project/pom.xml

<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>project</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>project</name>
<modules>
    <module>project-lib</module>
    <module>project-ejb</module>
    <module>project-web</module>
    <module>project-ear</module>
</modules>

Snippet of project-ear/pom.xml

<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.example</groupId>
    <artifactId>project</artifactId>
    <version>1.0-SNAPSHOT</version>
</parent>
<artifactId>project-ear</artifactId>
<packaging>ear</packaging>
<dependencies>
    <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>project-tfl</artifactId>
        <version>${project.version}</version>   <--- Line I wish to remove! -->
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>project-ejb</artifactId>
        <type>ejb</type>
    </dependency>
    <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>project-web</artifactId>
        <type>war</type>
    </dependency>
</dependencies>

Snippet of project-lib/pom.xml

<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.example</groupId>
    <artifactId>project</artifactId>
    <version>1.0-SNAPSHOT</version>
</parent>
<artifactId>project-lib</artifactId>
<packaging>jar</packaging>
<properties>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
    <finalName>${project.artifactId}</finalName>
</build>


问:
How to format the email content using mailx command
I'm trying to send this content using mailx command in bash script. I could see spaces between each lines. How should I remove spaces between each line and the content to look in good format?

```<code>echo "Hello there,
      Please find the attachment.
      Email content is having spaces between the lines. I want the spaces to be removed.
      Thanks"| mailx -s "Test Email" "${attachments[@]}" "abc@gmail.com""
</code>```

Any guidance please.

Mailx command

```<code>echo "Hello there,
      Please find the attachment.
      Email content is having spaces between the lines. I want the spaces to be removed.
      Thanks"| mailx -s "Test Email" "${attachments[@]}" "abc@gmail.com""
</code>```

I want the email content to be well formatted. Thanks!

Body:
I'm trying to send this content using mailx command in bash script. I could see spaces between each lines. How should I remove spaces between each line and the content to look in good format?

echo "Hello there,
      Please find the attachment.
      Email content is having spaces between the lines. I want the spaces to be removed.
      Thanks"| mailx -s "Test Email" "${attachments[@]}" "abc@gmail.com""

Any guidance please.

Mailx command

echo "Hello there,
      Please find the attachment.
      Email content is having spaces between the lines. I want the spaces to be removed.
      Thanks"| mailx -s "Test Email" "${attachments[@]}" "abc@gmail.com""

I want the email content to be well formatted. Thanks!


问:
what's CURL_Opessl_4 symbol means?
I'm compile the libarrow, which depend on curl_xxx@CURL_OPENSSL_4. (which seems the original libcurl4 from apt install)

```<code>/usr/lib/x86_64-linux-gnu/libarrow.so.1000.1.0: undefined reference to `curl_global_cleanup@CURL_OPENSSL_4'
</code>```

but I have installed the libcurl from source code, whose symbols is curl_xxx@OPENSSL3 (I compile it with libssl.so.3)
My question is

what does the @CURL_OPENSSL_4 mean? it is a namespace or something else?

how to replace the @xxx symbols of libcurl so that I can link the libarrow with it?

I have try the libcurl install configure with --with-ssl, but it can not made the CURL_OPENSSL_4 symbol..

Title: what's CURL_Opessl_4 symbol means?

Body:
I'm compile the libarrow, which depend on curl_xxx@CURL_OPENSSL_4. (which seems the original libcurl4 from apt install)

/usr/lib/x86_64-linux-gnu/libarrow.so.1000.1.0: undefined reference to `curl_global_cleanup@CURL_OPENSSL_4'

but I have installed the libcurl from source code, whose symbols is curl_xxx@OPENSSL3 (I compile it with libssl.so.3)
My question is

what does the @CURL_OPENSSL_4 mean? it is a namespace or something else?

how to replace the @xxx symbols of libcurl so that I can link the libarrow with it?

I have try the libcurl install configure with --with-ssl, but it can not made the CURL_OPENSSL_4 symbol..


问:
Run a specific test once in the test-suite for pytest
so currently I have a test suite written as:

```<code>@pytest.fixture(scope="module", params=[True, False], autouse=True)
def setup_for_my_test(request):

    if request.param:
        #do a bunch of stuff for True case
    else:
        #do a bunch of stuff for False case

    def reset_my_modifications():
        #revert the changes I had done for either of the cases
    request.addfinalizer(reset_my_modifications)

def test_1():
    #tests

def test_2():
    #tests

def test_run_this_once():
    #tests that will run only once in the whole suite
</code>```

What I want to do is let test_1 and test_2 run for all the values in the fixture which it does. But I want test_run_this_once to only run once in the whole session essentially like set the scope of the test to session.

So something like:

```<code>Collected 5 items...
test_1[True]
test_2[True]
test_1[False]
test_2[False]
test_run_this_once
</code>```

Any reference to docs or how this can be done would be really really helpful.
Thanks in advance for the help

Body:
so currently I have a test suite written as:

@pytest.fixture(scope="module", params=[True, False], autouse=True)
def setup_for_my_test(request):

    if request.param:
        #do a bunch of stuff for True case
    else:
        #do a bunch of stuff for False case

    def reset_my_modifications():
        #revert the changes I had done for either of the cases
    request.addfinalizer(reset_my_modifications)

def test_1():
    #tests

def test_2():
    #tests

def test_run_this_once():
    #tests that will run only once in the whole suite

What I want to do is let test_1 and test_2 run for all the values in the fixture which it does. But I want test_run_this_once to only run once in the whole session essentially like set the scope of the test to session.

So something like:

Collected 5 items...
test_1[True]
test_2[True]
test_1[False]
test_2[False]
test_run_this_once

Any reference to docs or how this can be done would be really really helpful.
Thanks in advance for the help


问:
Trying to run this code but I keep getting this error
I want to train an Artificial Neural Network on matlab r2020a for an automatic voltage regulator, I already have a simulink file for my output, but whenever I want to run this code:

```<code>I = out.input';
T = out.output';
net=newff(minmax(I),[3,5,1],{'logsig','tansig','purelin'},'trainlm');
net = init(net);                     % Used to initialize the network (weight and biases)
net.trainParam.show =1;     % The result of error (mse) is shown at each iteration (epoch)
net.trainParam.epochs = 10000;       % Maximum limit of the network training iteration process    (epoch)
net.trainParam.goal =1e-12;          % Stopping criterion based on error (mse) goal
net=train(net,I,T);                % Start training the network
</code>```

I keep facing this error:

```<code>Unrecognized function or variable 'procInfo'.

Error in nnMex.netHints (line 143)
    processingInfoArray = [processingInfoArray procInfo];

Error in nncalc.setup1>setupImpl (line 201)
  calcHints = calcMode.netHints(net,calcHints);

Error in nncalc.setup1 (line 16)
[calcMode,calcNet,calcData,calcHints,net,resourceText] = setupImpl(calcMode,net,data);

Error in nncalc.setup (line 7)
[calcMode,calcNet,calcData,calcHints,net,resourceText] = nncalc.setup1(calcMode,net,data);

Error in network/train (line 361)
    [calcLib,calcNet,net,resourceText] = nncalc.setup(calcMode,net,data);

Error in ann (line 8)
net=train(net,I,T);                % Start training the network
</code>```

I'm not sure where to start to my search for this problem, but I think it might be a compiler issue

I tried searching online, but all I got was just suggestion to download compilers and toolboxes.

Body:
I want to train an Artificial Neural Network on matlab r2020a for an automatic voltage regulator, I already have a simulink file for my output, but whenever I want to run this code:

I = out.input';
T = out.output';
net=newff(minmax(I),[3,5,1],{'logsig','tansig','purelin'},'trainlm');
net = init(net);                     % Used to initialize the network (weight and biases)
net.trainParam.show =1;     % The result of error (mse) is shown at each iteration (epoch)
net.trainParam.epochs = 10000;       % Maximum limit of the network training iteration process    (epoch)
net.trainParam.goal =1e-12;          % Stopping criterion based on error (mse) goal
net=train(net,I,T);                % Start training the network

I keep facing this error:

Unrecognized function or variable 'procInfo'.

Error in nnMex.netHints (line 143)
    processingInfoArray = [processingInfoArray procInfo];

Error in nncalc.setup1>setupImpl (line 201)
  calcHints = calcMode.netHints(net,calcHints);

Error in nncalc.setup1 (line 16)
[calcMode,calcNet,calcData,calcHints,net,resourceText] = setupImpl(calcMode,net,data);

Error in nncalc.setup (line 7)
[calcMode,calcNet,calcData,calcHints,net,resourceText] = nncalc.setup1(calcMode,net,data);

Error in network/train (line 361)
    [calcLib,calcNet,net,resourceText] = nncalc.setup(calcMode,net,data);

Error in ann (line 8)
net=train(net,I,T);                % Start training the network

I'm not sure where to start to my search for this problem, but I think it might be a compiler issue

I tried searching online, but all I got was just suggestion to download compilers and toolboxes.


问:
FFMPEG: Convert a bunch of image files to a video
I am trying to convert a bunch of .webp files to a mp4 file. I

```<code>cat $(find ../myFolder -type f | grep .webp | sort | tail -24) | ffmpeg -framerate 10 -i - -c:v libx264 -pix_fmt yuv420p out.mp4
</code>```

I am getting the following errors:

```<code>Input #0, webp_pipe, from 'pipe:':
  Duration: N/A, bitrate: N/A
    Stream #0:0: Video: webp, none, 10 tbr, 10 tbn, 10 tbc
Output #0, mp4, to 'out.mp4':
Output file #0 does not contain any stream
</code>```

I am not sure what is not right here - I am trying to have the smallest file size without compromising much on the video quality.

Body:
I am trying to convert a bunch of .webp files to a mp4 file. I

cat $(find ../myFolder -type f | grep .webp | sort | tail -24) | ffmpeg -framerate 10 -i - -c:v libx264 -pix_fmt yuv420p out.mp4

I am getting the following errors:

Input #0, webp_pipe, from 'pipe:':
  Duration: N/A, bitrate: N/A
    Stream #0:0: Video: webp, none, 10 tbr, 10 tbn, 10 tbc
Output #0, mp4, to 'out.mp4':
Output file #0 does not contain any stream

I am not sure what is not right here - I am trying to have the smallest file size without compromising much on the video quality.


问:
How can I apply the model that I built against the different data using stat models?
How can I apply the model that I built against different data using stat models?

For example here I use OLS to model the data in file1. I want to use the modelX against on file2 data. Is that possible?

```<code>modelX = sm.OLS(y~ a+b+c, data=file1).fit()
modelY = sm.modelX.apply(y~ a+b+c, data=file2)
</code>```

tried

```<code>import statsmodels.api as sm
import seaborn as sns
mpg = sns.load_dataset("mpg")

model = sm.OLS(mpg.weight, mpg.mpg)
results = model.fit()
results.apply(mpg.weight, mpg.mpg)
</code>```

error

```<code>AttributeError: 'OLSResults' object has no attribute 'apply'
</code>```

Body:
How can I apply the model that I built against different data using stat models?

For example here I use OLS to model the data in file1. I want to use the modelX against on file2 data. Is that possible?

modelX = sm.OLS(y~ a+b+c, data=file1).fit()
modelY = sm.modelX.apply(y~ a+b+c, data=file2)

tried

import statsmodels.api as sm
import seaborn as sns
mpg = sns.load_dataset("mpg")

model = sm.OLS(mpg.weight, mpg.mpg)
results = model.fit()
results.apply(mpg.weight, mpg.mpg)

error

AttributeError: 'OLSResults' object has no attribute 'apply'


问:
502 Bad Gateway | Gunicorn - ngnix - django
I wanted to that my dango app run in server and I tried with gunciron. When i run my app with gunicorn, server is working.
I mean

```<code>`# gunicorn --bind 0.0.0.0:8000 myapp.wsgi`
</code>```

is working

But if i disconnect with server, server is not working. So i used ngnix.

I followed this source https://github.com/satssehgal/URLShortnerDjango- . I did all them. I controlled my path but all path is right. What can i do for server work?

systemctl status nginx
enter image description here

ps aux | grep php-fpm

enter image description here

ngnix.conf:

```<code>user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
         include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

         gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/x$
        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;

        fastcgi_buffers 8 16k;
        fastcgi_buffer_size 32k;
        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
}
</code>```

/etc/nginx/sites-available/myapp:

```<code>server {
    listen 80;

    location = /favicon.ico { access_log off; log_not_found off; }
    keepalive_timeout 10;
    charset     utf-8;
    location /static/ {
        root /root/ayzguci/myapp;
    }
    location / {
        include proxy_params;
        proxy_pass http://unix:/root/ayzguci/myapp/myapp.sock;
        proxy_redirect     off;
        proxy_set_header   X-Forwarded-Host $5.105.5.140;
    }
        }
</code>```

ps ax|grep gunicorn outout:

```<code> 1782 ?        Ss     0:00 /root/ayzguci/myenv/bin/python3 /root/ayzguci/myenv/bin/gunicorn --access-logfile - --timeout 1000 --workers 3 --bind unix:/root/ayzguci/myapp/myapp.sock myapp.wsgi:application
 1812 ?        S      0:00 /root/ayzguci/myenv/bin/python3 /root/ayzguci/myenv/bin/gunicorn --access-logfile - --timeout 1000 --workers 3 --bind unix:/root/ayzguci/myapp/myapp.sock myapp.wsgi:application
 1813 ?        S      0:00 /root/ayzguci/myenv/bin/python3 /root/ayzguci/myenv/bin/gunicorn --access-logfile - --timeout 1000 --workers 3 --bind unix:/root/ayzguci/myapp/myapp.sock myapp.wsgi:application
 1814 ?        S      0:00 /root/ayzguci/myenv/bin/python3 /root/ayzguci/myenv/bin/gunicorn --access-logfile - --timeout 1000 --workers 3 --bind unix:/root/ayzguci/myapp/myapp.sock myapp.wsgi:application
 1900 pts/0    S+     0:00 grep --color=auto gunicorn
</code>```

netstat -an|grep 8000 output:

```<code>root@localhost:~# sudo apt install net-tools
Reading package lists... Done
Building dependency tree
Reading state information... Done
net-tools is already the newest version (1.60+git20161116.90da8a0-1ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 72 not upgraded.
root@localhost:~# netstat -an|grep 8000
root@localhost:~#
</code>```

Body:
I wanted to that my dango app run in server and I tried with gunciron. When i run my app with gunicorn, server is working.
I mean

`# gunicorn --bind 0.0.0.0:8000 myapp.wsgi`

is working

But if i disconnect with server, server is not working. So i used ngnix.

I followed this source https://github.com/satssehgal/URLShortnerDjango- . I did all them. I controlled my path but all path is right. What can i do for server work?

systemctl status nginx
enter image description here

ps aux | grep php-fpm

enter image description here

ngnix.conf:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
         include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

         gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/x$
        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;

        fastcgi_buffers 8 16k;
        fastcgi_buffer_size 32k;
        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
}

/etc/nginx/sites-available/myapp:

server {
    listen 80;

    location = /favicon.ico { access_log off; log_not_found off; }
    keepalive_timeout 10;
    charset     utf-8;
    location /static/ {
        root /root/ayzguci/myapp;
    }
    location / {
        include proxy_params;
        proxy_pass http://unix:/root/ayzguci/myapp/myapp.sock;
        proxy_redirect     off;
        proxy_set_header   X-Forwarded-Host $5.105.5.140;
    }
        }

ps ax|grep gunicorn outout:

 1782 ?        Ss     0:00 /root/ayzguci/myenv/bin/python3 /root/ayzguci/myenv/bin/gunicorn --access-logfile - --timeout 1000 --workers 3 --bind unix:/root/ayzguci/myapp/myapp.sock myapp.wsgi:application
 1812 ?        S      0:00 /root/ayzguci/myenv/bin/python3 /root/ayzguci/myenv/bin/gunicorn --access-logfile - --timeout 1000 --workers 3 --bind unix:/root/ayzguci/myapp/myapp.sock myapp.wsgi:application
 1813 ?        S      0:00 /root/ayzguci/myenv/bin/python3 /root/ayzguci/myenv/bin/gunicorn --access-logfile - --timeout 1000 --workers 3 --bind unix:/root/ayzguci/myapp/myapp.sock myapp.wsgi:application
 1814 ?        S      0:00 /root/ayzguci/myenv/bin/python3 /root/ayzguci/myenv/bin/gunicorn --access-logfile - --timeout 1000 --workers 3 --bind unix:/root/ayzguci/myapp/myapp.sock myapp.wsgi:application
 1900 pts/0    S+     0:00 grep --color=auto gunicorn

netstat -an|grep 8000 output:

root@localhost:~# sudo apt install net-tools
Reading package lists... Done
Building dependency tree
Reading state information... Done
net-tools is already the newest version (1.60+git20161116.90da8a0-1ubuntu1).
0 upgraded, 0 newly installed, 0 to remove and 72 not upgraded.
root@localhost:~# netstat -an|grep 8000
root@localhost:~#


问:
How can I access foreign table in my nodejs TypeORM code
This is my database view and I need to access this foreign table using Typeform
enter image description here

I can only access my table using their entities but there is no entity in case of a foreign table so how can I access them in my code

```<code>const employeRepo = AppDatasource.getRepository(Employee);
const employeedata = await employeRepo.find()
</code>```

This is how I access my other tables

Body:
This is my database view and I need to access this foreign table using Typeform
enter image description here

I can only access my table using their entities but there is no entity in case of a foreign table so how can I access them in my code

const employeRepo = AppDatasource.getRepository(Employee);
const employeedata = await employeRepo.find()

This is how I access my other tables


问:
FirebaseError: Function setDoc() called with invalid data
In my Angular app I use Firebase and I wrote the following register-method:

```<code>  register(form) {
    this.isLoading = true;
    console.log(form.value);
    this.authService.register(form.value).then((data: any) => {
      console.log(data);
      this.router.navigateByUrl('/home');
      this.isLoading = false;
      form.reset();
    })
    .catch(e => {
      console.log(e);
      this.isLoading = false;
      let msg: string = 'Could not sign up, please try again.';
      if(e.code == 'auth/email-already-in-use') {
        msg = 'Email already in use';
      }
      this.showAlert(msg);
    });
  }
</code>```

When I click on the sign-in button, I get the following error message:

```<code>"FirebaseError: Function setDoc() called with invalid data. Unsupported field value: undefined (found in field name in document user/e65KFYQCd3cbBODLp1rcgLC22643)"
</code>```

I tried changing the types but the error remains.

Body:
In my Angular app I use Firebase and I wrote the following register-method:

  register(form) {
    this.isLoading = true;
    console.log(form.value);
    this.authService.register(form.value).then((data: any) => {
      console.log(data);
      this.router.navigateByUrl('/home');
      this.isLoading = false;
      form.reset();
    })
    .catch(e => {
      console.log(e);
      this.isLoading = false;
      let msg: string = 'Could not sign up, please try again.';
      if(e.code == 'auth/email-already-in-use') {
        msg = 'Email already in use';
      }
      this.showAlert(msg);
    });
  }

When I click on the sign-in button, I get the following error message:

"FirebaseError: Function setDoc() called with invalid data. Unsupported field value: undefined (found in field name in document user/e65KFYQCd3cbBODLp1rcgLC22643)"

I tried changing the types but the error remains.


问:
Change date format to "dd-mm-yyyy" in Django rest framwork
Hi below is my request payload and i am using normal serializer and i want to save date in "dd-mm-YYYY" format in DB

```<code>{
    "start_date": "2022-10-10",
    "end_date": "2022-12-10"
}
</code>```

Here is my serializer

```<code>class StudentSerializer(serializers.Serializer):
    start_date = serializers.DateField()
    end_date = serializers.DateField()
</code>```

Note: I don't want to change the requested payload date format only change on saving the record by changing the format to "dd-mm-YYY".

Here is my django settings.py file configuration

```<code>REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'common.exception.custom_exception_handler.custom_exception_handler',
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'NON_FIELD_ERRORS_KEY': "detail",
    'DATE_FORMAT': ["%d-%M-%Y"]
}
</code>```

Body:
Hi below is my request payload and i am using normal serializer and i want to save date in "dd-mm-YYYY" format in DB

{
    "start_date": "2022-10-10",
    "end_date": "2022-12-10"
}

Here is my serializer

class StudentSerializer(serializers.Serializer):
    start_date = serializers.DateField()
    end_date = serializers.DateField()

Note: I don't want to change the requested payload date format only change on saving the record by changing the format to "dd-mm-YYY".

Here is my django settings.py file configuration

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'common.exception.custom_exception_handler.custom_exception_handler',
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'NON_FIELD_ERRORS_KEY': "detail",
    'DATE_FORMAT': ["%d-%M-%Y"]
}


问:
How to hide proceed to Checkout button if cart value is low in woocommerce
This is my code I saw this in stack overflow but it's not working anyone please help me?

```<code><?php

   $current_screen_user = wp_get_current_user();

    if( in_array( 'wholesale', $current_screen_user->roles ) ) {
      $minimum = 251; // Set the minimum amt.
      $cart_amt = WC()->cart->subtotal; // cart sub_total, this is actual total excluding discounts and shipping.

        if ( $cart_amt < $minimum ) {
          if( is_cart() ) {
        //Added notices for cart page.
              wc_print_notice(
                  sprintf( 'You must have an order with a minimum of %s to place your order, your current order total is %s.' ,
                      wc_price( $minimum ),
                      wc_price( $cart_amt )
                  ), 'error'
              );
          } else {
        //Added notice msg for checkout page.

              wc_add_notice(
                  sprintf( 'You must have an order with a minimum of %s to place your order, your current order total is %s.' ,
                      wc_price( $minimum ),
                      wc_price( $cart_amt)
                  ), 'error'
              );
          }
      } else {
          do_action( 'woocommerce_proceed_to_checkout' );
      }
    } else {
      do_action( 'woocommerce_proceed_to_checkout' );
    }
    ?>
</code>```

I don't know how to call woocommerce cart global variable. I try many ways but it's not working main logic is -- >> if the cart value is less than 250 then hide the checkout button and else it is greater than 250 then show the proceed to checkout button.

Body:
This is my code I saw this in stack overflow but it's not working anyone please help me?

<?php

   $current_screen_user = wp_get_current_user();

    if( in_array( 'wholesale', $current_screen_user->roles ) ) {
      $minimum = 251; // Set the minimum amt.
      $cart_amt = WC()->cart->subtotal; // cart sub_total, this is actual total excluding discounts and shipping.

        if ( $cart_amt < $minimum ) {
          if( is_cart() ) {
        //Added notices for cart page.
              wc_print_notice(
                  sprintf( 'You must have an order with a minimum of %s to place your order, your current order total is %s.' ,
                      wc_price( $minimum ),
                      wc_price( $cart_amt )
                  ), 'error'
              );
          } else {
        //Added notice msg for checkout page.

              wc_add_notice(
                  sprintf( 'You must have an order with a minimum of %s to place your order, your current order total is %s.' ,
                      wc_price( $minimum ),
                      wc_price( $cart_amt)
                  ), 'error'
              );
          }
      } else {
          do_action( 'woocommerce_proceed_to_checkout' );
      }
    } else {
      do_action( 'woocommerce_proceed_to_checkout' );
    }
    ?>

I don't know how to call woocommerce cart global variable. I try many ways but it's not working main logic is -- >> if the cart value is less than 250 then hide the checkout button and else it is greater than 250 then show the proceed to checkout button.


问:
How can I save my file image to a folder of the project in javascript?
I want to save my image to my project's folder, the image that I have in two shapes (base64 or file).</p>
```<code>        var base = canvas.toDataURL().replace("data:image/png;base64,", "");

        let file;
        const linkSource = `data:image/png;base64,${base}`;
        await fetch(linkSource)
          .then(res => res.blob())
          .then(blob => {
            file = new File([blob], "test",{ type: "image/png" });
            }
            console.log('base64  ',base);
            console.log('file  ',file);
</code>```

Body:
I want to save my image to my project's folder, the image that I have in two shapes (base64 or file).

        var base = canvas.toDataURL().replace("data:image/png;base64,", "");

        let file;
        const linkSource = `data:image/png;base64,${base}`;
        await fetch(linkSource)
          .then(res => res.blob())
          .then(blob => {
            file = new File([blob], "test",{ type: "image/png" });
            }
            console.log('base64  ',base);
            console.log('file  ',file);


问:
Finding patterns within a log file
For example, out of 'yes' and 'no' I'm looking for a pattern of yes' and no's that guarantees me a no.

Eg.
'Yes, yes, no, yes' always or 90% of the time gives a 'no' next

I'm trying to find a tool to search for patterns to me and I haven't been able to find one. I saw a  uni paper on it but that didn't do what I was searching for.

Title: Finding patterns within a log file


问:
Local DNS Resolution With Raspberry Pi
How can one set up a local network so that you can go to my-website.com on any machine and be directed to a Raspberry Pi's webserver, running on port 80?

The Pi is currently connected to my local network, and I can go to it's IP address (say 192.10.4.12) and will be served up content from the webserver running on the Pi. I'd like to be able to configure my local DNS so that if any device on the network goes to my-website.com it resolves that human-readable domain to the Raspberry PI's IP address.

From my understanding (and this could be wrong) I need to:

Set up a DNS locally to do this resolution

Tell my Wifi router to use the DNS

Add an entry to the DNS pointing my-website.com to the IP of the Raspberry Pi.

I've installed dnsmasq onto the Raspberry Pi. It's running. I've added the following line to the configuration file:

```<code>address=/my-website.com/127.0.0.1
</code>```

When I run curl my-website.com from the PI, I now hit my webserver.

I've also added a line in my Wifi Router's configuration for DNS servers. When running scutil --dns | grep 'nameserver\[[0-9]*\]' on my personal machine, I see the following:

```<code>  nameserver[0] : 100.64.0.2
  nameserver[0] : 100.64.0.2
  nameserver[0] : 192.168.0.242       #  This is the IP of my Pi
  nameserver[1] : 192.168.0.1
  nameserver[0] : 100.64.0.2
</code>```

This would seem to suggest that the dnsmasq should be serving as a DNS server for my local network. However, this doesn't seem to work because curling my-website.com from my local machine isn't directing me to the PI's IP address. In fact, none of the addresses that I add to the dnsmasq configuration file seem to get picked up by my local machine at all, which would suggest that either my machine is not actually using the PI as a DNS, or else I've done something else wrong.

Can someone please explain how I can set up a DNS locally, so that I'm able to resolve a custom domain, like my-website.com to point to the IP address and Port 80 of my Raspberry PI? What am I doing wrong here?

Title: Local DNS Resolution With Raspberry Pi

Body:
How can one set up a local network so that you can go to my-website.com on any machine and be directed to a Raspberry Pi's webserver, running on port 80?

The Pi is currently connected to my local network, and I can go to it's IP address (say 192.10.4.12) and will be served up content from the webserver running on the Pi. I'd like to be able to configure my local DNS so that if any device on the network goes to my-website.com it resolves that human-readable domain to the Raspberry PI's IP address.

From my understanding (and this could be wrong) I need to:

Set up a DNS locally to do this resolution

Tell my Wifi router to use the DNS

Add an entry to the DNS pointing my-website.com to the IP of the Raspberry Pi.

I've installed dnsmasq onto the Raspberry Pi. It's running. I've added the following line to the configuration file:

address=/my-website.com/127.0.0.1

When I run curl my-website.com from the PI, I now hit my webserver.

I've also added a line in my Wifi Router's configuration for DNS servers. When running scutil --dns | grep 'nameserver\[[0-9]*\]' on my personal machine, I see the following:

  nameserver[0] : 100.64.0.2
  nameserver[0] : 100.64.0.2
  nameserver[0] : 192.168.0.242       #  This is the IP of my Pi
  nameserver[1] : 192.168.0.1
  nameserver[0] : 100.64.0.2

This would seem to suggest that the dnsmasq should be serving as a DNS server for my local network. However, this doesn't seem to work because curling my-website.com from my local machine isn't directing me to the PI's IP address. In fact, none of the addresses that I add to the dnsmasq configuration file seem to get picked up by my local machine at all, which would suggest that either my machine is not actually using the PI as a DNS, or else I've done something else wrong.

Can someone please explain how I can set up a DNS locally, so that I'm able to resolve a custom domain, like my-website.com to point to the IP address and Port 80 of my Raspberry PI? What am I doing wrong here?