问:
NGINX forward all url requests except for the root URL
I would like nginx to forward all requests to an app that runs on port 80 in the backend. So whatever I type in in the url should just be forwarded, EXCEPT for the root URL which is "/" e.g.

```<code> www.hellworld.com/hello --> should be forwared to localhost/hello
  www.hellworld.com/app1/hello --> should be forwared to localhost/app1/hello
  www.helloworld.com/ --> should be forwared to localhost/rootapp/hello
</code>```

So the root URL should go internally for example to /rootapp/hello as a hardwired redirect while the others are just being forwarded 1:1.

I am using caprover btw.

I have this in my nginx configuration, which doesnt work... :

```<code>   location  = / {
            return 302 https://$http_host/pyjsaw;
        }

  location  ^~ \ {
    return 302 https://$http_host$request_uri ;
  }

</code>```

What am I doing wrong?

Thanks!

Body:
I would like nginx to forward all requests to an app that runs on port 80 in the backend. So whatever I type in in the url should just be forwarded, EXCEPT for the root URL which is "/" e.g.

 www.hellworld.com/hello --> should be forwared to localhost/hello
  www.hellworld.com/app1/hello --> should be forwared to localhost/app1/hello
  www.helloworld.com/ --> should be forwared to localhost/rootapp/hello

So the root URL should go internally for example to /rootapp/hello as a hardwired redirect while the others are just being forwarded 1:1.

I am using caprover btw.

I have this in my nginx configuration, which doesnt work... :

   location  = / {
            return 302 https://$http_host/pyjsaw;
        }

  location  ^~ \ {
    return 302 https://$http_host$request_uri ;
  }

What am I doing wrong?

Thanks!


来源: stackexchange

问:
Unable to fit a function onto a givin set of data points in Python using the Scipy library
I have been trying to fit a function(the function is given in the code under the name concave_func) onto data points in python but have had very little to no success. I have 7 parameters(C_1, C_2, alpha_one, alpha_two, I_x, nu_t, T_e) in the function that I have to estimate, and only 6 data points. I have tried 2 methods to fit the curve and estimate the parameters,

1). scipy.optimize.minimize

2). scipy.optimize.curve_fit.

However, I'm not obtaining the desired results i.e the curve is not fitting the data points.
I have attached my code below.

```<code>frequency = np.array([22,45,150,408,1420,23000]) #x_values
b_temp = [2.55080863e+04, 4.90777800e+03, 2.28984753e+02, 2.10842949e+01, 3.58631166e+00, 5.68716056e-04] #y_values

#Defining the function that I want to fit
def concave_func(x, C_1, C_2, alpha_one, alpha_two, I_x, nu_t, T_e):
    one = x**(-alpha_one)
    two = (C_2/C_1)*(x**(-alpha_two))
    three = I_x*(x**-2.1)
    expo = np.exp(-1*((nu_t/x)**2.1))
    eqn_one = C_1*(one + two + three)*expo
    eqn_two = T_e*(1 - expo)
    return eqn_one + eqn_two

#Defining chi_square function
def chisq(params, xobs, yobs):
    ynew = concave_func(xobs, *params)
    #yerr = np.sum((ynew- yobs)**2)
    yerr = np.sum(((yobs- ynew)/ynew)**2)
    print(yerr)
    return yerr

result = minimize(chisq, [1,2,2,2,1,1e6,8000], args = (frequency,b_temp),  method = 'Nelder-Mead', options = {'disp' : True, 'maxiter': 10000})
x = np.linspace(-300,24000,1000)
plt.yscale("log")
plt.xscale("log")
plt.plot(x,concave_func(x, *result.x))
print(result.x)
print(result)
plt.plot(frequency, b_temp, 'r*' )
plt.xlabel("log Frequency[MHz]")
plt.ylabel("log Temp[K]")
plt.title('log Temparature vs log Frequency')

plt.grid()
plt.savefig('the_plot_2060.png')
</code>```

I have attached the plot that I obtained below.

The plot clearly does not fit the data, and something is definitely wrong. I would also want my parameters alpha_one and alpha_two to be constrained to lie between 2 and 3. I also do not want my parameter T_e to exceed 10,000. Any thoughts?

ContentLicense: CC BY-SA 4.0

Body:
I have been trying to fit a function(the function is given in the code under the name concave_func) onto data points in python but have had very little to no success. I have 7 parameters(C_1, C_2, alpha_one, alpha_two, I_x, nu_t, T_e) in the function that I have to estimate, and only 6 data points. I have tried 2 methods to fit the curve and estimate the parameters,

1). scipy.optimize.minimize

2). scipy.optimize.curve_fit.

However, I'm not obtaining the desired results i.e the curve is not fitting the data points.
I have attached my code below.

frequency = np.array([22,45,150,408,1420,23000]) #x_values
b_temp = [2.55080863e+04, 4.90777800e+03, 2.28984753e+02, 2.10842949e+01, 3.58631166e+00, 5.68716056e-04] #y_values

#Defining the function that I want to fit
def concave_func(x, C_1, C_2, alpha_one, alpha_two, I_x, nu_t, T_e):
    one = x**(-alpha_one)
    two = (C_2/C_1)*(x**(-alpha_two))
    three = I_x*(x**-2.1)
    expo = np.exp(-1*((nu_t/x)**2.1))
    eqn_one = C_1*(one + two + three)*expo
    eqn_two = T_e*(1 - expo)
    return eqn_one + eqn_two

#Defining chi_square function
def chisq(params, xobs, yobs):
    ynew = concave_func(xobs, *params)
    #yerr = np.sum((ynew- yobs)**2)
    yerr = np.sum(((yobs- ynew)/ynew)**2)
    print(yerr)
    return yerr

result = minimize(chisq, [1,2,2,2,1,1e6,8000], args = (frequency,b_temp),  method = 'Nelder-Mead', options = {'disp' : True, 'maxiter': 10000})
x = np.linspace(-300,24000,1000)
plt.yscale("log")
plt.xscale("log")
plt.plot(x,concave_func(x, *result.x))
print(result.x)
print(result)
plt.plot(frequency, b_temp, 'r*' )
plt.xlabel("log Frequency[MHz]")
plt.ylabel("log Temp[K]")
plt.title('log Temparature vs log Frequency')

plt.grid()
plt.savefig('the_plot_2060.png')

I have attached the plot that I obtained below.

The plot clearly does not fit the data, and something is definitely wrong. I would also want my parameters alpha_one and alpha_two to be constrained to lie between 2 and 3. I also do not want my parameter T_e to exceed 10,000. Any thoughts?


问:
MatLab help, Invalid training data
I don't understand how i should format the inputs.

I have this line to train the network:

```<code>net = trainNetwork(imgs, true_labels_fix, layers, options);
</code>```

And imgs and true_labels_fix look like this:

imgs - 1200x1 cell

true_labels_fix - 1200x1 categorical

Where each cell in the imgs is a 255x301 uint8 image.

The error is:
"
Invalid training data. Predictors must be a numeric array, a datastore, or a
table. For networks with sequence input, predictors can also be a cell array of
sequences."

The layers look like this:

```<code>input_size = [255, 301];

layers = [
    imageInputLayer(input_size)
    fullyConnectedLayer(100)
    reluLayer
    fullyConnectedLayer(10)
    softmaxLayer
    classificationLayer
];
</code>```

I've tried to reformat the inputs but with no success. Also tried looking at examples but nothing have helped.

Title: MatLab help, Invalid training data

Body:
I don't understand how i should format the inputs.

I have this line to train the network:

net = trainNetwork(imgs, true_labels_fix, layers, options);

And imgs and true_labels_fix look like this:

imgs - 1200x1 cell

true_labels_fix - 1200x1 categorical

Where each cell in the imgs is a 255x301 uint8 image.

The error is:
"
Invalid training data. Predictors must be a numeric array, a datastore, or a
table. For networks with sequence input, predictors can also be a cell array of
sequences."

The layers look like this:

input_size = [255, 301];

layers = [
    imageInputLayer(input_size)
    fullyConnectedLayer(100)
    reluLayer
    fullyConnectedLayer(10)
    softmaxLayer
    classificationLayer
];

I've tried to reformat the inputs but with no success. Also tried looking at examples but nothing have helped.


问:
How to put two videos below in the background of the site?
When I put two videos, the videos are placed on top of each other or with a space.enter image description herelike this

I posted two videos with different classes, but no matter what I do, the background doesn't turn out the way I want.enter image description here
I want it to be like this


