问:
Create large random boolean matrix with numpy
I am trying to create a huge boolean matrix which is randomly filled with True and False with a given probability p. At first I used this code:

```<code>N = 30000
p = 0.1
np.random.choice(a=[False, True], size=(N, N), p=[p, 1-p])
</code>```

But sadly it does not seem to terminate for this big N. So I tried to split it up into the generation of the single rows by doing this:

```<code>N = 30000
p = 0.1
mask = np.empty((N, N))
for i in range (N):
     mask[i] = np.random.choice(a=[False, True], size=N, p=[p, 1-p])
     if (i % 100 == 0):
          print(i)
</code>```

Now, there happens something strange (at least on my device): The first ~1100 rows are very fastly generated - but after it, the code becomes horribly slow. Why is this happening? What do I miss here? Are there better ways to create a big matrix which has True entries with probability p and False entries with probability 1-p?

Edit: As many of you assumed that the RAM will be a problem: As the device which will run the code has almost 500GB RAM, this won't be a problem.

答:
Really surprised no one has mentioned this solution yet..

This line

np.random.choice(a=[False, True], size=(N, N), p=[p, 1-p])
```
<p>runs NXN Bernoulli Trials. (In your case, 900M of them!) A Bernoulli trial is just a random experiment with two possible outcomes, with probabilities p and 1-p.</p>
<p>The sum of N Bernoulli trials, each with probability p, can be modeled by the Binomial distribution.</p>
<p>We can leverage this fact to randomly simulate the total count of True elements. With NumPy,</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np

N = 30000
p = 0.1

# Build a random number generator
rng = np.random.default_rng(123)

# Randomly determine the total number of True values
Ntrue = rng.binomial(n=N*N, p=p, size=1)[0]  # 90016776
</code>```

Now we can randomly determine the position of each True element by randomly choosing row and col indices without replacement.

# Randomly determine true position
position_ids = rng.choice(a=N*N, size=Ntrue, replace=False)
positions = np.unravel_index(position_ids, shape=(N,N))
```
<p>And now we can populate a compressed sparse row (CSR) matrix.</p>
<pre class="lang-py prettyprint-override"><code>from scipy import sparse

# Build a compressed sparse row matrix with the constructor:
# csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
result = sparse.csr_matrix((np.ones(shape=Ntrue), positions), shape=(N,N))
</code>```

Notice this solution avoids storing and computing 900M boolean values.

Funny enough, I wrote about a nearly identical problem before stumbling upon this question.

Body:
I am trying to create a huge boolean matrix which is randomly filled with True and False with a given probability p. At first I used this code:

N = 30000
p = 0.1
np.random.choice(a=[False, True], size=(N, N), p=[p, 1-p])

But sadly it does not seem to terminate for this big N. So I tried to split it up into the generation of the single rows by doing this:

N = 30000
p = 0.1
mask = np.empty((N, N))
for i in range (N):
     mask[i] = np.random.choice(a=[False, True], size=N, p=[p, 1-p])
     if (i % 100 == 0):
          print(i)

Now, there happens something strange (at least on my device): The first ~1100 rows are very fastly generated - but after it, the code becomes horribly slow. Why is this happening? What do I miss here? Are there better ways to create a big matrix which has True entries with probability p and False entries with probability 1-p?

Edit: As many of you assumed that the RAM will be a problem: As the device which will run the code has almost 500GB RAM, this won't be a problem.

Body:
Really surprised no one has mentioned this solution yet..

This line

np.random.choice(a=[False, True], size=(N, N), p=[p, 1-p])

runs NXN Bernoulli Trials. (In your case, 900M of them!) A Bernoulli trial is just a random experiment with two possible outcomes, with probabilities p and 1-p.

The sum of N Bernoulli trials, each with probability p, can be modeled by the Binomial distribution.

We can leverage this fact to randomly simulate the total count of True elements. With NumPy,

import numpy as np

N = 30000
p = 0.1

# Build a random number generator
rng = np.random.default_rng(123)

# Randomly determine the total number of True values
Ntrue = rng.binomial(n=N*N, p=p, size=1)[0]  # 90016776

Now we can randomly determine the position of each True element by randomly choosing row and col indices without replacement.

# Randomly determine true position
position_ids = rng.choice(a=N*N, size=Ntrue, replace=False)
positions = np.unravel_index(position_ids, shape=(N,N))

And now we can populate a compressed sparse row (CSR) matrix.

from scipy import sparse

# Build a compressed sparse row matrix with the constructor:
# csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
result = sparse.csr_matrix((np.ones(shape=Ntrue), positions), shape=(N,N))

Notice this solution avoids storing and computing 900M boolean values.

Funny enough, I wrote about a nearly identical problem before stumbling upon this question.


来源: stackexchange

问:
How do I convert a 44 bytes long base64 string (public key) to a 32 bytes long UInt8 array?
I'm using the swift-sodium library and need a 32 bytes long UInt8 array (public key) to seal a message. However, the public key which is generated by the tweetnacl-js library that I got from an api is a 44 bytes long base64 string. How do I convert the 44 bytes long base64 public key to a 32 bytes long UInt8 array so I can pass it to the seal function?</p>

答:
You can convert your Base64-String using the following example:</p>
```<code>extension Data {
   public var bytes: [UInt8]{
      return [UInt8](self)
   }
}

// USAGE IN CODE
let data = Data(base64Encoded: <YOUR BASE64 PUBLIC KEY>, options: .ignoreUnknownCharacters)
print(data?.bytes)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can convert your Base64-String using the following example:

extension Data {
   public var bytes: [UInt8]{
      return [UInt8](self)
   }
}

// USAGE IN CODE
let data = Data(base64Encoded: <YOUR BASE64 PUBLIC KEY>, options: .ignoreUnknownCharacters)
print(data?.bytes)


问:
CORS Error when React App tries to connect via SignalR to .NET CORE Web App having Windows Authentication enabled
I am trying to send data from React App to .NET Core Web App using SignalR.
The .NET Core Web App has Windows Authentication enabled. With Windows Authentication enabled, I am getting the CORS error when my React App tries to send message to .NET Core App via SignalR.
It works fine if I disable windows authentication and enable anonymous authentication.

Can you please help me with your valuable inputs to make the connection work?

React JS app code looks like below:

```<code>const hubConnection = new HubConnectionBuilder()
      .withUrl(window.config.APP_URL, options)
      .withAutomaticReconnect()
      .build();

    this.setState({ hubConnection }, () => {
      this.state.hubConnection
        .start()
        .then(() => console.log("SignalR Connection started!"))
        .catch((err) =>
          console.log("SignalR Error while establishing connection :(", err)
        );
    });
  }

  sendMessage = () => {
    console.log("sendMessage() Properties: ", this.props);

    const signalRMessage = {
      UserName: this.props.userName,
    };
    this.state.hubConnection
      .invoke("SendMessage", signalRMessage)
      .catch((err) => console.error(err));
  };
</code>```

I tried to explicitly add the ‘Access-Control-Allow-Origin’ header as shown below. But still I see the CORS error.

```<code>componentDidMount() {

    let options = {
      httpClient: {
        post: (url, httpOptions) => {

          // httpOptions.headers = {
          //   ...httpOptions.headers,
          //   "Access-Control-Allow-Origin": window.config.CORS_ALLOW_ORIGIN_URL,
          //   //"Access-Control-Allow-Methods": "POST, GET, HEAD",
          // };
          // httpOptions.method = "POST";
          // httpOptions.url = url;

          // return httpOptions;

          const headers = {
            ...httpOptions.headers,
            "Access-Control-Allow-Origin": window.config.CORS_ALLOW_ORIGIN_URL,
            "Access-Control-Allow-Methods": "POST, GET, HEAD",
          };
          let newResponse = {};

          return axios.post(url, {}, { headers }).then(response => {
            return (newResponse = {
              statusCode: response.status,
              statusText: response.statusText,
              content: JSON.stringify(response.data)
            });
          });

        }
      }
    };
</code>```

Below is the CORS error that I see in console logs at React App side:
enter image description here

```<code>public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(IISDefaults.AuthenticationScheme);

            services.AddRazorPages();

            services.AddCors(options =>
            {
                options.AddPolicy("ClientPermissionPolicy", policy =>
                {

                    policy.WithOrigins("https://xxxx.com")
                        .AllowAnyHeader()
                        .AllowAnyMethod().AllowCredentials();
                });
            });

            ...
        }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");

                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseCors("ClientPermissionPolicy");

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapHub<TapHub>("/hubs/tap");
            });

        }
