问:
assignment operator in complex type vs arrays in C++
It seems that BoVector rhs1 and BoVector rhs2 can assign all elements by a = square(bv); successfully. But it might not be a case in a common assignment of one array to another, say

```<code>int b[2]{ 1,2,3 };
int c[2]{ 3,4,5 };
c = b; //it doesn't work
</code>```

c =b; will generate a compiler error. Why is that? since the code below, doesn't overwrite the operator= to be capable of array assignment.

P.S: Please DO NOT ask me what not to use or use in the comment section (this is like asking me delete the question and forget about it!). My question is why inside the class under the hood assigning arrays work but in a regular way it doesn't  work!

```<code>template <typename T>
T square(T x)
{
    return x * x;
}
template<typename T>
class BoVector
{
private:
    T arr[1000];
    size_t size;
public:

    BoVector():
        size(0)
    {}
    void push(T x)
    {
        this->arr[this->size] = x;
        ++(this->size);

    }

    T get(int i) const
    {
        return arr[i];
    }
    size_t getSize() const { return this->size; };
    void print() const
    {
        for (size_t i=0;i<size;++i )
        {
            std::cout << this->arr[i] << '\n';
        }
    }
};
template<typename T>
BoVector<T> operator*(const BoVector<T>& rhs1, const BoVector<T>& rhs2 )
{
    BoVector<T> result;
    for (size_t i = 0; i < rhs1.getSize(); ++i)
    {

        result.push(rhs1.get(i) * rhs2.get(i));

    }
    return result;
}
int main()
{

    BoVector<int> bv;
    bv.push(2);
    bv.push(10);
    bv.push(3);
    bv.push(20);

    BoVector<int> a;
    a = square(bv); //it works perfectly
    a.print();

    int b[2]{ 1,2,3 };
    int c[2]{ 3,4,5 };
    c = b; //it doesn't work

}
</code>```

Body:
It seems that BoVector rhs1 and BoVector rhs2 can assign all elements by a = square(bv); successfully. But it might not be a case in a common assignment of one array to another, say

int b[2]{ 1,2,3 };
int c[2]{ 3,4,5 };
c = b; //it doesn't work

c =b; will generate a compiler error. Why is that? since the code below, doesn't overwrite the operator= to be capable of array assignment.

P.S: Please DO NOT ask me what not to use or use in the comment section (this is like asking me delete the question and forget about it!). My question is why inside the class under the hood assigning arrays work but in a regular way it doesn't  work!

template <typename T>
T square(T x)
{
    return x * x;
}
template<typename T>
class BoVector
{
private:
    T arr[1000];
    size_t size;
public:

    BoVector():
        size(0)
    {}
    void push(T x)
    {
        this->arr[this->size] = x;
        ++(this->size);

    }

    T get(int i) const
    {
        return arr[i];
    }
    size_t getSize() const { return this->size; };
    void print() const
    {
        for (size_t i=0;i<size;++i )
        {
            std::cout << this->arr[i] << '\n';
        }
    }
};
template<typename T>
BoVector<T> operator*(const BoVector<T>& rhs1, const BoVector<T>& rhs2 )
{
    BoVector<T> result;
    for (size_t i = 0; i < rhs1.getSize(); ++i)
    {

        result.push(rhs1.get(i) * rhs2.get(i));

    }
    return result;
}
int main()
{

    BoVector<int> bv;
    bv.push(2);
    bv.push(10);
    bv.push(3);
    bv.push(20);

    BoVector<int> a;
    a = square(bv); //it works perfectly
    a.print();

    int b[2]{ 1,2,3 };
    int c[2]{ 3,4,5 };
    c = b; //it doesn't work

}


来源: stackexchange

问:
Batch file: comparison operators LEQ, LSS not working as I expecting
I don't understand why these comparison operators LEQ LSS don't work. I need it to be true if the two if are fulfilled. More exactly if number 1 Less than or Equal 20 and if number 2 less than 1 then Do something if the two condition are not fulfilled then don't execute.

If I fill 22 and 2 for example working, If I fill 100 and 10 give me true on ifs.

Which is strange for me

I think I did not understood very well how works.

thank you for help

```<code>echo off

set /p numarcanale=Number 1=
set /p numarvideopecanal=Number 2=

IF "%numarcanale%" LEQ "20" (
   IF "%numarvideopecanal%" LSS "2" (

echo  Do Something

   )
)

Pause
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I don't understand why these comparison operators LEQ LSS don't work. I need it to be true if the two if are fulfilled. More exactly if number 1 Less than or Equal 20 and if number 2 less than 1 then Do something if the two condition are not fulfilled then don't execute.

If I fill 22 and 2 for example working, If I fill 100 and 10 give me true on ifs.

Which is strange for me

I think I did not understood very well how works.

thank you for help

echo off

set /p numarcanale=Number 1=
set /p numarvideopecanal=Number 2=

IF "%numarcanale%" LEQ "20" (
   IF "%numarvideopecanal%" LSS "2" (

echo  Do Something

   )
)

Pause


问:
document is undefined in script.min.js
I use Bootstrap studio 5 and I published the website directly from it. When I navigate to it (https://my-website-name.bss.design/) I notice that javascript functionalities are not there. There is an error in the console:

script.min.js?h=fb924772e895278c3c5f2d161d9d0ebd:1 Uncaught TypeError: Cannot read properties of undefined (reading 'addEventListener')     at script.min.js?h=fb924772e895278c3c5f2d161d9d0ebd:1:649

It's at the first line but the file only has one line (minified) so this is where the problem is:
document.addEventListener("DOMContentLoaded",(function(){[].slice.call(document.querySelectorAll ...

Somehow document is undefined which makes no sense since that file is loaded at the end of the html body just like it should. Can somehow please tell me what the heck is going on here? I can provide the full script.min.js if necessary.

I didn't try anything since the problem itself makes no sense to me and Bootstrap studio automatically minifies javascript without giving me options.

Title: document is undefined in script.min.js


问:
Calculating Pandas Column from Prior Row's Value
I have a data frame of order start times and expected completion times for each order across different days.

I'd like to calculate a column that calculates the completion time for each order but updates the Order Start Time to be prior order's completion time if it is completed later than the original Order Start Time. Also, I'd like this calculation to be segmented across days (that is, the first order of the day doesn't depend on the completion time of the last order from the prior day).

```<code>data = {'Date': ['2022-12-01', '2022-12-01', '2022-12-01', '2022-12-01', '2022-12-02', '2022-12-02', '2022-12-02', '2022-12-02'],
        'Order Start Time': ['2022-12-01 10:50:00.000', '2022-12-01 10:53:33.721', '2022-12-01 10:58:14.217', '2022-12-01 10:58:57.162',
                             '2022-12-02 10:50:00.000', '2022-12-02 10:53:33.721', '2022-12-02 10:58:14.217', '2022-12-02 10:58:57.162'],
        'Order Rank Within Day': [1, 2, 3, 4, 1, 2, 3, 4],
        'Expected Completion Time': [125, 153, 75, 99, 165, 133, 85, 129]}

df = pd.DataFrame(data, columns=['Date', 'Order Start Time', 'Order Rank Within Day', 'Expected Completion Time'])
</code>```

The code I have is:

```<code>for row in df.itertuples():
  df['completion_time'] = np.where(df['Order Rank Within Day']==1, pd.to_datetime(df['Order Start Time']) + pd.to_timedelta(df['Expected Completion Time'], unit='s'), df['completion_time'].at[row.Index-1])
</code>```

But I get a KeyError. Is there a suggested solution?

Body:
I have a data frame of order start times and expected completion times for each order across different days.

I'd like to calculate a column that calculates the completion time for each order but updates the Order Start Time to be prior order's completion time if it is completed later than the original Order Start Time. Also, I'd like this calculation to be segmented across days (that is, the first order of the day doesn't depend on the completion time of the last order from the prior day).

data = {'Date': ['2022-12-01', '2022-12-01', '2022-12-01', '2022-12-01', '2022-12-02', '2022-12-02', '2022-12-02', '2022-12-02'],
        'Order Start Time': ['2022-12-01 10:50:00.000', '2022-12-01 10:53:33.721', '2022-12-01 10:58:14.217', '2022-12-01 10:58:57.162',
                             '2022-12-02 10:50:00.000', '2022-12-02 10:53:33.721', '2022-12-02 10:58:14.217', '2022-12-02 10:58:57.162'],
        'Order Rank Within Day': [1, 2, 3, 4, 1, 2, 3, 4],
        'Expected Completion Time': [125, 153, 75, 99, 165, 133, 85, 129]}

df = pd.DataFrame(data, columns=['Date', 'Order Start Time', 'Order Rank Within Day', 'Expected Completion Time'])

The code I have is:

for row in df.itertuples():
  df['completion_time'] = np.where(df['Order Rank Within Day']==1, pd.to_datetime(df['Order Start Time']) + pd.to_timedelta(df['Expected Completion Time'], unit='s'), df['completion_time'].at[row.Index-1])

But I get a KeyError. Is there a suggested solution?


问:
C#: adding a new row to datagrid with values from textboxes using bindingsource
I have a datagridview and textboxes all bound to a bindingsource. I also have buttons for actions Create and Update. The latter works as intended: the item in the selected row updates with values from the textboxes. Here's the whole code behind the Update button:

```<code>myBindingSource.EndEdit();
myTableAdapter.Update(myDataSet.myTable);
</code>```

The Create button in current implementation adds an empty row and clears all the textboxes, so the only way to add actual values is using the Update button afterwards. Here's the whole code behind the Create button:

```<code>myBindingSource.CancelEdit();
myBindingSource.AddNew();
</code>```

But I want the Create button to add a row with values already entered into the textboxes, and then clear them. I tried to only use this line:

```<code>myBindingSource.AddNew();
</code>```

But if I don't cancel pending changes, 1) they'll be applied to the item currently selected in datagridview, 2) an empty row will be added to datagridview.

How can I change the Create button's behavior, so that it added rows with values from the textboxes without affecting currently selected row?

Body:
I have a datagridview and textboxes all bound to a bindingsource. I also have buttons for actions Create and Update. The latter works as intended: the item in the selected row updates with values from the textboxes. Here's the whole code behind the Update button:

myBindingSource.EndEdit();
myTableAdapter.Update(myDataSet.myTable);

The Create button in current implementation adds an empty row and clears all the textboxes, so the only way to add actual values is using the Update button afterwards. Here's the whole code behind the Create button:

myBindingSource.CancelEdit();
myBindingSource.AddNew();

But I want the Create button to add a row with values already entered into the textboxes, and then clear them. I tried to only use this line:

myBindingSource.AddNew();

But if I don't cancel pending changes, 1) they'll be applied to the item currently selected in datagridview, 2) an empty row will be added to datagridview.

How can I change the Create button's behavior, so that it added rows with values from the textboxes without affecting currently selected row?


问:
Spark Streaming: write source records and calculate aggregates in single pass
I am reading from a Kinesis stream:

```<code>import pyspark.sql.types as T
import pyspark.sql.functions as F

