问:
Return information about netCDF file in Python 3.x
I am trying to read an unknown structure file (netCDF) in python.
Performing a normal read procedure produces the following warnings.
The documentation in netCDF says that to read files with unknown content, you must also use the nc_inq functions (https://docs.unidata.ucar.edu/netcdf-c/current/reading_unknown.html() ).
Can you please tell me how can I use these functions in Python?
Thank you!</p>
```<code>import netCDF4
ds = netCDF4.Dataset("KKAR.nc", "r")
</code>```
```<code>  kndc@devel:~/Projects/netCDF2base$ ./netCDF2base.1.py
/home/kndc/Projects/netCDF2base/./netCDF2base.1.py:5: UserWarning: WARNING: unsupported Compound type, skipping...
  ds  = netCDF4.Dataset("./KKAR.nc")
/home/kndc/Projects/netCDF2base/./netCDF2base.1.py:5: UserWarning: WARNING: unsupported VLEN type, skipping...
  ds  = netCDF4.Dataset("./KKAR.nc")
/home/kndc/Projects/netCDF2base/./netCDF2base.1.py:5: UserWarning: WARNING: variable 'Config' has unsupported compound datatype, skipping ..
  ds  = netCDF4.Dataset("./KKAR.nc")
/home/kndc/Projects/netCDF2base/./netCDF2base.1.py:5: UserWarning: WARNING: variable 'Site' has unsupported compound datatype, skipping ..
  ds  = netCDF4.Dataset("./KKAR.nc")
/home/kndc/Projects/netCDF2base/./netCDF2base.1.py:5: UserWarning: WARNING: variable 'Pixel' has unsupported compound datatype, skipping ..
  ds  = netCDF4.Dataset("./KKAR.nc")
/home/kndc/Projects/netCDF2base/./netCDF2base.1.py:5: UserWarning: WARNING: variable 'Family' has unsupported compound datatype, skipping ..
  ds  = netCDF4.Dataset("./KKAR.nc")
</code>```

Body:
I am trying to read an unknown structure file (netCDF) in python.
Performing a normal read procedure produces the following warnings.
The documentation in netCDF says that to read files with unknown content, you must also use the nc_inq functions (https://docs.unidata.ucar.edu/netcdf-c/current/reading_unknown.html() ).
Can you please tell me how can I use these functions in Python?
Thank you!

import netCDF4
ds = netCDF4.Dataset("KKAR.nc", "r")

  kndc@devel:~/Projects/netCDF2base$ ./netCDF2base.1.py
/home/kndc/Projects/netCDF2base/./netCDF2base.1.py:5: UserWarning: WARNING: unsupported Compound type, skipping...
  ds  = netCDF4.Dataset("./KKAR.nc")
/home/kndc/Projects/netCDF2base/./netCDF2base.1.py:5: UserWarning: WARNING: unsupported VLEN type, skipping...
  ds  = netCDF4.Dataset("./KKAR.nc")
/home/kndc/Projects/netCDF2base/./netCDF2base.1.py:5: UserWarning: WARNING: variable 'Config' has unsupported compound datatype, skipping ..
  ds  = netCDF4.Dataset("./KKAR.nc")
/home/kndc/Projects/netCDF2base/./netCDF2base.1.py:5: UserWarning: WARNING: variable 'Site' has unsupported compound datatype, skipping ..
  ds  = netCDF4.Dataset("./KKAR.nc")
/home/kndc/Projects/netCDF2base/./netCDF2base.1.py:5: UserWarning: WARNING: variable 'Pixel' has unsupported compound datatype, skipping ..
  ds  = netCDF4.Dataset("./KKAR.nc")
/home/kndc/Projects/netCDF2base/./netCDF2base.1.py:5: UserWarning: WARNING: variable 'Family' has unsupported compound datatype, skipping ..
  ds  = netCDF4.Dataset("./KKAR.nc")


来源: stackexchange

问:
Change specific point on precision recall curve
I am using a precision recall curve and I am interested on find the recall for an specific value of precision, but to create this curve i need to use sklearn precision_recall_curve and the precision points it return are not the ones i am interested. How can I change this to get the right coordinates for that specific point

What I have is

```<code>logic = LogisticRegression().fit(X_train, y_train)
predicciones = logic.predict(X_test)

precision, recall, thresholds = precision_recall_curve(y_test, predicciones)
</code>```

And the precision returns
[0.01474926 0.92647059 1.        ]

I want that one of those points to be equal to 0.84 to get the correct value for recall

ContentLicense: CC BY-SA 4.0

Body:
I am using a precision recall curve and I am interested on find the recall for an specific value of precision, but to create this curve i need to use sklearn precision_recall_curve and the precision points it return are not the ones i am interested. How can I change this to get the right coordinates for that specific point

What I have is

logic = LogisticRegression().fit(X_train, y_train)
predicciones = logic.predict(X_test)

precision, recall, thresholds = precision_recall_curve(y_test, predicciones)

And the precision returns
[0.01474926 0.92647059 1.        ]

I want that one of those points to be equal to 0.84 to get the correct value for recall


问:
How does luci handle an incoming ajax request?
Normal ajax request in js before luci on the user side

```<code>object.ajax("set_param", {
    noOverlay: 1
}, e, {
    success: function (e, t, a) {
        console.log("Success")
    },
    fail: function (e, t, a) {
        console.log("fail")
    }
})
</code>```

The request is sent to /cgi-bin/luci/;stok=xxxxxxx/admin/set_param, which, as far as I understand, has a standard form.

```<code>#!/usr/bin/lua
require "luci.cacheloader"
require "luci.sgi.cgi"
luci.dispatcher.indexcache = "/tmp/luci-indexcache"
luci.sgi.cgi.run()
</code>```

The question is where does luci forward and how does it process the ajax request?

Body:
Normal ajax request in js before luci on the user side

object.ajax("set_param", {
    noOverlay: 1
}, e, {
    success: function (e, t, a) {
        console.log("Success")
    },
    fail: function (e, t, a) {
        console.log("fail")
    }
})

The request is sent to /cgi-bin/luci/;stok=xxxxxxx/admin/set_param, which, as far as I understand, has a standard form.

#!/usr/bin/lua
require "luci.cacheloader"
require "luci.sgi.cgi"
luci.dispatcher.indexcache = "/tmp/luci-indexcache"
luci.sgi.cgi.run()

The question is where does luci forward and how does it process the ajax request?


问:
numpy.vectorize: "ValueError: setting an array element with a sequence"
I'm having trouble when using np.vectorize in my code:

import numpy as np
from sklearn.neighbors import KNeighborsClassifier

length = 1000

evens = np.array([np.arange(0, length*2, 2)])
odds = np.array([np.arange(1, length*2, 2)])

zeroes = np.array([np.resize([[0]], length)])
ones = np.array([np.resize([[1]], length)])

evens_data = np.concatenate((evens.T, zeroes.T), axis=1)
odds_data = np.concatenate((odds.T, ones.T), axis=1)

data = np.array(np.append(evens_data, odds_data)).reshape(length*2, 2)
np.random.shuffle(data)
X = np.array(data[:,0], dtype=np.uint8).reshape(length*2,1)
y = data[:,1]

###
### IF I COMMENT FROM HERE
###
print(f'1 X.dtype: {X.dtype} X[0].dtype: {X[0].dtype} and X.shape {X.shape} and X[0].shape {X[0].shape}')
X = tobinstr(X)
print(f'2 X.dtype: {X.dtype} X[0].dtype: {X[0].dtype} and X.shape {X.shape} and X[0].shape {X[0].shape}')
X = tobits(X)
print(f'3 X.dtype: {X.dtype} X[0].dtype: {X[0].dtype} and X.shape {X.shape} and X[0].shape {X[0].shape} and X[0][0].shape {X[0][0].shape}')
X = X[:,0]
print(f'4 X.dtype: {X.dtype} X[0].dtype: {X[0].dtype} and X.shape {X.shape} and X[0].shape {X[0].shape}')
###
### TO HERE, the code works fine
###

KNeighborsClassifier(3).fit(X, y)

# The line above fails with error "TypeError: only size-1 arrays can be converted to Python scalars"
# Caused by: ValueError: setting an array element with a sequence.
```
<p>And here's the output:</p>
```1 X.dtype: uint8 X[0].dtype: uint8 and X.shape (2000, 1) and X[0].shape (1,)
2 X.dtype: <U16 X[0].dtype: <U16 and X.shape (2000, 1) and X[0].shape (1,)
3 X.dtype: object X[0].dtype: object and X.shape (2000, 1) and X[0].shape (1,) and X[0][0].shape (16,)
4 X.dtype: object X[0].dtype: uint8 and X.shape (2000,) and X[0].shape (16,)
```

How do I turn X into a shape of (2000,16)?

OwnerDisplayName: thiagoh

Body:
I'm having trouble when using np.vectorize in my code:

import numpy as np
from sklearn.neighbors import KNeighborsClassifier

length = 1000

evens = np.array([np.arange(0, length*2, 2)])
odds = np.array([np.arange(1, length*2, 2)])

zeroes = np.array([np.resize([[0]], length)])
ones = np.array([np.resize([[1]], length)])

evens_data = np.concatenate((evens.T, zeroes.T), axis=1)
odds_data = np.concatenate((odds.T, ones.T), axis=1)

data = np.array(np.append(evens_data, odds_data)).reshape(length*2, 2)
np.random.shuffle(data)
X = np.array(data[:,0], dtype=np.uint8).reshape(length*2,1)
y = data[:,1]

###
### IF I COMMENT FROM HERE
###
print(f'1 X.dtype: {X.dtype} X[0].dtype: {X[0].dtype} and X.shape {X.shape} and X[0].shape {X[0].shape}')
X = tobinstr(X)
print(f'2 X.dtype: {X.dtype} X[0].dtype: {X[0].dtype} and X.shape {X.shape} and X[0].shape {X[0].shape}')
X = tobits(X)
print(f'3 X.dtype: {X.dtype} X[0].dtype: {X[0].dtype} and X.shape {X.shape} and X[0].shape {X[0].shape} and X[0][0].shape {X[0][0].shape}')
X = X[:,0]
print(f'4 X.dtype: {X.dtype} X[0].dtype: {X[0].dtype} and X.shape {X.shape} and X[0].shape {X[0].shape}')
###
### TO HERE, the code works fine
###

KNeighborsClassifier(3).fit(X, y)

# The line above fails with error "TypeError: only size-1 arrays can be converted to Python scalars"
# Caused by: ValueError: setting an array element with a sequence.

And here's the output:

1 X.dtype: uint8 X[0].dtype: uint8 and X.shape (2000, 1) and X[0].shape (1,)
2 X.dtype: <U16 X[0].dtype: <U16 and X.shape (2000, 1) and X[0].shape (1,)
3 X.dtype: object X[0].dtype: object and X.shape (2000, 1) and X[0].shape (1,) and X[0][0].shape (16,)
4 X.dtype: object X[0].dtype: uint8 and X.shape (2000,) and X[0].shape (16,)

How do I turn X into a shape of (2000,16)?


问:
Dart equivalent of Swift Integer closed range
I have a use-case where I have a start and end value from Json and would like to be able to define a closed range between them. Coming from Swift, I would use the Closed Integer Range. This way, I can perform contains() functions on them as well as find the start and end values. I was wondering if there was an equivalent of this built into Dart? If not, what is the most efficient way of creating this? I would assume something with sets? Thank you in advance


问:
HTML string to NSAttributed string, Bullet point with sub bullet point issue Swift
I am converting an HTML string to an NSAttributedstring to set in TextView, while in text, there are bullet points with sub-bullet points. Bullet points are coming correctly but sub-bullet point alignment is changed.

My actual HTML Text is this

And after converting it to an NSAttributed string it looks something like this

All bullet points are coming with the same indentation.

I have created a String extension to convert an HTML string to an NSAttributed String.

```<code>var htmlToAttributedString: NSAttributedString {
        var attributedString = NSMutableAttributedString()
        guard !self.isBlank, let data = data(using: .utf8) else {
            return NSAttributedString(string: "-", attributes: [NSAttributedString.Key.font: AppFonts.sfProTextRegular(size: 14) as Any]) as? NSMutableAttributedString ?? NSMutableAttributedString()
        }
        do {
            attributedString = try NSMutableAttributedString(data: data,
                                                             options: [.documentType: NSAttributedString.DocumentType.html,
                                                                       .characterEncoding:String.Encoding.utf8.rawValue],
                                                             documentAttributes: nil)
            let range = NSRange(location: 0, length: attributedString.length)
            attributedString.enumerateAttribute(NSAttributedString.Key.font, in: range, options: .longestEffectiveRangeNotRequired) { value, range, _ in
                let currentFont: UIFont = value as! UIFont
                var replacementFont: UIFont? = nil
                if currentFont.fontName.contains("bold") || currentFont.fontName.contains("Bold") {
                    replacementFont = AppFonts.sfProTextBold(size: 14)
                } else if currentFont.fontName.contains("italic") || currentFont.fontName.contains("Italic") {
                    replacementFont = AppFonts.sfProTextRegularItalic(size: 14)
                } else {
                    replacementFont = AppFonts.sfProTextRegular(size: 14)
                }
                let replacementAttribute = [NSAttributedString.Key.font:replacementFont!]
                attributedString.addAttributes(replacementAttribute, range: range)
                attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: AppColors.darkTextColor() as Any, range: NSRange(location: 0, length: attributedString.length))
            }
        } catch {
            return NSAttributedString(string: "-", attributes: [NSAttributedString.Key.font: AppFonts.sfProTextRegular(size: 14) as Any]) as? NSMutableAttributedString ?? NSMutableAttributedString()
        }
        return attributedString
    }
</code>```

This is the HTML string that I am converting to NSAttributed string

```<code>" <p>CUSTOMER / PM:</p>
<p>
  <strong style=\"color: rgb(47, 84, 150);\">Abigail Weighell </strong>
  <strong style=\"color: rgb(31, 73, 125);\">| </strong>
  <strong style=\"color: rgb(47, 84, 150);\">Resource Analyst</strong>
</p>
<p>
  <span style=\"color: rgb(47, 84, 150);\">Email: </span>
  <span style=\"color: rgb(5, 99, 193);\">aeweighell@yorktel.com</span>
</p>
<p>
  <span style=\"color: rgb(47, 84, 150);\">C: 978-907-4648</span>
</p>
<p>
  <br>
</p>
<p>SITE HOURS:</p>
<ul>
  <li>9:00 AM</li>
  <li>
    <strong>MUST</strong> print out the attached \"Room is under maintenance\" sign before arrival - See notes below
  </li>
  <li class=\"ql-indent-1\">test layer 1</li>
  <li class=\"ql-indent-1\">test layer 1 double</li>
  <li class=\"ql-indent-2\">test layer 2</li>
  <li class=\"ql-indent-3\">test layer 3</li>
</ul>
<p>
  <br>
</p>
</code>```

I just want my bullet point to be the same as the first image.
Could you guys help me out?

Thanks in advance

Body:
I am converting an HTML string to an NSAttributedstring to set in TextView, while in text, there are bullet points with sub-bullet points. Bullet points are coming correctly but sub-bullet point alignment is changed.

My actual HTML Text is this

And after converting it to an NSAttributed string it looks something like this

All bullet points are coming with the same indentation.

I have created a String extension to convert an HTML string to an NSAttributed String.

var htmlToAttributedString: NSAttributedString {
        var attributedString = NSMutableAttributedString()
        guard !self.isBlank, let data = data(using: .utf8) else {
            return NSAttributedString(string: "-", attributes: [NSAttributedString.Key.font: AppFonts.sfProTextRegular(size: 14) as Any]) as? NSMutableAttributedString ?? NSMutableAttributedString()
        }
        do {
            attributedString = try NSMutableAttributedString(data: data,
                                                             options: [.documentType: NSAttributedString.DocumentType.html,
                                                                       .characterEncoding:String.Encoding.utf8.rawValue],
                                                             documentAttributes: nil)
            let range = NSRange(location: 0, length: attributedString.length)
            attributedString.enumerateAttribute(NSAttributedString.Key.font, in: range, options: .longestEffectiveRangeNotRequired) { value, range, _ in
                let currentFont: UIFont = value as! UIFont
                var replacementFont: UIFont? = nil
                if currentFont.fontName.contains("bold") || currentFont.fontName.contains("Bold") {
                    replacementFont = AppFonts.sfProTextBold(size: 14)
                } else if currentFont.fontName.contains("italic") || currentFont.fontName.contains("Italic") {
                    replacementFont = AppFonts.sfProTextRegularItalic(size: 14)
                } else {
                    replacementFont = AppFonts.sfProTextRegular(size: 14)
                }
                let replacementAttribute = [NSAttributedString.Key.font:replacementFont!]
                attributedString.addAttributes(replacementAttribute, range: range)
                attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: AppColors.darkTextColor() as Any, range: NSRange(location: 0, length: attributedString.length))
            }
        } catch {
            return NSAttributedString(string: "-", attributes: [NSAttributedString.Key.font: AppFonts.sfProTextRegular(size: 14) as Any]) as? NSMutableAttributedString ?? NSMutableAttributedString()
        }
        return attributedString
    }

This is the HTML string that I am converting to NSAttributed string

"
CUSTOMER / PM:

  Abigail Weighell
  |
  Resource Analyst

  Email:
  aeweighell@yorktel.com

  C: 978-907-4648

SITE HOURS:

9:00 AM

    MUST print out the attached \"Room is under maintenance\" sign before arrival - See notes below

test layer 1

test layer 1 double

test layer 2

test layer 3

I just want my bullet point to be the same as the first image.
Could you guys help me out?

Thanks in advance


问:
awsParamStore error 'The security token included in the request is invalid.'
I ran into a problem using the aws-sdk and aws-param-store modules. I created the following process to load the set AWS parameters.

import aws from 'aws-sdk';
import awsParamStore from 'aws-param-store';

aws.config.update({
  region: 'ap-northeast-2',
  accessKeyId: process.env.AWS_ACCESS_KEY,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
});

const getAWSParams = () => {
  awsParamStore
    .getParametersByPath('/bangba', { region: 'ap-northeast-2' })
    .then((params) => console.log(params))
    .catch((error) => console.log(error));
};

getAWSParams();
```
<p>However, the following error occurred.</p>
```  message: 'The security token included in the request is invalid.',
  code: 'UnrecognizedClientException',
```

According to the contents of the error, I thought there would be no problem because I had already set the access key and secret access key above. Still, I don't know why the error occurs.

Body:
I ran into a problem using the aws-sdk and aws-param-store modules. I created the following process to load the set AWS parameters.

import aws from 'aws-sdk';
import awsParamStore from 'aws-param-store';

aws.config.update({
  region: 'ap-northeast-2',
  accessKeyId: process.env.AWS_ACCESS_KEY,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
});

const getAWSParams = () => {
  awsParamStore
    .getParametersByPath('/bangba', { region: 'ap-northeast-2' })
    .then((params) => console.log(params))
    .catch((error) => console.log(error));
};

getAWSParams();

However, the following error occurred.

  message: 'The security token included in the request is invalid.',
  code: 'UnrecognizedClientException',

According to the contents of the error, I thought there would be no problem because I had already set the access key and secret access key above. Still, I don't know why the error occurs.


问:
How to delete extended_calendar using Autosys jil
I was able to find the JIL syntax/format for the creation of extended_calendars in Autosys. But I couldn't find any syntax to delete any extended calendars.

Can anyone please provide a sample example. Thanks in advance.


问:
Error: 'object' is not an exported object from 'namespace:package'?
I am using a package called {butteR} and a function called butteR::closest_distance_rtree() to match coordinates with their closest known settlement. The code looks like this:

```<code># install.packages("devtools")
# devtools::install_github("zackarno/butteR")

matched_coordinates <- butteR::closest_distance_rtree(coordinates, master_settlement_list)
</code>```

Should be simple enough, but I keep getting the following error:

```<code>Error: 'knn.RTree' is not an exported object from 'namespace:rtree'
</code>```

I've re-installed both {butteR} and {rtree}, checked the namespace for {rtree}, re-started R and cleared the environment, and checked for typos. Any ideas would be appreciated!

Body:
I am using a package called {butteR} and a function called butteR::closest_distance_rtree() to match coordinates with their closest known settlement. The code looks like this:

# install.packages("devtools")
# devtools::install_github("zackarno/butteR")

matched_coordinates <- butteR::closest_distance_rtree(coordinates, master_settlement_list)

Should be simple enough, but I keep getting the following error:

Error: 'knn.RTree' is not an exported object from 'namespace:rtree'

I've re-installed both {butteR} and {rtree}, checked the namespace for {rtree}, re-started R and cleared the environment, and checked for typos. Any ideas would be appreciated!


问:
Pdfescape Desktop version - checkbox and radio button issue

My organization is using paid subscription of Pdfescape desktop latest version 4.0. In the desktop version for checkbox and radio button we are not able to find the option to set the export value for the mentioned buttons.

The export value option is available in the free online version but we are unable the option in the desktop version.

We have tried to search a solution on the net and various forums but were unsuccessful.
Can anyone help here


问:
Is there a way to batch render textures in Qt?
I have been trying to batch render two different pictures.  I have 2 different QOpenGLTexture objects I want to draw in a single draw call with batch rendering but am struggling.  Both texture objects have id's but only the last texture objects image is drawn.  I believe my problem is with setting up the or frag shader.

```<code>
//..............Setting up uniform...............//
const GLuint vals[] = {m_texture1->textureId(), m_texture2->textureId()};
m_program->setUniformValueArray("u_TextureID", vals, 2);

//..............frag Shader.....................//
#version 330 core
out vec4 color;
in vec2 v_textCoord;               // Texture coordinate
in float v_index;                  // (0, 1) Vertex for which image to draw.
                                   // 0 would draw the image of the first texture object
uniform sampler2D u_Texture[2];

void main()
{
    int index = int(v_index);
    color = texture(u_Texture[index], v_textCoord);
};

</code>```

I've tried experimenting with the index value in the frag shader but it only draws the last texture image or blacks out.  I tried implementing it how you would with openGL but have had no luck.

Body:
I have been trying to batch render two different pictures.  I have 2 different QOpenGLTexture objects I want to draw in a single draw call with batch rendering but am struggling.  Both texture objects have id's but only the last texture objects image is drawn.  I believe my problem is with setting up the or frag shader.

//..............Setting up uniform...............//
const GLuint vals[] = {m_texture1->textureId(), m_texture2->textureId()};
m_program->setUniformValueArray("u_TextureID", vals, 2);

//..............frag Shader.....................//
#version 330 core
out vec4 color;
in vec2 v_textCoord;               // Texture coordinate
in float v_index;                  // (0, 1) Vertex for which image to draw.
                                   // 0 would draw the image of the first texture object
uniform sampler2D u_Texture[2];

void main()
{
    int index = int(v_index);
    color = texture(u_Texture[index], v_textCoord);
};

I've tried experimenting with the index value in the frag shader but it only draws the last texture image or blacks out.  I tried implementing it how you would with openGL but have had no luck.


问:
Fruit detection - No matching function for call to 'cv::SimpleBlobDetector::SimpleBlobDetector(cv::SimpleBlobDetector::Params&)'
Currently I'm trying to use OpenCV for fruit detector project with camera. I take the source code from https://github.com/JackThePie/fruit-detector. I use QT Creator app in Ubuntu. I am new to OpenCV can someone help me with this issue? Note: I use OpenCV-MinGW-Build-OpenCV-4.5.0-with-contrib library which I am sure it is OpenCV2.

This is some part of my .cpp file for Blob detection.

```<code>// Blob detection
void MainWindow::on_pushButton_4_clicked()
{
    // Capture the video from web cam
    VideoCapture capture(filename1);
    // If not success, exit program
    if (!capture.isOpened())
    {
        cout << "Cannot open the video file" << endl;
    }

    namedWindow("Ustawienia Blob", WINDOW_AUTOSIZE); // Create a window called "Ustawienia Blob"
    int colour = 10;
    int iLowTresh = 0;
    int iHighTresh = 300;
    int minArea = 150;
    int minCirc = 0.1;
    int minConv = 0.087;
    int minInertia = 0.0001;

    // Create trackbars in "Ustawienia Blob" window
    createTrackbar("Colour", "Ustawienia Blob", &colour, 255); //Hue (0 - 179)
    createTrackbar("minTresh", "Ustawienia Blob", &iLowTresh, 100); //Hue (0 - 179)
    createTrackbar("maxTresh", "Ustawienia Blob", &iHighTresh, 700);
    createTrackbar("minArea", "Ustawienia Blob", &minArea, 700); //Saturation (0 - 255)
    createTrackbar("minCirc", "Ustawienia Blob", &minCirc, 200); //Value (0 - 255)
    createTrackbar("minConv", "Ustawienia Blob", &minConv, 200);
    createTrackbar("minInertia", "Ustawienia Blob", &minInertia, 100);

    while (true)
    {
        Mat imgOriginal;
        // Read a new frame from video
        bool bSuccess = capture.read(imgOriginal);
        // If not success, break loop
        if (!bSuccess)
        {
            break;
        }
        // Setup SimpleBlobDetector parameters.
        SimpleBlobDetector::Params params;

        params.filterByColor = true;
        params.blobColor = colour;

        // Change thresholds
        params.minThreshold = iLowTresh;
        params.maxThreshold = iHighTresh;

        // Filter by Area
        params.filterByArea = true;
        params.minArea = minArea;

        // Filter by Circularity
        params.filterByCircularity = true;
        params.minCircularity = minCirc;

        // Filter by Convexity
        params.filterByConvexity = true;
        params.minConvexity = minConv;

        // Filter by Inertia
        params.filterByInertia = true;
        params.minInertiaRatio = minInertia;

        // Set up detector with params

        SimpleBlobDetector detector(params); //HERE WHERE THE ERROR IS
        // Storage for blobs
        std::vector<KeyPoint> keypoints;

        // Detect blobs
        detector.detect(imgOriginal, keypoints);

        // Draw detected blobs as red circles.
        // DrawMatchesFlags::DRAW_RICH_KEYPOINTS flag ensures
        // the size of the circle corresponds to the size of blob

        Mat im_with_keypoints;
        drawKeypoints(imgOriginal, keypoints, im_with_keypoints, Scalar(0,0,255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS );

        QImage qigm=MatToQImage(imgOriginal);
        image=imgOriginal.clone();
        ui->label->setPixmap(QPixmap::fromImage(qigm).scaledToWidth(ui->label->size().width(),Qt::FastTransformation));

        QImage qigm2=MatToQImage(im_with_keypoints);
        image=im_with_keypoints.clone();
        ui->label_2->setPixmap(QPixmap::fromImage(qigm2).scaledToWidth(ui->label->size().width(),Qt::FastTransformation));

        // Wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
        if (waitKey(30) == 27)
        {
            break;
        }
    }
}
</code>```

When I try to run the code, there is an error occur in line :

```<code>SimpleBlobDetector detector(params);
</code>```

The error is stated in the picture Line 147

Thank You!

I try to find the solution here https://docs.opencv.org/4.x/d0/d7a/classcv_1_1SimpleBlobDetector.html#details but cannot find any solution..

Body:
Currently I'm trying to use OpenCV for fruit detector project with camera. I take the source code from https://github.com/JackThePie/fruit-detector. I use QT Creator app in Ubuntu. I am new to OpenCV can someone help me with this issue? Note: I use OpenCV-MinGW-Build-OpenCV-4.5.0-with-contrib library which I am sure it is OpenCV2.

This is some part of my .cpp file for Blob detection.

// Blob detection
void MainWindow::on_pushButton_4_clicked()
{
    // Capture the video from web cam
    VideoCapture capture(filename1);
    // If not success, exit program
    if (!capture.isOpened())
    {
        cout << "Cannot open the video file" << endl;
    }

    namedWindow("Ustawienia Blob", WINDOW_AUTOSIZE); // Create a window called "Ustawienia Blob"
    int colour = 10;
    int iLowTresh = 0;
    int iHighTresh = 300;
    int minArea = 150;
    int minCirc = 0.1;
    int minConv = 0.087;
    int minInertia = 0.0001;

    // Create trackbars in "Ustawienia Blob" window
    createTrackbar("Colour", "Ustawienia Blob", &colour, 255); //Hue (0 - 179)
    createTrackbar("minTresh", "Ustawienia Blob", &iLowTresh, 100); //Hue (0 - 179)
    createTrackbar("maxTresh", "Ustawienia Blob", &iHighTresh, 700);
    createTrackbar("minArea", "Ustawienia Blob", &minArea, 700); //Saturation (0 - 255)
    createTrackbar("minCirc", "Ustawienia Blob", &minCirc, 200); //Value (0 - 255)
    createTrackbar("minConv", "Ustawienia Blob", &minConv, 200);
    createTrackbar("minInertia", "Ustawienia Blob", &minInertia, 100);

    while (true)
    {
        Mat imgOriginal;
        // Read a new frame from video
        bool bSuccess = capture.read(imgOriginal);
        // If not success, break loop
        if (!bSuccess)
        {
            break;
        }
        // Setup SimpleBlobDetector parameters.
        SimpleBlobDetector::Params params;

        params.filterByColor = true;
        params.blobColor = colour;

        // Change thresholds
        params.minThreshold = iLowTresh;
        params.maxThreshold = iHighTresh;

        // Filter by Area
        params.filterByArea = true;
        params.minArea = minArea;

        // Filter by Circularity
        params.filterByCircularity = true;
        params.minCircularity = minCirc;

        // Filter by Convexity
        params.filterByConvexity = true;
        params.minConvexity = minConv;

        // Filter by Inertia
        params.filterByInertia = true;
        params.minInertiaRatio = minInertia;

        // Set up detector with params

        SimpleBlobDetector detector(params); //HERE WHERE THE ERROR IS
        // Storage for blobs
        std::vector<KeyPoint> keypoints;

        // Detect blobs
        detector.detect(imgOriginal, keypoints);

        // Draw detected blobs as red circles.
        // DrawMatchesFlags::DRAW_RICH_KEYPOINTS flag ensures
        // the size of the circle corresponds to the size of blob

        Mat im_with_keypoints;
        drawKeypoints(imgOriginal, keypoints, im_with_keypoints, Scalar(0,0,255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS );

        QImage qigm=MatToQImage(imgOriginal);
        image=imgOriginal.clone();
        ui->label->setPixmap(QPixmap::fromImage(qigm).scaledToWidth(ui->label->size().width(),Qt::FastTransformation));

        QImage qigm2=MatToQImage(im_with_keypoints);
        image=im_with_keypoints.clone();
        ui->label_2->setPixmap(QPixmap::fromImage(qigm2).scaledToWidth(ui->label->size().width(),Qt::FastTransformation));

        // Wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
        if (waitKey(30) == 27)
        {
            break;
        }
    }
}

When I try to run the code, there is an error occur in line :

SimpleBlobDetector detector(params);

The error is stated in the picture Line 147

Thank You!

I try to find the solution here https://docs.opencv.org/4.x/d0/d7a/classcv_1_1SimpleBlobDetector.html#details but cannot find any solution..


问:
Declaration of a value-type Class
I want to specify my Class as a value-type one, so it can be stacked in method calls.

I tried the @jdk.internal.ValueBased annotation but it is not exposed from its module.
The doco gives a list of required properties, but does not say how to declare it.

If the compiler is left to its own judgment (in deciding to make a Class value-based or not), how can I tell which decision it took?

Note: this is Dec 2022, so the current target is Java 19

Title: Declaration of a value-type Class


问:
ModuleNotFoundError: in google Colab
I'm trying to run the code provided here ( https://github.com/jychoi118/P2-weighting ) in google Colab for research purposes but I keep getting these errors like ModuleNotFoundError

it's not reading all the classes, how can I solve it and make it run properly?

Title: ModuleNotFoundError: in google Colab


问:
Adding a link in a side bar with php code
Sorry, guys, I'm a newbie to PHP.

enter image description hereI have a social media site based purely on PHP, I would like to add a link to the right sidebar, but I am not very good at PHP.

This part is the sidebar.phtml

```<code>            <li>
                <a href="<?php echo Wo_SeoLink('index.php?link1=explore');?>" data-ajax="?link1=explore">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="#8BC34A" d="M14.19,14.19L6,18L9.81,9.81L18,6M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,10.9A1.1,1.1 0 0,0 10.9,12A1.1,1.1 0 0,0 12,13.1A1.1,1.1 0 0,0 13.1,12A1.1,1.1 0 0,0 12,10.9Z"></svg><img src="<?php echo $wo['config']['theme_url'];?>/img/sidebar/explorein.svg"> <?php echo $wo['lang']['explore'];?>
                </a>
            </li>
</code>```

I want to add a link going outside the site.

Body:
Sorry, guys, I'm a newbie to PHP.

enter image description hereI have a social media site based purely on PHP, I would like to add a link to the right sidebar, but I am not very good at PHP.

This part is the sidebar.phtml

                <a href="<?php echo Wo_SeoLink('index.php?link1=explore');?>" data-ajax="?link1=explore">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="#8BC34A" d="M14.19,14.19L6,18L9.81,9.81L18,6M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,10.9A1.1,1.1 0 0,0 10.9,12A1.1,1.1 0 0,0 12,13.1A1.1,1.1 0 0,0 13.1,12A1.1,1.1 0 0,0 12,10.9Z"></svg><img src="<?php echo $wo['config']['theme_url'];?>/img/sidebar/explorein.svg"> <?php echo $wo['lang']['explore'];?>

I want to add a link going outside the site.


问:
Rabbitmq Micronaut not reading queue message
I am facing an issue in rabbitmq-micronaut.
Issue: When I publish a message the rabbitmq the listener doesnt read the message and message goes into unack mode in the queue and when I restart this service which contain listener then the listener reads the message which are present in queue but will not read new messages untill i restart again.

I expect that when message arrives on the queue it should be read my the rabbitmq listener(routing key is perfectly matched)


问:
what is the difference between 3 yolo layers and 5 yolo layers in yolov3?
Yolov3 has 3 layer cfg and 5 layer cfg files. What is the difference between the number of layers in cfg and how does it affect out inference?

I have tried cfg with 3 yolo layers


问:
Syntax issue in tcsh alias
I have the following alias in a tcsh script

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

alias check_error 'set STAT="\!:1"                         \
echo "$STAT"                                               \
set FILA="\!:2"                                            \
echo "$FILA"                                               \
set DEST="\!:3"                                            \
echo "$DEST"                                               \
if ( $STAT != 1 ) then                                     \
   echo "ERROR: Failed  $FILA to $DEST."                   \
   exit 1                                                  \
endif'

set STATUS = 33
set fn = "2345"
check_error $STATUS $fn third
</code>```

The first echo in the alias prints 33 as expected but it then fails with the message

```<code>0: Event not found.
</code>```

I am not sure what the issue is

Title: Syntax issue in tcsh alias

Body:
I have the following alias in a tcsh script

#!/bin/tcsh

alias check_error 'set STAT="\!:1"                         \
echo "$STAT"                                               \
set FILA="\!:2"                                            \
echo "$FILA"                                               \
set DEST="\!:3"                                            \
echo "$DEST"                                               \
if ( $STAT != 1 ) then                                     \
   echo "ERROR: Failed  $FILA to $DEST."                   \
   exit 1                                                  \
endif'

set STATUS = 33
set fn = "2345"
check_error $STATUS $fn third

The first echo in the alias prints 33 as expected but it then fails with the message

0: Event not found.

I am not sure what the issue is


问:
Google Form: map multiple answer to unique decimal numer
I have a Google Form where user can select multiple answers from few questions. How to map the user's section to unique decimal number as output.
E.g.

```<code>Q1. Select your age group (User can select only one value here):
o 25-30
o 30-35
o 35-40
etc

Q2. What type of exercise do you do (User can select multiple choices here):
[] Walk
[] Run
[] HIIT
etc
</code>```

Assume Q1A represents Q1 Answer A (first answer), Q1C represents Q1 Answer C (last answer) etc.
A value 0 means it is not selected, a value 1 means it is selected by user.

I want to map each of the possible combination of user choices to one unique decimal number as output. It looks like below binary table.

```<code>Q1A Q1B Q1C Q2A Q2B Q2C    Output (Decimal mapping)
1    0   0  1   0   0       1
1    0   0  0   1   0       2
1    0   0  0   0   1       3
</code>```

Is there a way to google form automatically give the output as a unique decimal digit based on user's selection? If if it gives binary number, there could be any function to convert binary number to decimal number.

Tried few google searches to find the answer but didn't get better answer.

Body:
I have a Google Form where user can select multiple answers from few questions. How to map the user's section to unique decimal number as output.
E.g.

Q1. Select your age group (User can select only one value here):
o 25-30
o 30-35
o 35-40
etc

Q2. What type of exercise do you do (User can select multiple choices here):
[] Walk
[] Run
[] HIIT
etc

Assume Q1A represents Q1 Answer A (first answer), Q1C represents Q1 Answer C (last answer) etc.
A value 0 means it is not selected, a value 1 means it is selected by user.

I want to map each of the possible combination of user choices to one unique decimal number as output. It looks like below binary table.

Q1A Q1B Q1C Q2A Q2B Q2C    Output (Decimal mapping)
1    0   0  1   0   0       1
1    0   0  0   1   0       2
1    0   0  0   0   1       3

Is there a way to google form automatically give the output as a unique decimal digit based on user's selection? If if it gives binary number, there could be any function to convert binary number to decimal number.

Tried few google searches to find the answer but didn't get better answer.


问:
Swift: Downcasting a Binding within a List while retaining link
I have the following view code (unworking):

import SwiftUI

struct SearchFilterView: View {
    @Binding var filters: [any SourceFilter]

    var body: some View {
        List($filters, id: \.id) { filter in
            switch filter.wrappedValue {
            case var textFilter as SourceTextFilter:
                TextField(
                    textFilter.name,
                    text: Binding(get: { textFilter.value }, set: { textFilter.value = $0 })
                )
            case var toggleFilter as SourceToggleFilter:
                Toggle(
                    toggleFilter.name,
                    isOn: Binding(get: { toggleFilter.value }, set: { toggleFilter.value = $0 })
                )
            case var segmentFilter as SourceSegmentFilter:
                Picker(
                    segmentFilter.name,
                    selection: Binding(get: { segmentFilter.value }, set: { segmentFilter.value = $0 })
                ) {
                    ForEach(segmentFilter.selections, id: \.self) { selection in
                        Text(selection).tag(selection)
                    }
                }.pickerStyle(.segmented)
            default:
                EmptyView()
            }
        }
    }
}
```
<p>The code above compiles, but even though the values change for each filter, as soon as the view reloads, all of the changes are lost. The code for the <code>SourceFilter</code>s are below.</p>
<pre class="lang-swift prettyprint-override"><code>protocol JSObjectEncodable {
    var object: [String: Any] { get }
}

protocol JSObjectDecodable {
    init?(from object: [String: Any])
}

protocol JSObjectCodable: JSObjectDecodable, JSObjectEncodable {}

protocol SourceFilter<ValueType>: JSObjectCodable, Sendable {
    associatedtype ValueType
    var id: String { get }
    var value: ValueType { get set }
    var name: String { get }
}

struct SourceTextFilter: SourceFilter {
    init?(from object: [String: Any]) {
        guard let id = object["id"] as? String,
              let value = object["value"] as? String,
              let name = object["name"] as? String else { return nil }
        self.id = id
        self.value = value
        self.name = name
    }

    let id: String
    var value: String
    let name: String

    var object: [String: Any] {
        [
            "id": id,
            "value": value,
            "name": name
        ]
    }
}

struct SourceToggleFilter: SourceFilter {
    init?(from object: [String: Any]) {
        guard let id = object["id"] as? String,
              let value = object["value"] as? Bool,
              let name = object["name"] as? String else { return nil }
        self.id = id
        self.value = value
        self.name = name
    }

    let id: String
    var value: Bool
    let name: String

    var object: [String: Any] {
        [
            "id": id,
            "value": value,
            "name": name
        ]
    }
}

struct SourceSegmentFilter: SourceFilter {
    init?(from object: [String: Any]) {
        guard let id = object["id"] as? String,
              let value = object["value"] as? String,
              let name = object["name"] as? String,
              let selections = object["selections"] as? [String] else { return nil }
        self.id = id
        self.value = value
        self.name = name
        self.selections = selections
    }

    let id: String
    var value: String
    let name: String
    let selections: [String]

    var object: [String: Any] {
        [
            "id": id,
            "value": value,
            "name": name,
            "selections": selections
        ]
    }
}
</code>```

How do I have it so that my changes to the filter values are saved, even after being downcast to their respective filter type? Thanks in advance.

Body:
I have the following view code (unworking):

import SwiftUI

struct SearchFilterView: View {
    @Binding var filters: [any SourceFilter]

    var body: some View {
        List($filters, id: \.id) { filter in
            switch filter.wrappedValue {
            case var textFilter as SourceTextFilter:
                TextField(
                    textFilter.name,
                    text: Binding(get: { textFilter.value }, set: { textFilter.value = $0 })
                )
            case var toggleFilter as SourceToggleFilter:
                Toggle(
                    toggleFilter.name,
                    isOn: Binding(get: { toggleFilter.value }, set: { toggleFilter.value = $0 })
                )
            case var segmentFilter as SourceSegmentFilter:
                Picker(
                    segmentFilter.name,
                    selection: Binding(get: { segmentFilter.value }, set: { segmentFilter.value = $0 })
                ) {
                    ForEach(segmentFilter.selections, id: \.self) { selection in
                        Text(selection).tag(selection)
                    }
                }.pickerStyle(.segmented)
            default:
                EmptyView()
            }
        }
    }
}

The code above compiles, but even though the values change for each filter, as soon as the view reloads, all of the changes are lost. The code for the SourceFilters are below.

protocol JSObjectEncodable {
    var object: [String: Any] { get }
}

protocol JSObjectDecodable {
    init?(from object: [String: Any])
}

protocol JSObjectCodable: JSObjectDecodable, JSObjectEncodable {}

protocol SourceFilter<ValueType>: JSObjectCodable, Sendable {
    associatedtype ValueType
    var id: String { get }
    var value: ValueType { get set }
    var name: String { get }
}

struct SourceTextFilter: SourceFilter {
    init?(from object: [String: Any]) {
        guard let id = object["id"] as? String,
              let value = object["value"] as? String,
              let name = object["name"] as? String else { return nil }
        self.id = id
        self.value = value
        self.name = name
    }

    let id: String
    var value: String
    let name: String

    var object: [String: Any] {
        [
            "id": id,
            "value": value,
            "name": name
        ]
    }
}

struct SourceToggleFilter: SourceFilter {
    init?(from object: [String: Any]) {
        guard let id = object["id"] as? String,
              let value = object["value"] as? Bool,
              let name = object["name"] as? String else { return nil }
        self.id = id
        self.value = value
        self.name = name
    }

    let id: String
    var value: Bool
    let name: String

    var object: [String: Any] {
        [
            "id": id,
            "value": value,
            "name": name
        ]
    }
}

struct SourceSegmentFilter: SourceFilter {
    init?(from object: [String: Any]) {
        guard let id = object["id"] as? String,
              let value = object["value"] as? String,
              let name = object["name"] as? String,
              let selections = object["selections"] as? [String] else { return nil }
        self.id = id
        self.value = value
        self.name = name
        self.selections = selections
    }

    let id: String
    var value: String
    let name: String
    let selections: [String]

    var object: [String: Any] {
        [
            "id": id,
            "value": value,
            "name": name,
            "selections": selections
        ]
    }
}

How do I have it so that my changes to the filter values are saved, even after being downcast to their respective filter type? Thanks in advance.


问:
How to handle out of memory exception in okio sink?
I have a progress emitting request body..

class ProgressEmittingRequestBody(
    private val delegate: RequestBody,
    private val progressListener: ProgressListener,
) : RequestBody() {
    override fun contentType(): MediaType? = delegate.contentType()

    override fun contentLength(): Long {
        try {
            return delegate.contentLength()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return -1
    }

    override fun writeTo(sink: BufferedSink) {
        val bufferedSink = CountingSink(sink).buffer()
        delegate.writeTo(bufferedSink)
        bufferedSink.flush()
    }

    private inner class CountingSink(
        delegate: Sink
    ) : ForwardingSink(delegate) {
        var bytesWritten = 0L
        override fun write(source: Buffer, byteCount: Long) {
            super.write(source, byteCount)
            bytesWritten += byteCount
            progressListener.onProgressUpdate(bytesWritten, contentLength())
        }

    }

}

```
<p>But when I try to upload large files.. sometimes.. the following out of memory exception is thrown..</p>
<p><img src="https://i.stack.imgur.com/GjMgb.png" alt="Exception" /></p>
<p>The custom http logging interceptor I am using is..</p>
<pre class="lang-kotlin prettyprint-override"><code>      if (!logBody || requestBody == null) {
                logger.log("--> END ${request.method}")
            } else if (bodyHasUnknownEncoding(request.headers)) {
                logger.log("--> END ${request.method} (encoded body omitted)")
            } else if (requestBody.isDuplex()) {
                logger.log("--> END ${request.method} (duplex request body omitted)")
            } else if (requestBody.isOneShot()) {
                logger.log("--> END ${request.method} (one-shot body omitted)")
            } else {
                if (requestBody.contentLength() == -1L) {
                    logger.log("Unknown content length.")
                } else if (requestBody.contentLength() > 1024L * 1024) {
                    logger.log("Request body size exceeded ${1024 * 1024} bytes. Cannot log the request body.") //So that large source are not buffered.. Main change over here..
                } else {
                    var buffer = Buffer()
                    requestBody.writeTo(buffer)

                    var gzippedLength: Long? = null
                    if ("gzip".equals(headers["Content-Encoding"], ignoreCase = true)) {
                        gzippedLength = buffer.size
                        GzipSource(buffer).use { gzippedResponseBody ->
                            buffer = Buffer()
                            buffer.writeAll(gzippedResponseBody)
                        }
                    }

                    val charset: Charset = requestBody.contentType().charset()

                    logger.log("")
                    if (!buffer.isProbablyUtf8()) {
                        logger.log(
                            "--> END ${request.method} (binary ${requestBody.contentLength()}-byte body omitted)"
                        )
                    } else if (gzippedLength != null) {
                        logger.log("--> END ${request.method} (${buffer.size}-byte, $gzippedLength-gzipped-byte body)")
                    } else {
                        logger.log(buffer.readString(charset))

                        logger.log("--> END ${request.method} (${requestBody.contentLength()}-byte body)")
                    }
                }
            }
</code>```

If the out of memory exception was always happening, I would have trace the error.. But OOM is thrown for about 1 in 5 uploads and I am not able to track the error..

What am I doing wrong?

Body:
I have a progress emitting request body..

class ProgressEmittingRequestBody(
    private val delegate: RequestBody,
    private val progressListener: ProgressListener,
) : RequestBody() {
    override fun contentType(): MediaType? = delegate.contentType()

    override fun contentLength(): Long {
        try {
            return delegate.contentLength()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return -1
    }

    override fun writeTo(sink: BufferedSink) {
        val bufferedSink = CountingSink(sink).buffer()
        delegate.writeTo(bufferedSink)
        bufferedSink.flush()
    }

    private inner class CountingSink(
        delegate: Sink
    ) : ForwardingSink(delegate) {
        var bytesWritten = 0L
        override fun write(source: Buffer, byteCount: Long) {
            super.write(source, byteCount)
            bytesWritten += byteCount
            progressListener.onProgressUpdate(bytesWritten, contentLength())
        }

    }

}

But when I try to upload large files.. sometimes.. the following out of memory exception is thrown..

The custom http logging interceptor I am using is..

      if (!logBody || requestBody == null) {
                logger.log("--> END ${request.method}")
            } else if (bodyHasUnknownEncoding(request.headers)) {
                logger.log("--> END ${request.method} (encoded body omitted)")
            } else if (requestBody.isDuplex()) {
                logger.log("--> END ${request.method} (duplex request body omitted)")
            } else if (requestBody.isOneShot()) {
                logger.log("--> END ${request.method} (one-shot body omitted)")
            } else {
                if (requestBody.contentLength() == -1L) {
                    logger.log("Unknown content length.")
                } else if (requestBody.contentLength() > 1024L * 1024) {
                    logger.log("Request body size exceeded ${1024 * 1024} bytes. Cannot log the request body.") //So that large source are not buffered.. Main change over here..
                } else {
                    var buffer = Buffer()
                    requestBody.writeTo(buffer)

                    var gzippedLength: Long? = null
                    if ("gzip".equals(headers["Content-Encoding"], ignoreCase = true)) {
                        gzippedLength = buffer.size
                        GzipSource(buffer).use { gzippedResponseBody ->
                            buffer = Buffer()
                            buffer.writeAll(gzippedResponseBody)
                        }
                    }

                    val charset: Charset = requestBody.contentType().charset()

                    logger.log("")
                    if (!buffer.isProbablyUtf8()) {
                        logger.log(
                            "--> END ${request.method} (binary ${requestBody.contentLength()}-byte body omitted)"
                        )
                    } else if (gzippedLength != null) {
                        logger.log("--> END ${request.method} (${buffer.size}-byte, $gzippedLength-gzipped-byte body)")
                    } else {
                        logger.log(buffer.readString(charset))

                        logger.log("--> END ${request.method} (${requestBody.contentLength()}-byte body)")
                    }
                }
            }

If the out of memory exception was always happening, I would have trace the error.. But OOM is thrown for about 1 in 5 uploads and I am not able to track the error..

What am I doing wrong?


问:
WinAPI: repeatable check in a separate thread that notifies UI thread when check fails
My application has a separate thread that repeatably performs some check. If the check fails, the UI thread is notified (a MessageBox is displayed that requires user action what to do next).

Unfortunately, I have to use C++03 compiler (Visual Studio 2010 SP1) and boost library usage is prohibited. Therefore, I cannot use <thread>, <atomic>, <chrono>, etc. Thats why I have to use  CreateThread, PostMessage and other WinAPI functions.

Here is my UI thread code (simplified). My main window is CMDIFrameWnd (from MFC):

```<code>//a struct with all parameters that is needed for a repeatable check
struct RepeatFunctionParameters
{
    unsigned int repeatDelayInMilliseconds;
    HWND checkIsFailedPostMessageWindowHandler;
    UINT checkIsFailedPostMessageMessageId;
    HANDLE checkIsPausedMutexHandle;

    RepeatFunctionParameters(unsigned int _repeatDelayInMilliseconds, HWND _checkIsFailedPostMessageWindowHandler,
        UINT _checkIsFailedPostMessageMessageId, HANDLE _haspSerialCheckIsPausedMutexHandle)
        : repeatDelayInMilliseconds(_repeatDelayInMilliseconds), checkIsFailedPostMessageWindowHandler(_checkIsFailedPostMessageWindowHandler),
        checkIsFailedPostMessageMessageId(_checkIsFailedPostMessageMessageId), haspSerialCheckIsPausedMutexHandle(_haspSerialCheckIsPausedMutexHandle)
    {}
};

----------------------------
//creating a mutex to pause repeatable checks (whe Messagebox is displayed in UI thread)
HANDLE haspSerialCheckIsPausedMutexHandle = CreateMutex(NULL, FALSE, NULL);

//starting a separate thread with a check that repeats every 5000 milliseconds
auto params = new RepeatFunctionParameters(5000, myApp_hWnd, WM_USER_HASP_CHECK_FAILED, haspSerialCheckIsPausedMutexHandle);
CreateThread(NULL, 0, RepeatFunction, params, 0, NULL);

----------------------------
//special message that is sended when check is failed
#define WM_USER_HASP_CHECK_FAILED              (WM_USER+0x150)

//mapping message handling function to that message
ON_MESSAGE( WM_USER_HASP_CHECK_FAILED, OnUserHaspCheckFailed)

//message handling function definition
afx_msg LRESULT OnUserHaspCheckFailed(WPARAM wParam, LPARAM lParam);

//message handling function body
LRESULT CMainWnd::OnUserHaspCheckFailed(WPARAM wParam, LPARAM lParam)
{
    //capturing a mutex that signals to pause repeatable checks
    WaitForSingleObject(haspSerialCheckIsPausedMutexHandle, INFINITE);

    //show a messagebox that requires user action what to do next
    if (::MessageBox(myApp_hWnd, ("Check is failed! Retry or cancel?").c_str(),
            myApp_name, MB_RETRYCANCEL | MB_ICONERROR | MB_SYSTEMMODAL) == IDCANCEL)
            //closing main windows if user clicks Cancel
            pWnd->SendMessage(WM_CLOSE, 0x00010000, 0);

    //releasing a mutex that signals to pause repeatable checks
    ReleaseMutex(haspSerialCheckIsPausedMutexHandle);

    return 0;
}

//WM_CLOSE handling function body
LRESULT CMainWnd::OnClose( WPARAM wParam, LPARAM lParam)
{
    ----------------------------

    if( haspSerialCheckIsPausedMutexHandle != NULL)
        CloseHandle( haspSerialCheckIsPausedMutexHandle);

    ----------------------------

    CMDIFrameWnd::OnClose();
    return NULL;
}
</code>```

Here is my separate thread with repeatable check code (simplified):

```<code>DWORD WINAPI RepeatFunction(LPVOID parameters)
{
    //getting parameters struct from a pointer
    auto temp = static_cast<RepeatFunctionParameters*>(parameters);
    //make a struct local copy (Further, all work goes only with it, regardless of the
    state of the object, the pointer to which came as a function parameter)
    auto params = *temp;
    //deleting the structure, the pointer to which came as a function parameter
    delete temp;

    //repeatable check
    while (true)
    {
        //checking a mutex that signals to pause repeatable checks. if it is free
        //then there is no messagebox in UI thread and we can perform a check.
        //if it is captured - wait until user clicks some button in that messagebox
        WaitForSingleObject(params.haspSerialCheckIsPausedMutexHandle, INFINITE);
        //and releasing it immediately
        ReleaseMutex(params.haspSerialCheckIsPausedMutexHandle);

        auto startMilliseconds = GetTickCount();
        //performing a check
        BOOL success = PerformACheck();

        unsigned long defaultSleepDelay = 1000;
        //if PerformACheck() will last longer than params.repeatDelayInMilliseconds,
        //then check will be repeated after 1000 milliseconds, otherwise -
        //after params.repeatDelayInMilliseconds minus PerformACheck() call time
        auto endMilliseconds = GetTickCount();
        if ((endMilliseconds - startMilliseconds) < params.repeatDelayInMilliseconds)
            sleepDelay = params.repeatDelayInMilliseconds - (endMilliseconds - startMilliseconds);

        //if check is failed
        if (!success)
        {
            //sending a message with an identifier params.checkIsFailedPostMessageMessageId
            //to a HWND params.checkIsFailedPostMessageWindowHandler so in it's
            //handling function a messagebox with will be displayed and a mutex
            //params.haspSerialCheckCanRunMutexHandle will be captured until
            //user click some button in that messagebox
            PostMessage(params.checkIsFailedPostMessageWindowHandler, params.checkIsFailedPostMessageMessageId, 0, 0);

            //if check is failed then next check always repeats after 1000 milliseconds
            sleepDelay = 1000;
        }

        Sleep(sleepDelay);
    }
}
</code>```

The result is that the main window becomes unresponsive after some time. It looks like my code has some logical mistake, or a memory leak.

I'm a newbie to C++ (and especially to outdated standards).

Body:
My application has a separate thread that repeatably performs some check. If the check fails, the UI thread is notified (a MessageBox is displayed that requires user action what to do next).

Unfortunately, I have to use C++03 compiler (Visual Studio 2010 SP1) and boost library usage is prohibited. Therefore, I cannot use <thread>, <atomic>, <chrono>, etc. Thats why I have to use  CreateThread, PostMessage and other WinAPI functions.

Here is my UI thread code (simplified). My main window is CMDIFrameWnd (from MFC):

//a struct with all parameters that is needed for a repeatable check
struct RepeatFunctionParameters
{
    unsigned int repeatDelayInMilliseconds;
    HWND checkIsFailedPostMessageWindowHandler;
    UINT checkIsFailedPostMessageMessageId;
    HANDLE checkIsPausedMutexHandle;

    RepeatFunctionParameters(unsigned int _repeatDelayInMilliseconds, HWND _checkIsFailedPostMessageWindowHandler,
        UINT _checkIsFailedPostMessageMessageId, HANDLE _haspSerialCheckIsPausedMutexHandle)
        : repeatDelayInMilliseconds(_repeatDelayInMilliseconds), checkIsFailedPostMessageWindowHandler(_checkIsFailedPostMessageWindowHandler),
        checkIsFailedPostMessageMessageId(_checkIsFailedPostMessageMessageId), haspSerialCheckIsPausedMutexHandle(_haspSerialCheckIsPausedMutexHandle)
    {}
};

----------------------------
//creating a mutex to pause repeatable checks (whe Messagebox is displayed in UI thread)
HANDLE haspSerialCheckIsPausedMutexHandle = CreateMutex(NULL, FALSE, NULL);

//starting a separate thread with a check that repeats every 5000 milliseconds
auto params = new RepeatFunctionParameters(5000, myApp_hWnd, WM_USER_HASP_CHECK_FAILED, haspSerialCheckIsPausedMutexHandle);
CreateThread(NULL, 0, RepeatFunction, params, 0, NULL);

----------------------------
//special message that is sended when check is failed
#define WM_USER_HASP_CHECK_FAILED              (WM_USER+0x150)

//mapping message handling function to that message
ON_MESSAGE( WM_USER_HASP_CHECK_FAILED, OnUserHaspCheckFailed)

//message handling function definition
afx_msg LRESULT OnUserHaspCheckFailed(WPARAM wParam, LPARAM lParam);

//message handling function body
LRESULT CMainWnd::OnUserHaspCheckFailed(WPARAM wParam, LPARAM lParam)
{
    //capturing a mutex that signals to pause repeatable checks
    WaitForSingleObject(haspSerialCheckIsPausedMutexHandle, INFINITE);

    //show a messagebox that requires user action what to do next
    if (::MessageBox(myApp_hWnd, ("Check is failed! Retry or cancel?").c_str(),
            myApp_name, MB_RETRYCANCEL | MB_ICONERROR | MB_SYSTEMMODAL) == IDCANCEL)
            //closing main windows if user clicks Cancel
            pWnd->SendMessage(WM_CLOSE, 0x00010000, 0);

    //releasing a mutex that signals to pause repeatable checks
    ReleaseMutex(haspSerialCheckIsPausedMutexHandle);

    return 0;
}

//WM_CLOSE handling function body
LRESULT CMainWnd::OnClose( WPARAM wParam, LPARAM lParam)
{
    ----------------------------

    if( haspSerialCheckIsPausedMutexHandle != NULL)
        CloseHandle( haspSerialCheckIsPausedMutexHandle);

    ----------------------------

    CMDIFrameWnd::OnClose();
    return NULL;
}

Here is my separate thread with repeatable check code (simplified):

DWORD WINAPI RepeatFunction(LPVOID parameters)
{
    //getting parameters struct from a pointer
    auto temp = static_cast<RepeatFunctionParameters*>(parameters);
    //make a struct local copy (Further, all work goes only with it, regardless of the
    state of the object, the pointer to which came as a function parameter)
    auto params = *temp;
    //deleting the structure, the pointer to which came as a function parameter
    delete temp;

    //repeatable check
    while (true)
    {
        //checking a mutex that signals to pause repeatable checks. if it is free
        //then there is no messagebox in UI thread and we can perform a check.
        //if it is captured - wait until user clicks some button in that messagebox
        WaitForSingleObject(params.haspSerialCheckIsPausedMutexHandle, INFINITE);
        //and releasing it immediately
        ReleaseMutex(params.haspSerialCheckIsPausedMutexHandle);

        auto startMilliseconds = GetTickCount();
        //performing a check
        BOOL success = PerformACheck();

        unsigned long defaultSleepDelay = 1000;
        //if PerformACheck() will last longer than params.repeatDelayInMilliseconds,
        //then check will be repeated after 1000 milliseconds, otherwise -
        //after params.repeatDelayInMilliseconds minus PerformACheck() call time
        auto endMilliseconds = GetTickCount();
        if ((endMilliseconds - startMilliseconds) < params.repeatDelayInMilliseconds)
            sleepDelay = params.repeatDelayInMilliseconds - (endMilliseconds - startMilliseconds);

        //if check is failed
        if (!success)
        {
            //sending a message with an identifier params.checkIsFailedPostMessageMessageId
            //to a HWND params.checkIsFailedPostMessageWindowHandler so in it's
            //handling function a messagebox with will be displayed and a mutex
            //params.haspSerialCheckCanRunMutexHandle will be captured until
            //user click some button in that messagebox
            PostMessage(params.checkIsFailedPostMessageWindowHandler, params.checkIsFailedPostMessageMessageId, 0, 0);

            //if check is failed then next check always repeats after 1000 milliseconds
            sleepDelay = 1000;
        }

        Sleep(sleepDelay);
    }
}

The result is that the main window becomes unresponsive after some time. It looks like my code has some logical mistake, or a memory leak.

I'm a newbie to C++ (and especially to outdated standards).


问:
TU-local entity definition contains a recursive reference to itself
I think the following 2 paragraphs of the standard recursively reference each other. Is it a defect or am I missing something?

https://eel.is/c++draft/basic.link#14

A declaration is an exposure if it either names a TU-local entity
(defined below), ignoring

...

or defines a constexpr variable initialized to a TU-local value
(defined below).

https://eel.is/c++draft/basic.link#15

An entity is TU-local if it is

...

a specialization of a template whose (possibly instantiated) declaration is an exposure.

The definition of a TU-local value is based on the definition of a TU-local entity too.


问:
Unable to gracefully close http2 client stream in nodejs
I have the following code which has been heavily inspired from nodejs official documentation of a client-side example

```<code>import http2 from 'http2';

// The `http2.connect` method creates a new session with example.com
const session = http2.connect('https://somedomain.com');

// Handle errors
session.on('error', (err) => console.error(err))

const req = session.request({
  ':authority': 'somedomain.com',
  ':path': '/some-path',
  ':method': 'GET',
  ':scheme': 'https',
  'accept': 'text/html',
});

// To fetch the response body, we set the encoding
// we want and initialize an empty data string
req.setEncoding('utf8')
let data = ''

// append response data to the data string every time
// we receive new data chunks in the response
req.on('data', (chunk) => { data += chunk })

// Once the response is finished, log the entire data
// that we received
req.on('end', () => {
  console.log(`\n${data}`)
  session.close();
});

req.on('error', (error) => {
  console.log(error);
});
req.end();
</code>```

Please note that the actual hostname has been replaced with somedomain.com. Running this, results in data getting logged, as expected, however, the process doesn't shut down gracefully. I get the following unhandled error in the terminal.

```<code>node:events:504
      throw er; // Unhandled 'error' event
      ^

Error [ERR_HTTP2_STREAM_ERROR]: Stream closed with error code NGHTTP2_FLOW_CONTROL_ERROR
    at new NodeError (node:internal/errors:371:5)
    at ClientHttp2Stream._destroy (node:internal/http2/core:2330:13)
    at _destroy (node:internal/streams/destroy:102:25)
    at ClientHttp2Stream.destroy (node:internal/streams/destroy:64:5)
    at Http2Stream.onStreamClose (node:internal/http2/core:544:12)
Emitted 'error' event on ClientHttp2Stream instance at:
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'ERR_HTTP2_STREAM_ERROR'
}
</code>```

I understand it is possible that the server is behaving incorrectly. However, there should be a way on the nodejs client to close the session gracefully. Regardless, what would be the ideal way to handle such errors? I've already tried listening to session.on('error') and req.on('error') but that doesn't work.

Body:
I have the following code which has been heavily inspired from nodejs official documentation of a client-side example

import http2 from 'http2';

// The `http2.connect` method creates a new session with example.com
const session = http2.connect('https://somedomain.com');

// Handle errors
session.on('error', (err) => console.error(err))

const req = session.request({
  ':authority': 'somedomain.com',
  ':path': '/some-path',
  ':method': 'GET',
  ':scheme': 'https',
  'accept': 'text/html',
});

// To fetch the response body, we set the encoding
// we want and initialize an empty data string
req.setEncoding('utf8')
let data = ''

// append response data to the data string every time
// we receive new data chunks in the response
req.on('data', (chunk) => { data += chunk })

// Once the response is finished, log the entire data
// that we received
req.on('end', () => {
  console.log(`\n${data}`)
  session.close();
});

req.on('error', (error) => {
  console.log(error);
});
req.end();

Please note that the actual hostname has been replaced with somedomain.com. Running this, results in data getting logged, as expected, however, the process doesn't shut down gracefully. I get the following unhandled error in the terminal.

node:events:504
      throw er; // Unhandled 'error' event
      ^

Error [ERR_HTTP2_STREAM_ERROR]: Stream closed with error code NGHTTP2_FLOW_CONTROL_ERROR
    at new NodeError (node:internal/errors:371:5)
    at ClientHttp2Stream._destroy (node:internal/http2/core:2330:13)
    at _destroy (node:internal/streams/destroy:102:25)
    at ClientHttp2Stream.destroy (node:internal/streams/destroy:64:5)
    at Http2Stream.onStreamClose (node:internal/http2/core:544:12)
Emitted 'error' event on ClientHttp2Stream instance at:
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'ERR_HTTP2_STREAM_ERROR'
}

I understand it is possible that the server is behaving incorrectly. However, there should be a way on the nodejs client to close the session gracefully. Regardless, what would be the ideal way to handle such errors? I've already tried listening to session.on('error') and req.on('error') but that doesn't work.


问:
github action - Check if Personal access tokens (classic) has expired
I am using github Personal access tokens (classic) to pull the code in a VM. This VM is created using the terraform and a startup script runs that pulls the code from my github repo.
Now, before running the terraform code, I want to know if Personal access tokens (classic) has expired or, if it's expired I don't want to create a VM.

Please suggest,
Thanks


问:
GGplot legend square - why doesn't it fill entirely?
I have a graph I've plotted and used squares in my legend but for some reason it seems to have a line running through it - not sure why?

This is the code I used to get this:

```<code>guides(color = guide_legend(override.aes = list(shape = 15))
</code>```

I'd like it to be a solid-filled square

Body:
I have a graph I've plotted and used squares in my legend but for some reason it seems to have a line running through it - not sure why?

This is the code I used to get this:

guides(color = guide_legend(override.aes = list(shape = 15))

I'd like it to be a solid-filled square


问:
Is it possible to run a python script when another computer connects to the website?
Im trying to set up a prank for my coder friends(have to clarify its not something bad, its just a harmless joke) and they are much more experienced than me. They like to brag about it, so I wanted to make them look like they got hacked by getting a singular file from their computer. Is it possible to run a script to take a their file from their computer as soon as they click on a link that i can share on discord?

I got python script to get a file, but its only when you download the script and use it, it also requires you to have any python version 3+ to run the code. Tried to make a short link but couldnt get it work either.


问:
how to cut a video and combine them into one with python-ffmpeg?
For example, I have a file video.mp4. I would like to cut it into 3 pieces: 0 - 1 min, 2 - 3 min, and 4 - 5 min. Then combine them into one mp4 file.

I've tried something like and it doesn't seem to work

```<code>import ffmpeg

stream = ffmpeg.input("video.mp4")
video_1 = ffmpeg.trim(stream, start = 0, end = 60)
video_2 = ffmpeg.trim(stream, start = 120, end = 180)
video_3 = ffmpeg.trim(stream, start = 240, end = 300)
combined = ffmpeg.concat(video_1, video_2, video_3, v=3)
output = ffmpeg.output(combined, "output", format="mp4")
ffmpeg.run(output)
</code>```

The goal is to combine the video part, audio can be ignored for now.

Body:
For example, I have a file video.mp4. I would like to cut it into 3 pieces: 0 - 1 min, 2 - 3 min, and 4 - 5 min. Then combine them into one mp4 file.

I've tried something like and it doesn't seem to work

import ffmpeg

stream = ffmpeg.input("video.mp4")
video_1 = ffmpeg.trim(stream, start = 0, end = 60)
video_2 = ffmpeg.trim(stream, start = 120, end = 180)
video_3 = ffmpeg.trim(stream, start = 240, end = 300)
combined = ffmpeg.concat(video_1, video_2, video_3, v=3)
output = ffmpeg.output(combined, "output", format="mp4")
ffmpeg.run(output)

The goal is to combine the video part, audio can be ignored for now.


问:
assert_called_once_with with different parameters
I am trying to understand how assert_called_once_with work so I wrote below small program where I am mocking calculate method which is being called 3 times with different args.

When I call assert_called_once_with method it gives me below assertion error. My desired assertion is to assert method call with specific argument which was 1 in case of addition operation.

How do I achieve this?

```<code>self = <MagicMock name='calculate' id='2603213283344'>
args = ('addition', 10, 20), kwargs = {}
msg = "Expected 'calculate' to be called once. Called 3 times.\nCalls: [call('addition', 10, 20),\n call('subscription', 20, 30),\n call('multiplication', 30, 40)]."
</code>```

calculator.py

```<code>def calculate(operation, a, b):
    if operation == 'addition':
        return a + b
    elif operation == 'subscription':
        return a - b
    else:
        return a * b

def perform_all(a, b):
    addition_result = calculate('addition', a, b)
    subscription_result = calculate('subscription', a + 10, b + 10)
    multiplication_result = calculate('multiplication', a + 20, b + 20)
    return addition_result, subscription_result, multiplication_result
</code>```

test_calculate.py

```<code>from unittest.mock import patch

from customer.calculator import perform_all

def calculate_side_effect(*args, **kwargs):
    if args == ('addition', 10, 20):
        return 20
    elif args == ('subscription', 20, 30):
        return -10
    else:
        return 1200

@patch('customer.calculator.calculate')
def test_get_customers(calculate_mock):
    calculate_mock.side_effect = calculate_side_effect

    addition_result, subscription_result, multiplication_result = perform_all(10, 20)

    assert addition_result == 20
    assert subscription_result == -10
    assert multiplication_result == 1200

    assert calculate_mock.assert_called_once_with('addition', 10, 20)
    assert calculate_mock.assert_called_once_with('subscription', 20, 30)
    assert calculate_mock.assert_called_once_with('multiplication', 30, 40)
</code>```

Body:
I am trying to understand how assert_called_once_with work so I wrote below small program where I am mocking calculate method which is being called 3 times with different args.

When I call assert_called_once_with method it gives me below assertion error. My desired assertion is to assert method call with specific argument which was 1 in case of addition operation.

How do I achieve this?

self = <MagicMock name='calculate' id='2603213283344'>
args = ('addition', 10, 20), kwargs = {}
msg = "Expected 'calculate' to be called once. Called 3 times.\nCalls: [call('addition', 10, 20),\n call('subscription', 20, 30),\n call('multiplication', 30, 40)]."

calculator.py

def calculate(operation, a, b):
    if operation == 'addition':
        return a + b
    elif operation == 'subscription':
        return a - b
    else:
        return a * b

def perform_all(a, b):
    addition_result = calculate('addition', a, b)
    subscription_result = calculate('subscription', a + 10, b + 10)
    multiplication_result = calculate('multiplication', a + 20, b + 20)
    return addition_result, subscription_result, multiplication_result

test_calculate.py

from unittest.mock import patch

from customer.calculator import perform_all

def calculate_side_effect(*args, **kwargs):
    if args == ('addition', 10, 20):
        return 20
    elif args == ('subscription', 20, 30):
        return -10
    else:
        return 1200

@patch('customer.calculator.calculate')
def test_get_customers(calculate_mock):
    calculate_mock.side_effect = calculate_side_effect

    addition_result, subscription_result, multiplication_result = perform_all(10, 20)

    assert addition_result == 20
    assert subscription_result == -10
    assert multiplication_result == 1200

    assert calculate_mock.assert_called_once_with('addition', 10, 20)
    assert calculate_mock.assert_called_once_with('subscription', 20, 30)
    assert calculate_mock.assert_called_once_with('multiplication', 30, 40)


问:
Uncaught TypeError: Cannot read properties of null (reading 'querySelectorAll')
In my form view, I have used some style that when the user submits the form, it checked with javascript that all the required input fields are filled.

Then I load Please wait for message until the form pass to the controller and submits the data.

This worked well in my current project and today I have removed my previous HTML theme and added a new one.

Now when I tried to do the same in the same form, I'm return with an error

```<code>Uncaught TypeError: Cannot read properties of null (reading 'querySelectorAll')
</code>```

What could be the problem I made?

This is my form

```<code><form class="forms">
  @using (Html.BeginForm("AcceptTask", "SelfCareTasks", FormMethod.Post , new {@id = "CreateTask"}))
  {
    @Html.AntiForgeryToken();
    @Html.HiddenFor(model => model.CustomerId)
    @Html.HiddenFor(model => model.ServiceId)
    @Html.HiddenFor(model => model.ServiceEndDate)
    @Html.HiddenFor(model => model.ServicePrice)

   <div class="form-group">
     @Html.LabelFor(model => model.ServiceName, htmlAttributes: new { @class = "control-label col-md-3 required" })
     @Html.EditorFor(model => model.ServiceName, new { htmlAttributes = new { @class = "form-control", placeholder = "Type Surename Here",  @disabled = true } })
     @Html.ValidationMessageFor(model => model.ServiceName, "", new { @class = "text-danger" })
    </div>

    <div class="form-group">
     @Html.LabelFor(model => model.ServicePrice, htmlAttributes: new { @class = "control-label col-md-3 required" })
     @Html.EditorFor(model => model.ServicePrice, new { htmlAttributes = new { @class = "form-control", placeholder = "Type Surename Here",  @disabled = true } })
     @Html.ValidationMessageFor(model => model.ServicePrice, "", new { @class = "text-danger" })
     </div>

    <div class="form-group">
     @Html.LabelFor(model => model.ServiceEndDate, htmlAttributes: new { @class = "control-label col-md-3 required" })
     @Html.TextBoxFor(model => model.ServiceEndDate, "{0:yyyy-MM-dd}", new { @class = "form-control", @disabled = true, @type = "date" })
     @Html.ValidationMessageFor(model => model.ServiceEndDate, "", new { @class = "text-danger" })
    </div>

    <div class="form-group row">
      <div class="col-md-4 col-sm-4 form-group" style="width:32.5%">
        @Html.LabelFor(model => model.Note, htmlAttributes: new { @class = "control-label col-md-3" })
      </div>
      <div>
      <div class="col-sm-10 col-md-10 form-group">
         @Html.TextAreaFor(model => model.Note, 08, 400, htmlAttributes: new { @class = "form-control", @id = "TaskNote",@required = true, placeholder = "Type Additional Notes here",  })
         @Html.ValidationMessageFor(model => model.Note, "", new { @class = "text-danger" })
      </div>
     </div>
    </div>

  <input type="submit"  id="submitButton" class="btn btn-success" onclick="return DisplayProgressMessage(this, 'Checking...');" />
  <a href="@Url.Action("Index","SelfService")" class="btn btn-dark">Back to List</a>
 }
</form>

<script type = "text/javascript" >

  function DisplayProgressMessage(ctl, msg) {

    let allAreFilled = true;
    document.getElementById("CreateTask").querySelectorAll("[required]").forEach(function (i) {
      if (!allAreFilled) return;
      if (!i.value) {
        allAreFilled = false;
        return;
      }
    })
    if (!allAreFilled) {

      return;
    } else {
      console.log("succ");
      $(ctl).prop("disabled", true);
      $(ctl).text(msg);
      $(".submit-progress").removeClass("hidden");
      $("body").addClass("submit-progress-bg");
      document.getElementById("CreateTask").submit();

    }
  };

</script>
</code>```

Body:
In my form view, I have used some style that when the user submits the form, it checked with javascript that all the required input fields are filled.

Then I load Please wait for message until the form pass to the controller and submits the data.

This worked well in my current project and today I have removed my previous HTML theme and added a new one.

Now when I tried to do the same in the same form, I'm return with an error

Uncaught TypeError: Cannot read properties of null (reading 'querySelectorAll')

What could be the problem I made?

This is my form

<form class="forms">
  @using (Html.BeginForm("AcceptTask", "SelfCareTasks", FormMethod.Post , new {@id = "CreateTask"}))
  {
    @Html.AntiForgeryToken();
    @Html.HiddenFor(model => model.CustomerId)
    @Html.HiddenFor(model => model.ServiceId)
    @Html.HiddenFor(model => model.ServiceEndDate)
    @Html.HiddenFor(model => model.ServicePrice)

     @Html.LabelFor(model => model.ServiceName, htmlAttributes: new { @class = "control-label col-md-3 required" })
     @Html.EditorFor(model => model.ServiceName, new { htmlAttributes = new { @class = "form-control", placeholder = "Type Surename Here",  @disabled = true } })
     @Html.ValidationMessageFor(model => model.ServiceName, "", new { @class = "text-danger" })

     @Html.LabelFor(model => model.ServicePrice, htmlAttributes: new { @class = "control-label col-md-3 required" })
     @Html.EditorFor(model => model.ServicePrice, new { htmlAttributes = new { @class = "form-control", placeholder = "Type Surename Here",  @disabled = true } })
     @Html.ValidationMessageFor(model => model.ServicePrice, "", new { @class = "text-danger" })

     @Html.LabelFor(model => model.ServiceEndDate, htmlAttributes: new { @class = "control-label col-md-3 required" })
     @Html.TextBoxFor(model => model.ServiceEndDate, "{0:yyyy-MM-dd}", new { @class = "form-control", @disabled = true, @type = "date" })
     @Html.ValidationMessageFor(model => model.ServiceEndDate, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Note, htmlAttributes: new { @class = "control-label col-md-3" })

         @Html.TextAreaFor(model => model.Note, 08, 400, htmlAttributes: new { @class = "form-control", @id = "TaskNote",@required = true, placeholder = "Type Additional Notes here",  })
         @Html.ValidationMessageFor(model => model.Note, "", new { @class = "text-danger" })

  <input type="submit"  id="submitButton" class="btn btn-success" onclick="return DisplayProgressMessage(this, 'Checking...');" />
  Back to List
 }
</form>


问:
Update single row of table in template page using ajax in Django
I am working on Django project and I have no idea of ajax that how to implement it. The scenario is my db contains a table name "demo" which contains the column stat_id. My database contains the following details:

```<code>table name = demo
id int primary key NOT NULL,
stat_id int(11) NOT NULL             #value is 1
</code>```

Now, the scenario is that I am getting the stat_id value from database and its purpose to show the running and complete button. If python script is running then it will display the running button and if python script has executed it will display the completed button.

status.html:

```<code>    <td>
    <form action = "/modules" method="get">
    {% if status == 1 %}
    {% csrf_token %}
    <button link="submit" class="btn btn-default btn-sm">
    <span class="badge badge-dot mr-4">
    <i class="bg-success"></i>Completed</button>
    </form>
     {% else %}
    <button type="button" class="btn btn-default btn-sm">
    <span class="badge badge-dot mr-4">
    <i class="bg-warning"></i>Running</button>
     {% endif %}

views.py:

    def process(request):
     hash_id = request.session.get('hash_id')
     print(hash_id)
     check = request.session.pop('check_status',)
      if hash_id and check:
        stat = status_mod.objects.filter(hash_id = hash_id).order_by('-id').first()
        if stat:
          stat = stat.stat_id
        print(stat)

      return render(request, 'enroll/status.html', {'status': stat})
</code>```

urls.py:

```<code>path('status', views.process, name='process')
</code>```

models.py:

```<code>class status_mod(models.Model):
  id = models.BigIntegerField(primary_key=True)
  stat_id = models.BigIntegerField()

  class Meta:
    db_table = "demo"
</code>```

jquery / ajax in my status.html page:

```<code><script>
$(document).ready(function() {
   setInterval(function() {
     $.ajax({
     type: 'GET',
    url: "{% url 'process' %}",
      success: function(response){
      console.log(response)

},
error: function(response){
alert("NO DATA FOUND")
}

});
     }, 2500);
   });
</script>
</code>```

Now, I want to update my table row as situation will be if status == 1 then completed button will display else running. Hence it is working fine without ajax but I have to refresh again and again when process function is executed. So, I want to use ajax in this case to update the table row automatically without reloading it.

Body:
I am working on Django project and I have no idea of ajax that how to implement it. The scenario is my db contains a table name "demo" which contains the column stat_id. My database contains the following details:

table name = demo
id int primary key NOT NULL,
stat_id int(11) NOT NULL             #value is 1

Now, the scenario is that I am getting the stat_id value from database and its purpose to show the running and complete button. If python script is running then it will display the running button and if python script has executed it will display the completed button.

status.html:

    <form action = "/modules" method="get">
    {% if status == 1 %}
    {% csrf_token %}
    <button link="submit" class="btn btn-default btn-sm">

    Completed</button>
    </form>
     {% else %}
    <button type="button" class="btn btn-default btn-sm">

    Running</button>
     {% endif %}

views.py:

    def process(request):
     hash_id = request.session.get('hash_id')
     print(hash_id)
     check = request.session.pop('check_status',)
      if hash_id and check:
        stat = status_mod.objects.filter(hash_id = hash_id).order_by('-id').first()
        if stat:
          stat = stat.stat_id
        print(stat)

      return render(request, 'enroll/status.html', {'status': stat})

urls.py:

path('status', views.process, name='process')

models.py:

class status_mod(models.Model):
  id = models.BigIntegerField(primary_key=True)
  stat_id = models.BigIntegerField()

  class Meta:
    db_table = "demo"

jquery / ajax in my status.html page:

Now, I want to update my table row as situation will be if status == 1 then completed button will display else running. Hence it is working fine without ajax but I have to refresh again and again when process function is executed. So, I want to use ajax in this case to update the table row automatically without reloading it.