</code>```

Went through many posts here in stackoverflow and tried below but in vain.

In Configure():

app.UseCors(builder => builder.WithOrigins("https://xxxx.com").AllowAnyMethod().AllowAnyHeader().AllowCredentials());

In ConfigureServices():

services.AddCors(options =>
{
options.AddPolicy("ClientPermissionPolicy", policy =>
{
policy.WithOrigins("https://xxxxx.com")
.AllowAnyHeader()
.AllowAnyMethod().AllowCredentials()
.SetIsOriginAllowed((host) => true);
});
});

Tried AllowAnyOrigin()

Tried removing AllowCredentials()

Like I said above, it works fine if I disable windows authentication and enable anonymous authentication. The React App successfully connects to the hub endpoint in case of anonymous authentication. The CORS error comes into picture only when I enable windows authentication. I need Windows Authentication enabled for my requirement. Requesting you to help fix the issue.

Thanks!

答:
A bit late, however I faced similar problem right now. Even with enabled CORS, it still rejected me. In the end, I found out that problem is in the

```<code>app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});
</code>```

When I included CORS into this part, it started to work ... finally

```<code>app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers().RequireCors("ClientPermissionPolicy");
});
</code>```

Body:
I am trying to send data from React App to .NET Core Web App using SignalR.
The .NET Core Web App has Windows Authentication enabled. With Windows Authentication enabled, I am getting the CORS error when my React App tries to send message to .NET Core App via SignalR.
It works fine if I disable windows authentication and enable anonymous authentication.

Can you please help me with your valuable inputs to make the connection work?

React JS app code looks like below:

const hubConnection = new HubConnectionBuilder()
      .withUrl(window.config.APP_URL, options)
      .withAutomaticReconnect()
      .build();

    this.setState({ hubConnection }, () => {
      this.state.hubConnection
        .start()
        .then(() => console.log("SignalR Connection started!"))
        .catch((err) =>
          console.log("SignalR Error while establishing connection :(", err)
        );
    });
  }

  sendMessage = () => {
    console.log("sendMessage() Properties: ", this.props);

    const signalRMessage = {
      UserName: this.props.userName,
    };
    this.state.hubConnection
      .invoke("SendMessage", signalRMessage)
      .catch((err) => console.error(err));
  };

I tried to explicitly add the ‘Access-Control-Allow-Origin’ header as shown below. But still I see the CORS error.

componentDidMount() {

    let options = {
      httpClient: {
        post: (url, httpOptions) => {

          // httpOptions.headers = {
          //   ...httpOptions.headers,
          //   "Access-Control-Allow-Origin": window.config.CORS_ALLOW_ORIGIN_URL,
          //   //"Access-Control-Allow-Methods": "POST, GET, HEAD",
          // };
          // httpOptions.method = "POST";
          // httpOptions.url = url;

          // return httpOptions;

          const headers = {
            ...httpOptions.headers,
            "Access-Control-Allow-Origin": window.config.CORS_ALLOW_ORIGIN_URL,
            "Access-Control-Allow-Methods": "POST, GET, HEAD",
          };
          let newResponse = {};

          return axios.post(url, {}, { headers }).then(response => {
            return (newResponse = {
              statusCode: response.status,
              statusText: response.statusText,
              content: JSON.stringify(response.data)
            });
          });

        }
      }
    };

Below is the CORS error that I see in console logs at React App side:
enter image description here

public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(IISDefaults.AuthenticationScheme);

            services.AddRazorPages();

            services.AddCors(options =>
            {
                options.AddPolicy("ClientPermissionPolicy", policy =>
                {

                    policy.WithOrigins("https://xxxx.com")
                        .AllowAnyHeader()
                        .AllowAnyMethod().AllowCredentials();
                });
            });

            ...
        }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");

                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseCors("ClientPermissionPolicy");

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapHub<TapHub>("/hubs/tap");
            });

        }

Went through many posts here in stackoverflow and tried below but in vain.

In Configure():

app.UseCors(builder => builder.WithOrigins("https://xxxx.com").AllowAnyMethod().AllowAnyHeader().AllowCredentials());

In ConfigureServices():

services.AddCors(options =>
{
options.AddPolicy("ClientPermissionPolicy", policy =>
{
policy.WithOrigins("https://xxxxx.com")
.AllowAnyHeader()
.AllowAnyMethod().AllowCredentials()
.SetIsOriginAllowed((host) => true);
});
});

Tried AllowAnyOrigin()

Tried removing AllowCredentials()

Like I said above, it works fine if I disable windows authentication and enable anonymous authentication. The React App successfully connects to the hub endpoint in case of anonymous authentication. The CORS error comes into picture only when I enable windows authentication. I need Windows Authentication enabled for my requirement. Requesting you to help fix the issue.

Thanks!

Body:
A bit late, however I faced similar problem right now. Even with enabled CORS, it still rejected me. In the end, I found out that problem is in the

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

When I included CORS into this part, it started to work ... finally

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers().RequireCors("ClientPermissionPolicy");
});


问:
Programmatically interacting with gdb using java
I'm writing an application that uses GDB to access information through java.

Using Runtime.getRuntime.exec, I'm able to attach GDB to any processes.

The problem is that I am unable to send inputs to GDB after it has been started.

**EDIT (19/8/2011):

At the line "out.println(gdbcommand)", gdb is started. How do I get the stdout of the newly spawned gdb, write inputs to it and then read the stdin. So far, I'm only able get the output up till "out.println(gdbcommand)". All attempts at trying to programmatically send inputs to gdb have not been working so far.**

Refer to trojanfoe's comments below my question.
Below is an edited sample of my code:

```<code>try {
    String gdbcommand = "/data/bin/gdb " + pidS + " " + pidS;
    String line;

    Process process = Runtime.getRuntime().exec("su");

    if (process != null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())),true);

        out.println(gdbcommand);

        //Note this line does not get sent to gdb's interface after starting gdb.
        //Is it possible to connect to the new stdout of gdb's interface?
        out.println("info registers");

        out.flush();
        out.close();

        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        process.destroy();
    }

} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Note that "info registers" is not sent to GDB's interface and after calling out.close(), gdb's interface quits. (As seen below)

```<code>08-18 14:40:36.595: INFO/System.out(4408): 0xafd0c51c in epoll_wait () from /system/lib/libc.so

08-18 14:40:36.595: INFO/System.out(4408): (gdb) Hangup detected on fd 0

08-18 14:40:36.595: INFO/System.out(4408): error detected on stdin

08-18 14:40:36.595: INFO/System.out(4408): The program is running.  Quit anyway (and detach it)? (y or n) [answered Y; input not from terminal]
</code>```

答:
gdb reads from stdin immediately upon starting, sees there's no input (and that it's not a terminal) and so immediately quits.  To avoid this, you want to pass -batch to run it in batch mode, and then put the commands you wish to execute in a command file which you specify on the command line using the -x argument.

Your code would then be something like:

```<code>out.println("/data/bin/gdb -batch -x " + commandFilenameS + " " + pidS + " " + pidS);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm writing an application that uses GDB to access information through java.

Using Runtime.getRuntime.exec, I'm able to attach GDB to any processes.

The problem is that I am unable to send inputs to GDB after it has been started.

**EDIT (19/8/2011):

At the line "out.println(gdbcommand)", gdb is started. How do I get the stdout of the newly spawned gdb, write inputs to it and then read the stdin. So far, I'm only able get the output up till "out.println(gdbcommand)". All attempts at trying to programmatically send inputs to gdb have not been working so far.**

Refer to trojanfoe's comments below my question.
Below is an edited sample of my code:

try {
    String gdbcommand = "/data/bin/gdb " + pidS + " " + pidS;
    String line;

    Process process = Runtime.getRuntime().exec("su");

    if (process != null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())),true);

        out.println(gdbcommand);

        //Note this line does not get sent to gdb's interface after starting gdb.
        //Is it possible to connect to the new stdout of gdb's interface?
        out.println("info registers");

        out.flush();
        out.close();

        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        process.destroy();
    }

} catch (Exception e) {
    e.printStackTrace();
}

Note that "info registers" is not sent to GDB's interface and after calling out.close(), gdb's interface quits. (As seen below)

08-18 14:40:36.595: INFO/System.out(4408): 0xafd0c51c in epoll_wait () from /system/lib/libc.so

08-18 14:40:36.595: INFO/System.out(4408): (gdb) Hangup detected on fd 0

08-18 14:40:36.595: INFO/System.out(4408): error detected on stdin

08-18 14:40:36.595: INFO/System.out(4408): The program is running.  Quit anyway (and detach it)? (y or n) [answered Y; input not from terminal]

Body:
gdb reads from stdin immediately upon starting, sees there's no input (and that it's not a terminal) and so immediately quits.  To avoid this, you want to pass -batch to run it in batch mode, and then put the commands you wish to execute in a command file which you specify on the command line using the -x argument.

Your code would then be something like:

out.println("/data/bin/gdb -batch -x " + commandFilenameS + " " + pidS + " " + pidS);


问:
Im trying to create an array of user Objects in local Storage using vanilla JS
I'm creating a simple quiz app and i would like to store an object of each user and their score in an array stored in local Storage. The problem is every time I initiate the function instead of adding a new object to the array the existing object values are changed instead</p>
```<code>//JS code

function storeUsers(userObject) {
    if (localStorage.getItem(users) === null) {
        users = []
    } else {
        users = JSON.parse(localStorage.getItem(users))
    }

     const userScoreTemplate = function (usersName, usersScore) {
            this.user = usersName;
            this.score = usersScore;
        }

        newUser = new userScoreTemplate(userName, score);

    users.push(userObject);
    localStorage.setItem("users", JSON.stringify(users))

}

storeUsers(newUser);
</code>```

答:
You miss quotes in localStorage.getItem.

I also recommend you separate the functionality of your function like below:

class UserScoreTemplate {
    constructor(userName, userScore) {
        this.user = userName;
        this.score = userScore;
    }
}

function storeUsers(userObject) {
    let users = [];

    if (localStorage.getItem("users")) {
        users = JSON.parse(localStorage.getItem("users"));
    }

    users.push(userObject);
    localStorage.setItem("users", JSON.stringify(users));
}

const newUser = new UserScoreTemplate("John", "Doe");

storeUsers(newUser);
```

Body:
I'm creating a simple quiz app and i would like to store an object of each user and their score in an array stored in local Storage. The problem is every time I initiate the function instead of adding a new object to the array the existing object values are changed instead

//JS code

function storeUsers(userObject) {
    if (localStorage.getItem(users) === null) {
        users = []
    } else {
        users = JSON.parse(localStorage.getItem(users))
    }

     const userScoreTemplate = function (usersName, usersScore) {
            this.user = usersName;
            this.score = usersScore;
        }

        newUser = new userScoreTemplate(userName, score);

    users.push(userObject);
    localStorage.setItem("users", JSON.stringify(users))

}

storeUsers(newUser);


问:
How to make a widget maximum size be equal to the flex value in a row
I have this small code:

Container(
  color: Colors.blue,
  child: Row(
    children: [
      Expanded(
        child: Container(
          color: Colors.red,
          child: const Text('Red text that can be long long long long long'),
        ),
      ),
      Flexible(
        child: Container(
          color: Colors.green,
          child: const Text('Small text'),
        ),
      ),
    ],
  ),
),
```
<p>which renders into this:</p>
<p><img src="https://i.stack.imgur.com/ZP2wy.png" alt="enter image description here" /></p>
<p>Notice how the long text is wrapped even though there is still space around the small text.</p>
<p>I would like the small text to only take the size it needs to let the long text take the rest. And if the small text becomes bigger, its maximum size would be the size of the <code>Flexible</code> widget in the row (half of the <code>Row</code> in my example since both <code>Expanded</code> and <code>Flexible</code> have <code>flex: 1</code>).</p>
<p>If the small text is small enough, it should look like:</p>
```| Red text that can be long long long long | Small text |
| long                                     |            |
```
<p>And if the "small" text is long too:</p>
```| Red text that can be long | Small text that is also  |
| long long long long       | very long                |
```

Is there a way to do that?

答:
```<code>    Row(
    children: <Widget>[
    Expanded(
    child:Container(
      color: Colors.green,
      child: const Text('Small text'),
    ),
   ),
   Expanded(
   child: Container(
      color: Colors.red,
      child: const Text('Small text'),
    ),
   ),
   ]
   )