schema = T.StructType(
    [
        T.StructField("data", T.StringType(), True),
        T.StructField("metadata", T.StructType([
            T.StructField("timestamp", T.TimestampType(), True),
            T.StructField("record-type", T.StringType(), True),
            T.StructField("operation", T.StringType(), True),
            T.StructField("partition-key-type", T.StringType(), True),
            T.StructField("partition-key-value", T.StringType(), True),
            T.StructField("schema-name", T.StringType(), True),
            T.StructField("table-name", T.StringType(), True)
        ]), True)
    ]
)

kinesis = (
    spark.readStream
        .format("kinesis")
        .option("streamName", "data-platform-aws-dms-poc-dms-sample")
        .option("region", "us-east-1")
        .option("initialPosition", "TRIM_HORIZON")
        .load()
        .selectExpr("partitionKey", "CAST(data AS STRING) AS data", "stream", "shardId", "sequenceNumber", "approximateArrivalTimestamp")
        .withColumn("data", F.from_json("data", schema))
        .selectExpr("partitionKey", "data.data", "data.metadata.*", "stream", "shardId", "sequenceNumber", "approximateArrivalTimestamp")
)
</code>```

And writing the output to Delta Lake:

```<code>checkpoint_path = "s3://route-databricks-sandbox-data/checkpoint/sandbox.route.dms_sample"

query = (
    kinesis
        .writeStream
        .format("delta")
        .queryName("dms_sample_output")
        .outputMode("append")
        .option("checkpointLocation", checkpoint_path)
        .partitionBy("schema-name", "table-name")
        .toTable("sandbox.public.dms_sample")
)
</code>```

I want to perform an aggregation over the data as it flows through my pipeline without having to re-read the data from the stream. The aggregation will be a calculation over each Kinesis shardId so it will be small and fit easily in memory.

Body:
I am reading from a Kinesis stream:

import pyspark.sql.types as T
import pyspark.sql.functions as F

schema = T.StructType(
    [
        T.StructField("data", T.StringType(), True),
        T.StructField("metadata", T.StructType([
            T.StructField("timestamp", T.TimestampType(), True),
            T.StructField("record-type", T.StringType(), True),
            T.StructField("operation", T.StringType(), True),
            T.StructField("partition-key-type", T.StringType(), True),
            T.StructField("partition-key-value", T.StringType(), True),
            T.StructField("schema-name", T.StringType(), True),
            T.StructField("table-name", T.StringType(), True)
        ]), True)
    ]
)

kinesis = (
    spark.readStream
        .format("kinesis")
        .option("streamName", "data-platform-aws-dms-poc-dms-sample")
        .option("region", "us-east-1")
        .option("initialPosition", "TRIM_HORIZON")
        .load()
        .selectExpr("partitionKey", "CAST(data AS STRING) AS data", "stream", "shardId", "sequenceNumber", "approximateArrivalTimestamp")
        .withColumn("data", F.from_json("data", schema))
        .selectExpr("partitionKey", "data.data", "data.metadata.*", "stream", "shardId", "sequenceNumber", "approximateArrivalTimestamp")
)

And writing the output to Delta Lake:

checkpoint_path = "s3://route-databricks-sandbox-data/checkpoint/sandbox.route.dms_sample"

query = (
    kinesis
        .writeStream
        .format("delta")
        .queryName("dms_sample_output")
        .outputMode("append")
        .option("checkpointLocation", checkpoint_path)
        .partitionBy("schema-name", "table-name")
        .toTable("sandbox.public.dms_sample")
)

I want to perform an aggregation over the data as it flows through my pipeline without having to re-read the data from the stream. The aggregation will be a calculation over each Kinesis shardId so it will be small and fit easily in memory.


问:
How to disable manifest mode in vcpkg?
Vcpkg has a manifest mode where one specifies a vcpkg.json file with all the packages required for a project. I would like to temporarily disable this feature and instead use vcpkg install mypackage directly. However, if a vcpkg.json file is present in your root directory vcpkg automatically switches to manifest mode, so when I try to run vcpkg install I get:

error: In manifest mode, vcpkg install does not support individual package arguments.
To install additional packages, edit vcpkg.json and then run vcpkg install without any package arguments.

To get around this I instead tried this:

```<code>export VCPKG_MANIFEST_MODE=OFF
./vcpkg install mypackage
</code>```

But I still get the same error. Is there a way to disable manifest mode? The only way I've found so far is to delete the vcpkg.json file temporarily, but this is rather cumbersome.

Title: How to disable manifest mode in vcpkg?

Body:
Vcpkg has a manifest mode where one specifies a vcpkg.json file with all the packages required for a project. I would like to temporarily disable this feature and instead use vcpkg install mypackage directly. However, if a vcpkg.json file is present in your root directory vcpkg automatically switches to manifest mode, so when I try to run vcpkg install I get:

error: In manifest mode, vcpkg install does not support individual package arguments.
To install additional packages, edit vcpkg.json and then run vcpkg install without any package arguments.

To get around this I instead tried this:

export VCPKG_MANIFEST_MODE=OFF
./vcpkg install mypackage

But I still get the same error. Is there a way to disable manifest mode? The only way I've found so far is to delete the vcpkg.json file temporarily, but this is rather cumbersome.


问:
Element wise addition of two n dimensional lists
When I need to add two 2D lists element wise, the approach I am using is

```<code>l1 = [[1, 1, 1],
      [2, 2, 2],
      [3, 3, 3]]

l2 = [[1, 1, 1],
      [2, 2, 2],
      [3, 3, 3]]

new = list(map(lambda e: [sum(x) for x in zip(*e)], zip(l1, l2)))
print(new)
</code>```
```<code>output : [[2, 2, 2],
          [4, 4, 4],
          [6, 6, 6]]
</code>```

This code is already difficult to read.

So how would I add two n dimensional lists element wise? Is there a pythonic way to do it or should I use numpy?

Body:
When I need to add two 2D lists element wise, the approach I am using is

l1 = [[1, 1, 1],
      [2, 2, 2],
      [3, 3, 3]]

l2 = [[1, 1, 1],
      [2, 2, 2],
      [3, 3, 3]]

new = list(map(lambda e: [sum(x) for x in zip(*e)], zip(l1, l2)))
print(new)

output : [[2, 2, 2],
          [4, 4, 4],
          [6, 6, 6]]

This code is already difficult to read.

So how would I add two n dimensional lists element wise? Is there a pythonic way to do it or should I use numpy?


问:
Why sonarqube doesnot show code coverage percentage of a specific file eventhough it's unit test classes are written.?
I am using the latest SonarQube Enterprise Version.

I have a python file named project/projectName/script/fileName.py. This file has many methods written.

Also, I have the unit test written for the fileName.py under the location project/projectName/test/fileNameTest.py.

In SonarQube I am not able to see the percentage of the coverage of fileName.py. It is shown 0.0% even though I have written the test classes of the methods in the file fileNameTest.py.

But SonarQube calculates the entire project's code coverage successfully in the Overview section of dashboard.

Why the coverage percentage of some specific files are not
calculated/not displayed even though it's unit test for methods are
written.?


问:
Google Cloud Speech permission issue
I am trying to process speech in real time in order to transcribe it, using Google Cloud's speech API.

I have a service account associated with the speech service, plus a local JSON which should authorize my requests to Google Cloud (it contains a couple of credentials). Even if the key is set to expire on January 1st, 10000, attempting to obtain the transcript generates the following error:

```<code>google.api_core.exceptions.Unauthenticated: 401 Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project. [reason: "ACCESS_TOKEN_EXPIRED"
domain: "googleapis.com"
metadata {
  key: "method"
  value: "google.cloud.speech.v1.Speech.StreamingRecognize"
}
metadata {
  key: "service"
  value: "speech.googleapis.com"
}
]
</code>```

What am I doing wrong? I cannot seem to find a solution for this online.
Thank you!

Title: Google Cloud Speech permission issue

Body:
I am trying to process speech in real time in order to transcribe it, using Google Cloud's speech API.

I have a service account associated with the speech service, plus a local JSON which should authorize my requests to Google Cloud (it contains a couple of credentials). Even if the key is set to expire on January 1st, 10000, attempting to obtain the transcript generates the following error:

google.api_core.exceptions.Unauthenticated: 401 Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project. [reason: "ACCESS_TOKEN_EXPIRED"
domain: "googleapis.com"
metadata {
  key: "method"
  value: "google.cloud.speech.v1.Speech.StreamingRecognize"
}
metadata {
  key: "service"
  value: "speech.googleapis.com"
}
]

What am I doing wrong? I cannot seem to find a solution for this online.
Thank you!


问:
How to grep in parallel with multiple matching pattern?
I'm trying to make a search in a big file for a matching sequence

```<code>genotype.phased="~/Desktop/test.txt.gz"
selected.chr.pos = c("NC761570.1_123", "NC761572.1_425634")
cmd = paste("gzcat ", genotype.phased, " | parallel -j8 --pipe --block 300M --cat grep -E ",
     paste0("'",paste0(selected.chr.pos, collapse = "|"),"'"), "{}")
cmd
</code>```

gives

```<code>gzcat  ~/Desktop/test.txt.gz  | parallel -j8 --pipe --block 300M --cat grep -E  'NC761570.1_123|NC761572.1_425634' {}
</code>```

But this is not working as the pipe | seems to need an escape like this \|:

```<code>gzcat  ~/Desktop/test.txt.gz  | parallel -j8 --pipe --block 300M --cat grep -E  'NC761570.1_123\|NC761572.1_425634' {}
</code>```

When I run the above command, it does work.

It's easy to add this by hand, but I have ~200 search patterns and thus would be nice to have a way to generate this sequence.

The problem is that when I use

```<code>paste0(selected.chr.pos, collapse = "\|")
</code>```

I get

```<code>Error: '\|' is an unrecognized escape in character string starting ""\|"
</code>```

And I can't find a way to add a \

So how could I generate the search pattern (with the \|) to run inside a terminal but within R, like so:

```<code>sub.line = system(command.paste, # Will search the chr position combo
                  intern = TRUE) # Report the data inside R so it can be used
