问:
Can you throttle requests rather than responses in Cypress?
I am trying to end to end test a file upload page in Cypress, which includes testing if a file upload progress bar works.

Unfortunately, in the local environment the upload happens instantly so the progress bar is not shown.

I am aware that you can throttle the response speed using cy.intercept() to simulate slow networks.  However, this isn't slowing the request upload speed:

cy.intercept('post', `/route`, (req) => {
    req.on('response', (res) => {
        res.setThrottle(1000)
    })
}).as('post')
```

Is there any way that I can apply a throttle to the outgoing request?

答:
In the routeHandler, use setTimeout() to delay the call to req.continue().

To get the command queue to wait for setTimeout, return a Promise wrapper.  See Request phase

If the handler returned a Promise, wait for the Promise to resolve.

If you want a delay longer than the default command timeout of 4 seconds, you will need to increase the config since cy.intercept does not take a timeout option.

Cypress.config('defaultCommandTimeout', 6000)  // timeout in 6 seconds

cy.intercept('POST', '/route', (req) => {
  return new Promise(resolve => {
    setTimeout(() => resolve(req.continue()), 5000) // delay by 5 seconds
  })
}).as('delayedRequest')

// trigger POST

cy.wait('@delayedRequest')

Cypress.config('defaultCommandTimeout', 4000)  // revert to normal timeout
```
<hr />
<p><strong>Middleware</strong></p>
<p>If you already have a complex intercept, you can set the delay in a middleware intercept.</p>
<p>Middleware is always executed first, but if does not handle the request the call is passed to the next intercept.</p>
<pre class="lang-js prettyprint-override"><code>// request is delayed here
cy.intercept('POST', '/route', {
    middleware: true                       // middleware always fires first
  },
  (req) => new Promise(resolve =>
    setTimeout(() => resolve(), 5000)      // no handler, just delay
  )
)

// then passed to here
cy.intercept('POST', '/route',
  (req) => {
    req.continue()                            // handler for request
  }
).as('delayedRequest')

// trigger POST

cy.wait('@delayedRequest')
</code>```

Body:
I am trying to end to end test a file upload page in Cypress, which includes testing if a file upload progress bar works.

Unfortunately, in the local environment the upload happens instantly so the progress bar is not shown.

I am aware that you can throttle the response speed using cy.intercept() to simulate slow networks.  However, this isn't slowing the request upload speed:

cy.intercept('post', `/route`, (req) => {
    req.on('response', (res) => {
        res.setThrottle(1000)
    })
}).as('post')

Is there any way that I can apply a throttle to the outgoing request?

Body:
In the routeHandler, use setTimeout() to delay the call to req.continue().

To get the command queue to wait for setTimeout, return a Promise wrapper.  See Request phase

If the handler returned a Promise, wait for the Promise to resolve.

If you want a delay longer than the default command timeout of 4 seconds, you will need to increase the config since cy.intercept does not take a timeout option.

Cypress.config('defaultCommandTimeout', 6000)  // timeout in 6 seconds

cy.intercept('POST', '/route', (req) => {
  return new Promise(resolve => {
    setTimeout(() => resolve(req.continue()), 5000) // delay by 5 seconds
  })
}).as('delayedRequest')

// trigger POST

cy.wait('@delayedRequest')

Cypress.config('defaultCommandTimeout', 4000)  // revert to normal timeout

Middleware

If you already have a complex intercept, you can set the delay in a middleware intercept.

Middleware is always executed first, but if does not handle the request the call is passed to the next intercept.

// request is delayed here
cy.intercept('POST', '/route', {
    middleware: true                       // middleware always fires first
  },
  (req) => new Promise(resolve =>
    setTimeout(() => resolve(), 5000)      // no handler, just delay
  )
)

// then passed to here
cy.intercept('POST', '/route',
  (req) => {
    req.continue()                            // handler for request
  }
).as('delayedRequest')

// trigger POST

cy.wait('@delayedRequest')


来源: stackexchange

问:
MySQL JSON_OVERLAPS ... how do I compare json from one table to a group of ID values from another table?
I have 2 MySQL tables that look like this:

first_table: the "json_field" values are just lists of integers, but the field type is "json":

```<code>id   json_field
1    [1,2,3]
2    [2,3]
3    [1,3]
</code>```

second_table: just a simple table with 2 fields (integer, varchar):

```<code>id   name
1    bob
2    sam
3    mary
</code>```

I need a single query that gives me all rows from first_table for which json_field values intersect with any "id" value from second_table that satisfies a simple query condition of "where name = 'sam'" (e.g. using a subquery)

Here's what I have so far:

```<code>select * from first_table where
    JSON_OVERLAPS(json_field, (select group_concat(id) from second_table where name = 'sam'))
</code>```

This query gives this error, however:

"Invalid JSON text in argument 1 to function json_overlaps: "The document root must not be followed by other values." at position 1."

I also tried this thinking that I had to convert the result of group_concat to json first, but got an SQL syntax error:

```<code>select * from first_table where
    JSON_OVERLAPS(json_field, JSON_OBJECT(select group_concat(id) from second_table where name = 'sam'))
</code>```

The correct result should give me the following 2 rows, since those rows contain id = 2, which is the id that corresponds to "sam" in second_table

```<code>1   1,2,3
2   2,3
</code>```

Please assume that I must use a json field type for "first_table". The schema that I outlined above cannot be changed.

答:
Don't use GROUP_CONCAT(), because it returns a string, not a set of rows. It can't be used to compare to a JSON document, and it can't be used to convert into a JSON array.

Instead, use JSON_ARRAYAGG() on a set of rows. This function transforms the set of rows into a JSON array.

```<code>select id, json_pretty(json_field) from first_table
where json_overlaps(json_field,
  (select json_arrayagg(id) from second_table where name='Sam')
);
</code>```

Demo: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=7a8d4f8a47042c1f9fa763c0689287ea

ContentLicense: CC BY-SA 4.0

Body:
I have 2 MySQL tables that look like this:

first_table: the "json_field" values are just lists of integers, but the field type is "json":

id   json_field
1    [1,2,3]
2    [2,3]
3    [1,3]

second_table: just a simple table with 2 fields (integer, varchar):

id   name
1    bob
2    sam
3    mary

I need a single query that gives me all rows from first_table for which json_field values intersect with any "id" value from second_table that satisfies a simple query condition of "where name = 'sam'" (e.g. using a subquery)

Here's what I have so far:

select * from first_table where
    JSON_OVERLAPS(json_field, (select group_concat(id) from second_table where name = 'sam'))

This query gives this error, however:

"Invalid JSON text in argument 1 to function json_overlaps: "The document root must not be followed by other values." at position 1."

I also tried this thinking that I had to convert the result of group_concat to json first, but got an SQL syntax error:

select * from first_table where
    JSON_OVERLAPS(json_field, JSON_OBJECT(select group_concat(id) from second_table where name = 'sam'))

The correct result should give me the following 2 rows, since those rows contain id = 2, which is the id that corresponds to "sam" in second_table

1   1,2,3
2   2,3

Please assume that I must use a json field type for "first_table". The schema that I outlined above cannot be changed.

Body:
Don't use GROUP_CONCAT(), because it returns a string, not a set of rows. It can't be used to compare to a JSON document, and it can't be used to convert into a JSON array.

Instead, use JSON_ARRAYAGG() on a set of rows. This function transforms the set of rows into a JSON array.

select id, json_pretty(json_field) from first_table
where json_overlaps(json_field,
  (select json_arrayagg(id) from second_table where name='Sam')
);

Demo: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=7a8d4f8a47042c1f9fa763c0689287ea


问:
Django How to do a correlated EXISTS or NOT EXISTS
How can I perform the following correlated EXISTS and NOT EXISTS in Django?

I do not want to use IN and NOT IN. These are not the same as EXISTS and NOT EXISTS.

Correlated EXISTS:

```<code>SELECT *
FROM foo
WHERE EXISTS (
    SELECT 1
    FROM bar
    WHERE foo.baz = bar.baz

)
</code>```

Correlated NOT EXISTS:

```<code>SELECT *
FROM foo
WHERE NOT EXISTS (
    SELECT 1
    FROM bar
    WHERE foo.baz = bar.baz

)
</code>```

答:
You can use an Exists() subquery to generate a query like you desire. Not entirely sure how your model looks but the following may look similar to what you want

```<code>from django.db.models import Exists, OuterRef

matching_bars = Bar.objects.filter(baz=OuterRef('baz'))
Foo.objects.filter(Exists(matching_bars))
</code>```

To use NOT EXISTS just prefix the Exists subquery with ~

```<code>Foo.objects.filter(~Exists(matching_bars))
</code>```

Body:
How can I perform the following correlated EXISTS and NOT EXISTS in Django?

I do not want to use IN and NOT IN. These are not the same as EXISTS and NOT EXISTS.

Correlated EXISTS:

SELECT *
FROM foo
WHERE EXISTS (
    SELECT 1
    FROM bar
    WHERE foo.baz = bar.baz

)

Correlated NOT EXISTS:

SELECT *
FROM foo
WHERE NOT EXISTS (
    SELECT 1
    FROM bar
    WHERE foo.baz = bar.baz

)

Body:
You can use an Exists() subquery to generate a query like you desire. Not entirely sure how your model looks but the following may look similar to what you want

from django.db.models import Exists, OuterRef

matching_bars = Bar.objects.filter(baz=OuterRef('baz'))
Foo.objects.filter(Exists(matching_bars))

To use NOT EXISTS just prefix the Exists subquery with ~

Foo.objects.filter(~Exists(matching_bars))


问:
Uploading to S3 bucket using missing SessionToken in AWS SDK for .NET
I'm following this tutorial on uploading files to the AWS S3 bucket.

The author is using AppConfiguration for configuring AWS:

public class AppConfiguration : IAppConfiguration
{
    // Keep the following details in appsettings.config file or DB or Enivironment variable
    // Get those values from it and assign to the below varibales. Based on the approach , modify the below code.
    public AppConfiguration()
    {
        BucketName = "";
        Region = "";
        AwsAccessKey = "";
        AwsSecretAccessKey = "";
        AwsSessionToken = "";
    }

    public string BucketName { get; set; }
    public string Region { get; set; }
    public string AwsAccessKey { get; set; }
    public string AwsSecretAccessKey { get; set; }
    public string AwsSessionToken { get; set; }
}
```

Among others, there's a AwsSessionToken property which I don't know how to retrieve/generate.

How can I retrieve a session token?

答:
TLDR: use the shared AWS credentials file & delete all code related to credentials within your application including the credentials themselves as they are a security risk.

Never, ever, ever, ever, ever, ever, ever, ever, ever store credentials within application files.

Here is what the AWS SDK for .NET Developer Guide issues important warnings on, for credentials:

Do NOT put literal access keys in your application files. If you do, you create a risk of accidentally exposing your credentials if, for example, you upload the project to a public repository.

Do NOT include files that contain credentials in your project area.

This is pretty much reiterated everywhere else too:

We recommend that you never add your AWS access keys directly to the client in any production files. Many developers have had their account compromised by leaked keys.