</code>```

Body:
I have this small code:

Container(
  color: Colors.blue,
  child: Row(
    children: [
      Expanded(
        child: Container(
          color: Colors.red,
          child: const Text('Red text that can be long long long long long'),
        ),
      ),
      Flexible(
        child: Container(
          color: Colors.green,
          child: const Text('Small text'),
        ),
      ),
    ],
  ),
),

which renders into this:

Notice how the long text is wrapped even though there is still space around the small text.

I would like the small text to only take the size it needs to let the long text take the rest. And if the small text becomes bigger, its maximum size would be the size of the Flexible widget in the row (half of the Row in my example since both Expanded and Flexible have flex: 1).

If the small text is small enough, it should look like:

| Red text that can be long long long long | Small text |
| long                                     |            |

And if the "small" text is long too:

| Red text that can be long | Small text that is also  |
| long long long long       | very long                |

Is there a way to do that?


问:
How do I break a sentence using CSS?
I'm trying to break a sentence using CSS. I don't want to break the words, but break the sentence. So for example if there's a sentence like Hello world it's test. It should not break any of the words in that sentence and put it in a new line. It should only put new words in a new line. Here's the CSS that I have so far:

See attached image. Notice our some words break apart? I want a new word in a new line, not the characters in a single word to break.

.Main_Topics {
  background: linear-gradient(90deg, rgba(0, 0, 0, 0.546) 0%, rgba(0, 0, 0, 0.539) 23.54%, rgba(0, 0, 0, 0.469) 46.07%, rgba(0, 0, 0, 0) 58.09%), url(/assets/jerry.jpg);
  border-radius: 18px;
  min-height: 424px;
  width: 100%;
  color: white;
  padding: 47px 34px;
  margin: 120px auto;
  text-align: left;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: right top;
}

.Main_Topics h2 {
  font-size: 40px;
  margin-bottom: 30px;
}

.Main_Topics p {
  max-width: 552px;
  margin-bottom: 40px;
}

.Main_Topics .topic {
  background: #FFFFFF;
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
  border-radius: 8px;
  padding: 34px;
  height: 150px;
  text-align: center;
  font-size: 14px;
  color: #000000;
  ;
}

.category-wrapper {
  position: relative;
  max-width: 100%;
  height: 150px;
  margin: 0 auto;
  overflow-x: hidden;
  overflow-y: hidden;
}

.category-wrapper ul {
  height: 150px;
  box-sizing: border-box;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  -webkit-overflow-scrolling: touch;
}

.category-wrapper .topic {
  display: inline-block;
  width: 140px;
  height: 150px;
  margin-right: 26px;
  overflow-wrap: normal;
  vertical-align: top;
}

.category-wrapper .topic div {
  word-wrap: break-word;
  /* IE 5.5-7 */
  white-space: -moz-pre-wrap;
  /* Firefox 1.0-2.0 */
  white-space: pre-wrap;
  /* current browsers */
  font-size: 14px;
  height: 150px;
}

.paddle {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 3em;
  background: transparent;
  border: none;
}

.left-paddle {
  left: 0;
  background: transparent;
  border: none;
}

.right-paddle {
  right: 0;
  background: transparent;
  border: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row Main_Topics">
  <h2>What do you need help with?</h2>
  <p>Our experts are one Zoom call area. They'll give you honest advice. No BS. Straightforward and to the point.</p>
  <div class="category-wrapper">
    <ul>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
      <li class="topic">
        <div>{{name}}</div>
      </li>
    </ul>
    <div class="paddles">
      <button class="left-paddle paddle hidden">
                                <img src="/assets/paddle-left.svg" />
                            </button>
      <button class="right-paddle paddle">
                                <img src="/assets/paddle-right.svg" />
                            </button>
    </div>
  </div>
</div></code>```

答:
Well, while this is not the pretties solution. You can make the word-spacing property to some big value. Like 100vw since that would make it 100% of the view width. Making it so every word has to wrap.