问:
How to make the top element of a dropdown open when the page loads
I have this dropdown and I am trying to keep just have it open initially when the page loads, then users can click off of it or click on a different element of the dropdown to open another part of it and the original open piece closes. I have my js attempt but so far it doesnt work and has kinda broken my dropdown. I need the top one to look like the two bottom parts of the dropdown just open upon the page loading.

                 document.querySelectorAll(".dropdown-container-var ul li").forEach(d => {
                  d.addEventListener("click", e => {
                    const dropdown = e.target.closest(".dropdown-container-var ").querySelector("ul")
                    if(dropdown) {
                      dropdown.style.display = "block"
                      _ElementBlur2(e.target, () => {
                        dropdown.style.display = "none"
                      })
                    }
                  })
                })
                document.querySelectorAll(".dropdown-container-var").forEach(d => {
                  d.addEventListener("click", e => {
                    const dropdown = e.target.closest(".dropdown-container-var ").querySelector("ul")
                    if(dropdown) {
                      dropdown.style.display = "block"
                      _ElementBlur2(e.target, () => {
                        dropdown.style.display = "none"
                      })
                    }
                  })
                })

                document.querySelectorAll(".dropdown-container-var ul li").forEach(listItem => {
                  listItem.addEventListener("click", e => {
                    window.location.href = e.target.attributes.href.value;
                  })
                })
                document.querySelectorAll(".dropdown-container-var ul li").forEach(listItem => {
                  listItem.addEventListener("click", e => {
                    window.location.href = e.target.querySelector("a2").getAttribute("href");
                  })
                })

                // Functions for getting a 'blur' event on an element
                const _ElementBlur2 = (el, f = false) => {
                  const ac = new AbortController()
                  document.body.addEventListener("click", _CheckBlur2(el, f, ac), { signal: ac.signal })
                }

                const _CheckBlur2 = (el, f = false, ac) => {
                  return e => {
                    if(!document.elementsFromPoint(e.clientX, e.clientY).filter(efp => efp == el).length || !document.elementsFromPoint(e.clientX, e.clientY).length) {
                      if(f && typeof(f) == "function") f()
                      ac.abort()
                    }
                  }
                }

                const dropdown = document.getElementById("surface_open");

            // add the open attribute to the dropdown element
            dropdown.setAttribute("open", "");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>   a3 {
    color: white;
    text-decoration: none;/* Change this to the desired color */
    transition: background-color 0.2s;
    }

    a2 {
    color: black;
    text-decoration: none;/* Change this to the desired color */
    transition: background-color 0.2s;
    }

    .dropdown-container-var {
      position: relative; /* create a positioning context for the list items */
      background-color: #333;
        color: white;
        text-decoration: none;
    width: 600px;
    text-align: center;
        transition: background-color 0.2s;
        cursor: pointer;

        }

    .dropdown-container-var:hover { /* create a positioning context for the list items */
      background-color: #525252;
        transition: background-color 0.2s;
    }

    .dropdown-list-var {
      position: relative; /* position the list items absolutely */
     display: none; /* hide the list by default */

      list-style-type: none; /* remove the bullet points for the list items */
      padding: 0; /* remove the padding for the list */
      left: 0; /* position the list items at the left edge of the list */
      transition: border 0.2s; /* add a transition effect for the border */
      background-color: #b0b0b0;
      color: black;
      text-decoration: none;
    width: 600px;
        text-align: center;
        transition: background-color 0.2s;
        cursor: pointer;
    }

    .dropdown-list-var li:hover {
      background-color: #04AA6D;
        transition: background-color 0.2s;}/* change the background color of the list items
    to green when they are hovered over */
    }
    .dropdown-list-var li {
      color: black; /* set the color of the list items to black */
        text-align: center;
        transition: background-color 0.2s;
    }
    p2 {
      margin: 0;
    }

    .dropdown-list-var {
      margin: 0; /* <-- add this to the existing CSS code*/
      /* the rest */
    }
    optgroup {
      font-weight: bold;
      color: black;
      width: 520px;
        cursor: default;
    }</code>```

<link rel="stylesheet" href="styles.css">

      <p2><a3 href="#" >Surface and Precipitation</a3></p2>

              <select id="surface_open">
          <optgroup label="Surface">

<a2 href="#">2m Temperature</a2>

<a2 href="#">2m Dewpoint</a2>

<a2 href="#">Mean Sea Level Pressure</a2>

<a2 href="#">10m Wind</a2>

          </select>

      <p2><a3 href="#" >Upper-Air: Dynamics</a3></p2>

          <optgroup label="Vorticity">

<a2 href="#">500 hPa Height,Wind,Vorticity</a2>

<a2 href="#">700 hPa Height,Wind,Vorticity</a2>

<a2 href="#">850 hPa Height,Wind,Vorticity</a2>

      <p2><a3 href="#" >Upper-Air: Temperature,Wind</a3></p2>

          <optgroup label="Temperature">

<a2 href="#">700 hPa Temperature, Height, Wind</a2>

<a2 href="#">850 hPa Temperature, Height, Wind</a2>

<a2 href="#">925 hPa Temperature, Height, Wind</a2>

```

Body:
I have this dropdown and I am trying to keep just have it open initially when the page loads, then users can click off of it or click on a different element of the dropdown to open another part of it and the original open piece closes. I have my js attempt but so far it doesnt work and has kinda broken my dropdown. I need the top one to look like the two bottom parts of the dropdown just open upon the page loading.

                 document.querySelectorAll(".dropdown-container-var ul li").forEach(d => {
                  d.addEventListener("click", e => {
                    const dropdown = e.target.closest(".dropdown-container-var ").querySelector("ul")
                    if(dropdown) {
                      dropdown.style.display = "block"
                      _ElementBlur2(e.target, () => {
                        dropdown.style.display = "none"
                      })
                    }
                  })
                })
                document.querySelectorAll(".dropdown-container-var").forEach(d => {
                  d.addEventListener("click", e => {
                    const dropdown = e.target.closest(".dropdown-container-var ").querySelector("ul")
                    if(dropdown) {
                      dropdown.style.display = "block"
                      _ElementBlur2(e.target, () => {
                        dropdown.style.display = "none"
                      })
                    }
                  })
                })

                document.querySelectorAll(".dropdown-container-var ul li").forEach(listItem => {
                  listItem.addEventListener("click", e => {
                    window.location.href = e.target.attributes.href.value;
                  })
                })
                document.querySelectorAll(".dropdown-container-var ul li").forEach(listItem => {
                  listItem.addEventListener("click", e => {
                    window.location.href = e.target.querySelector("a2").getAttribute("href");
                  })
                })

                // Functions for getting a 'blur' event on an element
                const _ElementBlur2 = (el, f = false) => {
                  const ac = new AbortController()
                  document.body.addEventListener("click", _CheckBlur2(el, f, ac), { signal: ac.signal })
                }

                const _CheckBlur2 = (el, f = false, ac) => {
                  return e => {
                    if(!document.elementsFromPoint(e.clientX, e.clientY).filter(efp => efp == el).length || !document.elementsFromPoint(e.clientX, e.clientY).length) {
                      if(f && typeof(f) == "function") f()
                      ac.abort()
                    }
                  }
                }

                const dropdown = document.getElementById("surface_open");

            // add the open attribute to the dropdown element
            dropdown.setAttribute("open", "");

   a3 {
    color: white;
    text-decoration: none;/* Change this to the desired color */
    transition: background-color 0.2s;
    }

    a2 {
    color: black;
    text-decoration: none;/* Change this to the desired color */
    transition: background-color 0.2s;
    }

    .dropdown-container-var {
      position: relative; /* create a positioning context for the list items */
      background-color: #333;
        color: white;
        text-decoration: none;
    width: 600px;
    text-align: center;
        transition: background-color 0.2s;
        cursor: pointer;

        }

    .dropdown-container-var:hover { /* create a positioning context for the list items */
      background-color: #525252;
        transition: background-color 0.2s;
    }

    .dropdown-list-var {
      position: relative; /* position the list items absolutely */
     display: none; /* hide the list by default */

      list-style-type: none; /* remove the bullet points for the list items */
      padding: 0; /* remove the padding for the list */
      left: 0; /* position the list items at the left edge of the list */
      transition: border 0.2s; /* add a transition effect for the border */
      background-color: #b0b0b0;
      color: black;
      text-decoration: none;
    width: 600px;
        text-align: center;
        transition: background-color 0.2s;
        cursor: pointer;
    }

    .dropdown-list-var li:hover {
      background-color: #04AA6D;
        transition: background-color 0.2s;}/* change the background color of the list items
    to green when they are hovered over */
    }
    .dropdown-list-var li {
      color: black; /* set the color of the list items to black */
        text-align: center;
        transition: background-color 0.2s;
    }
    p2 {
      margin: 0;
    }

    .dropdown-list-var {
      margin: 0; /* <-- add this to the existing CSS code*/
      /* the rest */
    }
    optgroup {
      font-weight: bold;
      color: black;
      width: 520px;
        cursor: default;
    }

<link rel="stylesheet" href="styles.css">

      <p2><a3 href="#" >Surface and Precipitation</a3></p2>

              <select id="surface_open">
          <optgroup label="Surface">

<a2 href="#">2m Temperature</a2>

<a2 href="#">2m Dewpoint</a2>

<a2 href="#">Mean Sea Level Pressure</a2>

<a2 href="#">10m Wind</a2>

          </select>

      <p2><a3 href="#" >Upper-Air: Dynamics</a3></p2>

          <optgroup label="Vorticity">

<a2 href="#">500 hPa Height,Wind,Vorticity</a2>

<a2 href="#">700 hPa Height,Wind,Vorticity</a2>

<a2 href="#">850 hPa Height,Wind,Vorticity</a2>

      <p2><a3 href="#" >Upper-Air: Temperature,Wind</a3></p2>

          <optgroup label="Temperature">

<a2 href="#">700 hPa Temperature, Height, Wind</a2>

<a2 href="#">850 hPa Temperature, Height, Wind</a2>

<a2 href="#">925 hPa Temperature, Height, Wind</a2>


问:
I get the lambda event s3 key as url, want to get as string:
I am converting the s3 video to hls, in that case if the s3 file name has a space or bracket, it will converted into "+", so if the code search with the "+" in s3 bucket it didn't get object.

```<code>
def handler(event, context):

    assetID = str(uuid.uuid4())
    sourceS3Bucket = event['Records'][0]['s3']['bucket']['name']
    sourceS3Key = event['Records'][0]['s3']['object']['key']
    sourceS3 = 's3://'+ sourceS3Bucket + '/' + sourceS3Key
    sourceS3Basename = os.path.splitext(os.path.basename(sourceS3))[0]

</code>```

My S3 URI is :

s3://bucket_4999/ne gi.mp4

But in lambda i get it as
s3://bucket_4999/ne+gi.mp4

So in AWS Elemental MediaConvert, i get the error as

```<code>Unable to open input file [s3://bucket_4999/ne+gi.mp4]: [Failed probe/open: [Can't read input stream: [Failed to read data: HeadObject failed]]]
</code>```

Body:
I am converting the s3 video to hls, in that case if the s3 file name has a space or bracket, it will converted into "+", so if the code search with the "+" in s3 bucket it didn't get object.

def handler(event, context):

    assetID = str(uuid.uuid4())
    sourceS3Bucket = event['Records'][0]['s3']['bucket']['name']
    sourceS3Key = event['Records'][0]['s3']['object']['key']
    sourceS3 = 's3://'+ sourceS3Bucket + '/' + sourceS3Key
    sourceS3Basename = os.path.splitext(os.path.basename(sourceS3))[0]

My S3 URI is :

s3://bucket_4999/ne gi.mp4

But in lambda i get it as
s3://bucket_4999/ne+gi.mp4

So in AWS Elemental MediaConvert, i get the error as

Unable to open input file [s3://bucket_4999/ne+gi.mp4]: [Failed probe/open: [Can't read input stream: [Failed to read data: HeadObject failed]]]


问:
why fresh-tabula-js not working with nestJs?
Getting errors while using fresh-tabula-js with nestJs.

Express server

```<code>import Tabula from "fresh-tabula-js";

const table = new Tabula("t5.pdf", { spreadsheet: true });
  console.log(table.extractCsv().output);
</code>```

NestJS

1) code-1

```<code>import { Injectable } from '@nestjs/common';
import Tabula = require('fresh-tabula-js');

@Injectable()
export class PdfExtractorService {
  tabula: Tabula;
  constructor() {
    this.tabula = new Tabula('t5.pdf', { spreadsheet: true });
  }

  extractPdfToJson() {
    const data: Promise<{ output: string; error: string }> =
      this.tabula.getData();
    console.log(data);
  }
}

</code>```

Error:
this.tabula.getData is not a function

2) code-2

```<code>import { Injectable } from '@nestjs/common';
import Tabula = require('fresh-tabula-js');

@Injectable()
export class PdfExtractorService {
  tabula: Tabula;
  constructor() {
    this.tabula = new Tabula('t5.pdf', { spreadsheet: true });
  }

  extractPdfToJson() {
    const data: Promise<{ output: string; error: string }> =
      this.tabula.extractCsv().output;
    console.log(data);
  }
}

</code>```

Error:
error TS2339: Property 'extractCsv' does not exist on type 'Tabula'.
this.tabula.extractCsv().output;