Instead, use a method of providing credentials within the default credentials provider chain for the .NET SDK to securely provide credentials to your .NET application.

It's easier and much cleaner than creating a POCO, or handling credentials within your code.

For local development, I always prefer the shared AWS credentials file, which you can create yourself or use aws configure via the AWS CLI to set it up. The AWS SDK will then automatically pick up on the credentials without you needing to specify anything within the code.

Using an AWS credentials file offers the following benefits:

Your projects’ credentials are stored outside of your projects, so
there is no chance of accidentally committing them into version
control.

You can define and name multiple sets of credentials in one place.

You can easily reuse the same credentials among projects.

Other AWS SDKs and tools support, this same credentials file. This
allows you to reuse your credentials with other tools.

Just please don't hardcode credentials whatever you do.

FYI: session tokens are used to validate temporary AWS credentials. Your access key ID & secret access key are permanent methods of authenticating until they are deactivated/deleted, so you don't need to worry about session tokens at all.

Body:
I'm following this tutorial on uploading files to the AWS S3 bucket.

The author is using AppConfiguration for configuring AWS:

public class AppConfiguration : IAppConfiguration
{
    // Keep the following details in appsettings.config file or DB or Enivironment variable
    // Get those values from it and assign to the below varibales. Based on the approach , modify the below code.
    public AppConfiguration()
    {
        BucketName = "";
        Region = "";
        AwsAccessKey = "";
        AwsSecretAccessKey = "";
        AwsSessionToken = "";
    }

    public string BucketName { get; set; }
    public string Region { get; set; }
    public string AwsAccessKey { get; set; }
    public string AwsSecretAccessKey { get; set; }
    public string AwsSessionToken { get; set; }
}

Among others, there's a AwsSessionToken property which I don't know how to retrieve/generate.

How can I retrieve a session token?


问:
SwiftUI passing an observed object into a new view and getting updates
I am very new to swift working on my first app and having trouble having a view update. I am passing an object into a new view, however the new view does not update when there is change in the Firebase Database. Is there a way to get updates on the Gridview? I though by passing the observed object from the StyleboardView it would update the GridView however Gridview does not update. I am having trouble finding a way for the new Gridview to update and reload the images.</p>
```<code>struct StyleBoardView: View {

@State private var showingSheet = false
@ObservedObject var model = ApiModel()
@State var styleboardname = ""

let userEmail = Auth.auth().currentUser?.email

var body: some View {
    NavigationView {
        VStack {
            Text("Select Style Board")
            List (model.list) {item in
                Button(item.styleboardname) {
                            showingSheet.toggle()
                        }
                        .sheet(isPresented: $showingSheet) {
                            GridView(item: item)
                        }
            }

struct GridView: View {
var item: Todo
@ObservedObject var model = ApiModel()
@State var newImage = ""
@State var loc = ""
@State var shouldShowImagePicker = false
@State var image: UIImage?

var body: some View {
    NavigationView {
        var posts = item.styleboardimages

        VStack(alignment: .leading){
            Text(item.styleboardname)
                    GeometryReader{ geo in
                        LazyVGrid(columns: [
                            GridItem(.flexible()),
                            GridItem(.flexible()),
                            GridItem(.flexible())
                        ], spacing: 3 ){
                            ForEach(posts.sorted(by: <), id: \.key) { key, value in
                                if #available(iOS 15.0, *) {
                                    AsyncImage(url: URL(string: value), transaction: Transaction(animation: .spring())) { phase in
                                        switch phase {
                                        case .empty:
                                            Color.purple.opacity(0.1)

                                        case .success(let image):
                                            image
                                                .resizable()
                                                .scaledToFill()

                                        case .failure(_):
                                            Image(systemName: "exclamationmark.icloud")
                                                .resizable()
                                                .scaledToFit()

                                        @unknown default:
                                            Image(systemName: "exclamationmark.icloud")
                                        }
                                    }
                                    .frame(width: 100, height: 100)
                                    .cornerRadius(20)
</code>```

答:
You have a few problems with the code. First of all, the original view that creates the view model, or has created for it originally, should own the object. Therefore you declare it as a @StateObject.

```<code>struct StyleBoardView: View {

    @State private var showingSheet = false
    @StateObject var model = ApiModel() // @StateObject here
    @State var styleboardname = ""

    let userEmail = Auth.auth().currentUser?.email

    var body: some View {
        NavigationView {
            VStack {
                Text("Select Style Board")
                List ($model.list) { $item in // Change this to pass a Binding
                    Button(item.styleboardname) {
                        showingSheet.toggle()
                    }
                    .sheet(isPresented: $showingSheet) {
                        GridView(item: $item, model: model)
                    }
                }
            }
        }
    }
}
</code>```

Since you are passing to a .sheet, that will not automatically be re-rendered when StyleBoardView's model changes, so you have to use a @Binding to cause GridView to re-render. Lastly, once you have your @StateObject, you pass that to your next view. Otherwise, you continually make new models, so updates to one will not update the other.

```<code>struct GridView: View {
    @Binding var item: Todo // Make this a @Binding so it reacts to the changes.
    @ObservedObject var model: ApiModel // Pass the originally created view model in.

    ...

    var body: some View {
        NavigationView {
            ...
        }
    }
}
</code>```

Lastly, you did not post a Minimal, Reproducible Example (MRE). You also did not post the complete GridView struct. You may not even need your view model in that view as you do not use it in what you have posted.

Body:
I am very new to swift working on my first app and having trouble having a view update. I am passing an object into a new view, however the new view does not update when there is change in the Firebase Database. Is there a way to get updates on the Gridview? I though by passing the observed object from the StyleboardView it would update the GridView however Gridview does not update. I am having trouble finding a way for the new Gridview to update and reload the images.