.txt {
  word-spacing: 100vw;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="txt">This should work</h1></code>```

Found the answer from here Can CSS force a line break after each word in an element?

Title: How do I break a sentence using CSS?

Body:
I'm trying to break a sentence using CSS. I don't want to break the words, but break the sentence. So for example if there's a sentence like Hello world it's test. It should not break any of the words in that sentence and put it in a new line. It should only put new words in a new line. Here's the CSS that I have so far:

See attached image. Notice our some words break apart? I want a new word in a new line, not the characters in a single word to break.

.Main_Topics {
  background: linear-gradient(90deg, rgba(0, 0, 0, 0.546) 0%, rgba(0, 0, 0, 0.539) 23.54%, rgba(0, 0, 0, 0.469) 46.07%, rgba(0, 0, 0, 0) 58.09%), url(/assets/jerry.jpg);
  border-radius: 18px;
  min-height: 424px;
  width: 100%;
  color: white;
  padding: 47px 34px;
  margin: 120px auto;
  text-align: left;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: right top;
}

.Main_Topics h2 {
  font-size: 40px;
  margin-bottom: 30px;
}

.Main_Topics p {
  max-width: 552px;
  margin-bottom: 40px;
}

.Main_Topics .topic {
  background: #FFFFFF;
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
  border-radius: 8px;
  padding: 34px;
  height: 150px;
  text-align: center;
  font-size: 14px;
  color: #000000;
  ;
}

.category-wrapper {
  position: relative;
  max-width: 100%;
  height: 150px;
  margin: 0 auto;
  overflow-x: hidden;
  overflow-y: hidden;
}

.category-wrapper ul {
  height: 150px;
  box-sizing: border-box;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  -webkit-overflow-scrolling: touch;
}

.category-wrapper .topic {
  display: inline-block;
  width: 140px;
  height: 150px;
  margin-right: 26px;
  overflow-wrap: normal;
  vertical-align: top;
}

.category-wrapper .topic div {
  word-wrap: break-word;
  /* IE 5.5-7 */
  white-space: -moz-pre-wrap;
  /* Firefox 1.0-2.0 */
  white-space: pre-wrap;
  /* current browsers */
  font-size: 14px;
  height: 150px;
}

.paddle {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 3em;
  background: transparent;
  border: none;
}

.left-paddle {
  left: 0;
  background: transparent;
  border: none;
}

.right-paddle {
  right: 0;
  background: transparent;
  border: none;
}

What do you need help with?

Our experts are one Zoom call area. They'll give you honest advice. No BS. Straightforward and to the point.

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

{{name}}

      <button class="left-paddle paddle hidden">

                            </button>
      <button class="right-paddle paddle">

                            </button>

Body:
Well, while this is not the pretties solution. You can make the word-spacing property to some big value. Like 100vw since that would make it 100% of the view width. Making it so every word has to wrap.

.txt {
  word-spacing: 100vw;
}

<h1 class="txt">This should work</h1>

Found the answer from here Can CSS force a line break after each word in an element?


问:
The outcome of defining a set of constraints in pyomo is wrong
I create an optimization model in pyomo, and I have a list of tuples as a parameter “par”.

```<code>import pyomo.environ as pe
model = pe.ConcreteModel()
p_set = [(1,2), (2,3), (4,5)]
model.par = pe.Param(initialize=p_set, mutable= True)
def var_fix(model, i, j ):
    if (i,j) in model.par:
        constraint = (model.v[i,j] == 1)      # v is a binary variable
    else:
        constraint = (model.v[i,j] == 0)
    return constraint
model.var_fix = pe.Constraint(model.edges, rule=var_fix)
</code>```

But, after printing “var_fix” constraint, all of them are equall to zero:

```<code>Key       : Lower : Body     : Upper : Active
(1, 2)   :   0.0     :   v[1,2] :   0.0     :   True
(2, 3)   :   0.0     :   v[2,3] :   0.0     :   True
(4, 5)   :   0.0     :   v[4,5] :   0.0     :   True
</code>```

I define the parameter and constraint in this way since I want to iteratively change this parameter “par”  with a new one which may have different number of tuples, then solve the problem. In each iteration I will do :

```<code># generating par_new based on some random processes
par_new = [(5,10), (2,3), (4,5), (11,8), (10,6)]
model.par = par_new
# solve the problem again
</code>```

答:
The crux of your problem is that you are defining a single ScalarParam that holds a list of tuples.  Scalar objects in Pyomo are special cases of their Indexed counderparts that use an implicit index of None.  This is done so that code working with Pyomo models can treat all components as if they were indexed (which prevents code from being littered with if comp.is_indexed(): tests).  The __contains__ test that you are doing (if (i,j) in model.par) is testing if the tuple is in the Param's indexing set, and not in the Param's value.

The simplest change is to change the test to check the Param's value:

>>> from pyomo.environ import *
>>> m = ConcreteModel()
>>> m.p = Param(initialize=[(1,2),(3,4)], mutable=True, domain=Any)
>>> (1,2) in m.p
False
>>> (1,2) in m.p.value
True
```
<p>However, if you intend on updating the model iteratively (without rebuilding it), I would recommend making the param hold the RHS of the constraint.  That is, something more like:</p>
<pre class="lang-py prettyprint-override"><code>model = pe.ConcreteModel()

p_set = [(1,2), (2,3), (4,5)]
def par(m, i, j):
    return 1 if (i,j) in p_set else 0
model.par = pe.Param(model.edges, initialize=par, mutable=True)

def var_fix(model, i, j ):
    return model.v[i,j] == model.par[i,j]
model.var_fix = pe.Constraint(model.edges, rule=var_fix)
</code>```

This is because construction rules are not callbacks: they are called only when initially constructing the component and not during the solve.  Updating the Params would then look more like:

model.par.set_values(0)
for i,j in par_new:
    model.par[i,j] = 1
```

Body:
I create an optimization model in pyomo, and I have a list of tuples as a parameter “par”.

import pyomo.environ as pe
model = pe.ConcreteModel()
p_set = [(1,2), (2,3), (4,5)]
model.par = pe.Param(initialize=p_set, mutable= True)
def var_fix(model, i, j ):
    if (i,j) in model.par:
        constraint = (model.v[i,j] == 1)      # v is a binary variable
    else:
        constraint = (model.v[i,j] == 0)
    return constraint
model.var_fix = pe.Constraint(model.edges, rule=var_fix)

But, after printing “var_fix” constraint, all of them are equall to zero:

Key       : Lower : Body     : Upper : Active
(1, 2)   :   0.0     :   v[1,2] :   0.0     :   True
(2, 3)   :   0.0     :   v[2,3] :   0.0     :   True
(4, 5)   :   0.0     :   v[4,5] :   0.0     :   True

I define the parameter and constraint in this way since I want to iteratively change this parameter “par”  with a new one which may have different number of tuples, then solve the problem. In each iteration I will do :

# generating par_new based on some random processes
par_new = [(5,10), (2,3), (4,5), (11,8), (10,6)]
model.par = par_new
# solve the problem again

Body:
The crux of your problem is that you are defining a single ScalarParam that holds a list of tuples.  Scalar objects in Pyomo are special cases of their Indexed counderparts that use an implicit index of None.  This is done so that code working with Pyomo models can treat all components as if they were indexed (which prevents code from being littered with if comp.is_indexed(): tests).  The __contains__ test that you are doing (if (i,j) in model.par) is testing if the tuple is in the Param's indexing set, and not in the Param's value.

The simplest change is to change the test to check the Param's value:

>>> from pyomo.environ import *
>>> m = ConcreteModel()
>>> m.p = Param(initialize=[(1,2),(3,4)], mutable=True, domain=Any)
>>> (1,2) in m.p
False
>>> (1,2) in m.p.value
True

However, if you intend on updating the model iteratively (without rebuilding it), I would recommend making the param hold the RHS of the constraint.  That is, something more like:

model = pe.ConcreteModel()

p_set = [(1,2), (2,3), (4,5)]
def par(m, i, j):
    return 1 if (i,j) in p_set else 0
model.par = pe.Param(model.edges, initialize=par, mutable=True)

def var_fix(model, i, j ):
    return model.v[i,j] == model.par[i,j]
model.var_fix = pe.Constraint(model.edges, rule=var_fix)

This is because construction rules are not callbacks: they are called only when initially constructing the component and not during the solve.  Updating the Params would then look more like:

model.par.set_values(0)
for i,j in par_new:
    model.par[i,j] = 1


问:
List running local Shiny apps (and their port) from another R session
Assume I am running a Shiny app locally (I am not talking about Shiny server here), e.g.

```<code>library(shiny)
ui <- fluidPage()
server <- function(input, output) {}
shinyApp(ui = ui, server = server)
</code>```

which give the following output

```<code>Listening on http://127.0.0.1:3273
</code>```

In addition, http://127.0.0.1:3273 was automatically opened in a new tab in my web browser.

Assume I accidentally close my web browser, and I don't have a simple access to the window where Listening on http://127.0.0.1:3273 was printed (e.g. it is hidden, because run from an R script called from another script with some shady output redirection, or it is run from a container).

Problem: I do not know how to reopen my local Shiny app in my web browser because I do not remember which port it was using.

Questions:

Is there a simple way to know that a local Shiny app is running on port 3273 from another R session?

More generally, is there a way to list running local Shiny apps from another R session?

Note: I am trying to do that from R (eventually by using a specific R package) and without calling external system commands.

Edit: I know that if I close and reopen the app tag, it will be "reset" but it is not an issue.

答:
Usually, open TCP ports are managed by the OS so you can use system shell commands e.g. netstat -tulpn | grep LISTEN  | grep /R.
However, you can create an R function downloading HTML and detecting shiny specific text in it (here: the presence of the file shiny.min.css):

Let there be a shiny app running on the same host at port 3775:

```<code>library(tidyverse)
library(httr)

is_running_shiny <- function(port) {
  tryCatch(
    str_glue("http://127.0.0.1:{port}") %>%
      GET() %>%
      content() %>%
      as.character() %>%
      str_detect("shiny\\.min\\.css"),
    error = function(e) FALSE
  )
}

is_running_shiny(800)
# FALSE
is_running_shiny(3775)
# TRUE
</code>```

However, you need to run this function for every port of the totaling 65535.
Only the OS knows the list right away.

Body:
Assume I am running a Shiny app locally (I am not talking about Shiny server here), e.g.

library(shiny)
ui <- fluidPage()
server <- function(input, output) {}
shinyApp(ui = ui, server = server)

which give the following output

Listening on http://127.0.0.1:3273

In addition, http://127.0.0.1:3273 was automatically opened in a new tab in my web browser.

Assume I accidentally close my web browser, and I don't have a simple access to the window where Listening on http://127.0.0.1:3273 was printed (e.g. it is hidden, because run from an R script called from another script with some shady output redirection, or it is run from a container).

Problem: I do not know how to reopen my local Shiny app in my web browser because I do not remember which port it was using.

Questions:

Is there a simple way to know that a local Shiny app is running on port 3273 from another R session?

More generally, is there a way to list running local Shiny apps from another R session?

Note: I am trying to do that from R (eventually by using a specific R package) and without calling external system commands.

Edit: I know that if I close and reopen the app tag, it will be "reset" but it is not an issue.

Body:
Usually, open TCP ports are managed by the OS so you can use system shell commands e.g. netstat -tulpn | grep LISTEN  | grep /R.
However, you can create an R function downloading HTML and detecting shiny specific text in it (here: the presence of the file shiny.min.css):

Let there be a shiny app running on the same host at port 3775:

library(tidyverse)
library(httr)

is_running_shiny <- function(port) {
  tryCatch(
    str_glue("http://127.0.0.1:{port}") %>%
      GET() %>%
      content() %>%
      as.character() %>%
      str_detect("shiny\\.min\\.css"),
    error = function(e) FALSE
  )
}

is_running_shiny(800)
# FALSE
is_running_shiny(3775)
# TRUE

However, you need to run this function for every port of the totaling 65535.
Only the OS knows the list right away.


问:
Is there a way to kill uvicorn cleanly?
Is there a way to kill uvicorn cleanly?

I.e., I can type ^C at it, if it is running in the foreground on a terminal. This causes the uvivorn process to die and all of the worker processes to be cleaned up. (I.e., they go away.)

On the other hand, if uvicorn is running in the background without a terminal, then I can't figure out a way to kill it cleanly. It seems to ignore SIGTERM, SIGINT, and SIGHUP. I can kill it with SIGKILL (i.e. -9), but then the worker processes remain alive, and I have to track all the worker processes down and kill them too. This is not ideal.

I am using uvicorn with CPython 3.7.4, uvivorn version 0.11.2, and FastAPI 0.46.0 on Red Hat Enterprise Linux Server 7.3 (Maipo).

答:
In my case uvicorn managed to spawn new processes while pgrep -P was killing old ones,
so I decided to kill the whole process group at once, just like ^C does:

PID="$(pgrep -f example:app)"
if [[ -n "$PID" ]]
then
    PGID="$(ps --no-headers -p $PID -o pgid)"
    kill -SIGINT -- -${PGID// /}
fi
```

Each line explained:

pgrep -f example:app gets the PID of the parent uvicorn ... example:app

[[ -n "$PID" ]] checks this PID is not empty, to avoid further steps when uvicorn is not running

ps --no-headers -p $PID -o pgid gets PGID (Process Group ID) this PID is part of

kill -SIGINT is similar to polite ^C (you may use kill -9 for non-polite instant kill)

-- means the next token is a positional argument, not a named option, even if it starts with -

-${PGID - negative value lets kill know it is PGID, not PID

${PGID// /} removes all spaces ps added to PGID to align a column

Title: Is there a way to kill uvicorn cleanly?

Body:
In my case uvicorn managed to spawn new processes while pgrep -P was killing old ones,
so I decided to kill the whole process group at once, just like ^C does:

PID="$(pgrep -f example:app)"
if [[ -n "$PID" ]]
then
    PGID="$(ps --no-headers -p $PID -o pgid)"
    kill -SIGINT -- -${PGID// /}
fi

Each line explained:

pgrep -f example:app gets the PID of the parent uvicorn ... example:app

[[ -n "$PID" ]] checks this PID is not empty, to avoid further steps when uvicorn is not running

ps --no-headers -p $PID -o pgid gets PGID (Process Group ID) this PID is part of

kill -SIGINT is similar to polite ^C (you may use kill -9 for non-polite instant kill)

-- means the next token is a positional argument, not a named option, even if it starts with -

-${PGID - negative value lets kill know it is PGID, not PID

${PGID// /} removes all spaces ps added to PGID to align a column


问:
Connectx-6 LX scheduled sending only sending 25 packets
We are trying to use send scheduling on a Connectx-6 LX. If we set no timestamps on the packet buffers and manually send each packet at approximately the right time everything works. However if we set timestamps in the buffers then the first 25 packets are sent and the packets are received at the expected times but all subsequent calls to rte_eth_tx_burst return 0. If its relevant we are sending a single packet in each burst with timestamps 125 us apart.

We've tried setting the timestamps to low values and the packets are transmitted correctly and as expected the tx_pp_timestamp_past_errors value is incremented. We also set high values and this worked too with tx_pp_timestamp_future_errors incrementing.

Any ideas where to start debugging this? I couldn't see any API which would give an error code for rte_eth_tx_burst failing.

We're using DPDK 21.08 with the 5.4.3.1 Mellanox driver on Ubuntu 20.04.

答: It looks like this was caused by not having enough TX descriptors, we were only specifying 64, increasing to 1024 fixes the problem.</p>


问:
Python string formatting: padding negative numbers
I would like to format my integers as strings so that, without the sign, they will be zero-padded to have at least two digits.

For example I want

```<code>1
-1
10
-10
</code>```

to be

```<code>01
-01
10
-10
</code>```

Specifically, I want different minimum string lengths for negative numbers (3) and non-negative numbers (2). Simple number padding as detailed here is insufficient. Is this possible?

Body:
I would like to format my integers as strings so that, without the sign, they will be zero-padded to have at least two digits.

For example I want

1
-1
10
-10

to be

01
-01
10
-10

Specifically, I want different minimum string lengths for negative numbers (3) and non-negative numbers (2). Simple number padding as detailed here is insufficient. Is this possible?

Body:
Use zfill:

inp_list = [1,-1,10,-10,4]

out_list = [str(n).zfill(3 if n<0 else 2) for n in inp_list]

print(out_list)

result:

['01', '-01', '10', '-10', '04']


问:
How should I structure this code to break out of multiple nested loops at once?
I'm learning image detection and python writing a bot for a 2d game. There are certain targets we want to attack and certain targets we want to avoid. One target is displayed on the screen at a time out of a pool of 100 and you click next or attack depending on what you want to do. In doing this you're able to cycle through targets until you find one you want to attack. My code currently checks to see if it finds one of 24 different targets we want to avoid, if it does it avoids that target. Otherwise, it attacks that target.

At the moment my code:

```<code>1. Loads 24 different images of things we want to avoid into a NumPy array and checks with `py.locateCenterOnScreen`
   if we are on the correct screen to start the video loop
2. Uses cv2.imshow to display a real-time view of what is happening for use later with cv2.rectangles
3. Continuously loops through the NumPy array to determine if any of the loaded images have been found
4. If anything has been found it will either print "avoid" or "attack" to the terminal.
</code>```

There's also additional logging that I've not added to the below code as it isn't relevant. It simply logs the attack/avoid to a .txt file with time stamps.

```<code>My issue:
</code>```

At the moment my object detection loop for i in image_list: never stops when it finds one of the 24 images, it loops over them again and again swapping away from the found image.

```<code>My question:
</code>```

When one of the 24 images is detected, how do I stop my detection loop without stopping my cv2.imshow loop. For example, if image 5 is found. I want to keep image 5 highlighted with cv2.rectangle rather than only having it highlight for a fraction of a second when it comes up in the detection loop.

```<code># Load Images
def loadImages(directory):
    # Intialise empty array
    image_list = []
    # Add images to array
    for i in directory:
        img = cv.imread(i, cv.IMREAD_REDUCED_GRAYSCALE_2)
        image_list.append((img, i))
    return image_list

def objectDetection(image_list, threshold_value):
    # Video Loop
    while True:
        # Listener to check if attack! button displaying
        if py.locateCenterOnScreen('!attack.jpg', region = (1282, 931, 1585-1282, 1032-931), grayscale=True) != None:
            # Set attack_loop to false as haven't found anything yet, only set to true when something has been attacked
            attack_loop = False
            while attack_loop is False:
                # Grab PSS Window and find size
                window = pygetwindow.getWindowsWithTitle('App')[0]
                x1 = window.left
                y1 = window.top
                height = window.height
                width = window.width
                x2 = x1 + width
                y2 = y1 + height
                # Actual Video Loop, cropped down to the specific window,
                # resized to 1/2 size, and converted to BGR for OpenCV
                haystack_img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
                (width, height) = (haystack_img.width // 2, haystack_img.height // 2)
                haystack_img_resized = haystack_img.resize((width, height))
                crop = haystack_img_resized.crop((360,22,600,65))
                haystack_img_np = np.array(crop)
                haystack = cv.cvtColor(haystack_img_np, cv.COLOR_BGR2GRAY)
                cv.imshow("Screen", haystack)

                # Object Detection
                for i in image_list:
                    needle_img = i[0]
                    needle_name = i[1]
                    result = cv.matchTemplate(haystack, needle_img, cv.TM_CCORR_NORMED)

                    # Get the best match position
                    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)

                    # Define top left and bottom right and threshold
                    (H, W) = i[0].shape[:2]
                    top_left = max_loc
                    bottom_right = (top_left[0] + W, top_left[1] + H)
                    threshold = threshold_value

                    # If something has been detected click keep looking code
                    if max_val >= threshold:
                        cv.rectangle(haystack, top_left, bottom_right, 255, 2)
                        print("avoid")
                    else:
                        print("attack")
                        if max_val >= threshold:print(max_val)

### Main Script ###

# load images to detect
ships_to_avoid = loadImages(defeat)
# Run actual image detection
objectDetection(ships_to_avoid, 0.92)
</code>```

答:
If you want to break an inner loop breaking also the outer loop I would suggest an approach like this:

```<code>for a in xrange(10):
    for b in xrange(20):
        if <condition>:
            # Break the inner loop...
            break
    else: # The loop ended without any break
        # Continue if the inner loop wasn't broken.
        continue
    # Inner loop was broken, break the outer.
    break
</code>```

Body:
I'm learning image detection and python writing a bot for a 2d game. There are certain targets we want to attack and certain targets we want to avoid. One target is displayed on the screen at a time out of a pool of 100 and you click next or attack depending on what you want to do. In doing this you're able to cycle through targets until you find one you want to attack. My code currently checks to see if it finds one of 24 different targets we want to avoid, if it does it avoids that target. Otherwise, it attacks that target.

At the moment my code:

1. Loads 24 different images of things we want to avoid into a NumPy array and checks with `py.locateCenterOnScreen`
   if we are on the correct screen to start the video loop
2. Uses cv2.imshow to display a real-time view of what is happening for use later with cv2.rectangles
3. Continuously loops through the NumPy array to determine if any of the loaded images have been found
4. If anything has been found it will either print "avoid" or "attack" to the terminal.

There's also additional logging that I've not added to the below code as it isn't relevant. It simply logs the attack/avoid to a .txt file with time stamps.

My issue:

At the moment my object detection loop for i in image_list: never stops when it finds one of the 24 images, it loops over them again and again swapping away from the found image.

My question:

When one of the 24 images is detected, how do I stop my detection loop without stopping my cv2.imshow loop. For example, if image 5 is found. I want to keep image 5 highlighted with cv2.rectangle rather than only having it highlight for a fraction of a second when it comes up in the detection loop.

# Load Images
def loadImages(directory):
    # Intialise empty array
    image_list = []
    # Add images to array
    for i in directory:
        img = cv.imread(i, cv.IMREAD_REDUCED_GRAYSCALE_2)
        image_list.append((img, i))
    return image_list

def objectDetection(image_list, threshold_value):
    # Video Loop
    while True:
        # Listener to check if attack! button displaying
        if py.locateCenterOnScreen('!attack.jpg', region = (1282, 931, 1585-1282, 1032-931), grayscale=True) != None:
            # Set attack_loop to false as haven't found anything yet, only set to true when something has been attacked
            attack_loop = False
            while attack_loop is False:
                # Grab PSS Window and find size
                window = pygetwindow.getWindowsWithTitle('App')[0]
                x1 = window.left
                y1 = window.top
                height = window.height
                width = window.width
                x2 = x1 + width
                y2 = y1 + height
                # Actual Video Loop, cropped down to the specific window,
                # resized to 1/2 size, and converted to BGR for OpenCV
                haystack_img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
                (width, height) = (haystack_img.width // 2, haystack_img.height // 2)
                haystack_img_resized = haystack_img.resize((width, height))
                crop = haystack_img_resized.crop((360,22,600,65))
                haystack_img_np = np.array(crop)
                haystack = cv.cvtColor(haystack_img_np, cv.COLOR_BGR2GRAY)
                cv.imshow("Screen", haystack)

                # Object Detection
                for i in image_list:
                    needle_img = i[0]
                    needle_name = i[1]
                    result = cv.matchTemplate(haystack, needle_img, cv.TM_CCORR_NORMED)

                    # Get the best match position
                    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)

                    # Define top left and bottom right and threshold
                    (H, W) = i[0].shape[:2]
                    top_left = max_loc
                    bottom_right = (top_left[0] + W, top_left[1] + H)
                    threshold = threshold_value

                    # If something has been detected click keep looking code
                    if max_val >= threshold:
                        cv.rectangle(haystack, top_left, bottom_right, 255, 2)
                        print("avoid")
                    else:
                        print("attack")
                        if max_val >= threshold:print(max_val)

### Main Script ###

# load images to detect
ships_to_avoid = loadImages(defeat)
# Run actual image detection
objectDetection(ships_to_avoid, 0.92)

Body:
If you want to break an inner loop breaking also the outer loop I would suggest an approach like this:

for a in xrange(10):
    for b in xrange(20):
        if <condition>:
            # Break the inner loop...
            break
    else: # The loop ended without any break
        # Continue if the inner loop wasn't broken.
        continue
    # Inner loop was broken, break the outer.
    break


问:
Spring Kafka BufferExhaustedException sending messages in loop
I'm using the spring-kafka dependency version 2.8.1 with the following config:

```<code>  kafka:
    bootstrap-servers: localhost:9092
    producer:
      acks: all
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.apache.kafka.common.serialization.StringSerializer
      buffer-memory: 16384
</code>```

I'm trying to send about 65.000 messages to a topic but my server crashes with the following exception:

```<code>org.springframework.kafka.KafkaException: Send failed; nested exception is org.apache.kafka.clients.producer.BufferExhaustedException: Failed to allocate memory within the configured max blocking time 60000 ms.
</code>```

This is how I'm sending all of these messages to my topic:

```<code>public processMessages(List<Message> messages){
    for (Message msg: messages) {
        kafkaTemplate.send("prepared-messages", message.toJson());
    }
}
</code>```

I tried setting the batch size to 0 but that also didn't work.

答:
Have you tried increasing buffer.memory?

https://kafka.apache.org/documentation/#producerconfigs_buffer.memory

The total bytes of memory the producer can use to buffer records waiting to be sent to the server. If records are sent faster than they can be delivered to the server the producer will block for max.block.ms after which it will throw an exception.

This setting should correspond roughly to the total memory the producer will use, but is not a hard bound since not all memory the producer uses is used for buffering. Some additional memory will be used for compression (if compression is enabled) as well as for maintaining in-flight requests.

Body:
I'm using the spring-kafka dependency version 2.8.1 with the following config:

  kafka:
    bootstrap-servers: localhost:9092
    producer:
      acks: all
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.apache.kafka.common.serialization.StringSerializer
      buffer-memory: 16384

I'm trying to send about 65.000 messages to a topic but my server crashes with the following exception:

org.springframework.kafka.KafkaException: Send failed; nested exception is org.apache.kafka.clients.producer.BufferExhaustedException: Failed to allocate memory within the configured max blocking time 60000 ms.

This is how I'm sending all of these messages to my topic:

public processMessages(List<Message> messages){
    for (Message msg: messages) {
        kafkaTemplate.send("prepared-messages", message.toJson());
    }
}

I tried setting the batch size to 0 but that also didn't work.


问:
Swift iOS sometimes not detecting touches
I am creating an iOS keyboard extension with UIInputViewController, and using UIButton for each key. I have two issues:

Sometimes buttons don't detect touches.

Touches at the edges of the screen are recognized with a delay.

I assume first one happens when I type too fast, or when touch area is too big (bigger than the button). I tried using different methods of detecting touch (button target, touchesBegan, touchesEnded, UITapGestureRecognizer) and all have the same issue.

I assume second happens because of the iOS edge false touch rejection. I tried changing preferredScreenEdgesDeferringSystemGestures but it had no effect.

Please help.

答:
Turns out I was playing a quick animation on the UIButton press, so I had to set .allowUserInteraction in the animation options.

I used UILongPressGestureRecognizer with minimumPressDuration = 0 which, for some reason, is always instant even at the edges.


问:
Project an array in jsonb
Suppose we have this table:

```<code>CREATE TEMPORARY TABLE TEST (FIELD jsonb);
INSERT INTO TEST VALUES ('[{"key": 1},{"key": 2}]');
SELECT field FROM TEST;
</code>```

Result:

```<code>field
[{"key": 1}, {"key": 2}]
</code>```

I would like to query the table in order to obtain this result:

```<code>field
[1, 2]
</code>```

that is, to project every element in the array respect to their key.

Can't find a simple way to do that.

答:
You can use a JSON path query:

```<code>SELECT jsonb_path_query_array(field, '$[*].key')
FROM test;
</code>```

[*] iterates over all values in the array and .key then returns the value for each key.

Title: Project an array in jsonb

Body:
Suppose we have this table:

CREATE TEMPORARY TABLE TEST (FIELD jsonb);
INSERT INTO TEST VALUES ('[{"key": 1},{"key": 2}]');
SELECT field FROM TEST;

Result:

field
[{"key": 1}, {"key": 2}]

I would like to query the table in order to obtain this result:

field
[1, 2]

that is, to project every element in the array respect to their key.

Can't find a simple way to do that.

Body:
You can use a JSON path query:

SELECT jsonb_path_query_array(field, '$[*].key')
FROM test;

[*] iterates over all values in the array and .key then returns the value for each key.


问:
How to refresh template of component by changing variable in other component Angular 13
I have component HeaderComponent with the following template :

```<code><button *ngIf="isConnected">Logout</button>
</code>```

And the template in composant LoginComponent

```<code><button (click)="login()">login</button>
</code>```

In AppComponent :

```<code><app-header></app-header>
<app-login></app-login>
</code>```

I would like to show Logout button when I click login button

Thank you for your helps

答:
you have a couple of options, you can work with Input() and Output()  or you could work with a shared service.

for example:
in login.service.ts

isConnected = false;
```
<p>in login.component.ts</p>
<pre class="lang-js prettyprint-override"><code>public login(){
  this.loginService.isConnected = true;
}
</code>```

in app.component.html

<app-header *ngIf="loginService.isConnected></app-header>
```

Body:
I have component HeaderComponent with the following template :

<button *ngIf="isConnected">Logout</button>

And the template in composant LoginComponent

<button (click)="login()">login</button>

In AppComponent :

<app-header></app-header>
<app-login></app-login>

I would like to show Logout button when I click login button

Thank you for your helps

Body:
you have a couple of options, you can work with Input() and Output()  or you could work with a shared service.

for example:
in login.service.ts

isConnected = false;

in login.component.ts

public login(){
  this.loginService.isConnected = true;
}

in app.component.html

<app-header *ngIf="loginService.isConnected></app-header>


问:
npm install hangs
This is my package.json:

```<code>{
"name": "my-example-app",
"version": "0.1.0",
"dependencies": {

  "request": "*",
  "nano": "3.3.x",
  "async": "~0.2"
  }
}
</code>```

Now, when I open the cmd and run npm install, the install hangs. What am I doing wrong?

答:
npm cache clear --force has fixed this issue for me in the past.

Furthermore, when running npm install on an air-gapped network (by the way, I provide a description about how to do this with Verdaccio), I had an issue where the install would hang at the very end. Turning off auditing (i.e. npm set audit false) on the machine on the air-gapped network resolved this issue.

Title: npm install hangs

Body:
This is my package.json:

{
"name": "my-example-app",
"version": "0.1.0",
"dependencies": {

  "request": "*",
  "nano": "3.3.x",
  "async": "~0.2"
  }
}

Now, when I open the cmd and run npm install, the install hangs. What am I doing wrong?


问:
How to mock third party API calls?
I have a spring boot application that has the below AuthFilter added for all rest apis exposed by the application. I want to test the below code that validates authorization token by calling a third party api call. I tried Mockito but how do I inject the mocked HttpPost, HttpClient etc object in the filter class?
Also what value do I pass to thirdPartyAPIUrl property which is configured in application.properties for test class

```<code>@Component
public class AuthTokenFilter implements Filter {

     public boolean isAuthTokenValid(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String authorizationToken = request.getHeader(RequestHeaders.AUTHORIZATION.toString());

        TokenRequest validateTokenRequest = new TokenRequest();
        validateTokenRequest.setToken(authorizationToken);

        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(this.thirdPartyAPIUrl); //fetched through application.properties
            httpPost.setHeader("Content-type", "application/json");
            StringEntity requestBody = new StringEntity(new Gson().toJson(validateTokenRequest));

            httpPost.setEntity(requestBody);
            try (CloseableHttpResponse validateTokenResponse = httpclient.execute(httpPost)) {
                HttpEntity rEntity = validateTokenResponse.getEntity();
                TokenResponse tokenResponse = new ObjectMapper().readValue(rEntity.getContent(),
                                                                                TokenResponse.class);
                logger.debug("API Response Object : {}", tokenResponse);
            }
        }

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

Thanks!

答:
I would recommend avoiding mocking HttpPost etc and instead just mocking the third-party server. My preferred tool to use for this is wiremock

Here is an example of how it would be used:

(make sure to import this for options, caused me a lot of headaches ;) )

```<code>import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
</code>```

... code

```<code>static WireMockServer wireMockServer = new WireMockServer(options().port(8080));

@BeforeAll
static void init() {
    wireMockServer.start();
}

//this is for the case that you have multiple test suites that mock the server, to avoid conflicts with ports
@AfterAll
static void releaseResource() {
        wireMockServer.stop();
    }

@Test
void test() {
    wireMockServer.stubFor(post("/endpoint").willReturn(aResponse().withStatus(200)));
</code>```

... more code

```<code>    filter.isAuthTokenValid(request, response);
}
</code>```

Title: How to mock third party API calls?

Body:
I have a spring boot application that has the below AuthFilter added for all rest apis exposed by the application. I want to test the below code that validates authorization token by calling a third party api call. I tried Mockito but how do I inject the mocked HttpPost, HttpClient etc object in the filter class?
Also what value do I pass to thirdPartyAPIUrl property which is configured in application.properties for test class

@Component
public class AuthTokenFilter implements Filter {

     public boolean isAuthTokenValid(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String authorizationToken = request.getHeader(RequestHeaders.AUTHORIZATION.toString());

        TokenRequest validateTokenRequest = new TokenRequest();
        validateTokenRequest.setToken(authorizationToken);

        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(this.thirdPartyAPIUrl); //fetched through application.properties
            httpPost.setHeader("Content-type", "application/json");
            StringEntity requestBody = new StringEntity(new Gson().toJson(validateTokenRequest));

            httpPost.setEntity(requestBody);
            try (CloseableHttpResponse validateTokenResponse = httpclient.execute(httpPost)) {
                HttpEntity rEntity = validateTokenResponse.getEntity();
                TokenResponse tokenResponse = new ObjectMapper().readValue(rEntity.getContent(),
                                                                                TokenResponse.class);
                logger.debug("API Response Object : {}", tokenResponse);
            }
        }

        return false; //temporary
    }
}

Thanks!

Body:
I would recommend avoiding mocking HttpPost etc and instead just mocking the third-party server. My preferred tool to use for this is wiremock

Here is an example of how it would be used:

(make sure to import this for options, caused me a lot of headaches ;) )

import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;

... code

static WireMockServer wireMockServer = new WireMockServer(options().port(8080));

@BeforeAll
static void init() {
    wireMockServer.start();
}

//this is for the case that you have multiple test suites that mock the server, to avoid conflicts with ports
@AfterAll
static void releaseResource() {
        wireMockServer.stop();
    }

@Test
void test() {
    wireMockServer.stubFor(post("/endpoint").willReturn(aResponse().withStatus(200)));

... more code

    filter.isAuthTokenValid(request, response);
}


问:
Xcode Failed to resolve dependency Firebase - GoogleAppMeasurement does not match requirement
I'm new to coding on Xcode and im trying to install Firebase on my project but i have an error that I don't know how to solve.
I have followed all the instructions from Firebase but still have the issue…

First issue:

Dependencies could not be resolved because no versions of 'GoogleAppMeasurement' match the requirement 8.12.0 and root depends on 'GoogleAppMeasurement' 8.12.0.
Failed to resolve dependencies

Second issue:

no such module 'Firebase'

Cannot find 'FirebaseApp' in scope

```<code>import UIKit
import Firebase

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        return true
    }
</code>```

How can I fix it?

Thanks for the help :)

答:
As Paul Beusterien correctly pointed out, we shouldn't use version 8.12.0 as it is still under development. However, I think this issue can happen when using Swift Package Manager (SPM) and 'master' as the version rule for the Firebase SDK.

After I've changed it to '8.11.0 - Next Major' everything was fetched correctly again and worked perfectly fine. Maybe it is enough to simply change the rules once.

To change the rules simply do the following (see screenshots below):

Select the project in the project navigator (Shortcut CMD + 1 to open the project navigator).

In the new view, you will get a list of the project and your targets. Select the project itself.

Select the tab 'Package Dependencies' at the top.

Double-click the 'firebase-ios-sdk' entry.

Change the version rule in the dialog.

Good luck!

Body:
I'm new to coding on Xcode and im trying to install Firebase on my project but i have an error that I don't know how to solve.
I have followed all the instructions from Firebase but still have the issue…

First issue:

Dependencies could not be resolved because no versions of 'GoogleAppMeasurement' match the requirement 8.12.0 and root depends on 'GoogleAppMeasurement' 8.12.0.
Failed to resolve dependencies

Second issue:

no such module 'Firebase'

Cannot find 'FirebaseApp' in scope

import UIKit
import Firebase

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        return true
    }

How can I fix it?

Thanks for the help :)


问:
How to disable other buttons onclick for a short period of time
i have simple quizz project where i fetch data of questions and answers my problem is when i click on one of the answers i want other buttons to be disabled because if someone keeps pressing on other options the quiz will rapidly change questions. i want to disable other answer options when i clik on the  answer and then after the next question generates enable them again and so on</p>
```<code>
import './App.css';
import axios from 'axios'
import {useState,useEffect} from 'react'

function App() {
  const [quiz,setQuiz] = useState([])
  const [answer,setAnswer] = useState([])
  const [correct,setCorrect] =useState('')
  const [points,setPoints] = useState(0)
  const [turns,setTurns] = useState(0)
  const [disabled,setDisabled] = useState(false)

  function refreshPage() {
    window.location.reload(false);
  }

  useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
    .then(res =>{
       setQuiz(res.data.results[0])
       let tempVar = res.data.results[0] ;
       setAnswer([...tempVar.incorrect_answers,tempVar.correct_answer].sort(()=>Math.random() - 0.5))
      setCorrect(tempVar.correct_answer)
      console.log(res.data)
      console.log(answer)

    })
    .catch(err=>{
      console.log(err);
    })
  },[])

  const  handleClick = (e) =>{
    setDisabled(true)
    if(disabled && e.target.innerText === correct){

      setPoints(points + 1)
      setTurns(turns + 1)
      e.target.style.background = 'green'
      setTimeout(() => e.target.style.background = '', 2000);

      setTimeout(() => {
        axios.get('https://opentdb.com/api.php?amount=10')
        .then(res=>{
           setQuiz(res.data.results[0])
           let tempVar = res.data.results[0] ;
           setAnswer([...tempVar.incorrect_answers,tempVar.correct_answer].sort(()=>Math.random() - 0.5))
          setCorrect(tempVar.correct_answer)
      })
      .catch(err=>{
        console.log(err);
      })
    }, 2000);
    console.log(points)
    } else if(e.target.innerText !== correct){
      setTurns(turns + 1)
      e.target.style.background = 'red'
     setTimeout(() => e.target.style.background='', 2000);

      setTimeout(() => {
        axios.get('https://opentdb.com/api.php?amount=10')
        .then(res=>{
           setQuiz(res.data.results[0])
           let tempVar = res.data.results[0] ;
           setAnswer([...tempVar.incorrect_answers,tempVar.correct_answer].sort(()=>Math.random() - 0.5))
          setCorrect(tempVar.correct_answer)
      })
      .catch(err=>{
        console.log(err);
      })
    }, 2000);
    }
    }