</code>```

Body:
I'm trying to make a search in a big file for a matching sequence

genotype.phased="~/Desktop/test.txt.gz"
selected.chr.pos = c("NC761570.1_123", "NC761572.1_425634")
cmd = paste("gzcat ", genotype.phased, " | parallel -j8 --pipe --block 300M --cat grep -E ",
     paste0("'",paste0(selected.chr.pos, collapse = "|"),"'"), "{}")
cmd

gives

gzcat  ~/Desktop/test.txt.gz  | parallel -j8 --pipe --block 300M --cat grep -E  'NC761570.1_123|NC761572.1_425634' {}

But this is not working as the pipe | seems to need an escape like this \|:

gzcat  ~/Desktop/test.txt.gz  | parallel -j8 --pipe --block 300M --cat grep -E  'NC761570.1_123\|NC761572.1_425634' {}

When I run the above command, it does work.

It's easy to add this by hand, but I have ~200 search patterns and thus would be nice to have a way to generate this sequence.

The problem is that when I use

paste0(selected.chr.pos, collapse = "\|")

I get

Error: '\|' is an unrecognized escape in character string starting ""\|"

And I can't find a way to add a \

So how could I generate the search pattern (with the \|) to run inside a terminal but within R, like so:

sub.line = system(command.paste, # Will search the chr position combo
                  intern = TRUE) # Report the data inside R so it can be used


问:
node_modules Is not showing In VsCode file explorer
node_modules is not showing in file explorer of VsCode, even if I install any module it is not updating in package.json. But module is installing.

I tried following:

```<code>npm init
npm install jest --save-dev
</code>```

It is showing the packages are installed but it was not generating node_modules and updating package.json

Body:
node_modules is not showing in file explorer of VsCode, even if I install any module it is not updating in package.json. But module is installing.

I tried following:

npm init
npm install jest --save-dev

It is showing the packages are installed but it was not generating node_modules and updating package.json


问:
Utilise M1 Pro single GPU on HuggingFace's pipeline via TensorFlow
How do we utilise GPU on HuggingFace's pipeline for inference especially using TensorFlow framework? Here is an example of my current pipeline code:

```<code>model_name = "some HuggingFace model"
pretrained_model = pipeline(
    "sentiment-analysis",
    model=model_name,
    tokenizer=model_name
)
</code>```

I found a solution online for Cuda and it went something like this:

```<code>model_name = "some HuggingFace model"
pretrained_model = pipeline(
    "sentiment-analysis",
    model=model_name,
    tokenizer=model_name,
    device=1
)
</code>```

Can I use the same solution for M1 Pro GPU irrespective of framework (PyTorch or TensorFlow)?

Body:
How do we utilise GPU on HuggingFace's pipeline for inference especially using TensorFlow framework? Here is an example of my current pipeline code:

model_name = "some HuggingFace model"
pretrained_model = pipeline(
    "sentiment-analysis",
    model=model_name,
    tokenizer=model_name
)

I found a solution online for Cuda and it went something like this:

model_name = "some HuggingFace model"
pretrained_model = pipeline(
    "sentiment-analysis",
    model=model_name,
    tokenizer=model_name,
    device=1
)

Can I use the same solution for M1 Pro GPU irrespective of framework (PyTorch or TensorFlow)?


问:
Cronitor CLI usage is different from documentation
I'm trying to install the Cronitor CLI on a Raspberry Pi running Raspbian. I've followed the steps from here, swapping amd64 for arm and taking /local/ out of the third command to match to where I put it with the second command. The specific commands I used were:

```<code>curl -sOL https://cronitor.io/dl/linux_arm.tar.gz
sudo tar xvf linux_arm.tar.gz -C /usr/bin/
sudo /usr/bin/cronitor configure --api-key [my api key]
</code>```

When I run "cronitor discover" after installing I get the following usage message:

```<code>usage: cronitor [-h] [--apiKey APIKEY] [--id ID] [--code CODE] [--msg MSG]
                (--run | --complete | --fail | --ok | --pause PAUSE)
</code>```

I haven't been able to find anywhere online where this usage is specified, and I'm not sure why this is different from what the documentation says. I do have the Cronitor python3 package installed using "sudo pip3 install cronitor", but my understanding is that it should not interfere, right? Any help would be appreciated.

To resolve the issue I have uninstalled both the CLI and the Python package and tried to reinstall the CLI without the Python package installed. It gives me the same results.

EDIT: For anyone stumbling across this same error in the future, "sudo cronitor" works as intended! Use sudo to access the CLI!

Body:
I'm trying to install the Cronitor CLI on a Raspberry Pi running Raspbian. I've followed the steps from here, swapping amd64 for arm and taking /local/ out of the third command to match to where I put it with the second command. The specific commands I used were:

curl -sOL https://cronitor.io/dl/linux_arm.tar.gz
sudo tar xvf linux_arm.tar.gz -C /usr/bin/
sudo /usr/bin/cronitor configure --api-key [my api key]

When I run "cronitor discover" after installing I get the following usage message:

usage: cronitor [-h] [--apiKey APIKEY] [--id ID] [--code CODE] [--msg MSG]
                (--run | --complete | --fail | --ok | --pause PAUSE)

I haven't been able to find anywhere online where this usage is specified, and I'm not sure why this is different from what the documentation says. I do have the Cronitor python3 package installed using "sudo pip3 install cronitor", but my understanding is that it should not interfere, right? Any help would be appreciated.

To resolve the issue I have uninstalled both the CLI and the Python package and tried to reinstall the CLI without the Python package installed. It gives me the same results.

EDIT: For anyone stumbling across this same error in the future, "sudo cronitor" works as intended! Use sudo to access the CLI!


问:
AWS API Gateway. Origin has been blocked by CORS Policy
Framework: Vue.js

Sending DELETE request(axios) to aws api gateway, that triggers a lambda function.

In API Gateway, I have created the DELETE method
screenshot

I have created/configured the OPTIONS method, where Gateway Responses DEFAULT 4XX AND DEFAULT 5XX are checked. Methods: DELETE and OPTIONS are checked, Access-Control-Allow-Headers: 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token' and Access-Control-Allow-Origin were manually set. i.e. a list of origins.

I confirm configuration was saved by taking a look at Gateway Responses
screenshot

Lambda Function created, responds with the following headers.
screenshot

Code on client side
screenshot

Executing program - Request Response does not include the Access-Control-Allow-Origins.

I've been stuck for a couple of days now, I don't know where else I should look into.

I have tried adding headers to request e.g. Access-Control-Allow-Origin: '*' ,and tried the list of specific origins that will ping the api.
set Access-Control-Allow-Origin in api gateway to '*'
uncheck Lambda Proxy Integration in Delete Method, Any Method in api gateway
lambda function response with 'Access-Control-Allow-Methods': 'list of methods'
use fetch


问:
Not able to access react-native android App in Android-Studio Highlight ---> ^SyntaxError: Unexpected token '?'
I create new app in react-native and after successfully creation am trying to create an bundle build where vartient == release, but in android-studio, the Gradle build is failing with build

this is the error
Please open the above like

When I try to build Gradle in Android-Studio
Caused by: java.lang.Exception: /home/venom/Documents/project/native/dBox/node_modules/@react-native-community/cli/build/index.js:156    cmd.option(opt.name, opt.description ?? '', opt.parse || (val => val), typeof opt.default === 'function' ? opt.default(rest[0]) : opt.default);                                          ^SyntaxError: Unexpected token '?'    at wrapSafe (internal/modules/cjs/loader.js:915:16)    at Module._compile (internal/modules/cjs/loader.js:963:27)    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)    at Module.load (internal/modules/cjs/loader.js:863:32)    at Function.Module._load (internal/modules/cjs/loader.js:708:14)    at Module.require (internal/modules/cjs/loader.js:887:19)    at require (internal/modules/cjs/helpers.js:74:18)    at Object. (/home/venom/Documents/project/native/dBox/node_modules/react-native/cli.js:13:11)    at Module._compile (internal/modules/cjs/loader.js:999:30)    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)

I checked i'n node_module  this [cmd.option(opt.name, opt.description ?? '', opt.parse || (val => val), typeof opt.default === 'function' ? opt.default(rest[0]) : opt.default);] statement is written , can you please help me out with this, like how I will over come through it ....


问:
How to use OpenCV stereoCalibrate output to map pixels from one camera to another
Context: I have two cameras of very different focus and size that I want to align for image processing. One is RGB, one is near-infrared. The cameras are in a static rig, so fixed relative to each other. Because the image focus/width are so different, it's hard to even get both images to recognize the chessboard at the same time. Pretty much only works when the chessboard is centered in both images with very little skew/tilt.

I need to perform computations on the aligned images, so I need as good of a mapping between the optical frames as I can get. Right now the results I'm getting are pretty far off. I'm not sure if I'm using the method itself wrong, or if I am misusing the output. Details and image below.

Computation: I am using OpenCV stereoCalibrate to estimate the rotation and translation matrices with the following code, and throwing out bad results based on final error.

```<code>    int flag = cv::CALIB_FIX_INTRINSIC;
    double err = cv::stereoCalibrate(temp_points_object_vec, temp_points_alignvec, temp_points_basevec, camera_mat_align, camera_distort_align, camera_mat_base, camera_distort_base, mat_align.size(), rotate_mat, translate_mat, essential_mat, F, flag, cv::TermCriteria(cv::TermCriteria::MAX_ITER + cv::TermCriteria::EPS, 30, 1e-6));
    if (last_error_ == -1.0 || (err < last_error_ + improve_threshold_)) {
        // -1.0 indicate first calibration, accept points. Other cond indicates acceptable error.
        points_alignvec_.push_back(addalign);
        points_basevec_.push_back(addbase);
        points_object_vec_.push_back(object_points);
    }