struct StyleBoardView: View {

@State private var showingSheet = false
@ObservedObject var model = ApiModel()
@State var styleboardname = ""

let userEmail = Auth.auth().currentUser?.email

var body: some View {
    NavigationView {
        VStack {
            Text("Select Style Board")
            List (model.list) {item in
                Button(item.styleboardname) {
                            showingSheet.toggle()
                        }
                        .sheet(isPresented: $showingSheet) {
                            GridView(item: item)
                        }
            }

struct GridView: View {
var item: Todo
@ObservedObject var model = ApiModel()
@State var newImage = ""
@State var loc = ""
@State var shouldShowImagePicker = false
@State var image: UIImage?

var body: some View {
    NavigationView {
        var posts = item.styleboardimages

        VStack(alignment: .leading){
            Text(item.styleboardname)
                    GeometryReader{ geo in
                        LazyVGrid(columns: [
                            GridItem(.flexible()),
                            GridItem(.flexible()),
                            GridItem(.flexible())
                        ], spacing: 3 ){
                            ForEach(posts.sorted(by: <), id: \.key) { key, value in
                                if #available(iOS 15.0, *) {
                                    AsyncImage(url: URL(string: value), transaction: Transaction(animation: .spring())) { phase in
                                        switch phase {
                                        case .empty:
                                            Color.purple.opacity(0.1)

                                        case .success(let image):
                                            image
                                                .resizable()
                                                .scaledToFill()

                                        case .failure(_):
                                            Image(systemName: "exclamationmark.icloud")
                                                .resizable()
                                                .scaledToFit()

                                        @unknown default:
                                            Image(systemName: "exclamationmark.icloud")
                                        }
                                    }
                                    .frame(width: 100, height: 100)
                                    .cornerRadius(20)

Body:
You have a few problems with the code. First of all, the original view that creates the view model, or has created for it originally, should own the object. Therefore you declare it as a @StateObject.

struct StyleBoardView: View {

    @State private var showingSheet = false
    @StateObject var model = ApiModel() // @StateObject here
    @State var styleboardname = ""

    let userEmail = Auth.auth().currentUser?.email

    var body: some View {
        NavigationView {
            VStack {
                Text("Select Style Board")
                List ($model.list) { $item in // Change this to pass a Binding
                    Button(item.styleboardname) {
                        showingSheet.toggle()
                    }
                    .sheet(isPresented: $showingSheet) {
                        GridView(item: $item, model: model)
                    }
                }
            }
        }
    }
}

Since you are passing to a .sheet, that will not automatically be re-rendered when StyleBoardView's model changes, so you have to use a @Binding to cause GridView to re-render. Lastly, once you have your @StateObject, you pass that to your next view. Otherwise, you continually make new models, so updates to one will not update the other.

struct GridView: View {
    @Binding var item: Todo // Make this a @Binding so it reacts to the changes.
    @ObservedObject var model: ApiModel // Pass the originally created view model in.

    ...

    var body: some View {
        NavigationView {
            ...
        }
    }
}

Lastly, you did not post a Minimal, Reproducible Example (MRE). You also did not post the complete GridView struct. You may not even need your view model in that view as you do not use it in what you have posted.


问:
PHP 8.1.1 issue with __toString() Method - causing Class not found if instance created before declaration of class itself
I have an issue after upgrade from PHP 7.3 to 8.1.1
There is lot to be done of course, but this is kind of weird.
This example is not working for me with error Fatal error:

Uncaught Error: Class "TestC" not found in
C:\xampp81\htdocs\helpdesk811\test81\index.php:2 Stack trace: #0
{main} thrown in C:\xampp81\htdocs\helpdesk811\test81\index.php on
line 2

```<code><?php
$a = new TestC;
echo $a->a;
class TestC
{
    public $a = "a_value";
    public $b;
    public function __toString()
    {
        return "string";
    }
}
</code>```

If I define class and create instance later, it works, but I was not able to find any documentation for this behavior.It's the same with static method (public static function foo(){echo "bar";}).

I tried 3v4l.org sandbox and it works in versions >5.0 && <8.0

答:
You can use a class before defining it, but only if early binding is allowed. Early binding does not work if some dependencies are not available yet, if the class uses traits or if it implements an interface. Since PHP 8 there is a new Stringable interface and every class that defines the __toString() function implicitly implements that interface, thus preventing early binding.

Nikita Popov (nikic) wrote an article about Early binding in PHP in which he mentions that this behavior is indeed not well documented.

Body:
I have an issue after upgrade from PHP 7.3 to 8.1.1
There is lot to be done of course, but this is kind of weird.
This example is not working for me with error Fatal error:

Uncaught Error: Class "TestC" not found in
C:\xampp81\htdocs\helpdesk811\test81\index.php:2 Stack trace: #0
{main} thrown in C:\xampp81\htdocs\helpdesk811\test81\index.php on
line 2

<?php
$a = new TestC;
echo $a->a;
class TestC
{
    public $a = "a_value";
    public $b;
    public function __toString()
    {
        return "string";
    }
}

If I define class and create instance later, it works, but I was not able to find any documentation for this behavior.It's the same with static method (public static function foo(){echo "bar";}).

I tried 3v4l.org sandbox and it works in versions >5.0 && <8.0


问:
AnimatedContainer onTap animate once forward and back
https://api.flutter.dev/flutter/widgets/AnimatedContainer-class.html

The example flutter.dev takes one tap to animate to a different look, and one tap to animate back to the original.
I was wondering, what if I want it to animate once forward, hold one second, and then backwards on one tap. Can I use a Timer to achieve this or should I be using AnimationController instead?

答:
AnimatedContainer provides onEnd, you can revese the animation from it.

child: AnimatedContainer(
  onEnd: () async {
    await Future.delayed(Duration(seconds: 1));
    setState(() {
      selected = false;
    });
  },
```

Also, you can use AnimationController with listener.

Body:
AnimatedContainer provides onEnd, you can revese the animation from it.

child: AnimatedContainer(
  onEnd: () async {
    await Future.delayed(Duration(seconds: 1));
    setState(() {
      selected = false;
    });
  },

Also, you can use AnimationController with listener.


问:
Verifying resources in a deployment yaml
In a deployment yaml, how we can verify that the resources we need for the running pods are guaranteed by the k8s?

Is there a way to figure that out?

答:
Specify your resource request in the deployment YAML. The kube-scheduler will ensure the resources even before scheduling the pods.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: frontend
spec:
  selector:
    matchLabels:
      app: guestbook
      tier: frontend
  replicas: 3
  template:
    metadata:
      labels:
        app: guestbook
        tier: frontend
    spec:
      containers:
      - name: php-redis
        image: gcr.io/google-samples/gb-frontend:v4
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
```

How Pods with resource requests are scheduled? Ref

When you create a Pod, the Kubernetes scheduler selects a node for the Pod to run on. Each node has a maximum capacity for each of the resource types: the amount of CPU and memory it can provide for Pods. The scheduler ensures that, for each resource type, the sum of the resource requests of the scheduled Containers is less than the capacity of the node. Note that although actual memory or CPU resource usage on nodes is very low, the scheduler still refuses to place a Pod on a node if the capacity check fails. This protects against a resource shortage on a node when resource usage later increases, for example, during a daily peak in request rate.

N.B.: However, if you want a container not to use more than its allowed resources, specify the limit too.

Body:
Specify your resource request in the deployment YAML. The kube-scheduler will ensure the resources even before scheduling the pods.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: frontend
spec:
  selector:
    matchLabels:
      app: guestbook
      tier: frontend
  replicas: 3
  template:
    metadata:
      labels:
        app: guestbook
        tier: frontend
    spec:
      containers:
      - name: php-redis
        image: gcr.io/google-samples/gb-frontend:v4
        resources:
          requests:
            cpu: 100m
            memory: 100Mi

How Pods with resource requests are scheduled? Ref

When you create a Pod, the Kubernetes scheduler selects a node for the Pod to run on. Each node has a maximum capacity for each of the resource types: the amount of CPU and memory it can provide for Pods. The scheduler ensures that, for each resource type, the sum of the resource requests of the scheduled Containers is less than the capacity of the node. Note that although actual memory or CPU resource usage on nodes is very low, the scheduler still refuses to place a Pod on a node if the capacity check fails. This protects against a resource shortage on a node when resource usage later increases, for example, during a daily peak in request rate.

N.B.: However, if you want a container not to use more than its allowed resources, specify the limit too.


问:
I cant make my bot go online and it shows TypeError [CLIENT_MISSING_INTENTS] (vscode)

const Discord = require("discord.js");
const Bot = new Discord.Client({Intents:[Discord.Intents.FLAGS.GUILD_MEMBERS, Discord.Intents.FLAGS.GUILDS]})

Bot.on('ready', () => {
    console.log("The bot is online")

    let commands = Bot.application.commands;

    commands.create({
        name: "hello" ,
        description: "reply hello to the user",
        options: [
            {
                name: "person",
                description: "The user you want to say hello to",
                require: true,
                type: Discord.Constants.ApplicationCommandOptionTypes.USER

            }
        ]
    })
 })

    Bot.on('interactionCreate', interaction => {
     if(!interaction.isCommand()) return;
     let name  = interaction.commandName
     let options = interaction.options;

     if(name == "hello") {
        interaction.reply({
            content: "Hello",
            ephemeral: false
        })
    }
    if(name == "sayhello"){
        let user = options.getUser('person');

        interaction.reply({
            content: 'Hello ${user.username}
        })
    }
})

bot.login("token")
```

答:
Well actually since the new discord.js update you need to provide the intents to the bot. This might help</p>
```<code>const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
</code>```

Body:
Well actually since the new discord.js update you need to provide the intents to the bot. This might help

const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });


问:
can some one please verify mistakes
suppose I have a line  -

```<code>NM1*85*2*NIVE HEALTH PHARMA, P.C. 428*****XX*1679857825~
</code>```

and from this I want to extract 1679857825 and append it to make a new column name df['npi']
and for that I am writing code -

```<code>if 'NM1*85*' in line and (line.split('NM1*85*')[1].split('*')[7][-9:].strip('~')[:5]).isnumeric() and (line.split('NM1*85*')[1].split('*')[7][0:9]).isnumeric():
    row['NPI'] = (line.split('NM1*85*')[1].split('*')[7].translate({ord('~'):None}))
    claims_yos.append(row)
</code>```

but my output is coming 0 where as it should be 1679857825. can some one verify the mistakes

答:
You could use a trivial regular expression as follows:

```<code>import re
my_string = 'NM1*85*2*NIVE HEALTH PHARMA, P.C. 428*****XX*1679857825~'
fa = re.findall(r'(\d+)', my_string)
print(fa[-1])
</code>```

Output:

```<code>1679857825
</code>```

Title: can some one please verify mistakes

Body:
suppose I have a line  -

NM1*85*2*NIVE HEALTH PHARMA, P.C. 428*****XX*1679857825~

and from this I want to extract 1679857825 and append it to make a new column name df['npi']
and for that I am writing code -

if 'NM1*85*' in line and (line.split('NM1*85*')[1].split('*')[7][-9:].strip('~')[:5]).isnumeric() and (line.split('NM1*85*')[1].split('*')[7][0:9]).isnumeric():
    row['NPI'] = (line.split('NM1*85*')[1].split('*')[7].translate({ord('~'):None}))
    claims_yos.append(row)

but my output is coming 0 where as it should be 1679857825. can some one verify the mistakes

Body:
You could use a trivial regular expression as follows:

import re
my_string = 'NM1*85*2*NIVE HEALTH PHARMA, P.C. 428*****XX*1679857825~'
fa = re.findall(r'(\d+)', my_string)
print(fa[-1])

Output:

1679857825


答:
SELECT t1.id, CAST(t1.json_field AS CHAR), t2.id, t2.name
FROM t1
JOIN t2 ON JSON_OVERLAPS(t1.json_field, CAST(t2.id AS JSON))
WHERE t2.name = 'sam'
```

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=6d065e49643b04d4630f0031096aa4ee

Title: MySQL JSON_OVERLAPS ... how do I compare json from one table to a group of ID values from another table?

Body:
SELECT t1.id, CAST(t1.json_field AS CHAR), t2.id, t2.name
FROM t1
JOIN t2 ON JSON_OVERLAPS(t1.json_field, CAST(t2.id AS JSON))
WHERE t2.name = 'sam'

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=6d065e49643b04d4630f0031096aa4ee


问:
PHP Print statement works only in Firefox
The site is built in drupal. The following code calls some data for the page:

```<code><span class="bold caps">Length: </span><?php print $node->field_length[0]['view'];?>
</code>```

The right information shows up when viewing the page in Firefox but that's it. Chrome, IE & Safari are all missing the info. The rendered HTML is fine but for the lack of the right data coming through.

Here is a link to the page in question

Any ideas?

答:
PHP doesn't randomly decide to NOT output something based on the browser that's requesting the page. The choice of browser can NOT affect how PHP runs a piece of code. However, the choice of browser CAN affect the data that is sent to the script as input, which can affect how the script runs.

So check what the differences are between what FF sends to your script against what the other browsers are sending.

ContentLicense: CC BY-SA 3.0

Body:
The site is built in drupal. The following code calls some data for the page:

Length: <?php print $node->field_length[0]['view'];?>

The right information shows up when viewing the page in Firefox but that's it. Chrome, IE & Safari are all missing the info. The rendered HTML is fine but for the lack of the right data coming through.

Here is a link to the page in question

Any ideas?


问:
How is Apache Zookeeper used in sharding?
We are thinking of centralizing cfg information and looks like zookeeper is a good choice. We are also interested in sharding and have a scheme. In the poweredBy[1] saw that Rackspace and Yahoo is using Zookeeper for sharding. Would appreciate pointers and details.</p>

<p>[1] https://cwiki.apache.org/confluence/display/ZOOKEEPER/PoweredBy  </p>

答:
For managing the lookup table .
Since this lookup table have to be strong consistent, this is where zookeeper comes into picture.</p>

Body:
We are thinking of centralizing cfg information and looks like zookeeper is a good choice. We are also interested in sharding and have a scheme. In the poweredBy[1] saw that Rackspace and Yahoo is using Zookeeper for sharding. Would appreciate pointers and details.

[1] https://cwiki.apache.org/confluence/display/ZOOKEEPER/PoweredBy


问:
Pass value to a NestJS service
In my NestJS app, I have a service that is used for performing HTTP requests with a vendor (acting as a client library for that vendor). The service needs an API key, which is available as an env var VENDOR_API_KEY.

For unit tests, I want to use another, hardcoded value for the API key - instead of taking it from VENDOR_API_KEY.

What is the idiomatic way of doing it? All of the options given in https://docs.nestjs.com/fundamentals/custom-providers seem like overkill.

I might be missing something obvious because I'm new to NestJS.

答:
Sounds like you'd need a very simple custom provider. Something as quick as

@Module({
  providers: [
    ServiceToBeUsed,
    {
      provide: 'API_KEY',
      useValue: process.env.VENDOR_API_KEY, //you could also use a factory and inject the config service
    }
  ]
})
export class SomeModule {}
```

And now you can use @Inject('API_KEY') private readonly apiKey: string in your service's constructor

Title: Pass value to a NestJS service

Body:
Sounds like you'd need a very simple custom provider. Something as quick as

@Module({
  providers: [
    ServiceToBeUsed,
    {
      provide: 'API_KEY',
      useValue: process.env.VENDOR_API_KEY, //you could also use a factory and inject the config service
    }
  ]
})
export class SomeModule {}

And now you can use @Inject('API_KEY') private readonly apiKey: string in your service's constructor


问:
Playwright intercept server side network request
Can't see to find any good docs on how to mock/stub the server Sider side requests with playwright.

An example would be to intercept the getServerSideProps in nextjs: hitting the routes makes the server do a request (db API etc). Then it can do some business logic (which should also be covered by testing) before it is passed to the component as props which is sent to the client (being server side rendered).

Mocking that db API request without having some test logic mixed into the business logic is what I am hoping to find an answer for.

答:
Playwright allows you to do interception and mocking/stubbing.
UI action can triger the API call, and without sending request you can intercept
the response.

And you can use moks and stubs as well.

```<code>const mock = { animals: [] }

await page.route('**/Zoo/v1/books', (animals) =>
    route.fulfill({
        status: 304,
        body: JSON.stringify(mock),
    })),
);

await page.goto('https://www.demoqa/animals');
</code>```

See more https://github.com/microsoft/playwright/issues/1774#issuecomment-769247500

And https://playwright.dev/docs/next/network#modify-responses

Body:
Playwright allows you to do interception and mocking/stubbing.
UI action can triger the API call, and without sending request you can intercept
the response.

And you can use moks and stubs as well.

const mock = { animals: [] }

await page.route('**/Zoo/v1/books', (animals) =>
    route.fulfill({
        status: 304,
        body: JSON.stringify(mock),
    })),
);

await page.goto('https://www.demoqa/animals');

See more https://github.com/microsoft/playwright/issues/1774#issuecomment-769247500

And https://playwright.dev/docs/next/network#modify-responses


问:
Does the routing paths order matter in angular?
I'm trying to make a router for one of my components, but it is not working as expected.

Initially it was working fine, but I had to add another route to decide which mat-tab would be open when redirecting. I added the second route like that, but for some reason the third one stopped working even though the first two were working fine.

```<code>import { Routes } from '@angular/router';
import { ActionComponent } from './action.component';
import { ActionResolver } from './action.resolver';
import { ACTION_RESULT_ROUTES } from './result/action-result.routes';

export const ACTION_ROUTES: Routes = [
  { path: ':id', component: ActionComponent, resolve: { action: ActionResolver } },
  { path: ':id/:tab', component: ActionComponent, resolve: { action: ActionResolver } },
  {
    path: 'action-result',
    children: ACTION_RESULT_ROUTES,
  },
];
</code>```

I got a pretty large error when trying the third route, but it starts like this:

ERROR Error: Uncaught (in promise): TypeError: You provided 'null' where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.

Just in case, I tried to reorder it and all three were working fine when I did it like this:

```<code>export const ACTION_ROUTES: Routes = [
  { path: ':id', component: ActionComponent, resolve: { action: ActionResolver } },
  {
    path: 'action-result',
    children: ACTION_RESULT_ROUTES,
  },
  { path: ':id/:tab', component: ActionComponent, resolve: { action: ActionResolver } },
];
</code>```

Can anyone tell me why it works like that?

Edit: Added the ACTION_RESULT_ROUTES for clarification

```<code>export const ACTION_RESULT_ROUTES: Routes = [
  { path: ':id', component: ActionResultComponent, resolve: { result: ActionResultResolver } },
];
</code>```

答:
According to Angular:

"The order of routes is important because the Router uses a
first-match wins strategy when matching routes, so more specific
routes should be placed above less specific routes."

It is recommended to have static routes first, therefore your action-result path should go first, followed by the :id/:tab path then :id path last. If you have a wildcard route, it should always be the last route in your array.

The reason behind this logic is that if you had the :id path above the action-result path, angular would use the word 'action-result' as the id in the :id path.
Similarly if you had the :id path above the :id/:tab path, angular would use the words id/tab as the id in the :id path.

So, a rule of thumb is to always put your static routes first, then your dynamic routes from the most specific to the least specific followed by your wildcard route at the end.
E. G.

PATH1

PATH2

PATH3/:USER/:ROLE/:PAGE

PATH4/:SITE/:ID

PATH5:/ID

Wildcard route (*)

Body:
I'm trying to make a router for one of my components, but it is not working as expected.

Initially it was working fine, but I had to add another route to decide which mat-tab would be open when redirecting. I added the second route like that, but for some reason the third one stopped working even though the first two were working fine.

import { Routes } from '@angular/router';
import { ActionComponent } from './action.component';
import { ActionResolver } from './action.resolver';
import { ACTION_RESULT_ROUTES } from './result/action-result.routes';

export const ACTION_ROUTES: Routes = [
  { path: ':id', component: ActionComponent, resolve: { action: ActionResolver } },
  { path: ':id/:tab', component: ActionComponent, resolve: { action: ActionResolver } },
  {
    path: 'action-result',
    children: ACTION_RESULT_ROUTES,
  },
];

I got a pretty large error when trying the third route, but it starts like this:

ERROR Error: Uncaught (in promise): TypeError: You provided 'null' where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.

Just in case, I tried to reorder it and all three were working fine when I did it like this:

export const ACTION_ROUTES: Routes = [
  { path: ':id', component: ActionComponent, resolve: { action: ActionResolver } },
  {
    path: 'action-result',
    children: ACTION_RESULT_ROUTES,
  },
  { path: ':id/:tab', component: ActionComponent, resolve: { action: ActionResolver } },
];

Can anyone tell me why it works like that?

Edit: Added the ACTION_RESULT_ROUTES for clarification

export const ACTION_RESULT_ROUTES: Routes = [
  { path: ':id', component: ActionResultComponent, resolve: { result: ActionResultResolver } },
];


问:
How to Reorder/Move certain elements in an array to the initial indexes based on a Boolean variable in JavaScript
Is there any way to filter this below array such that, the objects which has isTop:true has to be on the initial indexes of the array.
Actual Array:

```<code>[{id:'1',name:'CAR',isTop:false},
{id:'2',name:'BIKE',isTop:true},
{id:'3',name:'TRUCK',isTop:false},
{id:'4',name:'BUS',isTop:false},
{id:'5',name:'VAN',isTop:true},
{id:'6',name:'TRAIN',isTop:false}]
</code>```

Result Array I need:

```<code>[{id:'2',name:'BIKE',isTop:true},
{id:'5',name:'VAN',isTop:true},
{id:'3',name:'TRUCK',isTop:false},
{id:'4',name:'BUS',isTop:false},
{id:'1',name:'CAR',isTop:false},
{id:'6',name:'TRAIN',isTop:false}]
</code>```

答:
You could use array.sort.

In my solution, you could use the idea of true - false = 1 to do the sort

let array = [{id:'1',name:'CAR',isTop:false},
{id:'2',name:'BIKE',isTop:true},
{id:'3',name:'TRUCK',isTop:false},
{id:'4',name:'BUS',isTop:false},
{id:'5',name:'VAN',isTop:true},
{id:'6',name:'TRAIN',isTop:false}]

    array.sort((x, y) =>(y.isTop-x.isTop))
    console.log(array)```

Body:
Is there any way to filter this below array such that, the objects which has isTop:true has to be on the initial indexes of the array.
Actual Array:

[{id:'1',name:'CAR',isTop:false},
{id:'2',name:'BIKE',isTop:true},
{id:'3',name:'TRUCK',isTop:false},
{id:'4',name:'BUS',isTop:false},
{id:'5',name:'VAN',isTop:true},
{id:'6',name:'TRAIN',isTop:false}]

Result Array I need:

[{id:'2',name:'BIKE',isTop:true},
{id:'5',name:'VAN',isTop:true},
{id:'3',name:'TRUCK',isTop:false},
{id:'4',name:'BUS',isTop:false},
{id:'1',name:'CAR',isTop:false},
{id:'6',name:'TRAIN',isTop:false}]


问:
(api) .htaccess rewriting for /backend and /frontend folders
I'm trying to host a nuxt + symfony project, and I'm kind of stuck here.

I suppose what I need is some .htaccess rewriting.

I have 2 separate folders :

```<code>/
- /backend, which is basically my symfony folder.
- /frontend, containing my nuxt app.
</code>```

I would need to redirect all of the requests that do not contain "/api" to the /frontend folder, and all requests containing "/api" to "/backend/".

Example :

mydomain.com/articles/5 would redirect to mydomain.com/frontend/articles/5

mydomain.com/api/article/5 would redirect to mydomain.com/backend/article/5

Any help would be really useful,

thank you.

答:
Assuming you have additional .htaccess files in the /frontend and /backend subdirectories that also use mod_rewrite to route the URL then you could do something like the following in the root .htaccess file:

```<code>RewriteEngine On

# Rewrite "/api/<something>` to backend
RewriteRule ^api/(.*) backend/$1 [L]

# Everything else rewritten to frontend
RewriteRule (.*) frontend/$1 [L]
</code>```

Body:
I'm trying to host a nuxt + symfony project, and I'm kind of stuck here.

I suppose what I need is some .htaccess rewriting.

I have 2 separate folders :

/
- /backend, which is basically my symfony folder.
- /frontend, containing my nuxt app.

I would need to redirect all of the requests that do not contain "/api" to the /frontend folder, and all requests containing "/api" to "/backend/".

Example :

mydomain.com/articles/5 would redirect to mydomain.com/frontend/articles/5

mydomain.com/api/article/5 would redirect to mydomain.com/backend/article/5

Any help would be really useful,

thank you.

Body:
Assuming you have additional .htaccess files in the /frontend and /backend subdirectories that also use mod_rewrite to route the URL then you could do something like the following in the root .htaccess file:

RewriteEngine On

# Rewrite "/api/<something>` to backend
RewriteRule ^api/(.*) backend/$1 [L]

# Everything else rewritten to frontend
RewriteRule (.*) frontend/$1 [L]


问:
Remove "::before" — CSS

Currently heading of my blogpost on blogger looks like this. So I wanted to remove this "-" like looking element from my blog, which is a ::before. I tried this advice here and used a little ingenuity to added a CSS like so:

div.post-body-container::before{
    content: none;
}
```

And some other variations of the same. Where am I going wrong here?

This is my blog btw if it is needed on which I'm using Soho Neon theme.

答:
You are using a least specified selector.

In your CSS, the selector used to add the "-" is body.item-view .post-body-container::before, so with only div.post-body-container::before you will not be able to modify the rule.

You must use a more specific selector or remove it with a different rule (aka display: none).

PS: the same selector placed after will do it

body.item-view .post-body-container::before {
    content: none;
}

/* or */

.post-body-container::before {
    display: none;
}
```

Title: Remove "::before" — CSS

Body:
Currently heading of my blogpost on blogger looks like this. So I wanted to remove this "-" like looking element from my blog, which is a ::before. I tried this advice here and used a little ingenuity to added a CSS like so:

div.post-body-container::before{
    content: none;
}

And some other variations of the same. Where am I going wrong here?

This is my blog btw if it is needed on which I'm using Soho Neon theme.


问:
check if first two letter (digits) in a ip adress is '41' with PHP?
I use PHP:s ['REMOTE_ADDR'] to fetch the users ip.

I want to see if that ip starts with a 41.

```<code>$usr_ip = $_SERVER['REMOTE_ADDR'];
</code>```

Then I want to match, and if it starts with 41, then die()

I don't know how to do the matching.

答:
```<code>if(substr($_SERVER['REMOTE_ADDR'],0,2)=="41") die();
</code>```

regex is overkill here

Body:
I use PHP:s ['REMOTE_ADDR'] to fetch the users ip.

I want to see if that ip starts with a 41.

$usr_ip = $_SERVER['REMOTE_ADDR'];

Then I want to match, and if it starts with 41, then die()

I don't know how to do the matching.

Body:
if(substr($_SERVER['REMOTE_ADDR'],0,2)=="41") die();

regex is overkill here


问:
how to convert from fopen to open when trying to open a .data file?
```<code>FILE *inFile = fopen("dataFlow.dat", "r"); // read only
FILE *outFile = fopen("report.dat", "w"); // write only
</code>```

答:
Tag: linux

```<code>FILE *inFile = fopen("dataFlow.dat", "r"); // read only
FILE *outFile = fopen("report.dat", "w"); // write only
</code>```
```<code>int inFile = open("dataFlow.dat", O_RDONLY); // read only
int outFile = open("report.dat", O_WRONLY | O_CREAT, 0666); // write only
</code>```

Open is a weird function; if the call cannot create a file it takes two arguments, but if it can create a file it takes three arguments. The third argument is 0666 until proven otherwise; umask will be applied.

The return can't be passed to stdio functions except fdopen but can be used directly using read(), write(), lseek(), and close().

The return of open is a integer file handle or -1 for error.

(Posted answer while chqrle's answer was very wrong. He's proceeding to fix.)

Body:
Tag: linux

FILE *inFile = fopen("dataFlow.dat", "r"); // read only
FILE *outFile = fopen("report.dat", "w"); // write only

int inFile = open("dataFlow.dat", O_RDONLY); // read only
int outFile = open("report.dat", O_WRONLY | O_CREAT, 0666); // write only

Open is a weird function; if the call cannot create a file it takes two arguments, but if it can create a file it takes three arguments. The third argument is 0666 until proven otherwise; umask will be applied.

The return can't be passed to stdio functions except fdopen but can be used directly using read(), write(), lseek(), and close().

The return of open is a integer file handle or -1 for error.

(Posted answer while chqrle's answer was very wrong. He's proceeding to fix.)


问:
How to stream and save web camera video via a server?
My scenario is as follows.

I have three computers A, B, C. Device A has a webcam. I want to stream and save the video from A to device B. At the same time, I want to watch the live video on C (from B).

I successfully managed to do the first part (saving video from A to B). But could not compete with the later part (watching live video on C).

Following are the codes that I used to build the client (on A) and server (on B) respectively.

# Client part - Device A

import cv2
import numpy as np
import socket
import sys
import pickle
import struct

cap=cv2.VideoCapture(0)
clientsocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientsocket.connect(('your_real_IP_address',8089))

while True:
    ret,frame=cap.read()
    data = pickle.dumps(frame)

    message_size = struct.pack("L", len(data))

    clientsocket.sendall(message_size + data)
```
<pre class="lang-python prettyprint-override"><code># Server part - Device B

import pickle
import socket
import struct
import cv2

HOST = ''
PORT = 8089

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')

s.bind((HOST, PORT))
print('Socket bind complete')
s.listen(10)
print('Socket now listening')

conn, addr = s.accept()

data = b''
payload_size = struct.calcsize("Q")

result = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'MJPG'), 5, (640, 480))
while True:

    while len(data) < payload_size:
        data += conn.recv(8192)

    packed_msg_size = data[:payload_size]
    data = data[payload_size:]
    msg_size = struct.unpack("Q", packed_msg_size)[0]

    while len(data) < msg_size:
        data += conn.recv(8192)

    frame_data = data[:msg_size]
    data = data[msg_size:]

    frame = pickle.loads(frame_data)

    result.write(frame)

    if cv2.waitKey(1) & 0xFF == ord('s'):
        break

cv2.destroyAllWindows()

print("The video si successfully saved")
</code>```

For the later part, I tried to run the following code on device C to fetch the live video from B (while it is getting saved). But I did not succeed. Can anyone please help me to fix this problem?

import socket
import pickle
import struct
import cv2

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_ip = 'you_real_IP_address'  # paste your server ip address here
port = 8090
client_socket.connect((host_ip, port))
data = b""
payload_size = struct.calcsize("L")

while True:
    while len(data) < payload_size:
        packet = client_socket.recv(8192)
        if not packet: break
        data += packet # append the data packet got from server into data variable
    packed_msg_size = data[:payload_size] #will find the packed message size i.e. 8 byte, we packed on server side.
    data = data[payload_size:] # Actual frame data
    msg_size = struct.unpack("Q", packed_msg_size)[0] # meassage size
    # print(msg_size)

    while len(data) < msg_size:
        data += client_socket.recv(8192) # will receive all frame data from client socket
    frame_data = data[:msg_size] #recover actual frame data
    data = data[msg_size:]
    frame = pickle.loads(frame_data) # de-serialize bytes into actual frame type
    cv2.imshow("RECEIVING VIDEO", frame) # show video frame at client side
    key = cv2.waitKey(1) & 0xFF
    if key == ord('q'): # press q to exit video
        break

client_socket.close()
```

答:
You may use gstreamer for streaming. This answer assumes that you have gstreamer installed on A, B and C and opencv built with gstreamer support as well (at least on B).

Also note that streaming in raw mode may not be the most efficient way, but the following follows your description.

For A, the hard part is that you didn't give any details about your camera. Assuming it has a native mode of 640x480@30 fps, A code could be:

```<code>#!/usr/bin/env python

import time
import cv2

while True:

    while True:
       cap = cv2.VideoCapture("v4l2src device=/dev/video0 ! video/x-raw,width=640,height=480,framerate=30/1 ! videoconvert ! video/x-raw,format=BGR ! queue ! appsink drop=1", cv2.CAP_GSTREAMER)
       if cap.isOpened():
           print('Cam opened')
           break
       print('Waiting for camera')
       time.sleep(1)

    writer = cv2.VideoWriter("appsrc ! queue ! multipartmux ! tcpserversink port=8089 ", cv2.CAP_GSTREAMER, 0, 30.0, (640,480))
    if not writer.isOpened():
        print('Error: failed to open Writer')
        exit()
    print('Streaming camera')

    while True:
       ret_val, img = cap.read();
       if not ret_val:
          print('Failed to read from camera')
          break

       writer.write(img);
       cv2.waitKey(1)

    writer.release()
    cap.release()
</code>```

If you don't have opencv build with gstreamer support and don't need to do any processing, you can avoid opencv application and just run from shell:

```<code>gst-launch-1.0 v4l2src device=/dev/video0 ! video/x-raw,width=640,height=480,framerate=30/1 ! videoconvert ! video/x-raw,format=BGR ! multipartmux ! tcpserversink port=8089
</code>```

For B:

```<code>#!/usr/bin/env python

import time
import cv2

while True:

    while True:
        cap = cv2.VideoCapture("tcpclientsrc host=<IP_of_A> port=8089 ! multipartdemux ! video/x-raw,format=BGR, width=640, height=480, framerate=30/1 ! queue ! appsink drop=1", cv2.CAP_GSTREAMER)
        if cap.isOpened():
            print('Cam stream opened')
            break
        print('Waiting for camera')
        time.sleep(1)

    writer = cv2.VideoWriter("appsrc ! video/x-raw,format=BGR,width=640, height=480, framerate=30/1  ! queue ! videoconvert ! video/x-raw,format=I420 ! tee name=t ! queue ! jpegenc ! avimux ! video/x-msvideo ! filesink location=test.avi    t. ! queue ! multipartmux ! tcpserversink port=8192 ", cv2.CAP_GSTREAMER, 0, 30.0, (640,480))
    if not writer.isOpened():
        print('Error: failed to open Writer')
        exit()
    print('writer opened')

    while True:
        ret_val, img = cap.read();
        if not ret_val:
            print('Failed to read from camera')
            break

        #cv2.imshow('Test', img)
        writer.write(img);
        cv2.waitKey(1)

    writer.release()
    cap.release()
    time.sleep(1)

</code>```

where <IP_of_A> is the IP address of A streaming the camera.
Note that the avi file will be overwritten after the source has disconnected/reconnected, you would have to manage file names for that.

For C:

```<code>#!/usr/bin/env python

import time
import cv2

while True:

    while True:
       cap = cv2.VideoCapture("tcpclientsrc host=<IP_of_B> port=8192 ! multipartdemux ! video/x-raw,format=I420, width=640, height=480, framerate=30/1 ! videoconvert ! video/x-raw,format=BGR ! queue ! appsink drop=1", cv2.CAP_GSTREAMER)
       if cap.isOpened():
           print('Stream opened')
           break
       print('Waiting for server')
       time.sleep(1)

    while True:
       ret_val, img = cap.read();
       if not ret_val:
          print('Failed to read from server')
          break

       cv2.imshow('Received', img)
       cv2.waitKey(1)

    cap.release()
    cv2.destroyAllWindows()
    time.sleep(1)

</code>```

where <IP_of_B> is the IP address of B.

If you don't have gstreamer support in opencv on C, you can just use :

```<code>gst-launch-1.0 tcpclientsrc host=<IP_of_B> port=8192 ! multipartdemux ! video/x-raw,format=I420, width=640, height=480, framerate=30/1 ! videoconvert ! xvimagesink
</code>```

EDIT: In case only B has static IP, you can have A code to send to tcpclientsink host=<IP_of_B> instead of tcpserversink. So B would use tcpserversrc instead of tcpclientsrc host=<IP_of_A>. The limitation is that cv writer write() function doesn't return any value that could help to detect a failure such as B server being down... The only way I see would be to use a script launching python script and checking its output to detect the warnings issued by gstreamer backend writer code and in such case kill the program and restart a new one.

Body:
My scenario is as follows.

I have three computers A, B, C. Device A has a webcam. I want to stream and save the video from A to device B. At the same time, I want to watch the live video on C (from B).

I successfully managed to do the first part (saving video from A to B). But could not compete with the later part (watching live video on C).

Following are the codes that I used to build the client (on A) and server (on B) respectively.

# Client part - Device A

import cv2
import numpy as np
import socket
import sys
import pickle
import struct

cap=cv2.VideoCapture(0)
clientsocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientsocket.connect(('your_real_IP_address',8089))

while True:
    ret,frame=cap.read()
    data = pickle.dumps(frame)

    message_size = struct.pack("L", len(data))

    clientsocket.sendall(message_size + data)

# Server part - Device B

import pickle
import socket
import struct
import cv2

HOST = ''
PORT = 8089

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')

s.bind((HOST, PORT))
print('Socket bind complete')
s.listen(10)
print('Socket now listening')

conn, addr = s.accept()

data = b''
payload_size = struct.calcsize("Q")

result = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'MJPG'), 5, (640, 480))
while True:

    while len(data) < payload_size:
        data += conn.recv(8192)

    packed_msg_size = data[:payload_size]
    data = data[payload_size:]
    msg_size = struct.unpack("Q", packed_msg_size)[0]

    while len(data) < msg_size:
        data += conn.recv(8192)

    frame_data = data[:msg_size]
    data = data[msg_size:]

    frame = pickle.loads(frame_data)

    result.write(frame)

    if cv2.waitKey(1) & 0xFF == ord('s'):
        break

cv2.destroyAllWindows()

print("The video si successfully saved")

For the later part, I tried to run the following code on device C to fetch the live video from B (while it is getting saved). But I did not succeed. Can anyone please help me to fix this problem?

import socket
import pickle
import struct
import cv2

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_ip = 'you_real_IP_address'  # paste your server ip address here
port = 8090
client_socket.connect((host_ip, port))
data = b""
payload_size = struct.calcsize("L")

while True:
    while len(data) < payload_size:
        packet = client_socket.recv(8192)
        if not packet: break
        data += packet # append the data packet got from server into data variable
    packed_msg_size = data[:payload_size] #will find the packed message size i.e. 8 byte, we packed on server side.
    data = data[payload_size:] # Actual frame data
    msg_size = struct.unpack("Q", packed_msg_size)[0] # meassage size
    # print(msg_size)

    while len(data) < msg_size:
        data += client_socket.recv(8192) # will receive all frame data from client socket
    frame_data = data[:msg_size] #recover actual frame data
    data = data[msg_size:]
    frame = pickle.loads(frame_data) # de-serialize bytes into actual frame type
    cv2.imshow("RECEIVING VIDEO", frame) # show video frame at client side
    key = cv2.waitKey(1) & 0xFF
    if key == ord('q'): # press q to exit video
        break

client_socket.close()

Body:
You may use gstreamer for streaming. This answer assumes that you have gstreamer installed on A, B and C and opencv built with gstreamer support as well (at least on B).

Also note that streaming in raw mode may not be the most efficient way, but the following follows your description.

For A, the hard part is that you didn't give any details about your camera. Assuming it has a native mode of 640x480@30 fps, A code could be:

#!/usr/bin/env python

import time
import cv2

while True:

    while True:
       cap = cv2.VideoCapture("v4l2src device=/dev/video0 ! video/x-raw,width=640,height=480,framerate=30/1 ! videoconvert ! video/x-raw,format=BGR ! queue ! appsink drop=1", cv2.CAP_GSTREAMER)
       if cap.isOpened():
           print('Cam opened')
           break
       print('Waiting for camera')
       time.sleep(1)

    writer = cv2.VideoWriter("appsrc ! queue ! multipartmux ! tcpserversink port=8089 ", cv2.CAP_GSTREAMER, 0, 30.0, (640,480))
    if not writer.isOpened():
        print('Error: failed to open Writer')
        exit()
    print('Streaming camera')

    while True:
       ret_val, img = cap.read();
       if not ret_val:
          print('Failed to read from camera')
          break

       writer.write(img);
       cv2.waitKey(1)

    writer.release()
    cap.release()

If you don't have opencv build with gstreamer support and don't need to do any processing, you can avoid opencv application and just run from shell:

gst-launch-1.0 v4l2src device=/dev/video0 ! video/x-raw,width=640,height=480,framerate=30/1 ! videoconvert ! video/x-raw,format=BGR ! multipartmux ! tcpserversink port=8089

For B:

#!/usr/bin/env python

import time
import cv2

while True:

    while True:
        cap = cv2.VideoCapture("tcpclientsrc host=<IP_of_A> port=8089 ! multipartdemux ! video/x-raw,format=BGR, width=640, height=480, framerate=30/1 ! queue ! appsink drop=1", cv2.CAP_GSTREAMER)
        if cap.isOpened():
            print('Cam stream opened')
            break
        print('Waiting for camera')
        time.sleep(1)

    writer = cv2.VideoWriter("appsrc ! video/x-raw,format=BGR,width=640, height=480, framerate=30/1  ! queue ! videoconvert ! video/x-raw,format=I420 ! tee name=t ! queue ! jpegenc ! avimux ! video/x-msvideo ! filesink location=test.avi    t. ! queue ! multipartmux ! tcpserversink port=8192 ", cv2.CAP_GSTREAMER, 0, 30.0, (640,480))
    if not writer.isOpened():
        print('Error: failed to open Writer')
        exit()
    print('writer opened')

    while True:
        ret_val, img = cap.read();
        if not ret_val:
            print('Failed to read from camera')
            break

        #cv2.imshow('Test', img)
        writer.write(img);
        cv2.waitKey(1)

    writer.release()
    cap.release()
    time.sleep(1)

where <IP_of_A> is the IP address of A streaming the camera.
Note that the avi file will be overwritten after the source has disconnected/reconnected, you would have to manage file names for that.

For C:

#!/usr/bin/env python

import time
import cv2

while True:

    while True:
       cap = cv2.VideoCapture("tcpclientsrc host=<IP_of_B> port=8192 ! multipartdemux ! video/x-raw,format=I420, width=640, height=480, framerate=30/1 ! videoconvert ! video/x-raw,format=BGR ! queue ! appsink drop=1", cv2.CAP_GSTREAMER)
       if cap.isOpened():
           print('Stream opened')
           break
       print('Waiting for server')
       time.sleep(1)

    while True:
       ret_val, img = cap.read();
       if not ret_val:
          print('Failed to read from server')
          break

       cv2.imshow('Received', img)
       cv2.waitKey(1)

    cap.release()
    cv2.destroyAllWindows()
    time.sleep(1)

where <IP_of_B> is the IP address of B.

If you don't have gstreamer support in opencv on C, you can just use :

gst-launch-1.0 tcpclientsrc host=<IP_of_B> port=8192 ! multipartdemux ! video/x-raw,format=I420, width=640, height=480, framerate=30/1 ! videoconvert ! xvimagesink

EDIT: In case only B has static IP, you can have A code to send to tcpclientsink host=<IP_of_B> instead of tcpserversink. So B would use tcpserversrc instead of tcpclientsrc host=<IP_of_A>. The limitation is that cv writer write() function doesn't return any value that could help to detect a failure such as B server being down... The only way I see would be to use a script launching python script and checking its output to detect the warnings issued by gstreamer backend writer code and in such case kill the program and restart a new one.


问:
Multidimensional dictionary comprehension
Say I have a dictionary like this:

```<code>d = {key1: [1,2,3], key2: [4,6,7]}
</code>```

If I want to have a dictionary which subtracts from the values the mean of the respective array I can do:

```<code>new_d = {key: x - np.mean(x) for (key,x) in d.items()}
</code>```

Now say my dictionary actually looks like this:

```<code>d = {key1: [[1,2,3], [10,100,1000]], key2: [[4,5,6], [11,12,16]]}
</code>```

How would dictionary comprehension work in this case?

The result should look like this:

```<code>new_d = {key1: [[-1, 0, 1], [-360, -270, 630]], key2: [[-1, 0, 1], [-2, -1, 3]]}
</code>```

Thanks for your help!

答:
Following from your 1D solution, you just need a nested list comprehension:

```<code>>>> {key: [y-np.mean(y) for y in x] for key,x in d.items()}
{'key1': [array([-1.,  0.,  1.]), array([-360., -270.,  630.])],
 'key2': [array([-1.,  0.,  1.]), array([-2., -1.,  3.])]}
</code>```

But if you want exactly the output you wrote using idiomatic NumPy, it's a bit different:

Specify int datatype

Take the mean across rows

Convert back to list

```<code>>>> {key: (x - np.mean(x, axis=1, keepdims=True, dtype='int')).tolist()
...  for key,x in d.items()}
{'key1': [[-1, 0, 1], [-360, -270, 630]],
 'key2': [[-1, 0, 1], [-2, -1, 3]]}
</code>```

Body:
Say I have a dictionary like this:

d = {key1: [1,2,3], key2: [4,6,7]}

If I want to have a dictionary which subtracts from the values the mean of the respective array I can do:

new_d = {key: x - np.mean(x) for (key,x) in d.items()}

Now say my dictionary actually looks like this:

d = {key1: [[1,2,3], [10,100,1000]], key2: [[4,5,6], [11,12,16]]}

How would dictionary comprehension work in this case?

The result should look like this:

new_d = {key1: [[-1, 0, 1], [-360, -270, 630]], key2: [[-1, 0, 1], [-2, -1, 3]]}

Thanks for your help!

Body:
Following from your 1D solution, you just need a nested list comprehension:

>>> {key: [y-np.mean(y) for y in x] for key,x in d.items()}
{'key1': [array([-1.,  0.,  1.]), array([-360., -270.,  630.])],
 'key2': [array([-1.,  0.,  1.]), array([-2., -1.,  3.])]}

But if you want exactly the output you wrote using idiomatic NumPy, it's a bit different:

Specify int datatype

Take the mean across rows

Convert back to list

>>> {key: (x - np.mean(x, axis=1, keepdims=True, dtype='int')).tolist()
...  for key,x in d.items()}
{'key1': [[-1, 0, 1], [-360, -270, 630]],
 'key2': [[-1, 0, 1], [-2, -1, 3]]}


问:
Replace only leading NaN values in Pandas dataframe
I have a dataframe of time series data, in which data reporting starts at different times (columns) for different observation units (rows). Prior to first reported datapoint for each unit, the dataframe contains NaN values, e.g.

```<code>    0   1   2   3   4 ...
A   NaN NaN 4   5   6 ...
B   NaN 7   8   NaN 10...
C   NaN 2   11  24  17...
</code>```

I want to replace the leading (left-side) NaN values with 0, but only the leading ones (i.e. leaving the internal missing ones as NaN. So the result on the example above would be:

```<code>    0   1   2   3   4 ...
A   0   0   4   5   6 ...
B   0   7   8   NaN 10...
C   0   2   11  24  17...
</code>```

(Note the retained NaN for row B col 3)

I could iterate through the dataframe row-by-row, identify the first index of a non-NaN value in each row, and replace everything left of that with 0. But is there a way to do this as a whole-array operation?

答:
notna + cumsum by rows, cells with zeros are leading NaN:

```<code>df[df.notna().cumsum(1) == 0] = 0

df
     0    1   2     3   4
A  0.0  0.0   4   5.0   6
B  0.0  7.0   8   NaN  10
C  0.0  2.0  11  24.0  17
</code>```

Body:
I have a dataframe of time series data, in which data reporting starts at different times (columns) for different observation units (rows). Prior to first reported datapoint for each unit, the dataframe contains NaN values, e.g.

    0   1   2   3   4 ...
A   NaN NaN 4   5   6 ...
B   NaN 7   8   NaN 10...
C   NaN 2   11  24  17...

I want to replace the leading (left-side) NaN values with 0, but only the leading ones (i.e. leaving the internal missing ones as NaN. So the result on the example above would be:

    0   1   2   3   4 ...
A   0   0   4   5   6 ...
B   0   7   8   NaN 10...
C   0   2   11  24  17...

(Note the retained NaN for row B col 3)

I could iterate through the dataframe row-by-row, identify the first index of a non-NaN value in each row, and replace everything left of that with 0. But is there a way to do this as a whole-array operation?

Body:
notna + cumsum by rows, cells with zeros are leading NaN:

df[df.notna().cumsum(1) == 0] = 0

df
     0    1   2     3   4
A  0.0  0.0   4   5.0   6
B  0.0  7.0   8   NaN  10
C  0.0  2.0  11  24.0  17


问:
Jquery toggle with position absolute bottom
I've got an absolute positioned container, which is bottom aligned.

Now I would like to toggle (show/hide) some content without the container getting larger than its contents -  and preferably without setting the height explicitly.

html

```<code><div id="outer">
    <div class="expandableContent">
        <p class="toggler">Toggle</p>
        <div>
            <p>Some content here</p>
            <p>Some content there</p>
            <p>Some content everywhere</p>
        </div>
    </div>
</div>
</code>```

css

```<code>#outer {
     height: 300px;
     position: relative;
}

.expandableContent {
    position: absolute;
    bottom: 10px;
}

 .expandableContent > div {
     display: none;
 }
</code>```

jquery

```<code>$(document).ready(function () {
    $('.toggler').click( function() {
        $(this).next().toggle(1000);
    });
});
</code>```

Here's a link: http://jsfiddle.net/SunnyRed/A8pNv/1/

答:
Take a look at this, is much elegant now.

Working demo

Body:
I've got an absolute positioned container, which is bottom aligned.

Now I would like to toggle (show/hide) some content without the container getting larger than its contents -  and preferably without setting the height explicitly.

html

Toggle

Some content here

Some content there

Some content everywhere

css

#outer {
     height: 300px;
     position: relative;
}

.expandableContent {
    position: absolute;
    bottom: 10px;
}

 .expandableContent > div {
     display: none;
 }

jquery

$(document).ready(function () {
    $('.toggler').click( function() {
        $(this).next().toggle(1000);
    });
});

Here's a link: http://jsfiddle.net/SunnyRed/A8pNv/1/


问:
Adding string to a string before some certain characters?
```<code>myString = '(247, 246, 244), (13, 23, 24), (85, 101, 100)'

substring = 'rgb'
</code>```

I want to add this string the substring above, before every '(' character. So that it would be look like this below.

myString = 'rgb(247, 246, 244), rgb(13, 23, 24), rgb(85, 101, 100)'

答: Try using the .replace() method, ie myString.replace("(", "rgb(") this will just go through the string and replace every "(" with "rgb(".

Body:
myString = '(247, 246, 244), (13, 23, 24), (85, 101, 100)'

substring = 'rgb'

I want to add this string the substring above, before every '(' character. So that it would be look like this below.

myString = 'rgb(247, 246, 244), rgb(13, 23, 24), rgb(85, 101, 100)'


问:
Python venv env Fails - [WinError 2] The system cannot find the file specified
I installed the latest version of Python 3.8.2 on a Windows 10 machine. I previously had Python 3.7, which I uninstalled and confirmed in the System PATH it was no longer referenced.

After installing the latest version, I run through CMD as Admin:

```<code>py -m venv env
</code>```

and I get this error:

Error: [WinError 2] The system cannot find the file specified: 'C:\Users\test_user\Documents\app_test\env'

I know the Python Path is in the System Path environmental settings, but not specifically for the user (don't know if that makes a difference?).

I have also tried to uninstall virtualenv using powershell and reinstaling, but have the same result.

Any ideas on where else to look to solve this?

答:
You probably encounter this error because you have two or more versions of Python on your machine.
When installing the second version, you:

created the environment variable (ex PYTHON37_HOME -> C:/Users/..Python/Python37)

specified this variable in Path.

renamed the file python.exe to python37.exe

Now by opening the file C:\Users\....\Python\Python37\Lib\venv\__init__.py you can see that by executing the setup_python() function, python.exe cannot be found anymore in the suffixes = ['python.exe', ...] because we renamed it.

So you also have to rename suffixes = ['python.exe', ...] to suffixes = ['python37.exe', ...].

Execute again python37 -m venv venv and it should work

Body:
I installed the latest version of Python 3.8.2 on a Windows 10 machine. I previously had Python 3.7, which I uninstalled and confirmed in the System PATH it was no longer referenced.

After installing the latest version, I run through CMD as Admin:

py -m venv env

and I get this error:

Error: [WinError 2] The system cannot find the file specified: 'C:\Users\test_user\Documents\app_test\env'

I know the Python Path is in the System Path environmental settings, but not specifically for the user (don't know if that makes a difference?).

I have also tried to uninstall virtualenv using powershell and reinstaling, but have the same result.

Any ideas on where else to look to solve this?


答:
Using the same comprehension as yours with one extra level for the sublist:

```<code>new_d = {key: [x - np.mean(x) for x in l] for (key,l) in d.items()}
</code>```

As lists:

```<code>{key: [(x - np.mean(x)).tolist() for x in l] for (key,l) in d.items()}
</code>```

output:

```<code>{'key1': [[-1.0, 0.0, 1.0], [-360.0, -270.0, 630.0]],
 'key2': [[-1.0, 0.0, 1.0], [-2.0, -1.0, 3.0]]}
</code>```

Title: Multidimensional dictionary comprehension

Body:
Using the same comprehension as yours with one extra level for the sublist:

new_d = {key: [x - np.mean(x) for x in l] for (key,l) in d.items()}

As lists:

{key: [(x - np.mean(x)).tolist() for x in l] for (key,l) in d.items()}

output:

{'key1': [[-1.0, 0.0, 1.0], [-360.0, -270.0, 630.0]],
 'key2': [[-1.0, 0.0, 1.0], [-2.0, -1.0, 3.0]]}


问:
Make e-mail field from single product page review form not required
I would like to either remove or disable requirement of the woocommerce single product review e-mail field, but keep the name field.

If you uncheck the option "users have to enter name and email to comment" both of fields get removed. Making it easy to leave a review, but are likely not to be trusted by other users since there is no name next to it. If you make e-mail required, users are not likely to leave a review at all.

So far I tried:

Edit single-product-reviews.php by removing the "required" attribute and get_option from the fields:

```<code>                        'author' => array(
                            'label'    => __( 'Name', 'woocommerce' ),
                            'type'     => 'text',
                            'value'    => $commenter['comment_author'],
                            'required' => '',
                        ),
                        'email' => array(
                            'label'    => __( 'Email', 'woocommerce' ),
                            'type'     => 'email',
                            'value'    => $commenter['comment_author_email'],
                            'required' => '',
                        ),
                    );
</code>```

Unset the e-mail field via filter (works but field is still required):

```<code>add_filter( 'comment_form_fields', 'remove_email_field', 9 );
function remove_email_field( $fields ){
    unset ($fields['email']);
    return $fields;
}

</code>```

Make email field not required via filter (not working, breaks review form):

```<code>add_filter( 'comment_form_fields', 'email_field_not_required');
function email_field_not_required( $fields ){
    $fields['email']['required'] = false;
    return $fields;
}
</code>```

The end result should look something like this (no e-mail field but required name):

Can somebody please point me in the right direction?

答:
First, you have to hide email fields from a comment form rather than remove it.

```<code>function hide_email_field_on_comment(){

    if( !is_admin() && is_product() ){
        ?>
        <style type="text/css">
            .comment-form-email{
                display: none;
            }
        </style>
        <?php
    }

}
add_action( 'wp_head', 'hide_email_field_on_comment', 10, 1 );
</code>```

Then you can modify single-product-reviews.php and pass random email to value. so it will not give the required field error for email.

```<code>$fields = array(
    'author' => array(
        'label'    => __( 'Name', 'woocommerce' ),
        'type'     => 'text',
        'value'    => $commenter['comment_author'],
        'required' => $name_email_required,
    ),
    'email'  => array(
        'label'    => __( 'Email', 'woocommerce' ),
        'type'     => 'email',
        'value'    => 'test@test.com', // pass random email.
        'required' => $name_email_required,
    ),
);
</code>```

Now you have to remove email from comment when a comment is inserted. for that, you can use the preprocess_comment filter hook.

```<code>function remove_dummy_email( $commentdata ){
    unset( $commentdata['comment_author_email'] );
    return $commentdata;
}
add_filter( 'preprocess_comment', 'remove_dummy_email', 10, 1 );
</code>```

Body:
I would like to either remove or disable requirement of the woocommerce single product review e-mail field, but keep the name field.

If you uncheck the option "users have to enter name and email to comment" both of fields get removed. Making it easy to leave a review, but are likely not to be trusted by other users since there is no name next to it. If you make e-mail required, users are not likely to leave a review at all.

So far I tried:

Edit single-product-reviews.php by removing the "required" attribute and get_option from the fields:

                        'author' => array(
                            'label'    => __( 'Name', 'woocommerce' ),
                            'type'     => 'text',
                            'value'    => $commenter['comment_author'],
                            'required' => '',
                        ),
                        'email' => array(
                            'label'    => __( 'Email', 'woocommerce' ),
                            'type'     => 'email',
                            'value'    => $commenter['comment_author_email'],
                            'required' => '',
                        ),
                    );

Unset the e-mail field via filter (works but field is still required):

add_filter( 'comment_form_fields', 'remove_email_field', 9 );
function remove_email_field( $fields ){
    unset ($fields['email']);
    return $fields;
}

Make email field not required via filter (not working, breaks review form):

add_filter( 'comment_form_fields', 'email_field_not_required');
function email_field_not_required( $fields ){
    $fields['email']['required'] = false;
    return $fields;
}

The end result should look something like this (no e-mail field but required name):

Can somebody please point me in the right direction?

Body:
First, you have to hide email fields from a comment form rather than remove it.

function hide_email_field_on_comment(){

    if( !is_admin() && is_product() ){
        ?>
        <style type="text/css">
            .comment-form-email{
                display: none;
            }
        </style>
        <?php
    }

}
add_action( 'wp_head', 'hide_email_field_on_comment', 10, 1 );

Then you can modify single-product-reviews.php and pass random email to value. so it will not give the required field error for email.

$fields = array(
    'author' => array(
        'label'    => __( 'Name', 'woocommerce' ),
        'type'     => 'text',
        'value'    => $commenter['comment_author'],
        'required' => $name_email_required,
    ),
    'email'  => array(
        'label'    => __( 'Email', 'woocommerce' ),
        'type'     => 'email',
        'value'    => 'test@test.com', // pass random email.
        'required' => $name_email_required,
    ),
);

Now you have to remove email from comment when a comment is inserted. for that, you can use the preprocess_comment filter hook.

function remove_dummy_email( $commentdata ){
    unset( $commentdata['comment_author_email'] );
    return $commentdata;
}
add_filter( 'preprocess_comment', 'remove_dummy_email', 10, 1 );


问:
Why does VSCode not show errors in English?
I prefer learning about programming in English, but VSCode just makes that a lot harder.

For some reason, everything but errors are shown in English.

答:
I searched the settings for the Workbench and language and there was no setting for the UI language.

There is a command line argument to change the display language:

Try to start VSC with

```<code>code --locale en-US .
</code>```

Body:
I searched the settings for the Workbench and language and there was no setting for the UI language.

There is a command line argument to change the display language:

Try to start VSC with

code --locale en-US .


问:
How to " RESET to DEFAULT " colors of text editor in NetBeans?
I want to see Netbeans look as like Photoshop CS6 , Visual studio type. So

Installed a dark theme and

I changed some option and code elements colours for my satisfaction.

And I forgot what the changes I did

I tried all the colours combination  and it became worse

Even Reinstall also not helped me

I had searched a lot to make it default

My Problem (image) is  :

答:
In my case, i had changed the theme as well as how all my formatting was done. To get it back to default I changed the Netbeans.conf file and restarted the application. The file was found here.</p>
```<code>C:\Program Files\NetBeans-12.6\netbeans\etc
</code>```

Body:
In my case, i had changed the theme as well as how all my formatting was done. To get it back to default I changed the Netbeans.conf file and restarted the application. The file was found here.

C:\Program Files\NetBeans-12.6\netbeans\etc


问:
how to return results dependent on sign in user to partial view?
I am trying to return data from tables using LINQ dependent on the login in user name to partial view using injection.
but it fails.
this is my method

```<code> public  IEnumerable<CartView> SaveLater()
    {

        var model =  context.Orders.Where(a => a.User.UserName == User.Identity.Name)
            .Where(a => !context.Carts.Select(s => s.OrderId).Contains(a.Id))
            .Join(context.Products, order => order.ProductId, product => product.Id,
            (order, product) => new CartView
            {
                Name = product.Name,
                Amount = order.Amount,
                Description = product.Description,
                Image = product.Image,
                OrderId = order.Id,
                Price = product.Price
            }).AsEnumerable();
        return  model;
    }
</code>```

when I call the action in the browser route it runs ok, but when I run partial view this error is raised

I made inject for the controller in the main view

```<code>@inject CartController savelater
</code>```

this is my code to partial view

```<code>@{await Html.PartialAsync("../User/SaveLater", savelater.SaveLater()); }
</code>```

答:
I replace User.Identity to

```<code>var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
</code>```

to get the userId and it works fine

also, add services to startup

```<code> services.AddScoped<HttpContextAccessor>();
</code>```

I follow the instruction from this link: https://www.koskila.net/how-to-get-current-user-in-asp-net-core/#Background-2

Body:
I am trying to return data from tables using LINQ dependent on the login in user name to partial view using injection.
but it fails.
this is my method

 public  IEnumerable<CartView> SaveLater()
    {

        var model =  context.Orders.Where(a => a.User.UserName == User.Identity.Name)
            .Where(a => !context.Carts.Select(s => s.OrderId).Contains(a.Id))
            .Join(context.Products, order => order.ProductId, product => product.Id,
            (order, product) => new CartView
            {
                Name = product.Name,
                Amount = order.Amount,
                Description = product.Description,
                Image = product.Image,
                OrderId = order.Id,
                Price = product.Price
            }).AsEnumerable();
        return  model;
    }

when I call the action in the browser route it runs ok, but when I run partial view this error is raised

I made inject for the controller in the main view

@inject CartController savelater

this is my code to partial view

@{await Html.PartialAsync("../User/SaveLater", savelater.SaveLater()); }

Body:
I replace User.Identity to

var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

to get the userId and it works fine

also, add services to startup

 services.AddScoped<HttpContextAccessor>();

I follow the instruction from this link: https://www.koskila.net/how-to-get-current-user-in-asp-net-core/#Background-2


问:
Docker postgresql container IP address changes whenever it restarts

$ docker run -d \
    --name some-postgres \
    -e POSTGRES_USER=postgres \
    -e POSTGRES_PASSWORD=mysecretpassword \
    -p 5432:5432 \
    postgres
```
<p>I build postgresql container like above. Then when try to access Postgresql server. I always set the IP address like this in Python with Flask-SQLAlchemy:</p>
<pre class="lang-py prettyprint-override"><code>app.config['SQLALCHEMY_DATABASE_URI'] = postgresql://postgres:securepass@host.docker.internal:5432/some_db_name'
</code>```

instead of writing "host.docker.internal" can I set the IP address as static one?

答:
You need to create a custom network:

```<code>docker network create --subnet=172.18.0.0/16 customnet
</code>```

then, run the container

```<code>docker run -d \
--name some-postgres \
-e POSTGRES_USER=postgres \
-e POSTGRES_PASSWORD=mysecretpassword \
-p 5432:5432 \
--net customnet
--ip 172.18.0.33
postgres
</code>```

Body:
$ docker run -d \
    --name some-postgres \
    -e POSTGRES_USER=postgres \
    -e POSTGRES_PASSWORD=mysecretpassword \
    -p 5432:5432 \
    postgres

I build postgresql container like above. Then when try to access Postgresql server. I always set the IP address like this in Python with Flask-SQLAlchemy:

app.config['SQLALCHEMY_DATABASE_URI'] = postgresql://postgres:securepass@host.docker.internal:5432/some_db_name'

instead of writing "host.docker.internal" can I set the IP address as static one?

Body:
You need to create a custom network:

docker network create --subnet=172.18.0.0/16 customnet

then, run the container

docker run -d \
--name some-postgres \
-e POSTGRES_USER=postgres \
-e POSTGRES_PASSWORD=mysecretpassword \
-p 5432:5432 \
--net customnet
--ip 172.18.0.33
postgres


问:
Error: Member not found: 'packageRoot', how to solve ignore: deprecated_member_use in Flutter?
In my flutter project, I have made some updates of plugins and then used flutter upgrade. After that, whenever I am running my flutter project it is showing following error-

```<code>    /C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/platform-3.0.2/lib/src/interface/local_platform.dart:46:19: Error: Member not found: 'packageRoot'.
          io.Platform.packageRoot; // ignore: deprecated_member_use
                      ^^^^^^^^^^^ FAILURE: Build failed with an exception.

* Where: Script 'C:\src\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1102

* What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 20s Exception: Gradle task assembleDebug failed with exit code 1
</code>```

So, I need a suggestion that how can I solve this issue?

答:
Try add in pubspec.yaml file

```<code>dependencies: // under dependencies:
  platform: ^3.1.0
</code>```

then run  flutter pub get

Why this error occurred

../../../development/flutter/.pub-cache/hosted/pub.dartlang.org/platform-3.0.0/lib/src/interface/local_platform.dart:46:19: Error: Member not found: 'packageRoot'. io.Platform.packageRoot; // ignore: deprecated_member_use

this is the kind of error that you will get when you build the file.

if you notice the error was caused by package
platform:3.0.0

so we are just overriding this by incrementing it to 3.1.0

Body:
In my flutter project, I have made some updates of plugins and then used flutter upgrade. After that, whenever I am running my flutter project it is showing following error-

    /C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/platform-3.0.2/lib/src/interface/local_platform.dart:46:19: Error: Member not found: 'packageRoot'.
          io.Platform.packageRoot; // ignore: deprecated_member_use
                      ^^^^^^^^^^^ FAILURE: Build failed with an exception.

* Where: Script 'C:\src\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1102

* What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 20s Exception: Gradle task assembleDebug failed with exit code 1

So, I need a suggestion that how can I solve this issue?

Body:
Try add in pubspec.yaml file

dependencies: // under dependencies:
  platform: ^3.1.0

then run  flutter pub get

Why this error occurred

../../../development/flutter/.pub-cache/hosted/pub.dartlang.org/platform-3.0.0/lib/src/interface/local_platform.dart:46:19: Error: Member not found: 'packageRoot'. io.Platform.packageRoot; // ignore: deprecated_member_use

this is the kind of error that you will get when you build the file.

if you notice the error was caused by package
platform:3.0.0

so we are just overriding this by incrementing it to 3.1.0


问:
Redirect /openvas/ to OpenVAS Scanner with NGINX
I'm trying to make my OpenVAS Scanner available via path in nginx.
So I tried

```<code>location /openvas/ {
proxy_pass http://127.0.0.1:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;}
</code>```

thats not working, it gives a blank page

When I change it to root

```<code>location / {
proxy_pass http://127.0.0.1:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme; }
</code>```

its working

when checking nginx logfiles it seems it gets the first page, but not the other files requested

```<code>"GET /openvas/ HTTP/2.0" 200
"GET /config.js HTTP/2.0" 404
</code>```

答:
I have checked the docker container image and just proxying the traffic trough NGINX will not work. You have to set the Public Hostname for your OpenVAS instance as well to tell OpenVAS how to server static files and build directories in the frontend.

I have found this on docker hub.

```<code>docker run -d -p 443:443 -e PUBLIC_HOSTNAME=myopenvas.example.org --name openvas mikesplain/openvas

</code>```

In your case you should set the PUBLIC_HOSTNAME to example.com/openvas/. This will tell OpenVAS public domain used to access the application.

Your NGINX configuration will be

```<code>location /openvas/ {
  proxy_pass http://127.0.0.1:8080/;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header X-Forwarded-Proto $scheme;
}

</code>```

Body:
I'm trying to make my OpenVAS Scanner available via path in nginx.
So I tried

location /openvas/ {
proxy_pass http://127.0.0.1:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;}

thats not working, it gives a blank page

When I change it to root

location / {
proxy_pass http://127.0.0.1:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme; }

its working

when checking nginx logfiles it seems it gets the first page, but not the other files requested

"GET /openvas/ HTTP/2.0" 200
"GET /config.js HTTP/2.0" 404

Body:
I have checked the docker container image and just proxying the traffic trough NGINX will not work. You have to set the Public Hostname for your OpenVAS instance as well to tell OpenVAS how to server static files and build directories in the frontend.

I have found this on docker hub.

docker run -d -p 443:443 -e PUBLIC_HOSTNAME=myopenvas.example.org --name openvas mikesplain/openvas

In your case you should set the PUBLIC_HOSTNAME to example.com/openvas/. This will tell OpenVAS public domain used to access the application.

Your NGINX configuration will be

location /openvas/ {
  proxy_pass http://127.0.0.1:8080/;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header X-Forwarded-Proto $scheme;
}


问:
How to implement CSS into Wicket 9.8.0
Despite using the <wicket:link> tags around my <link> tags my CSS is still not being applied to my HTML even with some attempts to move the css file into my webapp folder (Currently its in the same package as my wicket files).

My current HTML file:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <wicket:link>
        <link rel="stylesheet" href="style.css" type="text/css">
    </wicket:link>
</head>
<header id="masthead" class="site-header" style="background-color: rgb(36, 0, 72);">

</header>
<body>
<div>

</div>
<span wicket:id="welcome">WELCOME</span>
<h1>testing</h1>
</body>
</html>
</code>```

My Current CSS file (simple just for testing):

```<code>h1 {
    font-size: 100px;
}
.site-header {
    display: flex;
    align-items: center;
    padding: 0 30px;
    z-index: 10002;
}

header {
    position: fixed;
    width: 100%;
    top: 0;
    height: 95px;
}
</code>```

答:
<wicket:link> helps to construct a correct url to style.css when it is in the classpath, next to MyPage.html file. I.e. if style.css is in src/main/resources/com/example/pages folder and MyPage.java is in com.example.pages  package.

Usually CSS files are put in src/main/webapp folder. In this case you don't need to wrap it with <wicket:link>. You can read more about it in the user guide.

The best way to start with Wicket is by using the quickstart application!

Title: How to implement CSS into Wicket 9.8.0

Body:
Despite using the <wicket:link> tags around my <link> tags my CSS is still not being applied to my HTML even with some attempts to move the css file into my webapp folder (Currently its in the same package as my wicket files).

My current HTML file:

<!DOCTYPE html>

    <wicket:link>
        <link rel="stylesheet" href="style.css" type="text/css">
    </wicket:link>

WELCOME

testing

My Current CSS file (simple just for testing):

h1 {
    font-size: 100px;
}
.site-header {
    display: flex;
    align-items: center;
    padding: 0 30px;
    z-index: 10002;
}

header {
    position: fixed;
    width: 100%;
    top: 0;
    height: 95px;
}