Tried all possible ways but it is not working with nestJs however it is working with expressJs.
How to make it run in nestJS?

Body:
Getting errors while using fresh-tabula-js with nestJs.

Express server

import Tabula from "fresh-tabula-js";

const table = new Tabula("t5.pdf", { spreadsheet: true });
  console.log(table.extractCsv().output);

NestJS

1) code-1

import { Injectable } from '@nestjs/common';
import Tabula = require('fresh-tabula-js');

@Injectable()
export class PdfExtractorService {
  tabula: Tabula;
  constructor() {
    this.tabula = new Tabula('t5.pdf', { spreadsheet: true });
  }

  extractPdfToJson() {
    const data: Promise<{ output: string; error: string }> =
      this.tabula.getData();
    console.log(data);
  }
}

Error:
this.tabula.getData is not a function

2) code-2

import { Injectable } from '@nestjs/common';
import Tabula = require('fresh-tabula-js');

@Injectable()
export class PdfExtractorService {
  tabula: Tabula;
  constructor() {
    this.tabula = new Tabula('t5.pdf', { spreadsheet: true });
  }

  extractPdfToJson() {
    const data: Promise<{ output: string; error: string }> =
      this.tabula.extractCsv().output;
    console.log(data);
  }
}

Error:
error TS2339: Property 'extractCsv' does not exist on type 'Tabula'.
this.tabula.extractCsv().output;

Tried all possible ways but it is not working with nestJs however it is working with expressJs.
How to make it run in nestJS?


问:
How to start a timer at the precise moment when the activity is displayed?
I want to start a chronometer when my activity is displayed. If I start it inside "onResume()", when it is shown on the screen, 2 or 3 seconds have already passed:

```<code>@Override
protected void onResume(){
    super.onResume();
    Chronometer myChronometer = (Chronometer)  findViewById(R.id.chronometer);
    myChronometer.start();
}
</code>```

I would like my Chronometer to start when the activity is displayed on the screen but there is no methods like "onDisplay()" or something similar as far as I know

Body:
I want to start a chronometer when my activity is displayed. If I start it inside "onResume()", when it is shown on the screen, 2 or 3 seconds have already passed:

@Override
protected void onResume(){
    super.onResume();
    Chronometer myChronometer = (Chronometer)  findViewById(R.id.chronometer);
    myChronometer.start();
}

I would like my Chronometer to start when the activity is displayed on the screen but there is no methods like "onDisplay()" or something similar as far as I know


问:
How to output the JSONObject ordered
I am solving the fixing flaky test, the test looks like this:

```<code>    @Test
    public void testButtonSignatureWithJSONObject() throws Exception {
        System.out.println("1");
        // final String payload1 = "{\"storeId\":\"amzn1.application-oa2-client.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"webCheckoutDetails\":{\"checkoutReviewReturnUrl\":\"https://localhost/test/CheckoutReview.php\",\"checkoutResultReturnUrl\":\"https://localhost/test/CheckoutResult.php\"}}";
        // final String signatureString1 = client.generateButtonSignature(payload);
        final JSONObject payload = new JSONObject();
        payload.put("storeId", "amzn1.application-oa2-client.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        final JSONObject webCheckoutDetails = new JSONObject();
        webCheckoutDetails.put("checkoutReviewReturnUrl", "https://localhost/test/CheckoutReview.php");
        webCheckoutDetails.put("checkoutResultReturnUrl", "https://localhost/test/CheckoutResult.php");
        payload.put("webCheckoutDetails", webCheckoutDetails);

        //String temp = payload.toString();
        final String signatureString = client.generateButtonSignature(payload);
        signature.update(PLAIN_TEXT.getBytes());
        Assert.assertTrue(signature.verify(Base64.decode(signatureString)));
    }
</code>```

It gives the assertion error. According to some research, I assume it is because when the objects are put into JSONObject, the order is non-deterministic. I am kinda get stuck about how to fix it. I would very appreciate your advice. Thank you!

Since it's about fixing some test open sourced. It's really nothing I can do more here. I tried to switch payload to String but it won't work. Thank you!

Title: How to output the JSONObject ordered

Body:
I am solving the fixing flaky test, the test looks like this:

    @Test
    public void testButtonSignatureWithJSONObject() throws Exception {
        System.out.println("1");
        // final String payload1 = "{\"storeId\":\"amzn1.application-oa2-client.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"webCheckoutDetails\":{\"checkoutReviewReturnUrl\":\"https://localhost/test/CheckoutReview.php\",\"checkoutResultReturnUrl\":\"https://localhost/test/CheckoutResult.php\"}}";
        // final String signatureString1 = client.generateButtonSignature(payload);
        final JSONObject payload = new JSONObject();
        payload.put("storeId", "amzn1.application-oa2-client.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        final JSONObject webCheckoutDetails = new JSONObject();
        webCheckoutDetails.put("checkoutReviewReturnUrl", "https://localhost/test/CheckoutReview.php");
        webCheckoutDetails.put("checkoutResultReturnUrl", "https://localhost/test/CheckoutResult.php");
        payload.put("webCheckoutDetails", webCheckoutDetails);

        //String temp = payload.toString();
        final String signatureString = client.generateButtonSignature(payload);
        signature.update(PLAIN_TEXT.getBytes());
        Assert.assertTrue(signature.verify(Base64.decode(signatureString)));
    }

It gives the assertion error. According to some research, I assume it is because when the objects are put into JSONObject, the order is non-deterministic. I am kinda get stuck about how to fix it. I would very appreciate your advice. Thank you!

Since it's about fixing some test open sourced. It's really nothing I can do more here. I tried to switch payload to String but it won't work. Thank you!


问:
CSS overflow: hidden element shrinking but not letting parent shrink past initial text size
I have a container which is 100% width of its parent, and some text inside it. The text has a max width of 60%, overflow: hidden and white-space: nowrap. However when the container shrinks past the length of the text, the text stops it shrinking further so it overflows the page. Any ideas why and how I fix it?

.channel-header {
    width: 100%;
    height: 55px;

    display: flex;
    align-items: center;

    background-color: var(--tertiary);
    color: var(--text-dull);

    box-shadow: 0px 0px 5px 0px black;

    z-index: 90;
}
.channel-name {
    max-width: 60%;

    margin: 0;
    margin-left: 20px;
    margin-right: 20px;

    font-size: 1.1em;
    font-weight: 600;

    overflow: clip;
    white-space: nowrap;
    text-overflow: ellipsis;
}
```


问:
when I run "sudo mysqladmin -u root password $DBRootPasswordroot'@'localhost' (using password: NO)'
I populated my credentials for my Database from parameters store into my instances but I keep getting access denied. I have tried all I can but nothing. I even started the lab from scratch but it's didn't work.

8 wasn't expecting an access denied after running  " sudo mysqladmin -u root password $DBRootPassword"in


问:
.NET Core 7 how to redirect unauthorize to login page not json response?
I try to create a simple ASP.NET Core 7 MVC website. When I add the [Authorize] annotation to the HomeController, I expect it will redirect to LoginController/Index, but it did not.

It shows this JSON result like this:

I already have a login route /login on the LoginController/Index.

This is my program.cs

using Application;
using Domain.Entities;
using Infrastructure.Identity;
using Infrastructure.Identity.Context;
using Infrastructure.Shared;
using Knowmore.Web;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;

var AllowedOrigins = "_Allowed_Origins_";

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddApplication();
builder.Services.AddPersistenceInfrastructure(builder.Configuration);

builder.Services.AddControllersWithViews();

builder.Services.AddMvcCore(options => options.EnableEndpointRouting = false);

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
        {
            options.LoginPath = new PathString("/login");
        });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

//SeederData.Initialize(app.Services);

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

app.UseRouting();

app.UseAuthorization();
app.UseAuthentication();

app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
```
<p>In my concern, I need to use custom identity, I already use <code>SignInManager</code> in <code>LoginController</code>.</p>
<p>This is my <code>LoginController</code>:</p>
```public class LoginController : Controller
{
    private readonly IAccountLoginService _svc;
    private readonly InitializeDataService _InitDataSvc;
    private readonly SignInManager<User> _signInManager;
    private readonly UserManager<User> _userManager;

    public LoginController(
        IAccountLoginService svc,
        InitializeDataService initializeDataService,
        SignInManager<User> signInManager,
        UserManager<User> userManager)
    {
        _svc = svc;
        _InitDataSvc = initializeDataService;
        _signInManager = signInManager;
        _userManager = userManager;
    }

    [HttpGet]
    [AllowAnonymous]
    public IActionResult Index()
    {
        return View(new LoginRequest());
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Index(LoginRequest model)
    {
        if (ModelState.IsValid)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);
            if (user == null)
            {
                model.Error = "User not found";
                return View(model);
            }
            await _signInManager.SignInAsync(user, true);
            return RedirectToAction("Index", "Home");
        }
        return View(model);
    }
}
```

How to solve it, so if user unauthorized, it will redirect to login page?

Body:
I try to create a simple ASP.NET Core 7 MVC website. When I add the [Authorize] annotation to the HomeController, I expect it will redirect to LoginController/Index, but it did not.

It shows this JSON result like this:

I already have a login route /login on the LoginController/Index.

This is my program.cs

using Application;
using Domain.Entities;
using Infrastructure.Identity;
using Infrastructure.Identity.Context;
using Infrastructure.Shared;
using Knowmore.Web;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;

var AllowedOrigins = "_Allowed_Origins_";

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddApplication();
builder.Services.AddPersistenceInfrastructure(builder.Configuration);

builder.Services.AddControllersWithViews();

builder.Services.AddMvcCore(options => options.EnableEndpointRouting = false);

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
        {
            options.LoginPath = new PathString("/login");
        });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

//SeederData.Initialize(app.Services);

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

app.UseRouting();

app.UseAuthorization();
app.UseAuthentication();

app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

In my concern, I need to use custom identity, I already use SignInManager in LoginController.

This is my LoginController:

public class LoginController : Controller
{
    private readonly IAccountLoginService _svc;
    private readonly InitializeDataService _InitDataSvc;
    private readonly SignInManager<User> _signInManager;
    private readonly UserManager<User> _userManager;

    public LoginController(
        IAccountLoginService svc,
        InitializeDataService initializeDataService,
        SignInManager<User> signInManager,
        UserManager<User> userManager)
    {
        _svc = svc;
        _InitDataSvc = initializeDataService;
        _signInManager = signInManager;
        _userManager = userManager;
    }

    [HttpGet]
    [AllowAnonymous]
    public IActionResult Index()
    {
        return View(new LoginRequest());
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Index(LoginRequest model)
    {
        if (ModelState.IsValid)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);
            if (user == null)
            {
                model.Error = "User not found";
                return View(model);
            }
            await _signInManager.SignInAsync(user, true);
            return RedirectToAction("Index", "Home");
        }
        return View(model);
    }
}

How to solve it, so if user unauthorized, it will redirect to login page?