if(points >= 10|| turns >= 10){
  return (
    <div className='score'>
      <h1>Well done !</h1>
     <p>Your Score: {points}</p>
      <button className='button-28' onClick={refreshPage}>New Test</button>
    </div>
  )
}

  return (
    <div className="App">
     <div className='grid'>
   <h1>{quiz.question}</h1>
   { answer?.map(answers =>
   <button className='button-28' onClick={handleClick}key={answers}>{answers}</button>
   )
   }

    </div>
    </div>

  );
}

export default App;
</code>```

答:
Here's how you can achieve what you wanted, I tried to do in your code
I added a state for tracking user's selected answer and that way you can disable other answers.</p>
```<code>import "./styles.css";
import axios from "axios";
import { useState, useEffect } from "react";

function App() {
  const [quiz, setQuiz] = useState([]);
  const [answer, setAnswer] = useState([]);
  const [correct, setCorrect] = useState("");
  const [selectedAnswer, setSelectedAnswer] = useState("");
  const [points, setPoints] = useState(0);
  const [turns, setTurns] = useState(0);
  const [disabled, setDisabled] = useState(false);

  function refreshPage() {
    window.location.reload(false);
  }

  useEffect(() => {
    axios
      .get("https://opentdb.com/api.php?amount=10")
      .then((res) => {
        setQuiz(res.data.results[0]);
        let tempVar = res.data.results[0];
        setAnswer(
          [...tempVar.incorrect_answers, tempVar.correct_answer].sort(
            () => Math.random() - 0.5
          )
        );
        setCorrect(tempVar.correct_answer);
        console.log(res.data);
        console.log(answer);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  const handleClick = (userAnswer) => (e) => {
    setSelectedAnswer(userAnswer);
    setDisabled(true);
    if (disabled && e.target.innerText === correct) {
      setPoints(points + 1);
      setTurns(turns + 1);
      e.target.style.background = "green";
      setTimeout(() => (e.target.style.background = ""), 2000);

      setTimeout(() => {
        axios
          .get("https://opentdb.com/api.php?amount=10")
          .then((res) => {
            setQuiz(res.data.results[0]);
            let tempVar = res.data.results[0];
            setAnswer(
              [...tempVar.incorrect_answers, tempVar.correct_answer].sort(
                () => Math.random() - 0.5
              )
            );
            setCorrect(tempVar.correct_answer);
            setSelectedAnswer("");
          })
          .catch((err) => {
            console.log(err);
          });
      }, 2000);
      console.log(points);
    } else if (e.target.innerText !== correct) {
      setTurns(turns + 1);
      e.target.style.background = "red";
      setTimeout(() => (e.target.style.background = ""), 2000);

      setTimeout(() => {
        axios
          .get("https://opentdb.com/api.php?amount=10")
          .then((res) => {
            setQuiz(res.data.results[0]);
            let tempVar = res.data.results[0];
            setAnswer(
              [...tempVar.incorrect_answers, tempVar.correct_answer].sort(
                () => Math.random() - 0.5
              )
            );
            setCorrect(tempVar.correct_answer);
            setSelectedAnswer("");
          })
          .catch((err) => {
            console.log(err);
          });
      }, 2000);
    }
  };

  if (points >= 10 || turns >= 10) {
    return (
      <div className="score">
        <h1>Well done !</h1>
        <p>Your Score: {points}</p>
        <button className="button-28" onClick={refreshPage}>
          New Test
        </button>
      </div>
    );
  }

  return (
    <div className="App">
      <div className="grid">
        <h1>{quiz.question}</h1>
        {answer?.map((answers) => (
          <button
            disabled={selectedAnswer && answers !== selectedAnswer}
            className="button-28"
            onClick={handleClick(answers)}
            key={answers}
          >
            {answers}
          </button>
        ))}
      </div>
    </div>
  );
}

export default App;
</code>```

Body:
i have simple quizz project where i fetch data of questions and answers my problem is when i click on one of the answers i want other buttons to be disabled because if someone keeps pressing on other options the quiz will rapidly change questions. i want to disable other answer options when i clik on the  answer and then after the next question generates enable them again and so on

import './App.css';
import axios from 'axios'
import {useState,useEffect} from 'react'

function App() {
  const [quiz,setQuiz] = useState([])
  const [answer,setAnswer] = useState([])
  const [correct,setCorrect] =useState('')
  const [points,setPoints] = useState(0)
  const [turns,setTurns] = useState(0)
  const [disabled,setDisabled] = useState(false)

  function refreshPage() {
    window.location.reload(false);
  }

  useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
    .then(res =>{
       setQuiz(res.data.results[0])
       let tempVar = res.data.results[0] ;
       setAnswer([...tempVar.incorrect_answers,tempVar.correct_answer].sort(()=>Math.random() - 0.5))
      setCorrect(tempVar.correct_answer)
      console.log(res.data)
      console.log(answer)

    })
    .catch(err=>{
      console.log(err);
    })
  },[])

  const  handleClick = (e) =>{
    setDisabled(true)
    if(disabled && e.target.innerText === correct){

      setPoints(points + 1)
      setTurns(turns + 1)
      e.target.style.background = 'green'
      setTimeout(() => e.target.style.background = '', 2000);

      setTimeout(() => {
        axios.get('https://opentdb.com/api.php?amount=10')
        .then(res=>{
           setQuiz(res.data.results[0])
           let tempVar = res.data.results[0] ;
           setAnswer([...tempVar.incorrect_answers,tempVar.correct_answer].sort(()=>Math.random() - 0.5))
          setCorrect(tempVar.correct_answer)
      })
      .catch(err=>{
        console.log(err);
      })
    }, 2000);
    console.log(points)
    } else if(e.target.innerText !== correct){
      setTurns(turns + 1)
      e.target.style.background = 'red'
     setTimeout(() => e.target.style.background='', 2000);

      setTimeout(() => {
        axios.get('https://opentdb.com/api.php?amount=10')
        .then(res=>{
           setQuiz(res.data.results[0])
           let tempVar = res.data.results[0] ;
           setAnswer([...tempVar.incorrect_answers,tempVar.correct_answer].sort(()=>Math.random() - 0.5))
          setCorrect(tempVar.correct_answer)
      })
      .catch(err=>{
        console.log(err);
      })
    }, 2000);
    }
    }

if(points >= 10|| turns >= 10){
  return (

Well done !

Your Score: {points}

      <button className='button-28' onClick={refreshPage}>New Test</button>

  )
}

  return (

{quiz.question}

   { answer?.map(answers =>
   <button className='button-28' onClick={handleClick}key={answers}>{answers}</button>
   )
   }

  );
}

export default App;

Body:
Here's how you can achieve what you wanted, I tried to do in your code
I added a state for tracking user's selected answer and that way you can disable other answers.

import "./styles.css";
import axios from "axios";
import { useState, useEffect } from "react";

function App() {
  const [quiz, setQuiz] = useState([]);
  const [answer, setAnswer] = useState([]);
  const [correct, setCorrect] = useState("");
  const [selectedAnswer, setSelectedAnswer] = useState("");
  const [points, setPoints] = useState(0);
  const [turns, setTurns] = useState(0);
  const [disabled, setDisabled] = useState(false);

  function refreshPage() {
    window.location.reload(false);
  }

  useEffect(() => {
    axios
      .get("https://opentdb.com/api.php?amount=10")
      .then((res) => {
        setQuiz(res.data.results[0]);
        let tempVar = res.data.results[0];
        setAnswer(
          [...tempVar.incorrect_answers, tempVar.correct_answer].sort(
            () => Math.random() - 0.5
          )
        );
        setCorrect(tempVar.correct_answer);
        console.log(res.data);
        console.log(answer);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  const handleClick = (userAnswer) => (e) => {
    setSelectedAnswer(userAnswer);
    setDisabled(true);
    if (disabled && e.target.innerText === correct) {
      setPoints(points + 1);
      setTurns(turns + 1);
      e.target.style.background = "green";
      setTimeout(() => (e.target.style.background = ""), 2000);

      setTimeout(() => {
        axios
          .get("https://opentdb.com/api.php?amount=10")
          .then((res) => {
            setQuiz(res.data.results[0]);
            let tempVar = res.data.results[0];
            setAnswer(
              [...tempVar.incorrect_answers, tempVar.correct_answer].sort(
                () => Math.random() - 0.5
              )
            );
            setCorrect(tempVar.correct_answer);
            setSelectedAnswer("");
          })
          .catch((err) => {
            console.log(err);
          });
      }, 2000);
      console.log(points);
    } else if (e.target.innerText !== correct) {
      setTurns(turns + 1);
      e.target.style.background = "red";
      setTimeout(() => (e.target.style.background = ""), 2000);

      setTimeout(() => {
        axios
          .get("https://opentdb.com/api.php?amount=10")
          .then((res) => {
            setQuiz(res.data.results[0]);
            let tempVar = res.data.results[0];
            setAnswer(
              [...tempVar.incorrect_answers, tempVar.correct_answer].sort(
                () => Math.random() - 0.5
              )
            );
            setCorrect(tempVar.correct_answer);
            setSelectedAnswer("");
          })
          .catch((err) => {
            console.log(err);
          });
      }, 2000);
    }
  };

  if (points >= 10 || turns >= 10) {
    return (
      <div className="score">
        <h1>Well done !</h1>
        <p>Your Score: {points}</p>
        <button className="button-28" onClick={refreshPage}>
          New Test
        </button>
      </div>
    );
  }

  return (
    <div className="App">
      <div className="grid">
        <h1>{quiz.question}</h1>
        {answer?.map((answers) => (
          <button
            disabled={selectedAnswer && answers !== selectedAnswer}
            className="button-28"
            onClick={handleClick(answers)}
            key={answers}
          >
            {answers}
          </button>
        ))}
      </div>
    </div>
  );
}

export default App;


问:
help with SQL query in Yii
Given the following diagram:

With the code below I have the Donations grouped for each organization now I am trying to calculate the total amount a given member has donated to a given organization.

Something like:

With this code it correctly groups that organizations as I need but the problem I have here is that for the 'Amount Donated to Organization' column all values equal the total of the Organization with the highest Id.  Therefore all rows in that column are showing $90

Yii Code:

```<code>// member view
<?php
     $dataProvider=new CActiveDataProvider(Donation::model(), array(
        'criteria'=>array(
            'with' => array(
                'member' => array(
                    'on'=>'member.MemberId='.$model->MemberId,
                    'group' => 't.MemberId, t.OrganizationId',
                    'joinType'=>'INNER JOIN',
                    ),
                ),
        'together'=> true,
        ),
    ));
    $this->widget('zii.widgets.grid.CGridView', array(
        'dataProvider'=>$dataProvider,
        'columns' => array(
            array(
               'name'=>'OrganizationId',
               'value' => '$data->OrganizationId',
            ),
            array(
               'name'=>'Amount',
               'value' => '$data->memberOrgBalance;',
            ),
        ),
    ));
?>

// member model

'memberOrgBalance' => array(self::STAT, 'Donation', 'MemberId',
       'select'=>'MemberId, OrganizationId, SUM(Amount)',
       'group' => 'OrganizationId'),

// donation model

'member' => array(self::BELONGS_TO, 'Member', 'MemberId'),
</code>```

EDIT: See also response to LDG

Using the advice from LDG I tried adding 'having' to my dataprovider, when that did not seem to affect the query I tried to add it to the relation memberOrgBalance where I am trying to pull the data.  This seems to affect the query but it is still not right.  I switched to:

```<code>'memberOrgBalance' => array(self::STAT, 'Donation', 'MemberId',
        'select'=>'MemberId, OrganizationId, SUM(Amount)',
        'group' => 'OrganizationId',
        'having'=> 'MemberId=member.MemberId',
        ),
</code>```

which gives this error:

```<code>   CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]:
Column not found: 1054 Unknown column 'member.MemberId' in 'having clause'.
The SQL statement executed was: SELECT `MemberId ` AS `c`, MemberId, OrganizationId,
SUM(Amount) AS `s` FROM `donation` `t` WHERE (`t`.`MemberId `='2')
GROUP BY `MemberId `, OrganizationId HAVING (MemberId=member.MemberId)
</code>```

This makes no sense since from the donation table I have the relation defined as originally posted above.  The query seems to be going the direction needed to get the SUM per organization as I want though.  Any other ideas?

答:
Ok after running around in circles with this someone was able to push me over the top to a solution on Yii forums.

The end result is

```<code>$criteria->condition='member.MemberId="'.$model->MemberId.'"';
$criteria->with='member';
$criteria->select='MemberId,OrganizationId,sum(Amount) as Amount';
$criteria->group='t.MemberId,OrganizationId';
$dataProvider=new CActiveDataProvider(Donations::model(),
    array(
        'criteria'=>$criteria,
</code>```

Thanks ldg for the help with this.

Title: help with SQL query in Yii

Body:
Given the following diagram:

With the code below I have the Donations grouped for each organization now I am trying to calculate the total amount a given member has donated to a given organization.

Something like:

With this code it correctly groups that organizations as I need but the problem I have here is that for the 'Amount Donated to Organization' column all values equal the total of the Organization with the highest Id.  Therefore all rows in that column are showing $90

Yii Code:

// member view
<?php
     $dataProvider=new CActiveDataProvider(Donation::model(), array(
        'criteria'=>array(
            'with' => array(
                'member' => array(
                    'on'=>'member.MemberId='.$model->MemberId,
                    'group' => 't.MemberId, t.OrganizationId',
                    'joinType'=>'INNER JOIN',
                    ),
                ),
        'together'=> true,
        ),
    ));
    $this->widget('zii.widgets.grid.CGridView', array(
        'dataProvider'=>$dataProvider,
        'columns' => array(
            array(
               'name'=>'OrganizationId',
               'value' => '$data->OrganizationId',
            ),
            array(
               'name'=>'Amount',
               'value' => '$data->memberOrgBalance;',
            ),
        ),
    ));
?>

// member model

'memberOrgBalance' => array(self::STAT, 'Donation', 'MemberId',
       'select'=>'MemberId, OrganizationId, SUM(Amount)',
       'group' => 'OrganizationId'),

// donation model

'member' => array(self::BELONGS_TO, 'Member', 'MemberId'),

EDIT: See also response to LDG

Using the advice from LDG I tried adding 'having' to my dataprovider, when that did not seem to affect the query I tried to add it to the relation memberOrgBalance where I am trying to pull the data.  This seems to affect the query but it is still not right.  I switched to:

'memberOrgBalance' => array(self::STAT, 'Donation', 'MemberId',
        'select'=>'MemberId, OrganizationId, SUM(Amount)',
        'group' => 'OrganizationId',
        'having'=> 'MemberId=member.MemberId',
        ),

which gives this error:

   CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]:
Column not found: 1054 Unknown column 'member.MemberId' in 'having clause'.
The SQL statement executed was: SELECT `MemberId ` AS `c`, MemberId, OrganizationId,
SUM(Amount) AS `s` FROM `donation` `t` WHERE (`t`.`MemberId `='2')
GROUP BY `MemberId `, OrganizationId HAVING (MemberId=member.MemberId)

This makes no sense since from the donation table I have the relation defined as originally posted above.  The query seems to be going the direction needed to get the SUM per organization as I want though.  Any other ideas?

Body:
Ok after running around in circles with this someone was able to push me over the top to a solution on Yii forums.

The end result is

$criteria->condition='member.MemberId="'.$model->MemberId.'"';
$criteria->with='member';
$criteria->select='MemberId,OrganizationId,sum(Amount) as Amount';
$criteria->group='t.MemberId,OrganizationId';
$dataProvider=new CActiveDataProvider(Donations::model(),
    array(
        'criteria'=>$criteria,

Thanks ldg for the help with this.


问:
Postgres duplicate column based on value in column
I've the following table in postgresql

id
product
customer
price
amount

1
Television
Alfred
12.00
1

2
Radio
Richard
20.00
3

3
Mobile
Richard
40.00
5

Is there some way via SQL to duplicate the line n-times in case the amount is greater than one?

This is how the table should look like after running the query:

id
product
customer
price
amount

1
Television
Alfred
12.00
1

2
Radio
Richard
20.00
3

3
Mobile
Richard
40.00
5

4
Radio
Richard
20.00
3

5
Radio
Richard
20.00
3

6
Mobile
Richard
40.00
5

7
Mobile
Richard
40.00
5

8
Mobile
Richard
40.00
5

9
Mobile
Richard
40.00
5

f.e. we now have 3 Radios that do match with the amount 3. Unfortunately, I do not even find a correct Google search term.

答:
You can use generate_series in the group by for this:</p>
```<code>DROP TABLE IF EXISTS _dat;

CREATE TEMP TABLE _dat
(
  id         INT,
  product    TEXT,
  customer   TEXT,
  price      DECIMAL,
  amount     INT
);

INSERT INTO _dat (id,product,customer,price,amount)
VALUES
(1,'Television','Alfred',12,1),
(2,'Radio','Richard',20,3),
(3,'Mobile','Richard',40,5);

SELECT id,
       product,
       customer,
       price,
       amount
FROM _dat
GROUP BY id,
         product,
         customer,
         price,
         amount,
         GENERATE_SERIES(1,amount);
</code>```

Body:
You can use generate_series in the group by for this:

DROP TABLE IF EXISTS _dat;

CREATE TEMP TABLE _dat
(
  id         INT,
  product    TEXT,
  customer   TEXT,
  price      DECIMAL,
  amount     INT
);

INSERT INTO _dat (id,product,customer,price,amount)
VALUES
(1,'Television','Alfred',12,1),
(2,'Radio','Richard',20,3),
(3,'Mobile','Richard',40,5);

SELECT id,
       product,
       customer,
       price,
       amount
FROM _dat
GROUP BY id,
         product,
         customer,
         price,
         amount,
         GENERATE_SERIES(1,amount);