</code>```

The result doesn't produce an OpenCV error as is, and due to the large difference between images, more than half of the matched points are rejected. Results are much better since I added the conditional on the error, but still pretty poor. Error as computed above starts around 30, but doesn't get lower than 15-17. For comparison, I believe a "good" error would be <1. So for starters, I know the output isn't great, but on top of that, I'm not sure I'm using the output right for validating visually. I've attached images showing some of the best and worst results I see. The middle image on the right of each shows the "cross-validated" chessboard keypoints. These are computed like this (note addalign is the temporary vector containing only the chessboard keypoints from the current image in the frame to be aligned):

```<code>    for (int i = 0; i < addalign.size(); i++) {
        cv::Point2f validate_pt;// = rotate_mat * addalign.at(i) + translate_mat;
        // Project pixel from image aligned to 3D
        cv::Point3f ray3d = align_camera_model_.projectPixelTo3dRay(addalign.at(i));
        // Rotate and translate
        rotate_mat.convertTo(rotate_mat, CV_32F);
        cv::Mat temp_result = rotate_mat * cv::Mat(ray3d, false);
        cv::Point3f ray_transformed;
        temp_result.copyTo(cv::Mat(ray_transformed, false));
        cv::Mat tmat = cv::Mat(translate_mat, false);
        ray_transformed.x += tmat.at<float>(0);
        ray_transformed.y += tmat.at<float>(1);
        ray_transformed.z += tmat.at<float>(2);
        // Reproject to base image pixel
        cv::Point2f pixel = base_camera_model_.project3dToPixel(ray_transformed);
        corners_validated.push_back(pixel);
    }
</code>```

Here are two images showing sample outputs, including both raw images, both images with "drawChessboard," and a cross-validated image showing the base image with above-computed keypoints translated from the alignment image.
Better result
Worse result

In the computation of corners_validated, I'm not sure I'm using rotate_mat andtranslate_mat correctly. I'm sure there is probably an OpenCV method that does this more efficiently, but I just did it the way that made sense to me at the time.

Also relevant: This is all inside a ROS package, using ROS noetic on Ubuntu 20.04 which only permits the use of OpenCV 4.2, so I don't have access to some of the newer opencv methods.

Body:
Context: I have two cameras of very different focus and size that I want to align for image processing. One is RGB, one is near-infrared. The cameras are in a static rig, so fixed relative to each other. Because the image focus/width are so different, it's hard to even get both images to recognize the chessboard at the same time. Pretty much only works when the chessboard is centered in both images with very little skew/tilt.

I need to perform computations on the aligned images, so I need as good of a mapping between the optical frames as I can get. Right now the results I'm getting are pretty far off. I'm not sure if I'm using the method itself wrong, or if I am misusing the output. Details and image below.

Computation: I am using OpenCV stereoCalibrate to estimate the rotation and translation matrices with the following code, and throwing out bad results based on final error.

    int flag = cv::CALIB_FIX_INTRINSIC;
    double err = cv::stereoCalibrate(temp_points_object_vec, temp_points_alignvec, temp_points_basevec, camera_mat_align, camera_distort_align, camera_mat_base, camera_distort_base, mat_align.size(), rotate_mat, translate_mat, essential_mat, F, flag, cv::TermCriteria(cv::TermCriteria::MAX_ITER + cv::TermCriteria::EPS, 30, 1e-6));
    if (last_error_ == -1.0 || (err < last_error_ + improve_threshold_)) {
        // -1.0 indicate first calibration, accept points. Other cond indicates acceptable error.
        points_alignvec_.push_back(addalign);
        points_basevec_.push_back(addbase);
        points_object_vec_.push_back(object_points);
    }

The result doesn't produce an OpenCV error as is, and due to the large difference between images, more than half of the matched points are rejected. Results are much better since I added the conditional on the error, but still pretty poor. Error as computed above starts around 30, but doesn't get lower than 15-17. For comparison, I believe a "good" error would be <1. So for starters, I know the output isn't great, but on top of that, I'm not sure I'm using the output right for validating visually. I've attached images showing some of the best and worst results I see. The middle image on the right of each shows the "cross-validated" chessboard keypoints. These are computed like this (note addalign is the temporary vector containing only the chessboard keypoints from the current image in the frame to be aligned):

    for (int i = 0; i < addalign.size(); i++) {
        cv::Point2f validate_pt;// = rotate_mat * addalign.at(i) + translate_mat;
        // Project pixel from image aligned to 3D
        cv::Point3f ray3d = align_camera_model_.projectPixelTo3dRay(addalign.at(i));
        // Rotate and translate
        rotate_mat.convertTo(rotate_mat, CV_32F);
        cv::Mat temp_result = rotate_mat * cv::Mat(ray3d, false);
        cv::Point3f ray_transformed;
        temp_result.copyTo(cv::Mat(ray_transformed, false));
        cv::Mat tmat = cv::Mat(translate_mat, false);
        ray_transformed.x += tmat.at<float>(0);
        ray_transformed.y += tmat.at<float>(1);
        ray_transformed.z += tmat.at<float>(2);
        // Reproject to base image pixel
        cv::Point2f pixel = base_camera_model_.project3dToPixel(ray_transformed);
        corners_validated.push_back(pixel);
    }

Here are two images showing sample outputs, including both raw images, both images with "drawChessboard," and a cross-validated image showing the base image with above-computed keypoints translated from the alignment image.
Better result
Worse result

In the computation of corners_validated, I'm not sure I'm using rotate_mat andtranslate_mat correctly. I'm sure there is probably an OpenCV method that does this more efficiently, but I just did it the way that made sense to me at the time.

Also relevant: This is all inside a ROS package, using ROS noetic on Ubuntu 20.04 which only permits the use of OpenCV 4.2, so I don't have access to some of the newer opencv methods.


问:
EF6 Garbage collecton increases unmanaged memory instead of releasing it
I have a .net webapi executing tasks in a background queue and it's deployed on k8s cluster. The pods keep getting evicted because of the memory threshold.

    private async Task BackgroundProcessing(CancellationToken stoppingToken)
    {

        while (!stoppingToken.IsCancellationRequested)
        {
            var task = await _taskQueue.DequeueAsync(stoppingToken);

            var scope = _services.CreateScope();
            await task(scope.ServiceProvider, stoppingToken);

            scope.Dispose();
        }
    }
```

My application seems to run "normaly", but when the garbage collection is is done, it seems to increase the unmanaged memory instead of releasing it.

Body:
I have a .net webapi executing tasks in a background queue and it's deployed on k8s cluster. The pods keep getting evicted because of the memory threshold.

    private async Task BackgroundProcessing(CancellationToken stoppingToken)
    {

        while (!stoppingToken.IsCancellationRequested)
        {
            var task = await _taskQueue.DequeueAsync(stoppingToken);

            var scope = _services.CreateScope();
            await task(scope.ServiceProvider, stoppingToken);

            scope.Dispose();
        }
    }

My application seems to run "normaly", but when the garbage collection is is done, it seems to increase the unmanaged memory instead of releasing it.


问:
How to send publisher present in lambda to ServerSentEvent channel
I have a code which consume messages from Kafka with high concurrency level but I have to send those messages consumed as ServerSentEvent over SSE channel. But this code return type is void while it accepts a function which can return a publisher as:

```<code>void react(Function<Consumer record<k,v> ,Publisher<?>> Function)
</code>```

Usage:

```<code>reactorProcessor.react(kafkaConsumerRecord -> { return Flux.just(new ServerSentEventBuilder().data(kafkaConsumerRecord).build();});
</code>```

Here reactorProcessor.react() return type is void.

How can I use the flux publisher present inside the lambda to be returned over SSE channel?

Please suggest how this result can be diverted to sse channel?

I tried this:

```<code>Flux<ServerSentEvent> getStream(){

Flux<ServerSentEvent> toreturn = Flux.empty();

reactorProcessor.react(record -> {
Flux<ServerSentEvent> event = Flux.just(new ServerSentEventBuilder ().data(record).build()):

toreturn.mergeWith(event);

return event;});

return toreturn;
}
</code>```

But once I open the SSE connection it does not return any record to the channel. Please suggest what I am doing wrong here.

Body:
I have a code which consume messages from Kafka with high concurrency level but I have to send those messages consumed as ServerSentEvent over SSE channel. But this code return type is void while it accepts a function which can return a publisher as:

void react(Function<Consumer record<k,v> ,Publisher<?>> Function)

Usage:

reactorProcessor.react(kafkaConsumerRecord -> { return Flux.just(new ServerSentEventBuilder().data(kafkaConsumerRecord).build();});

Here reactorProcessor.react() return type is void.

How can I use the flux publisher present inside the lambda to be returned over SSE channel?

Please suggest how this result can be diverted to sse channel?

I tried this:

Flux<ServerSentEvent> getStream(){

Flux<ServerSentEvent> toreturn = Flux.empty();

reactorProcessor.react(record -> {
Flux<ServerSentEvent> event = Flux.just(new ServerSentEventBuilder ().data(record).build()):

toreturn.mergeWith(event);

return event;});

return toreturn;
}

But once I open the SSE connection it does not return any record to the channel. Please suggest what I am doing wrong here.


问:
REST API - POST Behavior
In a true REST API how is POST supposed to behave for an operation like this

Supposse there is a
POST v1/report --> some body with id1, id2  - passed in a request

id1, id2 are part of unique index. For their combination needs to be unique for every resource.
If there already exists data in the table with id1 and id2 is POST supposed to

return that data. In this case do what GET would do

return an exception since there already exists data.

Since POST is not idempotent what is it supposed to do in true sense.

Making sure I implement REST API verbs in the correct way.

Title: REST API - POST Behavior


问:
Golang function DigitalOcean private repo or vendor folder
from what I can see on the digitalocean site for Go functions, it requires go 1.17, and has to be built on their systems. (no local build and push option).

trying to find an example or walkthrough on how to either allow the function build service access to a private repo or pass in vendor folder from go mod.

doctl -v serverless deploy . is the call being used, which works until I add a private repo of course.


问:
How the linux set the Mac address in /sys/class/net/eth0/address
How the linux set the Mac address in /sys/class/net/eth0/address

I tried to search in my linux SDK (user space + kernel) and see how the linux/kernel is setting the Mac in /sys/class/net/eth0/address ?

Does the kernel retrieve the address from the ethernet chipset and then returned in the file /sys/class/net/eth0/address ?

Does the HW manufacturer write it as constant in the file /sys/class/net/eth0/address ?


问:
How to make a proper jwt authentification for rest api using spring boot security?
I want to make a rest API where some endpoints are protected by an authentication base on users roles. I also would like to use JWT token and to check roles of user. Furthermore, I have seen countless confusing things in internet that are either depreciating or not working in my case.

My goal with this question is to get a better understanding of how spring work to generate JWT, how to generate one if user is login and how to make endpoint inaccessible if you don't have right. And most importantly, how to do that with last and best security standards and best code quality for the last version of spring (3.0.1).

I have tried to use spring security module with SecurityConfig class that has @EnableWebSecurity and I have tried to define a simple filter chain, but It seems to return me 401 error even if I'm on authorized endpoint.

Here is my conf :

@EnableWebSecurity
@Configuration
public class SecurityConfig {
    @Autowired
    DataSource dataSource;

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    public AuthenticationManager authenticationManager(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
        return auth.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeHttpRequests().requestMatchers("/api/auth/login").permitAll();
        http.authorizeHttpRequests().requestMatchers("/api/auth/register").permitAll();
        http.authorizeHttpRequests().anyRequest().authenticated();
        return http.build();
    }
}
```
<p>As you can see I provide a bean that provide UserDetailsService that I think can be used to check if user as a correct password. So here is my Service implementation :</p>
<pre class="lang-java prettyprint-override"><code>
@Service
public class MyUserDetailsService implements UserDetailsService {
    private final UserAuthService userAuthService;
    public GroMedUserDetailsService(UserAuthService userAuthService){
        this.userAuthService = userAuthService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> user = this.userAuthService.findUserByUsername(username);
        if(user.isEmpty()){
            throw  new UsernameNotFoundException("User not found");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(user.get().getGroMedRole().toString()));
        return new org.springframework.security.core.userdetails.User(user.get().getUsername(),user.get().getPassword(),authorities);
    }
}
</code>```

So I know I don't have all of component needed for authentification. But I'm here to learn how to correctly create it and use it. So if you know some good tutorial or you have a complete awnser for me I will be please to read it.

Body:
I want to make a rest API where some endpoints are protected by an authentication base on users roles. I also would like to use JWT token and to check roles of user. Furthermore, I have seen countless confusing things in internet that are either depreciating or not working in my case.

My goal with this question is to get a better understanding of how spring work to generate JWT, how to generate one if user is login and how to make endpoint inaccessible if you don't have right. And most importantly, how to do that with last and best security standards and best code quality for the last version of spring (3.0.1).

I have tried to use spring security module with SecurityConfig class that has @EnableWebSecurity and I have tried to define a simple filter chain, but It seems to return me 401 error even if I'm on authorized endpoint.

Here is my conf :

@EnableWebSecurity
@Configuration
public class SecurityConfig {
    @Autowired
    DataSource dataSource;

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    public AuthenticationManager authenticationManager(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
        return auth.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeHttpRequests().requestMatchers("/api/auth/login").permitAll();
        http.authorizeHttpRequests().requestMatchers("/api/auth/register").permitAll();
        http.authorizeHttpRequests().anyRequest().authenticated();
        return http.build();
    }
}

As you can see I provide a bean that provide UserDetailsService that I think can be used to check if user as a correct password. So here is my Service implementation :

@Service
public class MyUserDetailsService implements UserDetailsService {
    private final UserAuthService userAuthService;
    public GroMedUserDetailsService(UserAuthService userAuthService){
        this.userAuthService = userAuthService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> user = this.userAuthService.findUserByUsername(username);
        if(user.isEmpty()){
            throw  new UsernameNotFoundException("User not found");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(user.get().getGroMedRole().toString()));
        return new org.springframework.security.core.userdetails.User(user.get().getUsername(),user.get().getPassword(),authorities);
    }
}

So I know I don't have all of component needed for authentification. But I'm here to learn how to correctly create it and use it. So if you know some good tutorial or you have a complete awnser for me I will be please to read it.


问:
Training of custom model is working fine, but error `GELU' object has no attribute 'approximate'` during testing in yolov7 repository
I am training a YOLO model and it is working fine during training, but when I try to test it, I get the following error: AttributeError: 'GELU' object has no attribute 'approximate'. The model is using the GELU activation function and I am not sure why this error is occurring. Can anyone help me troubleshoot this issue and fix the model?

The error is associated with this line: self.act = nn.GELU().

OS: Ubuntu 22

ENV: pytorch 1.12

Python: 3.10


问:
How to get bank account balance from virtual payment address (VPA)?
I am building a payment tracker application using Flutter framework. I have designed the UI and started coding the application. To move further, I need to find the bank account balance from the virtual payment address (VPA) entered by the user. Is there any API or any method to get the bank account balance from VPA? Or is there any method to get the account balance other than VPA?</p>


问:
vb.net: keep form always keep back and never got font by click
I want to make a desktop item manager program using vb.net.
I hope to create a form there and use the menus etc. to make the desktop icons work.

You want to set the form to always be behind the other windows. Like a widget.
How to do this?


问:
I need help Debugging/Fixing this code, by the way this is in Xcode, I am using the OpenAI Package by adamrushy
I am having an issue, I don't know if it related to the package but it probably is so here is my code. This is the package I used; https://github.com/adamrushy/OpenAISwift

```<code>        // Send query to OpenAI
        openAI.send(prompt: query) { [weak self] (response, error) in
            guard let self = self else { return }
            if let error = error {
                print("Error: \(error.localizedDescription)")
                self.startListening()
                return
            }

            if let response = response {
                // Use Text to Speech to speak response
                let synthesizer = AVSpeechSynthesizer()
                let utterance = AVSpeechUtterance(string: response.text)
                synthesizer.speak(utterance)
            }

</code>```

By the way the below Bugs are on this line "openAI.send(prompt: query) { [weak self] (response, error) in"
Bug 1: Unable to infer type of closure parameter 'error' in the current context
Bug 2: Unable to infer type of a closure parameter 'response' in the current context
Bug 3: Value of type 'OpenAI' has no member 'send'

I tried removing the error thing itself, it gave more issues. I tried changing 'send' to other things, it just kept giving the same error. And I could not touch 'response' as it is important.

Body:
I am having an issue, I don't know if it related to the package but it probably is so here is my code. This is the package I used; https://github.com/adamrushy/OpenAISwift

        // Send query to OpenAI
        openAI.send(prompt: query) { [weak self] (response, error) in
            guard let self = self else { return }
            if let error = error {
                print("Error: \(error.localizedDescription)")
                self.startListening()
                return
            }

            if let response = response {
                // Use Text to Speech to speak response
                let synthesizer = AVSpeechSynthesizer()
                let utterance = AVSpeechUtterance(string: response.text)
                synthesizer.speak(utterance)
            }

By the way the below Bugs are on this line "openAI.send(prompt: query) { [weak self] (response, error) in"
Bug 1: Unable to infer type of closure parameter 'error' in the current context
Bug 2: Unable to infer type of a closure parameter 'response' in the current context
Bug 3: Value of type 'OpenAI' has no member 'send'

I tried removing the error thing itself, it gave more issues. I tried changing 'send' to other things, it just kept giving the same error. And I could not touch 'response' as it is important.


问:
To insert string from an excel cell into a URL in Power Automate
I am trying to append a URL with a string pulled from an excel sheet. I have a column which I would like to be used to append the URL, then have it write something pulled from that page, then move onto the next page by pulling from the next cell down in the column. So far I'm just trying to figure out how to append from excel in the URL. Below is what I have so far (a static URL).

UPDATE: I have figured out how to copy paste the URL from the excel sheet, however when pasted into the URL, the browser copy pastes the URL as well as some (what seem to be) random numbers and letters at the end. When I had this write to a text file on the other hand, these numbers and letters were not there.


问:
Create hidden input and populate it with uid in CF7
I need to send unique id along with form data so its possible to retrieve it and save it under this ID in CRM and other systems - once the form is submitted I retrieve the data and use curl to send it to CRM

```<code>    add_action( 'wpcf7_mail_sent', 'on_cf7_submit' );

function on_cf7_submit( $contact_form ){
    $submission = WPCF7_Submission::get_instance();
    $id = $submission->get_posted_data('lead-id'); <---- here is the problem
    $fullName = $submission->get_posted_data('your-name');
    $email = $submission->get_posted_data('your-email');
    $phone = $submission->get_posted_data('your-phone');
    ........
</code>```

Tried this snippet, but wasn't even able to create the hidden input in the html

```<code>add_action( 'wpcf7_init', 'init_form' );

function init_form( $tag ) {
    $id = uniqid(rand());
    return "<input type='hidden' name='lead-id' value='$id' />";
}
</code>```

Body:
I need to send unique id along with form data so its possible to retrieve it and save it under this ID in CRM and other systems - once the form is submitted I retrieve the data and use curl to send it to CRM

    add_action( 'wpcf7_mail_sent', 'on_cf7_submit' );

function on_cf7_submit( $contact_form ){
    $submission = WPCF7_Submission::get_instance();
    $id = $submission->get_posted_data('lead-id'); <---- here is the problem
    $fullName = $submission->get_posted_data('your-name');
    $email = $submission->get_posted_data('your-email');
    $phone = $submission->get_posted_data('your-phone');
    ........

Tried this snippet, but wasn't even able to create the hidden input in the html

add_action( 'wpcf7_init', 'init_form' );

function init_form( $tag ) {
    $id = uniqid(rand());
    return "<input type='hidden' name='lead-id' value='$id' />";
}


问:
Parallelize and orchestrate a large workload with IO dependency
I have a service that, when invoked, performs expensive operations on a large dataset.

The dataset is a list of items, i.e. something like a List<Item> which contains an average of a few million Item instances.

All Item instances in the list are different from each other and the service executes the same method on it, called Process(Item item): the Process(Item item) method is mostly CPU-bound, however, it requires exclusive access to a file on the File System to process the given Item correctly: this means all the items in the list cannot be processed in parallel.

Due to the large amount of data that needs to be processed, I am looking into a way to improve the performance by processing the items in parallel.

A simple (but not elegant) way to do that would be to make a few copies of the file and run an equal amount of threads: this would allow me to process as many Item instances in parallel as the total amount of file copies I make.

However, I wish to find a more clean and elegant way as I don't want to manually handle those file copies.

To do that, I am looking into using Docker containers and Kubernetes.

In such a setup, the Docker image would include both the service runtime as well as the file, so that each container (or Pod) that is created from that image would have its own copy of the file.

The question:

At this point, I am mostly missing how to orchestrate the processing of the Item instances across the various containers in a solid way.
How to do that?

Note that a similar question was raised in this StackOverflow question and most answers suggested to rely on Kubernetes liveness and readiness probes to avoid traffic to be routed to a given Pod, in my case the Pod that is already processing an Item instance.

However, I don't think probes where designed to be used this way and it is an approach that feels more like a hack to me, therefore I am looking for a more solid solution to better control how the Item instances are processed.


问:
Laravel 9 Livewire get Datatable from DB using Ajax request
with laravel controller the app working without anz problem,like that:
UserController.php

```<code>public function user_list(Request $request)
    {

        if ($request->ajax()) {

            $data = User::whereHas('roles')->get()->map(function($permission) {
                return [
                    'id'       => $permission->id,
                    'fullname' => $permission->name . ', ' . $permission->lastname,
                ];
            });
            return datatables()->of($data)->make(true);

        }

        $pageConfigs = ['pageHeader' => false];
        return view('/content/apps/user/app-user-list', ['pageConfigs' => $pageConfigs]);
    }
</code>```

in my view :

```<code>    <div class="card">
      <div class="table-responsive">
        <table class="users-table table">
          <thead class="table-light">
            <tr>
              <th>id</th>
              <th>Full Name</th>
            </tr>
          </thead>
        </table>
      </div>
    </div>
@section('page-script')

<script>
$(function() {
        $('.users-table').DataTable({
        ajax: "list", // JSON file to add data
        columns: [
            // columns according to JSON
            { data: "id" },
            { data: "fullname" },

</script>

@endsection
</code>```

and the route in Web.php is:

```<code>Route::get('users', [UsersController::class, 'user_list'])->name('list');
</code>```

now when i want to use Livewire component instead of Laravel controller , where should i du my request in 'render' function  or in 'mount' or schould i create another function, and how can i call if from route. or if there someway to call the function direct from controller without creating a new function on more time in Livewire component.
will be greate when someone can helpe

Body:
with laravel controller the app working without anz problem,like that:
UserController.php

public function user_list(Request $request)
    {

        if ($request->ajax()) {

            $data = User::whereHas('roles')->get()->map(function($permission) {
                return [
                    'id'       => $permission->id,
                    'fullname' => $permission->name . ', ' . $permission->lastname,
                ];
            });
            return datatables()->of($data)->make(true);

        }

        $pageConfigs = ['pageHeader' => false];
        return view('/content/apps/user/app-user-list', ['pageConfigs' => $pageConfigs]);
    }

in my view :

              id
              Full Name

@section('page-script')

@endsection

and the route in Web.php is:

Route::get('users', [UsersController::class, 'user_list'])->name('list');

now when i want to use Livewire component instead of Laravel controller , where should i du my request in 'render' function  or in 'mount' or schould i create another function, and how can i call if from route. or if there someway to call the function direct from controller without creating a new function on more time in Livewire component.
will be greate when someone can helpe


问:
How do I edit the values in my data frame to remove numerical values?
I have a data frame that looks like this:

In the "x" column, I want to remove the number values and just have the string character, i.e. "Benign_freq" or "Recessive". Is there a way to edit these values using R?


问:
`focusable()` broken for views that are not already focusable
This is taken from a completely fresh multiplatform SwiftUI project. I want to be able to make a custom view focusable, so I tried testing with a Text view but it's not working. Isn't that the whole point of .focusable() to declare an arbitrary view focusable? If that's the case, then why isn't it working in the below code:

```<code>import SwiftUI

struct ContentView: View {
    @FocusState private var focusedItem: Optional<FocusedItem>

    var body: some View {
        VStack {
            Text("Test")
                .focusable(true)
                .focused($focusedItem, equals: .two)

            Button("Toggle Focus") {
                self.focusedItem=(self.focusedItem == nil) ? .two : nil
                DispatchQueue.main.asyncAfter(deadline: .now() + 3) {

                    // Always prints `nil`.
                    print(self.focusedItem)
                }
            }
        }
    }

    enum FocusedItem {
        case one, two
        func other() -> FocusedItem {
            switch self {
            case .one: return .two
            case .two: return .one
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

</code>```

Body:
This is taken from a completely fresh multiplatform SwiftUI project. I want to be able to make a custom view focusable, so I tried testing with a Text view but it's not working. Isn't that the whole point of .focusable() to declare an arbitrary view focusable? If that's the case, then why isn't it working in the below code:

import SwiftUI

struct ContentView: View {
    @FocusState private var focusedItem: Optional<FocusedItem>

    var body: some View {
        VStack {
            Text("Test")
                .focusable(true)
                .focused($focusedItem, equals: .two)

            Button("Toggle Focus") {
                self.focusedItem=(self.focusedItem == nil) ? .two : nil
                DispatchQueue.main.asyncAfter(deadline: .now() + 3) {

                    // Always prints `nil`.
                    print(self.focusedItem)
                }
            }
        }
    }

    enum FocusedItem {
        case one, two
        func other() -> FocusedItem {
            switch self {
            case .one: return .two
            case .two: return .one
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


问:
Why does multiprocessing floating-point submatrices cause unexpected output?
I wrote a program to train a bigram model. To speed it up, I decided to split the counts matrix, process the submatrices on multiple threads, then reconcatenate them into one probability matrix.

I have a version of the code without multi-processing which works correctly, and the multi-processing version which only works with n_processes = 1. If I try to run it with 2, 8 or 16 processes, the first submatrix is processed correctly (the probabilities sum up to 1 in each row), while all the others contain numbers which are all over the place (they do not get progressively worse going from 2 to 16, they're just numbers ranging between 0.001 and 250.0)

Function that gets applied to the submatrices:

```<code>def kn_probs(bigram_counts, type_counts, d=0.75):
"""
Calculate Kneser-Ney probabilities on a matrix of bigram counts.

:param bigram_counts: 2D matrix of integer counts of bigrams
:param type_counts: number of bigram types, list of row types
counts, list of col types counts.
:param d: discount value subtracted from the count of each bigram
:return: a 2D matrix containing the Kneser-Ney bigram probabilities
"""
n_bigram_types, row_types_counts, col_types_counts = type_counts

# initialise matrix
kn_probs = np.zeros((len(bigram_counts), len(bigram_counts[0])), dtype=np.float16)

# iterate through the matrix
for row_i, row in enumerate(bigram_counts):

    # compute the pre_word (i.e. row) terms
    pre_word_count = np.sum(row)
    n_pre_word_followers = row_types_counts[row_i]
    kn_lambda = (d / pre_word_count) * n_pre_word_followers

    # iterate through the row
    for col_i, bigram_count in enumerate(row):

        n_word_precedents = col_types_counts[col_i]

        # compute KN prob and save it
        kn_prob = (max(bigram_count-d, 0) / pre_word_count)\
                    + (kn_lambda * (n_word_precedents / n_bigram_types))
        kn_probs[row_i][col_i] = kn_prob

return kn_probs
</code>```

Multiprocessing part:

```<code># split bigram_counts to allow for multiprocessing
n_processes = 16
bigram_counts_chunks = np.array_split(bigram_counts, n_processes)
length = len(bigram_counts)
del(bigram_counts)

# create a pool of worker processes
with mp.Pool(n_processes) as p:

    # compute type counts separately and merge them (needed for Kneser-Ney smoothing)
    chunks_type_counts = p.map(count_types, bigram_counts_chunks)
    n_bigram_types = sum([type_counts[0] for type_counts in chunks_type_counts])
    row_types_counts = np.concatenate([type_counts[1] for type_counts in chunks_type_counts])
    col_types_counts = [0] * length
    for type_counts in chunks_type_counts:
        col_types_counts = np.add(col_types_counts, type_counts[2])
    type_counts = (n_bigram_types, row_types_counts, col_types_counts)

    # map the kn_probs() function to each chunk in parallel
    bigram_probs_chunks = p.starmap(kn_probs, zip(bigram_counts_chunks, itertools.repeat(type_counts)))
    del(bigram_counts_chunks)

# concatenate chunks into one array
bigram_probs = np.concatenate(bigram_probs_chunks)
</code>```

Specifics: HP laptop with Windows 11, 64-bit, Python 3.11.0, 16GB RAM

Body:
I wrote a program to train a bigram model. To speed it up, I decided to split the counts matrix, process the submatrices on multiple threads, then reconcatenate them into one probability matrix.

I have a version of the code without multi-processing which works correctly, and the multi-processing version which only works with n_processes = 1. If I try to run it with 2, 8 or 16 processes, the first submatrix is processed correctly (the probabilities sum up to 1 in each row), while all the others contain numbers which are all over the place (they do not get progressively worse going from 2 to 16, they're just numbers ranging between 0.001 and 250.0)

Function that gets applied to the submatrices:

def kn_probs(bigram_counts, type_counts, d=0.75):
"""
Calculate Kneser-Ney probabilities on a matrix of bigram counts.

:param bigram_counts: 2D matrix of integer counts of bigrams
:param type_counts: number of bigram types, list of row types
counts, list of col types counts.
:param d: discount value subtracted from the count of each bigram
:return: a 2D matrix containing the Kneser-Ney bigram probabilities
"""
n_bigram_types, row_types_counts, col_types_counts = type_counts

# initialise matrix
kn_probs = np.zeros((len(bigram_counts), len(bigram_counts[0])), dtype=np.float16)

# iterate through the matrix
for row_i, row in enumerate(bigram_counts):

    # compute the pre_word (i.e. row) terms
    pre_word_count = np.sum(row)
    n_pre_word_followers = row_types_counts[row_i]
    kn_lambda = (d / pre_word_count) * n_pre_word_followers

    # iterate through the row
    for col_i, bigram_count in enumerate(row):

        n_word_precedents = col_types_counts[col_i]

        # compute KN prob and save it
        kn_prob = (max(bigram_count-d, 0) / pre_word_count)\
                    + (kn_lambda * (n_word_precedents / n_bigram_types))
        kn_probs[row_i][col_i] = kn_prob

return kn_probs

Multiprocessing part:

# split bigram_counts to allow for multiprocessing
n_processes = 16
bigram_counts_chunks = np.array_split(bigram_counts, n_processes)
length = len(bigram_counts)
del(bigram_counts)

# create a pool of worker processes
with mp.Pool(n_processes) as p:

    # compute type counts separately and merge them (needed for Kneser-Ney smoothing)
    chunks_type_counts = p.map(count_types, bigram_counts_chunks)
    n_bigram_types = sum([type_counts[0] for type_counts in chunks_type_counts])
    row_types_counts = np.concatenate([type_counts[1] for type_counts in chunks_type_counts])
    col_types_counts = [0] * length
    for type_counts in chunks_type_counts:
        col_types_counts = np.add(col_types_counts, type_counts[2])
    type_counts = (n_bigram_types, row_types_counts, col_types_counts)

    # map the kn_probs() function to each chunk in parallel
    bigram_probs_chunks = p.starmap(kn_probs, zip(bigram_counts_chunks, itertools.repeat(type_counts)))
    del(bigram_counts_chunks)

# concatenate chunks into one array
bigram_probs = np.concatenate(bigram_probs_chunks)

Specifics: HP laptop with Windows 11, 64-bit, Python 3.11.0, 16GB RAM


问:
Form for Searching and data editing in Access
I am trying to create a form where I will search for a value in a table "Request Table" search in column "ECN #". When the field is searched I would then be able to populate different areas of the table from that form and save the record. The issue I'm running into is "ECN #" is my primary key and when it is linked to the form it is not a searchable or editable field. If anyone could please help I would greatly appreciate it.

I have tried to create a query (not sure I did it correctly) and then create a form based off of that but I can't seem to get it to work.


问:
"Homebrew" Client/Server System is exiting with stack smashing detected error on Filetransfer
I am currently (trying) maintaining a small server/client system. The author abandoned the project 2 years ago. I don't really know C as I'm more at home with Swift.

So far it compiles/runs on a modern Linux. However when it comes to a file transfer the server crashes with the error *** stack smashing detected ***: terminated. I could fix this error by giving the gcc the flag -fno-stack-protector. But then I have the problem that the server runs permanently with a CPU load of 100% at some point. The task goes crazy.

The file which should be responsible for this is this one (I thinks so):

https://github.com/ProfDrLuigi/wired/blob/master/wired/transfers.c

To be honest I have no idea where to start. I think the server does this only since the OpenSSL libs were updated from 1.0 to 1.1 in the distro repos. Does anyone have an idea where to start?


问:
How to implement accessibility service to perform screen lock with GLOBAL_ACTION_LOCK_SCREEN? I prefer Kotlin code please
I need lock screen via accessibility service, I can d it with DEVICE ADMIN, but can't find any manual to implement it with AS.

I tried to follow official documentation, but it's not beginner friendly at all. I also tried with many other manuals, but no success. Please help.

P.S. this is my first ever question on Stackoverflow.


问:
Monte Carlo Tree Search to find the highest value leaf node
I'm currently trying to code the Question 2 here:
Assignment

All I need is a rough outline of how to go about this. All the examples I have seen of MCTS seem to be about 2X2 board games and I don't understand how to extrapolate that to this example. I just need someone to ask questions to. Thanks

I have created a list with node addresses and built the BINARY Tree as such:

```<code>def create_tree(depth):
    l = []
    lst = ['S', 'L', 'R']
    dummy = ['L', 'R']
    while len(l)<2**depth:
        l = []
        for i in dummy:
            l.append(i+'L')
            l.append(i+'R')
        lst.append(l)
        dummy = l.copy()
    return lst

# Building the binary tree
binary_tree = build(list(chain.from_iterable(create_tree(4))))
print('Binary tree from list :\n',
      binary_tree)
</code>```

Now I'm confused on how to proceed. Use UCB to select on child node of root and then simulate a path until we reach a leaf who's value is backpropagted to the chosen node. We repeat this as long as we can. Is this the way to go? Is creating the tree from a list the right choice? Please help!

Body:
I'm currently trying to code the Question 2 here:
Assignment

All I need is a rough outline of how to go about this. All the examples I have seen of MCTS seem to be about 2X2 board games and I don't understand how to extrapolate that to this example. I just need someone to ask questions to. Thanks

I have created a list with node addresses and built the BINARY Tree as such:

def create_tree(depth):
    l = []
    lst = ['S', 'L', 'R']
    dummy = ['L', 'R']
    while len(l)<2**depth:
        l = []
        for i in dummy:
            l.append(i+'L')
            l.append(i+'R')
        lst.append(l)
        dummy = l.copy()
    return lst

# Building the binary tree
binary_tree = build(list(chain.from_iterable(create_tree(4))))
print('Binary tree from list :\n',
      binary_tree)

Now I'm confused on how to proceed. Use UCB to select on child node of root and then simulate a path until we reach a leaf who's value is backpropagted to the chosen node. We repeat this as long as we can. Is this the way to go? Is creating the tree from a list the right choice? Please help!


问:
I am making a programme which plays a typing game. When it moves onto the next line it doesn't add a space which is required otherwise cant continue
This is what I currently have. I have also tried other options from what I have found but they all result in the same thing when moving onto the next line.

```<code>from pynput.keyboard import Controller
import pyautogui
import pytesseract
import time
from PIL import Image

colour = 12, 79, 150

time.sleep(3)

ssl = True
while True:

    ss = pyautogui.screenshot(region = (535, 475, 1000, 110))
    if ss.getpixel == colour:
        True
    elif ss.getpixel != colour:

        ss.save(r"C:\Users\there\OneDrive\Desktop\VS Code\TypeRacer\screenshot\ss.png")
        print("saved")

        keyboard = Controller()

        pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\Tesseract.exe"

        img = Image.open(r"C:\Users\there\OneDrive\Desktop\VS Code\TypeRacer\screenshot\ss.png")
        print("image opened")

        text = pytesseract.image_to_string(img)
        print("image is stringPaY")

        text = text.replace("1, 2, 3, 4, 5, 6, 7, 8, 9, 0, (, ), |, /, \, [, ], ',", "")
        text = text.replace("T", "T")
        text = text.replace("W", "W")
        print("done replacing")

        x = text.split(" ")
        x = " ".join(x)

        typing = True
        while typing:

            for chars in x:
                pyautogui.write(chars)

            colour2 = 209, 131, 131
            ss2 = pyautogui.screenshot(region = (535, 475, 1000, 110))

            if ss2.getpixel == colour2:
                typing = False

            else:
                pass

    quit()
</code>```

It works fine when it stay on one line, however it doesn't add the space on the final word of the line before it moves onto the next word.

here is an image of what I am referring to

Body:
This is what I currently have. I have also tried other options from what I have found but they all result in the same thing when moving onto the next line.

from pynput.keyboard import Controller
import pyautogui
import pytesseract
import time
from PIL import Image

colour = 12, 79, 150

time.sleep(3)

ssl = True
while True:

    ss = pyautogui.screenshot(region = (535, 475, 1000, 110))
    if ss.getpixel == colour:
        True
    elif ss.getpixel != colour:

        ss.save(r"C:\Users\there\OneDrive\Desktop\VS Code\TypeRacer\screenshot\ss.png")
        print("saved")

        keyboard = Controller()

        pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\Tesseract.exe"

        img = Image.open(r"C:\Users\there\OneDrive\Desktop\VS Code\TypeRacer\screenshot\ss.png")
        print("image opened")

        text = pytesseract.image_to_string(img)
        print("image is stringPaY")

        text = text.replace("1, 2, 3, 4, 5, 6, 7, 8, 9, 0, (, ), |, /, \, [, ], ',", "")
        text = text.replace("T", "T")
        text = text.replace("W", "W")
        print("done replacing")

        x = text.split(" ")
        x = " ".join(x)

        typing = True
        while typing:

            for chars in x:
                pyautogui.write(chars)

            colour2 = 209, 131, 131
            ss2 = pyautogui.screenshot(region = (535, 475, 1000, 110))

            if ss2.getpixel == colour2:
                typing = False

            else:
                pass

    quit()

It works fine when it stay on one line, however it doesn't add the space on the final word of the line before it moves onto the next word.

here is an image of what I am referring to


问:
comparing data between txt and csv in python
I have two files where I want to compare value of firstname, lastname and account_id between the two files in Python.
Content of the two files are as below

users.csv contains below content where column names are first_name,last_name,id respectively

```<code>Test1,Last1,1101011
Test2,Last2,1231231
</code>```

user1.txt contains

```<code>[{'firstname': 'Test1',
  'time_utc': 1672889600.0,
  'lastname': 'Last1',
  'name': 'Test Last1',
  'account_id': 1101011},
 {'firstname': 'Test2',
  'time_utc': None,
  'lastname': 'Last2',
  'name': 'Test2 Last2',
  'account_id': 1231231}]
</code>```

I tried with below code but it returns false result and returns all the users even though they are present in both the files.

```<code>import csv

with open ("users.csv", 'r') as read_csv:
    f = csv.reader(read_csv)
    with open ("user1.txt", 'r') as file:
        x = file.readlines()
        print (x)
        for row in f:
            print(row)
            if row not in x:
                print (row)

</code>```

Body:
I have two files where I want to compare value of firstname, lastname and account_id between the two files in Python.
Content of the two files are as below

users.csv contains below content where column names are first_name,last_name,id respectively

Test1,Last1,1101011
Test2,Last2,1231231

user1.txt contains

[{'firstname': 'Test1',
  'time_utc': 1672889600.0,
  'lastname': 'Last1',
  'name': 'Test Last1',
  'account_id': 1101011},
 {'firstname': 'Test2',
  'time_utc': None,
  'lastname': 'Last2',
  'name': 'Test2 Last2',
  'account_id': 1231231}]

I tried with below code but it returns false result and returns all the users even though they are present in both the files.

import csv

with open ("users.csv", 'r') as read_csv:
    f = csv.reader(read_csv)
    with open ("user1.txt", 'r') as file:
        x = file.readlines()
        print (x)
        for row in f:
            print(row)
            if row not in x:
                print (row)


问:
.NET Core How to check file not in use on network share
Situation:

a file share

one app write files to it

files are big and write process duration is long

another one app copy this files for "processing"

necessary to be sure a file already copied by first one app

I use File.Open approach, but it not work as expected. File in copy state can be freely copied/moved.

```<code>    public bool FileIsFreeToUse(Guid iterationGuid, FileInfo file)
    {
        try
        {
            using (File.Open(file.FullName, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
            {
                // log skipped

                return true;
            }
        }
        catch (IOException ex)
        {
            // log skipped

            return false;
        }
    }
</code>```

So, my questions.

Exists a way to check file in network share is not used with File.Open?

Is it file size check only possible way?

Best practice?

Thank you.

Body:
Situation:

a file share

one app write files to it

files are big and write process duration is long

another one app copy this files for "processing"

necessary to be sure a file already copied by first one app

I use File.Open approach, but it not work as expected. File in copy state can be freely copied/moved.

    public bool FileIsFreeToUse(Guid iterationGuid, FileInfo file)
    {
        try
        {
            using (File.Open(file.FullName, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
            {
                // log skipped

                return true;
            }
        }
        catch (IOException ex)
        {
            // log skipped

            return false;
        }
    }

So, my questions.

Exists a way to check file in network share is not used with File.Open?

Is it file size check only possible way?

Best practice?

Thank you.


问:
Flutter unusual error in errors_patch.dart
whenver I run my application, I run into this error in errors_patch.dart

```<code>  external static Never _throw(Object error, StackTrace stackTrace);
</code>```

here is my entire file if it helps

```<code>import 'dart:convert';
import 'dart:io';

import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:path_provider/path_provider.dart';

class PlayAudioBookScreen extends StatefulWidget {
  final Map<String, dynamic> initialChapterData;
  final Map<String, dynamic> audioBookData;
  const PlayAudioBookScreen(this.initialChapterData, this.audioBookData, {super.key});

  @override
  State<PlayAudioBookScreen> createState() => PlayAudioBookScreenState();
}

class PlayAudioBookScreenState extends State<PlayAudioBookScreen> {
  AudioPlayer player = AudioPlayer();
  bool playing = true;
  double sliderPos = 0;
  String bookTitle = "";
  String chapterTitle = "";
  String author = "";
  String audioFileLocalPath = "";
  String audioFileFirebasePath = "";
  int audioFileDuration = 0; // is in milliseconds
  Map<String, dynamic> currentChapterData = jsonDecode("{}");
  // in the below, bear in mind im limited by the variables (and equivalently the parameters) of the
  // PlayAudioBookScreen class must be final, so i cant just update the chapterData variable to the
  // next chapters data when reaching the end of the file.
  // a possible way of modifying the current chapter data used by the widget on the fly is by doing what
  // ive done with the commented out chapterData2 variable below here. just make a chapterData2 variable
  // like this, initialize it to widget.chapterData inside initState(), and then update it to the next
  // chapters data when reaching the end of the file.
  // other options would be to pop this screen and push a new one with the next chapters data, or to
  // have some global state management system like provider or bloc that i can consult to ask what
  // chapter where on now.
  // or even just provide the chapter number as a parameter called startChapter or sth, and inside the
  // state class have a "currentChapter" variable that is initialized to startChapter, and then updated
  // accordingly, and just get the chapter data of the currentChapter variable from audioBookData on an
  // adhoc basis.

  @override
  void initState() {
    bookTitle = widget.audioBookData["title"];
    author = widget.audioBookData["author"];
    currentChapterData = widget.initialChapterData;
    chapterTitle = currentChapterData["title"];
    audioFileLocalPath = currentChapterData["localPath"];
    audioFileFirebasePath = currentChapterData["firebasePath"];
    setupPlayer();
    super.initState();
  }

  void setupPlayer() async {
    Directory appDocDir = await getApplicationDocumentsDirectory();
    File audioFile = File("${appDocDir.path}/$audioFileLocalPath");
    if (!await audioFile.exists()) {
      // should have some error handling here if the download is unsuccessful in case the user is online,
      // maybe in other places of the app too <skull emoji>
      audioFile.create(recursive: true);
      print("come in here3");
      Reference audioFileFirebaseRef = FirebaseStorage.instance.ref(audioFileFirebasePath);
      await audioFileFirebaseRef.writeToFile(audioFile);
    }
    await player.setUrl(audioFile.path);
    player.createPositionStream();

    audioFileDuration = player.duration!.inMilliseconds;
    player.positionStream.listen((position) {
      if (position.inMilliseconds >= audioFileDuration) {
        if (int.parse(currentChapterData["chapterNumber"]) < widget.audioBookData["chapters"].length) {
          print("come in here");
          int nextChapterNumber = int.parse(currentChapterData["chapterNumber"]) + 1;
          print("I see this print statement");
          setupNewChapter(widget.audioBookData["chapters"][nextChapterNumber]);
        } else {
          print("acc here");
          player.pause();
          setState(() {
            sliderPos = audioFileDuration.toDouble();
            playing = false;
          });
        }
      } else {
        setState(() {
          sliderPos = position.inMilliseconds.toDouble();
        });
      }
    });

    player.play();
    setState(() {
      playing = true;
    });
  }

  void setupNewChapter(Map<String, dynamic> chapterData) {
    print("but dont see this print statement");
    currentChapterData = chapterData;
    print("come in here3");
    chapterTitle = currentChapterData["title"];
    print("come in her4S");
    audioFileLocalPath = currentChapterData["localPath"];
    print("come in here2");
    audioFileFirebasePath = currentChapterData["firebasePath"];
    print("come in here2");
    setupPlayer();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(children: [
        const SizedBox(height: 80),
        Text(bookTitle, style: const TextStyle(fontWeight: FontWeight.bold)),
        Text(chapterTitle, style: const TextStyle(fontWeight: FontWeight.bold)),
        Text("by $author"),
        const SizedBox(height: 20),
        playing
            ? IconButton(
                icon: const Icon(Icons.pause),
                onPressed: () async {
                  player.pause();
                  setState(() {
                    playing = false;
                  });
                },
              )
            : IconButton(
                icon: const Icon(Icons.play_arrow),
                onPressed: () async {
                  player.play();
                  setState(() {
                    playing = true;
                  });
                },
              ),
        Slider(
            min: 0,
            max: audioFileDuration.toDouble(),
            value: sliderPos,
            onChanged: (value) async {
              await player.seek(Duration(milliseconds: value.toInt()));
            }),
      ]),
    );
  }
}
</code>```

but there doesn't seem to be any explanation online that I can find as to what this error means. I have put print statements and I see up to the print statement that says "I see this print statement" but then I dont see the one that says "but I dont see this one"

Body:
whenver I run my application, I run into this error in errors_patch.dart

  external static Never _throw(Object error, StackTrace stackTrace);

here is my entire file if it helps

import 'dart:convert';
import 'dart:io';

import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:path_provider/path_provider.dart';

class PlayAudioBookScreen extends StatefulWidget {
  final Map<String, dynamic> initialChapterData;
  final Map<String, dynamic> audioBookData;
  const PlayAudioBookScreen(this.initialChapterData, this.audioBookData, {super.key});

  @override
  State<PlayAudioBookScreen> createState() => PlayAudioBookScreenState();
}

class PlayAudioBookScreenState extends State<PlayAudioBookScreen> {
  AudioPlayer player = AudioPlayer();
  bool playing = true;
  double sliderPos = 0;
  String bookTitle = "";
  String chapterTitle = "";
  String author = "";
  String audioFileLocalPath = "";
  String audioFileFirebasePath = "";
  int audioFileDuration = 0; // is in milliseconds
  Map<String, dynamic> currentChapterData = jsonDecode("{}");
  // in the below, bear in mind im limited by the variables (and equivalently the parameters) of the
  // PlayAudioBookScreen class must be final, so i cant just update the chapterData variable to the
  // next chapters data when reaching the end of the file.
  // a possible way of modifying the current chapter data used by the widget on the fly is by doing what
  // ive done with the commented out chapterData2 variable below here. just make a chapterData2 variable
  // like this, initialize it to widget.chapterData inside initState(), and then update it to the next
  // chapters data when reaching the end of the file.
  // other options would be to pop this screen and push a new one with the next chapters data, or to
  // have some global state management system like provider or bloc that i can consult to ask what
  // chapter where on now.
  // or even just provide the chapter number as a parameter called startChapter or sth, and inside the
  // state class have a "currentChapter" variable that is initialized to startChapter, and then updated
  // accordingly, and just get the chapter data of the currentChapter variable from audioBookData on an
  // adhoc basis.

  @override
  void initState() {
    bookTitle = widget.audioBookData["title"];
    author = widget.audioBookData["author"];
    currentChapterData = widget.initialChapterData;
    chapterTitle = currentChapterData["title"];
    audioFileLocalPath = currentChapterData["localPath"];
    audioFileFirebasePath = currentChapterData["firebasePath"];
    setupPlayer();
    super.initState();
  }

  void setupPlayer() async {
    Directory appDocDir = await getApplicationDocumentsDirectory();
    File audioFile = File("${appDocDir.path}/$audioFileLocalPath");
    if (!await audioFile.exists()) {
      // should have some error handling here if the download is unsuccessful in case the user is online,
      // maybe in other places of the app too <skull emoji>
      audioFile.create(recursive: true);
      print("come in here3");
      Reference audioFileFirebaseRef = FirebaseStorage.instance.ref(audioFileFirebasePath);
      await audioFileFirebaseRef.writeToFile(audioFile);
    }
    await player.setUrl(audioFile.path);
    player.createPositionStream();

    audioFileDuration = player.duration!.inMilliseconds;
    player.positionStream.listen((position) {
      if (position.inMilliseconds >= audioFileDuration) {
        if (int.parse(currentChapterData["chapterNumber"]) < widget.audioBookData["chapters"].length) {
          print("come in here");
          int nextChapterNumber = int.parse(currentChapterData["chapterNumber"]) + 1;
          print("I see this print statement");
          setupNewChapter(widget.audioBookData["chapters"][nextChapterNumber]);
        } else {
          print("acc here");
          player.pause();
          setState(() {
            sliderPos = audioFileDuration.toDouble();
            playing = false;
          });
        }
      } else {
        setState(() {
          sliderPos = position.inMilliseconds.toDouble();
        });
      }
    });

    player.play();
    setState(() {
      playing = true;
    });
  }

  void setupNewChapter(Map<String, dynamic> chapterData) {
    print("but dont see this print statement");
    currentChapterData = chapterData;
    print("come in here3");
    chapterTitle = currentChapterData["title"];
    print("come in her4S");
    audioFileLocalPath = currentChapterData["localPath"];
    print("come in here2");
    audioFileFirebasePath = currentChapterData["firebasePath"];
    print("come in here2");
    setupPlayer();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(children: [
        const SizedBox(height: 80),
        Text(bookTitle, style: const TextStyle(fontWeight: FontWeight.bold)),
        Text(chapterTitle, style: const TextStyle(fontWeight: FontWeight.bold)),
        Text("by $author"),
        const SizedBox(height: 20),
        playing
            ? IconButton(
                icon: const Icon(Icons.pause),
                onPressed: () async {
                  player.pause();
                  setState(() {
                    playing = false;
                  });
                },
              )
            : IconButton(
                icon: const Icon(Icons.play_arrow),
                onPressed: () async {
                  player.play();
                  setState(() {
                    playing = true;
                  });
                },
              ),
        Slider(
            min: 0,
            max: audioFileDuration.toDouble(),
            value: sliderPos,
            onChanged: (value) async {
              await player.seek(Duration(milliseconds: value.toInt()));
            }),
      ]),
    );
  }
}

but there doesn't seem to be any explanation online that I can find as to what this error means. I have put print statements and I see up to the print statement that says "I see this print statement" but then I dont see the one that says "but I dont see this one"