问:
Why CachedNetworkImage when receiving wrong url by error?
I have to display images that are first entered by the user via a form in which he must enter the relative Url, so I can't know if he will enter a correct Url. I tried to handle the error with the errorWidget property of the CachedNetworkImage but it doesn't work.

```<code>    CachedNetworkImage(

  width: larghezza / 5,
 imageUrl:
 "test",
 progressIndicatorBuilder: (context, url, downloadProgress) =>
LinearProgressIndicator(
 color: Colors.black,
   backgroundColor:
          Colors.blue[50],
    value:
      downloadProgress.progress),
 errorWidget:
 (context, url, error) =>
Icon(Icons.error),
 ),
</code>```

The error I get is this:

```<code>ArgumentError (Invalid argument(s): No host specified in URI s)
</code>```

Body:
I have to display images that are first entered by the user via a form in which he must enter the relative Url, so I can't know if he will enter a correct Url. I tried to handle the error with the errorWidget property of the CachedNetworkImage but it doesn't work.

    CachedNetworkImage(

  width: larghezza / 5,
 imageUrl:
 "test",
 progressIndicatorBuilder: (context, url, downloadProgress) =>
LinearProgressIndicator(
 color: Colors.black,
   backgroundColor:
          Colors.blue[50],
    value:
      downloadProgress.progress),
 errorWidget:
 (context, url, error) =>
Icon(Icons.error),
 ),

The error I get is this:

ArgumentError (Invalid argument(s): No host specified in URI s)


问:
Npm audit fix --force not working. Can't use npm
I have a problem with npm, when I try to install a package using npm it shows this error.

I tried to upgrade expo, reinstall expo and run npm audit fix --force but none of them worked.

```<code>qs  6.7.0 - 6.7.2
Severity: high
qs vulnerable to Prototype Pollution - https://github.com/advisories/GHSA-hrpp-h998-j3pp
fix available via `npm audit fix --force`
Will install expo@44.0.6, which is a breaking change
node_modules/qs
  body-parser  1.19.0
  Depends on vulnerable versions of qs
  node_modules/body-parser
    @expo/dev-server  *
    Depends on vulnerable versions of body-parser
    node_modules/@expo/dev-server
      @expo/cli  >=0.1.0
      Depends on vulnerable versions of @expo/dev-server
      node_modules/@expo/cli
        expo  >=45.0.0-beta.1
        Depends on vulnerable versions of @expo/cli
        node_modules/expo

5 high severity vulnerabilities
</code>```

Body:
I have a problem with npm, when I try to install a package using npm it shows this error.

I tried to upgrade expo, reinstall expo and run npm audit fix --force but none of them worked.

qs  6.7.0 - 6.7.2
Severity: high
qs vulnerable to Prototype Pollution - https://github.com/advisories/GHSA-hrpp-h998-j3pp
fix available via `npm audit fix --force`
Will install expo@44.0.6, which is a breaking change
node_modules/qs
  body-parser  1.19.0
  Depends on vulnerable versions of qs
  node_modules/body-parser
    @expo/dev-server  *
    Depends on vulnerable versions of body-parser
    node_modules/@expo/dev-server
      @expo/cli  >=0.1.0
      Depends on vulnerable versions of @expo/dev-server
      node_modules/@expo/cli
        expo  >=45.0.0-beta.1
        Depends on vulnerable versions of @expo/cli
        node_modules/expo

5 high severity vulnerabilities


问:
Authentication for React Native in AWS Amplify in November 2022 to beyond
I've been struggling setting up authentication using withAuthenticator as the old documentation suggested on AWS Amplify. The old one was not working, and the next one wasn't released yet. So, if like me you used to use withAuthenticator to wrap your RN app, now you can find the new way to do it here :

https://ui.docs.amplify.aws/react-native/connected-components/authenticator

I'm posting it here because it has not always been easy to find this doc, especially a few weeks ago they were almost no link pointing to it when you searched about react native as it wasn't ready  yet.

If you'r beginning on Amplify x React Native like me, you'll find useful to know that to get the current user, provided you are insided an Authenticator.Provider component, you can do

import { useAuthenticator } from '@aws-amplify/ui-react-native';
const { user, signOut } = useAuthenticator((context) => [context.user]);
```

With that you will access the sub_id of your Cognito User.

Before mid November 2022, I had to use withAuthenticator to wrap my app and it doesn't work anymore as it seems like the libraries you have to import to setup Authentication on an RN Amplify project have changed.

Body:
I've been struggling setting up authentication using withAuthenticator as the old documentation suggested on AWS Amplify. The old one was not working, and the next one wasn't released yet. So, if like me you used to use withAuthenticator to wrap your RN app, now you can find the new way to do it here :

https://ui.docs.amplify.aws/react-native/connected-components/authenticator

I'm posting it here because it has not always been easy to find this doc, especially a few weeks ago they were almost no link pointing to it when you searched about react native as it wasn't ready  yet.

If you'r beginning on Amplify x React Native like me, you'll find useful to know that to get the current user, provided you are insided an Authenticator.Provider component, you can do

import { useAuthenticator } from '@aws-amplify/ui-react-native';
const { user, signOut } = useAuthenticator((context) => [context.user]);

With that you will access the sub_id of your Cognito User.

Before mid November 2022, I had to use withAuthenticator to wrap my app and it doesn't work anymore as it seems like the libraries you have to import to setup Authentication on an RN Amplify project have changed.


问:
How to change the click area of an SVG shape so that two of them next to each other don't ovelap each other?

I have drawn a dashed line showing the boundaries of the black shape which is on top of the other shape. My problem is that where it overlaps the blue one, I want to click that blue shape and not the black one. So I want to be able to click each of them exacly where they are visible.

I have been trying to solve this for hours, but couldn't make it work.

Here is the code I have:

.rotate {
  transform: rotate(180deg);
  position: relative;
  margin-left: -71px;
  top: 1px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewBox="0 0 133 67" width="133" height="67" fill="white" xmlns="http://www.w3.org/2000/svg" pointer-events="visiblePainted">
  <path d="M66.5 1.5L1.5 66.5H131.5L66.5 1.5Z" fill="#000eee" stroke="black" cursor="pointer" pointer-events="visiblePainted" id="shape1"/>
</svg>
<svg class="rotate" viewBox="0 0 133 67" width="133" height="67" fill="white" xmlns="http://www.w3.org/2000/svg" pointer-events="visiblePainted">
  <path d="M66.5 1.5L1.5 66.5H131.5L66.5 1.5Z" fill="currentColor" stroke="black" cursor="pointer" pointer-events="visiblePainted" id="shape2"/>
</svg></code>```

Body:
I have drawn a dashed line showing the boundaries of the black shape which is on top of the other shape. My problem is that where it overlaps the blue one, I want to click that blue shape and not the black one. So I want to be able to click each of them exacly where they are visible.

I have been trying to solve this for hours, but couldn't make it work.

Here is the code I have:

.rotate {
  transform: rotate(180deg);
  position: relative;
  margin-left: -71px;
  top: 1px;
}

<svg viewBox="0 0 133 67" width="133" height="67" fill="white" xmlns="http://www.w3.org/2000/svg" pointer-events="visiblePainted">
  <path d="M66.5 1.5L1.5 66.5H131.5L66.5 1.5Z" fill="#000eee" stroke="black" cursor="pointer" pointer-events="visiblePainted" id="shape1"/>
</svg>
<svg class="rotate" viewBox="0 0 133 67" width="133" height="67" fill="white" xmlns="http://www.w3.org/2000/svg" pointer-events="visiblePainted">
  <path d="M66.5 1.5L1.5 66.5H131.5L66.5 1.5Z" fill="currentColor" stroke="black" cursor="pointer" pointer-events="visiblePainted" id="shape2"/>
</svg>


问:
Lambda Latency with Provisioned Concurrency and AWS Service Calls
This is a general question.

We have 15 provisioned containers running and our Lambda makes calls to a VPC Endpoint as well as to EFS. We've noticed that during deployments, Lambda duration really spikes. Its also worth noting that we might be over scaled in terms of the number of containers we need.

I understand there are AWS Connection timeouts (60 seconds)(https://code.amazon.com/packages/AWSJavaClientRuntime/blobs/mainline/--/main/com/amazonaws/ClientConfiguration.java#L111).

My general question is: Could the latency be coming from the containers having to reestablish connections to the VPC Endpoint / EFS?

We almost always see latency spikes for these service calls during deployments, and then it tends to smooth out. Interestingly though, if we increase provisioned concurrency too high, we tend to see more spikes than usual. My theory is that most container time out between themselves and VPC-E/EFS, and its these timeouts that we observe as latency spikes when provisioned concurrency is too high.

Is this possible? And is it possible to have too much provisioned concurrency (i.e. we need to hit a sweet spot for the best performance such that they're alway warm)?

Additional note:

We deploy to an alias in 10% / 3 minute increments. Deployments take 30 minutes, and we see these spikes for 30 or more minutes until they taper off. Spikes are more likely with higher provisioned concurrency as mentioned prior.


问:
octave: error: rgb2gray: RGB of invalid data type 'logical'
i have octave code who convert image into specific code on a game, it work well until file number 1507

```<code>% The images must be in the same folder as this script.
% The originY variable will be updated for each PNG file.
originY = 3010000;

% Threshold values modify which shades of grey are consirered scenery (0-255).
threshold1 = 50; %black is 0
threshold2 = 0; %white is 255

% The origin modifies where the rider begins relative to the image.
originX = 200;

% Images can be made larger using the scale option. Use only whole numbers.
% Note that there is a size limit for tracks uploaded to FRHD.
scaleX = 2;
scaleY = 2;

% Loop through each PNG file until 2154.png.
for n = 1505:2154
    % Create the file name for the current PNG file.
    filename = sprintf('%04d.png', n);

    % Read the PNG file.
    image = imread(filename);

    % Create the file name for the output text file.
    outputFilename = sprintf('%04d.txt', n);

    % Open the output text file for writing.
    output = fopen(outputFilename, 'w');

    grayImage = transpose(rgb2gray(image));
    sceneryString = sprintf('#');

    for j = 1:(size(grayImage,2)*scaleY)
        currentColor = 2; % 2 for white, 1 for gray, 0 for black
        for i = 1:size(grayImage,1)
            if originY+j >= 0
                row = lower(dec2base(originY+j, 32));
            else
                row = strcat('-', lower(dec2base(-(originY+j), 32)));
            end;

            if originX+i*scaleX >= 0
                xPos = lower(dec2base(originX+i*scaleX, 32));
            else
                xPos = strcat('-', lower(dec2base(-(originX+i*scaleX), 32)));
            end;

            pixel = grayImage(i,ceil(j/scaleY));

            if currentColor == 2
                if pixel > threshold2
                    continue;
                elseif pixel < threshold1
                    fprintf(output, '%s %s ', xPos, row);
                    currentColor = 0;
                else
                    sceneryString = sprintf('%s%s %s ', sceneryString, xPos, row);
                    currentColor = 1;
                end;
            elseif currentColor == 0
                if pixel < threshold1
                    continue;
                elseif pixel > threshold2
                    fprintf(output, '%s %s,', xPos, row);
                    currentColor = 2;
                else
                    fprintf(output, '%s %s,', xPos, row);
                    sceneryString = sprintf('%s%s %s ', sceneryString, xPos, row);
                    currentColor = 1;
                end;
            else
                if pixel > threshold2
                    sceneryString = sprintf('%s%s %s,', sceneryString, xPos, row);
                    currentColor = 2;
                elseif pixel < threshold1
                    sceneryString = sprintf('%s%s %s,', sceneryString, xPos, row);
                    fprintf(output, '%s %s ', xPos, row);
                    currentColor = 0;
                else
                    continue;
                end;
            end;
        end;

        if currentColor == 1
            sceneryString = sprintf('%s%s %s,', sceneryString, xPos, row);
        elseif currentColor == 0
            fprintf(output, '%s %s,', xPos, row);
        end;
    end;
    sceneryString = sprintf('%s#', sceneryString);
    fprintf(output, '%s', sceneryString);
    fclose(output);

    % Increase the value of originY by 2000 for the next iteration of the loop.
    originY = originY + 2000;
end;

</code>```

error message

```<code>error: rgb2gray: RGB of invalid data type 'logical'
error: called from
    colorspace_conversion_input_check at line 41 column 7
    rgb2gray at line 61 column 5
    FreeRiderImageMaker at line 31 column 15
</code>```

i try to start it again from 1505, but its still stop at 1507. i change the originY from 0 into 3010000 so the output coordinate is correct, but its still not working, anyone can help me fix this please??

Body:
i have octave code who convert image into specific code on a game, it work well until file number 1507

% The images must be in the same folder as this script.
% The originY variable will be updated for each PNG file.
originY = 3010000;

% Threshold values modify which shades of grey are consirered scenery (0-255).
threshold1 = 50; %black is 0
threshold2 = 0; %white is 255

% The origin modifies where the rider begins relative to the image.
originX = 200;

% Images can be made larger using the scale option. Use only whole numbers.
% Note that there is a size limit for tracks uploaded to FRHD.
scaleX = 2;
scaleY = 2;

% Loop through each PNG file until 2154.png.
for n = 1505:2154
    % Create the file name for the current PNG file.
    filename = sprintf('%04d.png', n);

    % Read the PNG file.
    image = imread(filename);

    % Create the file name for the output text file.
    outputFilename = sprintf('%04d.txt', n);

    % Open the output text file for writing.
    output = fopen(outputFilename, 'w');

    grayImage = transpose(rgb2gray(image));
    sceneryString = sprintf('#');

    for j = 1:(size(grayImage,2)*scaleY)
        currentColor = 2; % 2 for white, 1 for gray, 0 for black
        for i = 1:size(grayImage,1)
            if originY+j >= 0
                row = lower(dec2base(originY+j, 32));
            else
                row = strcat('-', lower(dec2base(-(originY+j), 32)));
            end;

            if originX+i*scaleX >= 0
                xPos = lower(dec2base(originX+i*scaleX, 32));
            else
                xPos = strcat('-', lower(dec2base(-(originX+i*scaleX), 32)));
            end;

            pixel = grayImage(i,ceil(j/scaleY));

            if currentColor == 2
                if pixel > threshold2
                    continue;
                elseif pixel < threshold1
                    fprintf(output, '%s %s ', xPos, row);
                    currentColor = 0;
                else
                    sceneryString = sprintf('%s%s %s ', sceneryString, xPos, row);
                    currentColor = 1;
                end;
            elseif currentColor == 0
                if pixel < threshold1
                    continue;
                elseif pixel > threshold2
                    fprintf(output, '%s %s,', xPos, row);
                    currentColor = 2;
                else
                    fprintf(output, '%s %s,', xPos, row);
                    sceneryString = sprintf('%s%s %s ', sceneryString, xPos, row);
                    currentColor = 1;
                end;
            else
                if pixel > threshold2
                    sceneryString = sprintf('%s%s %s,', sceneryString, xPos, row);
                    currentColor = 2;
                elseif pixel < threshold1
                    sceneryString = sprintf('%s%s %s,', sceneryString, xPos, row);
                    fprintf(output, '%s %s ', xPos, row);
                    currentColor = 0;
                else
                    continue;
                end;
            end;
        end;

        if currentColor == 1
            sceneryString = sprintf('%s%s %s,', sceneryString, xPos, row);
        elseif currentColor == 0
            fprintf(output, '%s %s,', xPos, row);
        end;
    end;
    sceneryString = sprintf('%s#', sceneryString);
    fprintf(output, '%s', sceneryString);
    fclose(output);

    % Increase the value of originY by 2000 for the next iteration of the loop.
    originY = originY + 2000;
end;

error message

error: rgb2gray: RGB of invalid data type 'logical'
error: called from
    colorspace_conversion_input_check at line 41 column 7
    rgb2gray at line 61 column 5
    FreeRiderImageMaker at line 31 column 15

i try to start it again from 1505, but its still stop at 1507. i change the originY from 0 into 3010000 so the output coordinate is correct, but its still not working, anyone can help me fix this please??


问:
Google IAM Permissions - Cloud Translation API 3 (.NET 7)
I enabled Cloud Translation API Admin, Cloud Translation API Editor, Cloud Translation API User for principal at https://console.cloud.google.com/iam-admin/ and still getting exception in the code. S

```<code>Grpc.Core.RpcException: 'Status(StatusCode="PermissionDenied", Detail="Cloud IAM permission 'cloudtranslate.generalModels.predict' denied. ")'
</code>```

One thing that I noticed, if I go to Service accounts - Manage permissions - +Grant Access - +Add another Role in select role dropdown I get No matches for "Cloud Translation API" Is this something related?

Is there something that I am missing? Any help appreciated.

Body:
I enabled Cloud Translation API Admin, Cloud Translation API Editor, Cloud Translation API User for principal at https://console.cloud.google.com/iam-admin/ and still getting exception in the code. S

Grpc.Core.RpcException: 'Status(StatusCode="PermissionDenied", Detail="Cloud IAM permission 'cloudtranslate.generalModels.predict' denied. ")'

One thing that I noticed, if I go to Service accounts - Manage permissions - +Grant Access - +Add another Role in select role dropdown I get No matches for "Cloud Translation API" Is this something related?

Is there something that I am missing? Any help appreciated.


问:
Returning blank lines instead of expected, list comprehension and dictionaries
The code should take the changes_text.txt, and format it using dictionaries and such. Except its returning as if theres no schedule changes even though there is.

```<code># Store the text data in a string variable instead of writing it to a file
raw_data = changes_txt.text
print(raw_data, 0)

# Use a dictionary to map strings to functions
operation_map = {
    'ביטול שעור': lambda line, i: f'Period {i} cancelled! W\n',
    'הזזת שיעור': lambda line, i: f'Class "{line.split(" לשיעור")[0].split(", ")[2]}" moved to period {i}\n',
    'מילוי מקום': lambda line, i: f'Period {i} replaced with class "{line.split(", ")[4]}"\n',
    'החלפת חדר': lambda line,
                        i: f'Class "{line.split(", ")[2]}" moved to room {line.split(", ")[-1].split(":")[-1]}\n',
}

# Split the raw data into lines
data_lines = raw_data.splitlines()
print(data_lines, 1)

# Use a list comprehension to apply the operations to the data
results = [operation_map[line.split(" ")[0]](line, i) if line.split(" ")[0] in operation_map else "\n"
           for line in data_lines for i in range(8)]

# Use string interpolation to format the output data
output = ''.join(results)
return output
</code>```

The changes_txt.text/raw_data is:

11.12.2022, שיעור 1, כרמי ציפי, מילוי מקום מורג אורית, אזרחות, חדר: 304 0

I'm expecting it to return something like this, where the first period is replaced and the rest of the lines should be empty

```<code>Period 1 replaced with class "אזרחות"
</code>```

I'm obviously not great with dictionaries which is why I need help

full code:
https://pastebin.com/YymFmfjW

Body:
The code should take the changes_text.txt, and format it using dictionaries and such. Except its returning as if theres no schedule changes even though there is.

# Store the text data in a string variable instead of writing it to a file
raw_data = changes_txt.text
print(raw_data, 0)

# Use a dictionary to map strings to functions
operation_map = {
    'ביטול שעור': lambda line, i: f'Period {i} cancelled! W\n',
    'הזזת שיעור': lambda line, i: f'Class "{line.split(" לשיעור")[0].split(", ")[2]}" moved to period {i}\n',
    'מילוי מקום': lambda line, i: f'Period {i} replaced with class "{line.split(", ")[4]}"\n',
    'החלפת חדר': lambda line,
                        i: f'Class "{line.split(", ")[2]}" moved to room {line.split(", ")[-1].split(":")[-1]}\n',
}

# Split the raw data into lines
data_lines = raw_data.splitlines()
print(data_lines, 1)

# Use a list comprehension to apply the operations to the data
results = [operation_map[line.split(" ")[0]](line, i) if line.split(" ")[0] in operation_map else "\n"
           for line in data_lines for i in range(8)]

# Use string interpolation to format the output data
output = ''.join(results)
return output

The changes_txt.text/raw_data is:

11.12.2022, שיעור 1, כרמי ציפי, מילוי מקום מורג אורית, אזרחות, חדר: 304 0

I'm expecting it to return something like this, where the first period is replaced and the rest of the lines should be empty

Period 1 replaced with class "אזרחות"

I'm obviously not great with dictionaries which is why I need help

full code:
https://pastebin.com/YymFmfjW


问:
Hibernate 5 getHibernateTemplate().bulkUpdate() with named parameters
I'm using hibernate 5.3.20 version, using hibernateTemplate I'm querying the result

```<code>getHibernateTemplate().bulkUpdate("UPDATE MessagingLog ml SET ml.retryAttempts = 1, ml.status = ? WHERE ml.retryAttempts > 0")
</code>```

but with above query I'm getting a below error

```<code>org.hibernate.QueryException: Legacy-style query parameters (`?`) are no longer supported; use JPA-style ordinal parameters (e.g., `?1`)
</code>```

If I change the "?" with ?1 then it is throwing error as "ordinal paramter [0] not found"

as hibernate internally mapping the bulkUpdate setParameter starting from index 0

as shown in the below snippet

```<code>public int bulkUpdate(String queryString, @Nullable Object... values) throws DataAccessException {
    Integer result = (Integer)this.executeWithNativeSession((session) -> {
        Query queryObject = queryObject(ReflectionUtils.invokeMethod(createQueryMethod, session, new Object[]{queryString}));
        this.prepareQuery(queryObject);
        if (values != null) {
            for(int i = 0; i < values.length; ++i) {
                queryObject.setParameter(i, values[i]);
            }
        }

        return queryObject.executeUpdate();
    });
    Assert.state(result != null, "No update count");
    return result;
}
</code>```

is there a way I can use setNamed parameters or any other way I achieve the bulkUpate starting from index 0 ??

Body:
I'm using hibernate 5.3.20 version, using hibernateTemplate I'm querying the result

getHibernateTemplate().bulkUpdate("UPDATE MessagingLog ml SET ml.retryAttempts = 1, ml.status = ? WHERE ml.retryAttempts > 0")

but with above query I'm getting a below error

org.hibernate.QueryException: Legacy-style query parameters (`?`) are no longer supported; use JPA-style ordinal parameters (e.g., `?1`)

If I change the "?" with ?1 then it is throwing error as "ordinal paramter [0] not found"

as hibernate internally mapping the bulkUpdate setParameter starting from index 0

as shown in the below snippet

public int bulkUpdate(String queryString, @Nullable Object... values) throws DataAccessException {
    Integer result = (Integer)this.executeWithNativeSession((session) -> {
        Query queryObject = queryObject(ReflectionUtils.invokeMethod(createQueryMethod, session, new Object[]{queryString}));
        this.prepareQuery(queryObject);
        if (values != null) {
            for(int i = 0; i < values.length; ++i) {
                queryObject.setParameter(i, values[i]);
            }
        }

        return queryObject.executeUpdate();
    });
    Assert.state(result != null, "No update count");
    return result;
}

is there a way I can use setNamed parameters or any other way I achieve the bulkUpate starting from index 0 ??


问:
Warm starting from solution basis obtained after solving a Pyomo Model
I want to warm start from a previously obtained solution using Pyomo. I came across a way to access the solution basis from the result object returned after solving a model (e.g. results.solution.basis).
I have attempted to do that using the gurobi and cplex solvers, but the basis is not available in the results object. Is someone aware of why this functionality is unavailable in Pyomo and whether there is a way to achieve the same? The code below illustrates better what I am trying to do:

```<code> solver = SolverFactory(solver_type)
    instance = model.create_instance()

    # Set solution basis for the computation
    if basis is not None and solver_type == "gurobi":
        instance.set_starting_basis(basis)
    elif basis is not None and solver_type == "cplex_direct":
        instance.set_start_basis(basis)

    results = solver.solve(instance, warmstart=True)  # Add warmstart=True in future for optimization
    print(results.solution.basis)
</code>```

Body:
I want to warm start from a previously obtained solution using Pyomo. I came across a way to access the solution basis from the result object returned after solving a model (e.g. results.solution.basis).
I have attempted to do that using the gurobi and cplex solvers, but the basis is not available in the results object. Is someone aware of why this functionality is unavailable in Pyomo and whether there is a way to achieve the same? The code below illustrates better what I am trying to do:

 solver = SolverFactory(solver_type)
    instance = model.create_instance()

    # Set solution basis for the computation
    if basis is not None and solver_type == "gurobi":
        instance.set_starting_basis(basis)
    elif basis is not None and solver_type == "cplex_direct":
        instance.set_start_basis(basis)

    results = solver.solve(instance, warmstart=True)  # Add warmstart=True in future for optimization
    print(results.solution.basis)


问:
OneSignal notification does not appear on iOS, but it does on Android (In App message works perfectly on both)
So I added onesignal-expo-plugin and react-native-onesignal to my  project, I made everything what was wrote on the website
After this i made a developmen-simulator build for my app
I tested the app on IOS and on Android too, on android i get the notification instantly but on IOS i'm not.

So i checked the notification report on OneSignal dashboard and the ios fall into failed. I checked everything, I added everything what i had to, the p12 file is correct, I did everything multiple times before i write here,
I haven't ejected my ios app because I want to keep expo managing my ios/android application well.
What should I try to fix this issue?

Android works correctly but ios don't and I really need your help!
The in-app message works correctly just the push notification don't

Versions:

```<code>    "react-native-onesignal": "^4.5.0",
    "onesignal-expo-plugin": "^1.3.0",
</code>```

I don't want to eject my ios code and I saw too many articles and videos how others use it and works. Please help me whats wrong.

My code example what I tried just now:

```<code> const initialOnesignal = async () => {

    OneSignal.setAppId('HIDEN FOR STACKOVERFLOW');

    OneSignal.promptForPushNotificationsWithUserResponse();

    OneSignal.setNotificationWillShowInForegroundHandler(
      notificationReceivedEvent => {
        console.log(
          'OneSignal: notification will show in foreground:',
          notificationReceivedEvent,
        );
        let notification = notificationReceivedEvent.getNotification();
        console.log('notification: ', notification);
        const data = notification.additionalData;
        console.log('additionalData: ', data);

        notificationReceivedEvent.complete(notification);
      },
    );

    OneSignal.setNotificationOpenedHandler(notification => {
      console.log('OneSignal: notification opened:', notification);
    });
  };

</code>```

And I also tried this way:

```<code>useEffect(() => {
    OneSignal.setAppId('HIDEN FOR STACKOVERFLOW');

    OneSignal.promptForPushNotificationsWithUserResponse(response => {
      console.log('Prompt response:', response);
    });

    OneSignal.setNotificationWillShowInForegroundHandler(
      notificationReceivedEvent => {
        console.log(
          'OneSignal: notification will show in foreground:',
          notificationReceivedEvent,
        );
        let notification = notificationReceivedEvent.getNotification();
        console.log('notification: ', notification);
        const data = notification.additionalData;
        console.log('additionalData: ', data);
        // Complete with null means don't show a notification.
        notificationReceivedEvent.complete(notification);
      },
    );

    OneSignal.setNotificationOpenedHandler(notification => {
      console.log('OneSignal: notification opened:', notification);
    });
  }, []);
</code>```

Tried to only add my AppId as well. I guess i tried everyting.

I have tried to regenerate p12 file, try multiple code examples, run on simultaor and on device too.
Tried to use useEffect and simple function as well.

Body:
So I added onesignal-expo-plugin and react-native-onesignal to my  project, I made everything what was wrote on the website
After this i made a developmen-simulator build for my app
I tested the app on IOS and on Android too, on android i get the notification instantly but on IOS i'm not.

So i checked the notification report on OneSignal dashboard and the ios fall into failed. I checked everything, I added everything what i had to, the p12 file is correct, I did everything multiple times before i write here,
I haven't ejected my ios app because I want to keep expo managing my ios/android application well.
What should I try to fix this issue?

Android works correctly but ios don't and I really need your help!
The in-app message works correctly just the push notification don't

Versions:

    "react-native-onesignal": "^4.5.0",
    "onesignal-expo-plugin": "^1.3.0",

I don't want to eject my ios code and I saw too many articles and videos how others use it and works. Please help me whats wrong.

My code example what I tried just now:

 const initialOnesignal = async () => {

    OneSignal.setAppId('HIDEN FOR STACKOVERFLOW');

    OneSignal.promptForPushNotificationsWithUserResponse();

    OneSignal.setNotificationWillShowInForegroundHandler(
      notificationReceivedEvent => {
        console.log(
          'OneSignal: notification will show in foreground:',
          notificationReceivedEvent,
        );
        let notification = notificationReceivedEvent.getNotification();
        console.log('notification: ', notification);
        const data = notification.additionalData;
        console.log('additionalData: ', data);

        notificationReceivedEvent.complete(notification);
      },
    );

    OneSignal.setNotificationOpenedHandler(notification => {
      console.log('OneSignal: notification opened:', notification);
    });
  };

And I also tried this way:

useEffect(() => {
    OneSignal.setAppId('HIDEN FOR STACKOVERFLOW');

    OneSignal.promptForPushNotificationsWithUserResponse(response => {
      console.log('Prompt response:', response);
    });

    OneSignal.setNotificationWillShowInForegroundHandler(
      notificationReceivedEvent => {
        console.log(
          'OneSignal: notification will show in foreground:',
          notificationReceivedEvent,
        );
        let notification = notificationReceivedEvent.getNotification();
        console.log('notification: ', notification);
        const data = notification.additionalData;
        console.log('additionalData: ', data);
        // Complete with null means don't show a notification.
        notificationReceivedEvent.complete(notification);
      },
    );

    OneSignal.setNotificationOpenedHandler(notification => {
      console.log('OneSignal: notification opened:', notification);
    });
  }, []);

Tried to only add my AppId as well. I guess i tried everyting.

I have tried to regenerate p12 file, try multiple code examples, run on simultaor and on device too.
Tried to use useEffect and simple function as well.


问:
How can you edit currency in datagrip?
I have a problem that datagrip on rows with "money" type adds local currency, I guess... But instead of currency it jsut shows "?" like this:
Wrong Currency Showcase

I prefer just turn off this function because it's breaking my pg_dump "COPY" because it can't parse this "some_num ?" to money format. But if that's not possible, at least I want it to show my locale currency

Title: How can you edit currency in datagrip?


问:
Is there better syntax for selecting multiple sub-elements?

blockquote {font-style:italic;}
blockquote em, blockquote i, blockquote cite {font-style:normal;}
```

I have the feeling that there is, or should be, a more readable way to write that second line, a way that only uses blockquote once. Is there?

Body:
blockquote {font-style:italic;}
blockquote em, blockquote i, blockquote cite {font-style:normal;}

I have the feeling that there is, or should be, a more readable way to write that second line, a way that only uses blockquote once. Is there?


问:
Allow iOS In-app purchases to be bought only in the app
Depending on certain parameters, we want to offer our users a different subscription in app product to be bought in our app. This basically works very well as our app can control which of the available in app products will be shown to the user. However on the app store page of our app the user can freely choose to subscripe to whatever in app product he wants. Is there any way to disable this (so that users can only buy through our app and not in the app store)? If not, how else could we handle this scenario?</p>


问:
Associating coastal lat/lon coordinates with country in R
I have a list of data points with lat/lon coordinates that I want to associate with their country. There is a great answer on how to do this using rworldmaps here, which is reproduced in the example below. However, because of the relatively large grid size of my data (plus previous spatial interpolation), a not insignificant number of coastal data points end up falling outside the country boundaries of rworldmaps. Is there any way to associate these points with the nearest country to avoid losing the coastal data?

Here is the coords2country function:

```<code>library(sp)
library(rworldmap)

#Function code from: https://stackoverflow.com/questions/14334970/convert-latitude-and-longitude-coordinates-to-country-name-in-r?rq=1
coords2country = function(points)
{
  countriesSP <- getMap(resolution='low')
  #countriesSP <- getMap(resolution='high') #high res version

  #setting CRS directly to that from rworldmap
  pointsSP = SpatialPoints(points, proj4string=CRS(proj4string(countriesSP)))

  # use 'over' to get indices of the Polygons object containing each point
  indices = over(pointsSP, countriesSP)
  # return the ADMIN names of each country
  indices$ADMIN
}
</code>```

Here is a sample of coordinate points and the response, with some missing coastal data points

```<code>pts <- data.frame(x = c(21.00, 21.25, 21.00, 21.25, 25.25, 25.75, 25.25, 25.75, 22.75, 26.50, 23.00),
                  y = c(65.75, 65.75, 65.50, 65.50, 65.00, 65.00, 64.75, 64.75, 63.75, 60.50, 60.00))

pts$country  <- coords2country(pts)

head(pts)
      x     y country
1 21.00 65.75  Sweden
2 21.25 65.75  Sweden
3 21.00 65.50  Sweden
4 21.25 65.50  Sweden
5 25.25 65.00    <NA>
6 25.75 65.00 Finland
</code>```

I'd like to modify this to count points such as x=25.25, 65.00 as part of Finland, or even capture a point that falls into the nearby ocean.

Note: Using the high resolution version of rworldmaps (with rworldxtra) does eliminate some of the NAs, but doesn't eliminate the problem.

Body:
I have a list of data points with lat/lon coordinates that I want to associate with their country. There is a great answer on how to do this using rworldmaps here, which is reproduced in the example below. However, because of the relatively large grid size of my data (plus previous spatial interpolation), a not insignificant number of coastal data points end up falling outside the country boundaries of rworldmaps. Is there any way to associate these points with the nearest country to avoid losing the coastal data?

Here is the coords2country function:

library(sp)
library(rworldmap)

#Function code from: https://stackoverflow.com/questions/14334970/convert-latitude-and-longitude-coordinates-to-country-name-in-r?rq=1
coords2country = function(points)
{
  countriesSP <- getMap(resolution='low')
  #countriesSP <- getMap(resolution='high') #high res version

  #setting CRS directly to that from rworldmap
  pointsSP = SpatialPoints(points, proj4string=CRS(proj4string(countriesSP)))

  # use 'over' to get indices of the Polygons object containing each point
  indices = over(pointsSP, countriesSP)
  # return the ADMIN names of each country
  indices$ADMIN
}

Here is a sample of coordinate points and the response, with some missing coastal data points

pts <- data.frame(x = c(21.00, 21.25, 21.00, 21.25, 25.25, 25.75, 25.25, 25.75, 22.75, 26.50, 23.00),
                  y = c(65.75, 65.75, 65.50, 65.50, 65.00, 65.00, 64.75, 64.75, 63.75, 60.50, 60.00))

pts$country  <- coords2country(pts)

head(pts)
      x     y country
1 21.00 65.75  Sweden
2 21.25 65.75  Sweden
3 21.00 65.50  Sweden
4 21.25 65.50  Sweden
5 25.25 65.00    <NA>
6 25.75 65.00 Finland

I'd like to modify this to count points such as x=25.25, 65.00 as part of Finland, or even capture a point that falls into the nearby ocean.

Note: Using the high resolution version of rworldmaps (with rworldxtra) does eliminate some of the NAs, but doesn't eliminate the problem.


问:
Django is unable to use the SMTP server in the tests environment
I am running a Django (4.1) app in Docker. As part of our test suite, I would like to make use of a development SMTP server which is also running in a Docker container (see docker-compose.yml below). I am using a Selenium driver to run the tests against a Django LiveServer instance. I am also using 1secmail as a temporary mailbox for the tests.

The SMTP server is working nicely with Django (i.e. Django is able to send emails with it) only if Django is not running from a LiveServer. Whenever I try to programmatically test a scenario where SMTP is involved (with a Selenium driver), the email never gets sent (see the failing test below).

The question is simple: how do I make Django and the SMTP server talk to each other in the tests environment?

My docker-compose.yml

```<code>version: '3.8'

services:
  myapp:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - ./:/usr/src/app/
    ports:
      - 8009:8000
    env_file:
      - ./.env.dev
    links:
      - selenium-chrome
      - dev-smtp-server

  myapp-db:
    image: postgres:14-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    environment:
      - POSTGRES_USER=blabla
      - POSTGRES_PASSWORD=blabla
      - POSTGRES_DB=blabla

  selenium-chrome:
    image: selenium/standalone-chrome
    ports:
      - 4444:4444   # actual Selenium
      - 5900:5900   # VNC server

  dev-smtp-server:
    image: bytemark/smtp
    restart: always

volumes:
  postgres_data:
</code>```

My test fixtures

...
from pytest_django.live_server_helper import LiveServer

@pytest.fixture(scope="session")
def test_server() -> LiveServer:
    host = socket.gethostbyname(socket.gethostname())
    if host not in settings.ALLOWED_HOSTS:
        settings.ALLOWED_HOSTS.append(host)
    server = LiveServer(host)
    yield server
    server.stop()

@pytest.fixture
def driver():
    options = webdriver.ChromeOptions()
    driver = webdriver.Remote(
        command_executor="http://selenium-chrome:4444/wd/hub",  # connect to the Selenium container defined in docker-compose
        options=options,
    )
    yield driver
    driver.quit()

@pytest.fixture
def forgot_my_password_page_driver(driver: Remote, test_server: LiveServer):
    forgotMyPasswordURL = reverse("password_reset")
    driver.get(f"{test_server.url}{forgotMyPasswordURL}")
    return driver

@pytest.fixture
def email_address_for_which_forgotten_password_form_has_just_been_filed(
    forgot_my_password_page_driver, db
):
    emailInput = forgot_my_password_page_driver.find_element(By.NAME, "email")
    emailAddress = OneSecMailAPI.get_random_email_address()
    emailInput.send_keys(emailAddress)

    sendButton = forgot_my_password_page_driver.find_element(
        By.CSS_SELECTOR, "input[type='submit']"
    )
    sendButton.click()
    return emailAddress
```
<h2>The failing test</h2>
<pre class="lang-py prettyprint-override"><code>def test_forgot_my_password_form_sends_an_email_to_actually_reset_your_password(
    email_address_for_which_forgotten_password_form_has_just_been_filed,
):
    emailAddress = email_address_for_which_forgotten_password_form_has_just_been_filed
    emailDomain = emailAddress.split("@")[1]

    emailReceived = False
    loopCounter = 0
    while not emailReceived and loopCounter < 5:
        messages = OneSecMailAPI.get_messages(login=emailAddress, domain=emailDomain)
        if len(messages) == 0:
            time.sleep(1)
            loopCounter = loopCounter + 1
        else:
            emailReceived = True

    assert emailReceived
</code>```

Body:
I am running a Django (4.1) app in Docker. As part of our test suite, I would like to make use of a development SMTP server which is also running in a Docker container (see docker-compose.yml below). I am using a Selenium driver to run the tests against a Django LiveServer instance. I am also using 1secmail as a temporary mailbox for the tests.

The SMTP server is working nicely with Django (i.e. Django is able to send emails with it) only if Django is not running from a LiveServer. Whenever I try to programmatically test a scenario where SMTP is involved (with a Selenium driver), the email never gets sent (see the failing test below).

The question is simple: how do I make Django and the SMTP server talk to each other in the tests environment?

My docker-compose.yml

version: '3.8'

services:
  myapp:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - ./:/usr/src/app/
    ports:
      - 8009:8000
    env_file:
      - ./.env.dev
    links:
      - selenium-chrome
      - dev-smtp-server

  myapp-db:
    image: postgres:14-alpine
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    environment:
      - POSTGRES_USER=blabla
      - POSTGRES_PASSWORD=blabla
      - POSTGRES_DB=blabla

  selenium-chrome:
    image: selenium/standalone-chrome
    ports:
      - 4444:4444   # actual Selenium
      - 5900:5900   # VNC server

  dev-smtp-server:
    image: bytemark/smtp
    restart: always

volumes:
  postgres_data:

My test fixtures

...
from pytest_django.live_server_helper import LiveServer

@pytest.fixture(scope="session")
def test_server() -> LiveServer:
    host = socket.gethostbyname(socket.gethostname())
    if host not in settings.ALLOWED_HOSTS:
        settings.ALLOWED_HOSTS.append(host)
    server = LiveServer(host)
    yield server
    server.stop()

@pytest.fixture
def driver():
    options = webdriver.ChromeOptions()
    driver = webdriver.Remote(
        command_executor="http://selenium-chrome:4444/wd/hub",  # connect to the Selenium container defined in docker-compose
        options=options,
    )
    yield driver
    driver.quit()

@pytest.fixture
def forgot_my_password_page_driver(driver: Remote, test_server: LiveServer):
    forgotMyPasswordURL = reverse("password_reset")
    driver.get(f"{test_server.url}{forgotMyPasswordURL}")
    return driver

@pytest.fixture
def email_address_for_which_forgotten_password_form_has_just_been_filed(
    forgot_my_password_page_driver, db
):
    emailInput = forgot_my_password_page_driver.find_element(By.NAME, "email")
    emailAddress = OneSecMailAPI.get_random_email_address()
    emailInput.send_keys(emailAddress)

    sendButton = forgot_my_password_page_driver.find_element(
        By.CSS_SELECTOR, "input[type='submit']"
    )
    sendButton.click()
    return emailAddress

The failing test

def test_forgot_my_password_form_sends_an_email_to_actually_reset_your_password(
    email_address_for_which_forgotten_password_form_has_just_been_filed,
):
    emailAddress = email_address_for_which_forgotten_password_form_has_just_been_filed
    emailDomain = emailAddress.split("@")[1]

    emailReceived = False
    loopCounter = 0
    while not emailReceived and loopCounter < 5:
        messages = OneSecMailAPI.get_messages(login=emailAddress, domain=emailDomain)
        if len(messages) == 0:
            time.sleep(1)
            loopCounter = loopCounter + 1
        else:
            emailReceived = True

    assert emailReceived


问:
Why is ScrollView text displayed only with a certain font_size value?
I have a program that parses text from a site and outputs it. But the problem is that when I put this text in ScrollView then at 4 pages of the book it is displayed, but at 57 pages it simply is not. Only if I change the value of font_size to 1, only then the entire text of the book is displayed, but obviously this is not what I need. How to solve this problem?</p>
```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from bs4 import BeautifulSoup
from kivy.uix.scrollview import ScrollView
import requests
    Builder.load_string('''

    # Define the scroll view
    <ScrollableLabel>:
        Label:
            id: label
            color: (1,1,1,1)
            font_size: 15
            text_size: self.width, None
            size_hint_y: None
            height: self.texture_size[1]
    ''')

    class MyButton(Button):
        color = (0, 0, 0, 1)
        valign = 'bottom'
        padding_y = 10
        background_color = (.93, .91, .67, 1)
        background_normal = ''

    class ScrollableLabel(ScrollView):
        pass

    class Box(BoxLayout):
        color = (.98, .98, .82, 1)
        orientation = "vertical"
        padding = [5, 5, 5, 5]
        spacing = 10

        def on_kv_post(self, widget):

            self.add_widget(MyButton(text='И. С. Тургенев. «Отцы и дети»', on_press=self.btn_press))

        def btn_press(self, instance):
            self.clear_widgets()
            sc = ScrollableLabel()
            x = 1
            data = ''
            while True:
                if x == 1:
                    url = "http://loveread.ec/read_book.php?id=12021&p=1"
                elif x < 4:
                    url = "http://loveread.ec/read_book.php?id=12021&p=" + f'{x}'
                else:
                    break
                request = requests.get(url)
                soup = BeautifulSoup(request.text, "html.parser")
                teme = soup.find_all("p", class_="MsoNormal")

                for temes in teme:
                    data += temes.text
                x = x + 1
            sc.ids.label.text = data
            self.add_widget(sc)

    class MyApp(App):

        def build(self):
            return Box()

    if __name__ == "__main__":
        MyApp().run()
</code>```

Body:
I have a program that parses text from a site and outputs it. But the problem is that when I put this text in ScrollView then at 4 pages of the book it is displayed, but at 57 pages it simply is not. Only if I change the value of font_size to 1, only then the entire text of the book is displayed, but obviously this is not what I need. How to solve this problem?

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from bs4 import BeautifulSoup
from kivy.uix.scrollview import ScrollView
import requests
    Builder.load_string('''

    # Define the scroll view
    <ScrollableLabel>:
        Label:
            id: label
            color: (1,1,1,1)
            font_size: 15
            text_size: self.width, None
            size_hint_y: None
            height: self.texture_size[1]
    ''')

    class MyButton(Button):
        color = (0, 0, 0, 1)
        valign = 'bottom'
        padding_y = 10
        background_color = (.93, .91, .67, 1)
        background_normal = ''

    class ScrollableLabel(ScrollView):
        pass

    class Box(BoxLayout):
        color = (.98, .98, .82, 1)
        orientation = "vertical"
        padding = [5, 5, 5, 5]
        spacing = 10

        def on_kv_post(self, widget):

            self.add_widget(MyButton(text='И. С. Тургенев. «Отцы и дети»', on_press=self.btn_press))

        def btn_press(self, instance):
            self.clear_widgets()
            sc = ScrollableLabel()
            x = 1
            data = ''
            while True:
                if x == 1:
                    url = "http://loveread.ec/read_book.php?id=12021&p=1"
                elif x < 4:
                    url = "http://loveread.ec/read_book.php?id=12021&p=" + f'{x}'
                else:
                    break
                request = requests.get(url)
                soup = BeautifulSoup(request.text, "html.parser")
                teme = soup.find_all("p", class_="MsoNormal")

                for temes in teme:
                    data += temes.text
                x = x + 1
            sc.ids.label.text = data
            self.add_widget(sc)

    class MyApp(App):

        def build(self):
            return Box()

    if __name__ == "__main__":
        MyApp().run()


问:
Is there an option in VSCode to show the matching line brace opening line as a hint when the mouse or cursor is on closing brace or line?
Is there an option to show what line a closing brace relates to when hovering over that closing brace in VSCode?

For example, if you have an if statement and the opening brace is off screen can vscode show the opening line?

```<code>if (red) {

   if (blue {

       if (yellow) {

           if (green) {

           }
       }
   }| "if (blue) {"
}
</code>```

If the cursor or mouse is on the second to last closing brace it shows the hint:

if (blue) {

If the cursor or mouse is on the last closing brace it shows the hint:

if (red) {

Does this make sense? Is this an existing feature?

Body:
Is there an option to show what line a closing brace relates to when hovering over that closing brace in VSCode?

For example, if you have an if statement and the opening brace is off screen can vscode show the opening line?

if (red) {

   if (blue {

       if (yellow) {

           if (green) {

           }
       }
   }| "if (blue) {"
}

If the cursor or mouse is on the second to last closing brace it shows the hint:

if (blue) {

If the cursor or mouse is on the last closing brace it shows the hint:

if (red) {

Does this make sense? Is this an existing feature?


问:
Could not import vxlapi: Could not find module 'vxlapi64'
I'm using this can bootloader. I get this error and I don't know how to load the driver.</p>
```<code>Could not import vxlapi: Could not find module 'vxlapi64' (or one of its dependencies). Try using the full path with constructor syntax.
Traceback (most recent call last):
  File "D:\stm32-can-bootloader\LOADER\PY-CAN-LOADER.py", line 442, in <module>
    bus = can.interface.Bus(bustype='vector', app_name='CANalyzer', channel=0, bitrate=500000)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\naomi\AppData\Local\Programs\Python\Python311\Lib\site-packages\can\interface.py", line 127, in __new__
    bus = cls(channel, *args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\naomi\AppData\Local\Programs\Python\Python311\Lib\site-packages\can\util.py", line 337, in wrapper
    return f(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^
  File "C:\Users\naomi\AppData\Local\Programs\Python\Python311\Lib\site-packages\can\interfaces\vector\canlib.py", line 154, in __init__
    raise CanInterfaceNotImplementedError("The Vector API has not been loaded")
can.exceptions.CanInterfaceNotImplementedError: The Vector API has not been loaded
</code>```

Body:
I'm using this can bootloader. I get this error and I don't know how to load the driver.

Could not import vxlapi: Could not find module 'vxlapi64' (or one of its dependencies). Try using the full path with constructor syntax.
Traceback (most recent call last):
  File "D:\stm32-can-bootloader\LOADER\PY-CAN-LOADER.py", line 442, in <module>
    bus = can.interface.Bus(bustype='vector', app_name='CANalyzer', channel=0, bitrate=500000)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\naomi\AppData\Local\Programs\Python\Python311\Lib\site-packages\can\interface.py", line 127, in __new__
    bus = cls(channel, *args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\naomi\AppData\Local\Programs\Python\Python311\Lib\site-packages\can\util.py", line 337, in wrapper
    return f(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^
  File "C:\Users\naomi\AppData\Local\Programs\Python\Python311\Lib\site-packages\can\interfaces\vector\canlib.py", line 154, in __init__
    raise CanInterfaceNotImplementedError("The Vector API has not been loaded")
can.exceptions.CanInterfaceNotImplementedError: The Vector API has not been loaded


问:
TypeError: Cannot read properties of undefined (reading 'getArguments')
When I deploy the application on Heroku, I get the following error, already tried different versions of webpack, also installed and uninstalled but nothing helped:

```<code>    [webpack-cli] TypeError: Cannot read properties of undefined (reading 'getArguments')
at WebpackCLI.getBuiltInOptions (/tmp/build_cb26c8c0/node_modules/webpack-cli/lib/webpack-cli.js:755:63)
at makeCommand.options.entry (/tmp/build_cb26c8c0/node_modules/webpack-cli/lib/webpack-cli.js:880:32)
at async WebpackCLI.makeCommand (/tmp/build_cb26c8c0/node_modules/webpack-cli/lib/webpack-cli.js:395:31)
at async loadCommandByName (/tmp/build_cb26c8c0/node_modules/webpack-cli/lib/webpack-cli.js:876:17)
at async Command.<anonymous> (/tmp/build_cb26c8c0/node_modules/webpack-cli/lib/webpack-cli.js:1272:17)
at async Command.parseAsync (/tmp/build_cb26c8c0/node_modules/webpack-cli/node_modules/commander/lib/command.js:916:5)
at async WebpackCLI.run (/tmp/build_cb26c8c0/node_modules/webpack-cli/lib/webpack-cli.js:1296:9)
at async runCLI (/tmp/build_cb26c8c0/node_modules/webpack-cli/lib/bootstrap.js:9:9)
</code>```

my package.json file:

```<code>{
  "dependencies": {
    "@babel/preset-react": "^7.18.6",
    "@rails/webpacker": "^5.4.3",
    "babel-plugin-transform-react-remove-prop-types": "^0.4.24",
    "html-webpack-plugin": "^5.5.0",
    "i18n-js": "^4.2.0",
    "path": "^0.12.7",
    "prop-types": "^15.8.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^9.1.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1",
    "webpack-dev-server": "^4.11.1"
  }
</code>```

Body:
When I deploy the application on Heroku, I get the following error, already tried different versions of webpack, also installed and uninstalled but nothing helped:

    [webpack-cli] TypeError: Cannot read properties of undefined (reading 'getArguments')
at WebpackCLI.getBuiltInOptions (/tmp/build_cb26c8c0/node_modules/webpack-cli/lib/webpack-cli.js:755:63)
at makeCommand.options.entry (/tmp/build_cb26c8c0/node_modules/webpack-cli/lib/webpack-cli.js:880:32)
at async WebpackCLI.makeCommand (/tmp/build_cb26c8c0/node_modules/webpack-cli/lib/webpack-cli.js:395:31)
at async loadCommandByName (/tmp/build_cb26c8c0/node_modules/webpack-cli/lib/webpack-cli.js:876:17)
at async Command.<anonymous> (/tmp/build_cb26c8c0/node_modules/webpack-cli/lib/webpack-cli.js:1272:17)
at async Command.parseAsync (/tmp/build_cb26c8c0/node_modules/webpack-cli/node_modules/commander/lib/command.js:916:5)
at async WebpackCLI.run (/tmp/build_cb26c8c0/node_modules/webpack-cli/lib/webpack-cli.js:1296:9)
at async runCLI (/tmp/build_cb26c8c0/node_modules/webpack-cli/lib/bootstrap.js:9:9)

my package.json file:

{
  "dependencies": {
    "@babel/preset-react": "^7.18.6",
    "@rails/webpacker": "^5.4.3",
    "babel-plugin-transform-react-remove-prop-types": "^0.4.24",
    "html-webpack-plugin": "^5.5.0",
    "i18n-js": "^4.2.0",
    "path": "^0.12.7",
    "prop-types": "^15.8.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^9.1.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.0.1",
    "webpack-dev-server": "^4.11.1"
  }


问:
How to implement the following Logic in Qlik Sense?
I am new to Qlik Sense. I am trying to implement a logic into qlik sense. I'm not sure how to or where to proceed.
So far, I had only created the inline table for all the input tables.

Input Tables

Result Pivot Table

In Result Table,

Based on the 'From' and 'Till' values in the "account details" table, the values are iterated over months.

'Pay' is calculated as, pay  in "account details" + the 'increase percentage' from "increase table".

'Social Contribution' is calculated as, percentage of Sum(Pay, All Bonuses - Rent). Percent taken from 'contribution percentage' from "Social Contribution" if the value is less than 'Peak Contribution' otherwise the 'contribution percentage' on the 'Peak Contribution'.

Bonus amounts are added on the months described in the "Special table"

Other amounts are iterated over the period of "Acc. Details" table.


问:
next-dev.js?3515:20 Material-UI: The value provided to the Tabs component is invalid. None of the Tabs' children match with `undefined`
next-dev.js?3515:20 Material-UI: The value provided to the Tabs component is invalid.
None of the Tabs' children match with undefined

next-dev.js?3515:20 Material-UI: The value provided to the Tabs component is invalid.
None of the Tabs' children match with undefined
Why this? i can't use material ui?