问:
FastAPI and Axios POST request misconfiguration
I have a FastAPI backend configured as such:

@app.post("/engines/completions")
async def read_completions(
    # engine_id:str,
    prompt: Optional[str] = None,
    max_tokens: Optional[int] = 16,
    temperature: Optional[float] = 1.0,
    top_p: Optional[float] = 1.0,
    top_k: Optional[int] = 40,
    n: Optional[int] = 1,
    stream: Optional[bool] = False,
    logprobs: Optional[int] = None,
    echo: Optional[bool] = False,
    stop: Optional[list] = None,
    presence_penalty: Optional[float] = 0.0001,
    frequency_penalty: Optional[float] = 0.0001,
    best_of: Optional[int] = 1,
    recursive_depth: Optional[int] = 0,
    recursive_refresh: Optional[int] = 0,
    logit_bias: Optional[Dict[str, float]] = None,
):
```
<p>and an Axios request configured like this:</p>
<pre class="lang-js prettyprint-override"><code>let stop = "stuff";
let prompt ="test";
let url = "http://localhost:8000/engines/completions";
const options = {
  method: "POST",
  headers: { "content-type": "application/json"},
  timeout: 2000000,
  body: {stop, prompt},
  url,
};
axios(options)
</code>```

My request goes through without getting a 442 error, but prompt and stop attributes would result in None in my read_completions function. What am I doing wrong?

答:
My request will go through without a 442

Your request goes through, as all parameters are defined as optional. Thus, not receiving these parameters, the server won't complain.

but prompt and stop will evaluate as None in my read_completions
function.

They are both None (null), as the server never received any values for them. Your endpoint expects these parameters being Query parameters, however, your client sends (or actually, attempts to send) body parameters.

Option 1

Adjust your endpoint to expect Form data. Also, if you are going to define a parameter to be a List, please have a look at this on how to do that properly.

from typing import Optional, List

@app.post("/engines/completions")
def read_completions(
    prompt: Optional[str] = Form(None),
    stop: Optional[List[str]] = Form(None)
):
    return {"prompt": prompt, "stop list": stop}
```
<p>Then, your client side should look like this:</p>
<pre class="lang-javascript prettyprint-override"><code>function uploadFormData() {
    var formData = new FormData();
    var alphaArray = ['A', 'B', 'C','D','E'];
    for (var i = 0; i < alphaArray.length; i++) {
        formData.append('stop', alphaArray [i]);
    }
    formData.append("prompt", "test");
    axios({
            method: 'post',
            url: '/engines/completions',
            data: formData,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
        })
        .then(response => {
            console.log(response);
        })
        .catch(error => {
            console.error(error);
        });
}
</code>```

Option 2

Adjust your endpoint to expect JSON (body) parameters. In FastAPI, you could do that using either Body parameters or Pydantic models. The example below uses the latter.

from pydantic import BaseModel
from typing import Optional, List

class Item(BaseModel):
    prompt: str = None
    stop: Optional[List[str]] = None

@app.post("/engines/completions")
def read_completions(item: Item):
    return {"prompt": item.prompt, "stop list": item.stop}
```
<p>Finally, the client side should look like the below:</p>
<pre class="lang-javascript prettyprint-override"><code>function uploadJSONdata() {
    axios({
            method: 'post',
            url: '/engines/completions',
            data: JSON.stringify({"prompt": "test", "stop": ['A', 'B', 'C','D','E']}),
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
        })
        .then(response => {
            console.log(response);
        })
        .catch(error => {
            console.error(error);
        });
}
</code>```

Body:
I have a FastAPI backend configured as such:

@app.post("/engines/completions")
async def read_completions(
    # engine_id:str,
    prompt: Optional[str] = None,
    max_tokens: Optional[int] = 16,
    temperature: Optional[float] = 1.0,
    top_p: Optional[float] = 1.0,
    top_k: Optional[int] = 40,
    n: Optional[int] = 1,
    stream: Optional[bool] = False,
    logprobs: Optional[int] = None,
    echo: Optional[bool] = False,
    stop: Optional[list] = None,
    presence_penalty: Optional[float] = 0.0001,
    frequency_penalty: Optional[float] = 0.0001,
    best_of: Optional[int] = 1,
    recursive_depth: Optional[int] = 0,
    recursive_refresh: Optional[int] = 0,
    logit_bias: Optional[Dict[str, float]] = None,
):

and an Axios request configured like this:

let stop = "stuff";
let prompt ="test";
let url = "http://localhost:8000/engines/completions";
const options = {
  method: "POST",
  headers: { "content-type": "application/json"},
  timeout: 2000000,
  body: {stop, prompt},
  url,
};
axios(options)

My request goes through without getting a 442 error, but prompt and stop attributes would result in None in my read_completions function. What am I doing wrong?

Body:
My request will go through without a 442

Your request goes through, as all parameters are defined as optional. Thus, not receiving these parameters, the server won't complain.

but prompt and stop will evaluate as None in my read_completions
function.

They are both None (null), as the server never received any values for them. Your endpoint expects these parameters being Query parameters, however, your client sends (or actually, attempts to send) body parameters.

Option 1

Adjust your endpoint to expect Form data. Also, if you are going to define a parameter to be a List, please have a look at this on how to do that properly.

from typing import Optional, List

@app.post("/engines/completions")
def read_completions(
    prompt: Optional[str] = Form(None),
    stop: Optional[List[str]] = Form(None)
):
    return {"prompt": prompt, "stop list": stop}

Then, your client side should look like this:

function uploadFormData() {
    var formData = new FormData();
    var alphaArray = ['A', 'B', 'C','D','E'];
    for (var i = 0; i < alphaArray.length; i++) {
        formData.append('stop', alphaArray [i]);
    }
    formData.append("prompt", "test");
    axios({
            method: 'post',
            url: '/engines/completions',
            data: formData,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
        })
        .then(response => {
            console.log(response);
        })
        .catch(error => {
            console.error(error);
        });
}

Option 2

Adjust your endpoint to expect JSON (body) parameters. In FastAPI, you could do that using either Body parameters or Pydantic models. The example below uses the latter.

from pydantic import BaseModel
from typing import Optional, List

class Item(BaseModel):
    prompt: str = None
    stop: Optional[List[str]] = None

@app.post("/engines/completions")
def read_completions(item: Item):
    return {"prompt": item.prompt, "stop list": item.stop}

Finally, the client side should look like the below:

function uploadJSONdata() {
    axios({
            method: 'post',
            url: '/engines/completions',
            data: JSON.stringify({"prompt": "test", "stop": ['A', 'B', 'C','D','E']}),
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
        })
        .then(response => {
            console.log(response);
        })
        .catch(error => {
            console.error(error);
        });
}


来源: stackexchange

问:
How to get array with intersected elements?
I have an array, that contains another arrays with string id's. I need to get an array with string ids, that are exists in all arrays of parent.

Here is example:

```<code>const parentArray = [ ['test1', 'test2', 'test3'], ['test2', 'test4', 'test5'], ['test3', 'test2', 'test6']];

//some magic. Maybe use lodash instersection func

console.log(result) => ['test2']
</code>```

Important note! I don't know, how much arrays of elements in parent array, thats the problem that i cant understand how to use lodash intersection function:(

答:
The below may be one possible way to achieve the desired result.

Code Sample

```<code>const commonElements = (arr1, arr2) => (
    arr1.length === 0
   ? arr2
   : [...(new Set([...arr1, ...arr2]))]
    .filter(
      x => arr1.includes(x) && arr2.includes(x)
    )
);

const intersectAllElements = (arr = parentArray) => (
    arr.reduce(
    (fin, itm) => (commonElements(fin, itm)),
    []
  )
);
</code>```

Explanation

Set a helper-method named commonElements that will share either common elements between 2 arrays, or if the first array is empty then the second array

Iterate over the parentArray using .reduce

Initialize the aggregator fin as an empty array

For each item (which will be an array) in parentArray, track the common elements between the aggregator and given item

Code Snippet

const parentArray = [ ['test1', 'test2', 'test3'], ['test2', 'test4', 'test5'], ['test3', 'test2', 'test6']];

const commonElements = (arr1, arr2) => (
    arr1.length === 0
   ? arr2
   : [...(new Set([...arr1, ...arr2]))]
    .filter(
      x => arr1.includes(x) && arr2.includes(x)
    )
);

const intersectAllElements = (arr = parentArray) => (
    arr.reduce(
    (fin, itm) => (commonElements(fin, itm)),
    []
  )
);

console.log(intersectAllElements());```

ContentLicense: CC BY-SA 4.0

Body:
I have an array, that contains another arrays with string id's. I need to get an array with string ids, that are exists in all arrays of parent.

Here is example:

const parentArray = [ ['test1', 'test2', 'test3'], ['test2', 'test4', 'test5'], ['test3', 'test2', 'test6']];

//some magic. Maybe use lodash instersection func

console.log(result) => ['test2']

Important note! I don't know, how much arrays of elements in parent array, thats the problem that i cant understand how to use lodash intersection function:(

Body:
The below may be one possible way to achieve the desired result.

Code Sample

const commonElements = (arr1, arr2) => (
    arr1.length === 0
   ? arr2
   : [...(new Set([...arr1, ...arr2]))]
    .filter(
      x => arr1.includes(x) && arr2.includes(x)
    )
);

const intersectAllElements = (arr = parentArray) => (
    arr.reduce(
    (fin, itm) => (commonElements(fin, itm)),
    []
  )
);

Explanation

Set a helper-method named commonElements that will share either common elements between 2 arrays, or if the first array is empty then the second array

Iterate over the parentArray using .reduce

Initialize the aggregator fin as an empty array

For each item (which will be an array) in parentArray, track the common elements between the aggregator and given item

Code Snippet

const parentArray = [ ['test1', 'test2', 'test3'], ['test2', 'test4', 'test5'], ['test3', 'test2', 'test6']];

const commonElements = (arr1, arr2) => (
    arr1.length === 0
   ? arr2
   : [...(new Set([...arr1, ...arr2]))]
    .filter(
      x => arr1.includes(x) && arr2.includes(x)
    )
);

const intersectAllElements = (arr = parentArray) => (
    arr.reduce(
    (fin, itm) => (commonElements(fin, itm)),
    []
  )
);

console.log(intersectAllElements());


问:
Pull password from gnome keyring in Julia?
I’ve looked around but can not find a julia package that will let me pull an encrypted password which is stored in my linux gnome keyring. I use it for keeping scripts that connect to SQL servers, anonymous because I have to distribute them to several group members.

In R, the “keyringer” package has a “decrypt_gk_pw” function that can pull a stored password right from the gnome keyring. Is there anything analogous in Julia or would we have to build it?

答:
https://rdrr.io/cran/keyringr/src/R/decrypt_gk_pw.R

```<code>invisible(system(paste("secret-tool lookup ", key_value_pairs, sep=""), intern=TRUE))
</code>```

so:

```<code>> secret-tool store --label=mylabel db mydb user user1
Password:
> julia -e 'read(`secret-tool lookup db mydb user user1`, String) |> println'
blah
</code>```

if you need it to go to your clipboard, you can replace the println with clipboard

Body:
https://rdrr.io/cran/keyringr/src/R/decrypt_gk_pw.R

invisible(system(paste("secret-tool lookup ", key_value_pairs, sep=""), intern=TRUE))

so:

> secret-tool store --label=mylabel db mydb user user1
Password:
> julia -e 'read(`secret-tool lookup db mydb user user1`, String) |> println'
blah

if you need it to go to your clipboard, you can replace the println with clipboard


问:
Pseudo Class Color Change on Hover
I have an accordion where upon hover, the text color changes. Sounds simple enough, but I have an issue with the content within a pseudo class changing color. I feel like I've added the :after:hover class in the to change the color, but it's not working? Any reason why?

There's a more detailed Codepen here.

```<code><div class="task-resources-accordion">
  Title
</div>
<div class="task-resources-accordion-panel">
  <div class="task-resources-accordion-content">
    <p>Content</p>
  </div>
</div>

</code>```
```<code>/* Accordions */

.task-resources-accordion {
  background-color: #eee;
  color: #1e1e1e;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  box-sizing: border-box;
  text-align: left;
  border: none;
  outline: none;
  transition: 0.4s ease;
  font-size: 18px;
  line-height: 24px;
  letter-spacing: 0;
}

.task-resources-accordion.active,
.task-resources-accordion:hover {
  background-color: #21bfb2;
  color: #fff;
}

.task-resources-accordion:after {
  content: "\2795";
  font-size: 13px;
  float: left;
  margin-right: 10px;
}

.task-resources-accordion:after:hover {
  color: #fff;
}

.task-resources-accordion.active:after {
  content: "\2796";
  color: #fff;
}

.task-resources-accordion-panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: 0.4s ease;
  opacity: 0;
  margin-bottom: 10px;
  border: 1px solid #eaeaea;
}

.task-resources-accordion-panel.show {
  opacity: 1;
  max-height: 1000px;
}

.task-resources-accordion-content {
  padding: 15px;
}

</code>```

答:
You are using unicode in content. Its color cannot be changed by css.
Can't change font color on unicode character</p>

Title: Pseudo Class Color Change on Hover

Body:
I have an accordion where upon hover, the text color changes. Sounds simple enough, but I have an issue with the content within a pseudo class changing color. I feel like I've added the :after:hover class in the to change the color, but it's not working? Any reason why?

There's a more detailed Codepen here.

  Title

Content

/* Accordions */

.task-resources-accordion {
  background-color: #eee;
  color: #1e1e1e;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  box-sizing: border-box;
  text-align: left;
  border: none;
  outline: none;
  transition: 0.4s ease;
  font-size: 18px;
  line-height: 24px;
  letter-spacing: 0;
}

.task-resources-accordion.active,
.task-resources-accordion:hover {
  background-color: #21bfb2;
  color: #fff;
}

.task-resources-accordion:after {
  content: "\2795";
  font-size: 13px;
  float: left;
  margin-right: 10px;
}

.task-resources-accordion:after:hover {
  color: #fff;
}

.task-resources-accordion.active:after {
  content: "\2796";
  color: #fff;
}

.task-resources-accordion-panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: 0.4s ease;
  opacity: 0;
  margin-bottom: 10px;
  border: 1px solid #eaeaea;
}

.task-resources-accordion-panel.show {
  opacity: 1;
  max-height: 1000px;
}

.task-resources-accordion-content {
  padding: 15px;
}


问:
How do you register onMouseMove event on a canvas ctx in React?
I just finished a course on React and am porting a previous vanilla JS project to React as a learning exercise.

In my previous code (which works properly) I have a stack of 2 HTML canvases with an image loaded into the bottom ctx and a white rectangle loaded into the top ctx. I then use the JS 'mousemove' event listener to erase the white rectangle on top to reveal the image below.

I think I am very close to the solution in my React code. (If you follow the link you'll just see a white page - that's the white rectangle on top of the image. I've verified that the image is indeed under there.)

I've loaded the bottom image and the top rectangle within useEffect() so that React doesn't get any undefined canvas ctx's when the component first renders. However, I'm having difficulty connecting my eraser functionality in the 'eraseImageHandler'. Any ideas what I may be doing wrong? Thanks.

答:
On the initial render it doesn't know how big the image is so it can't calculate the canvas sizes correctly. If the image had an intrinsic size as below then it would be able to calculate it.</p>
```<code>    <Fragment>
      <div className={classes.stack}>
        <canvas ref={bottomCanvasRef} />
        <canvas ref={topCanvasRef} onMouseMove={eraseImageHandler} />
      </div>
      <img
        ref={imageRef}
        hidden
        width={300}
        height={300}
        src="https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg"
        alt="Flower"
      />
    </Fragment>
</code>```

Body:
On the initial render it doesn't know how big the image is so it can't calculate the canvas sizes correctly. If the image had an intrinsic size as below then it would be able to calculate it.

    <Fragment>
      <div className={classes.stack}>
        <canvas ref={bottomCanvasRef} />
        <canvas ref={topCanvasRef} onMouseMove={eraseImageHandler} />
      </div>
      <img
        ref={imageRef}
        hidden
        width={300}
        height={300}
        src="https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg"
        alt="Flower"
      />
    </Fragment>


问:
Etherscan api on ropsten for balance checking does not work
I have a problem with the etherscan api on  ropsten testnetwork, the output of the code is: expecting value line 1 column 1 (char 0)

the code:

```<code>import requests, json

ADD = "0xfbb61B8b98a59FbC4bD79C23212AddbEFaEB289f"
KEY = "HERE THE API KEY"

REQ = requests.get(f"https://api-ropsten.etherscan.io/api?module=account&action=balance&address={str(ADD)}&tag=latest&apikey={str(KEY)}")

CONTENT = json.loads(REQ.content)
BALANCE = int(CONTENT['result'])

print(BALANCE)
</code>```

When I try to do a request it gives back <Response [403]>

答:
Some websites don't allow Python scripts to access their website. You can get around this by adding a user agent in you request.

the code would look something like this:

```<code>import requests, json

ADD = "0xfbb61B8b98a59FbC4bD79C23212AddbEFaEB289f"
KEY = "HERE THE API KEY"
LINK = f"https://api-ropsten.etherscan.io/api?module=account&action=balance&address={str(ADD)}&tag=latest&apikey={str(KEY)}"
headers = {"HERE YOUR USER-AGENT"}

REQ = requests.get(LINK, headers = headers)

CONTENT = json.loads(REQ.content)
BALANCE = int(CONTENT['result'])

print(BALANCE)
</code>```

To find your user agent simply type in google: my user agent

Body:
I have a problem with the etherscan api on  ropsten testnetwork, the output of the code is: expecting value line 1 column 1 (char 0)

the code:

import requests, json

ADD = "0xfbb61B8b98a59FbC4bD79C23212AddbEFaEB289f"
KEY = "HERE THE API KEY"

REQ = requests.get(f"https://api-ropsten.etherscan.io/api?module=account&action=balance&address={str(ADD)}&tag=latest&apikey={str(KEY)}")

CONTENT = json.loads(REQ.content)
BALANCE = int(CONTENT['result'])

print(BALANCE)

When I try to do a request it gives back <Response [403]>

Body:
Some websites don't allow Python scripts to access their website. You can get around this by adding a user agent in you request.

the code would look something like this:

import requests, json

ADD = "0xfbb61B8b98a59FbC4bD79C23212AddbEFaEB289f"
KEY = "HERE THE API KEY"
LINK = f"https://api-ropsten.etherscan.io/api?module=account&action=balance&address={str(ADD)}&tag=latest&apikey={str(KEY)}"
headers = {"HERE YOUR USER-AGENT"}

REQ = requests.get(LINK, headers = headers)

CONTENT = json.loads(REQ.content)
BALANCE = int(CONTENT['result'])

print(BALANCE)

To find your user agent simply type in google: my user agent


问:
Does Go have a format specifier for io.Readers?
What I want is something like this:

r := strings.NewReader("fee fi fo fum")
fmt.Printf("%r\n", r)
```

where the %r would be a format specifier that reads from an io.Reader. I didn't see anything like that in the fmt documentation https://pkg.go.dev/fmt, but it's possible I missed it.

答:
An io.Reader may be a stream which never ends, as such a fmt.Printf rendering may never complete.

If you know there will be a discrete payload and it's not excessively large, you can load the contents to memory:

```<code>r := strings.NewReader("fee fi fo fum")
b, _ := io.ReadAll(r)
fmt.Printf("%q\n", b)
</code>```

https://go.dev/play/p/DZybA_f6Ole

This will however move the reader current position to the end, so if you need to "replay" the reader in future calls, you need to use another io.Reader (e.g. bytes.Buffer) to hold the original content:

```<code>r := strings.NewReader("fee fi fo fum")

if debug {
    var b bytes.Buffer
    _, err = io.Copy(&b, r) // handle err

    log.Printf("io.Reader content: %q\n", b.String())

    r = &b // replay
}

// r io.Reader content and position preserved
</code>```

https://go.dev/play/p/JRS34uX1R1G

Body:
What I want is something like this:

r := strings.NewReader("fee fi fo fum")
fmt.Printf("%r\n", r)

where the %r would be a format specifier that reads from an io.Reader. I didn't see anything like that in the fmt documentation https://pkg.go.dev/fmt, but it's possible I missed it.

Body:
An io.Reader may be a stream which never ends, as such a fmt.Printf rendering may never complete.

If you know there will be a discrete payload and it's not excessively large, you can load the contents to memory:

r := strings.NewReader("fee fi fo fum")
b, _ := io.ReadAll(r)
fmt.Printf("%q\n", b)

https://go.dev/play/p/DZybA_f6Ole

This will however move the reader current position to the end, so if you need to "replay" the reader in future calls, you need to use another io.Reader (e.g. bytes.Buffer) to hold the original content:

r := strings.NewReader("fee fi fo fum")

if debug {
    var b bytes.Buffer
    _, err = io.Copy(&b, r) // handle err

    log.Printf("io.Reader content: %q\n", b.String())

    r = &b // replay
}

// r io.Reader content and position preserved

https://go.dev/play/p/JRS34uX1R1G


问:
optinal function in interface gives Cannot invoke an object which is possibly 'undefined' when inside a condition
I cannot removed an error even when I wrap it in a condition :

I have this in my interface :

and then in my code I do this :

I also have a condition to make sure this.customType exist

and that red line says :
Cannot invoke an object which is possibly 'undefined'.

How is this possible if I make sure it exist in a if right before?

I've made a typescript code here, apparently it's because I'm using a variable. anyway around this?
https://www.typescriptlang.org/play?ts=3.9.7#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgYQFcBnGCAW3wiXQQHNi4BvAKDjgG0BrYATwC44pKMjoBdQa3bsAbpgA2CACaZUAfgAU6eZjqDMSXgEpBAIwgR5wAwG42cAL52HLFtmqk42EmUrVaDIJEpBRUNPSMALzMLBwA5KYGBsBxEjHScHKKKqgaxEbpGXBQwDCEUEhCdhkOADRsLi5uHvDeIeQAKrxgwPgAFhbEwJXRCUlIKa4sCOhwGm2+YQHE8YlIyakAdFnKqsAFUtILof4Rq+MpYtsKu7lx8pZxRs5T0+jzPhRdPf2Dw3AAMgBXk+fnCDAO9hmc2OYOWHFh316AwgQyQVx2OX2hQysKWZ0R3WRf3R12yew090ez3sjSAA

答:
In your condition, try writing it as:

if (customConfigs?.[this.customType]?.validate) {
```

I'd suspect the error is on the possibility of either customConfigs or customConfigs[this.customType] of being undefined

EDIT

Thanks for the playground, that highlights where the issue stands; Forget the above and simply have it as customConfigs[this.customType].validate?()

The question mark before the validate function, allow you to invoke the function only if the object beforehand exists

Body:
In your condition, try writing it as:

if (customConfigs?.[this.customType]?.validate) {

I'd suspect the error is on the possibility of either customConfigs or customConfigs[this.customType] of being undefined

EDIT

Thanks for the playground, that highlights where the issue stands; Forget the above and simply have it as customConfigs[this.customType].validate?()

The question mark before the validate function, allow you to invoke the function only if the object beforehand exists


问:
WKExtension scheduleBackgroundRefreshWithPreferredDate requires WKExtensionDelegate to implement handleBackgroundTasks instead of handle
I'm implementing a background app refresh for a watch app. To initiate the background refresh, I call the function below during my model initiation when ContentView is loaded:

WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: preferredDate, userInfo: nil)
```
<p>Then I have my <code>ExtensionDelegate</code>:</p>
<pre class="lang-swift prettyprint-override"><code>class ExtensionDelegate: NSObject, WKExtensionDelegate {
    var backgroundURLTask: WKURLSessionRefreshBackgroundTask?

    func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
        for task in backgroundTasks {
            switch task {

            case let bgTask as WKApplicationRefreshBackgroundTask:
                ExtensionDelegate.scheduleNextAppBackgroundRefresh()
                let session = backgroundSession()
                // running a download task with the session

                bgTask.setTaskCompletedWithSnapshot(false)

            case let bgTask as WKURLSessionRefreshBackgroundTask:
                _ = backgroundSession()
                backgroundURLTask = bgTask

            case let bgTask as WKSnapshotRefreshBackgroundTask:
                bgTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.now.nextHourDate, userInfo: nil)

            default:
                task.setTaskCompletedWithSnapshot(false)
            }
        }
    }
</code>```

However, the app crashes with:

WatchKit Extension[53878:533420] [bg_app_refresh] -[WKExtension scheduleBackgroundRefreshWithPreferredDate:userInfo:scheduledCompletion:]:196: This call requires that your WKExtensionDelegate <SwiftUI.ExtensionDelegate: 0x6000039e5340> implement handleBackgroundTasks

So, it requires to implement handleBackgroundTasks. As I understand, handleBackgroundTasks was renamed to handle. Because Xcode 13.2.1 complains if I implement handleBackgroundTasks and doesn't compile:

handleBackgroundTasks' has been renamed to 'handle(_:)'

What's the problem with?

答:
It appeared that I needed to provide the delegate for SwiftUI explicitly:

@main
struct MyApp: App {
    @WKExtensionDelegateAdaptor(ExtensionDelegate.self) var delegate

    var body: some Scene {
        WindowGroup {
            NavigationView {
                ContentView()
            }
        }
    }
}
```

I was thinking that just writing a class ExtensionDelegate and specifying it in the extension's Info.plist would work. It wouldn't.

Body:
I'm implementing a background app refresh for a watch app. To initiate the background refresh, I call the function below during my model initiation when ContentView is loaded:

WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: preferredDate, userInfo: nil)

Then I have my ExtensionDelegate:

class ExtensionDelegate: NSObject, WKExtensionDelegate {
    var backgroundURLTask: WKURLSessionRefreshBackgroundTask?

    func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
        for task in backgroundTasks {
            switch task {

            case let bgTask as WKApplicationRefreshBackgroundTask:
                ExtensionDelegate.scheduleNextAppBackgroundRefresh()
                let session = backgroundSession()
                // running a download task with the session

                bgTask.setTaskCompletedWithSnapshot(false)

            case let bgTask as WKURLSessionRefreshBackgroundTask:
                _ = backgroundSession()
                backgroundURLTask = bgTask

            case let bgTask as WKSnapshotRefreshBackgroundTask:
                bgTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.now.nextHourDate, userInfo: nil)

            default:
                task.setTaskCompletedWithSnapshot(false)
            }
        }
    }

However, the app crashes with:

WatchKit Extension[53878:533420] [bg_app_refresh] -[WKExtension scheduleBackgroundRefreshWithPreferredDate:userInfo:scheduledCompletion:]:196: This call requires that your WKExtensionDelegate <SwiftUI.ExtensionDelegate: 0x6000039e5340> implement handleBackgroundTasks

So, it requires to implement handleBackgroundTasks. As I understand, handleBackgroundTasks was renamed to handle. Because Xcode 13.2.1 complains if I implement handleBackgroundTasks and doesn't compile:

handleBackgroundTasks' has been renamed to 'handle(_:)'

What's the problem with?

Body:
It appeared that I needed to provide the delegate for SwiftUI explicitly:

@main
struct MyApp: App {
    @WKExtensionDelegateAdaptor(ExtensionDelegate.self) var delegate

    var body: some Scene {
        WindowGroup {
            NavigationView {
                ContentView()
            }
        }
    }
}

I was thinking that just writing a class ExtensionDelegate and specifying it in the extension's Info.plist would work. It wouldn't.


问:
'ModuleNotFoundError: No module named 'keras.engine.base_layer_v1'' when running PyInstaller .exe file
I am trying to create an executable version of python script that predicts images using .h5 file. The file runs completely fine when on its own in the virtual environment. But when I run the exe after completing the hidden imports following this and data addition in .spec file, when I run the exe it gives the following error:

```<code>Traceback (most recent call last):
File "onefile.py", line 11, in <module>
  model = load_model('complex_model.h5')
File "keras\saving\save.py", line 201, in load_model
File "keras\saving\hdf5_format.py", line 180, in load_model_from_hdf5
File "keras\saving\model_config.py", line 59, in model_from_config
File "keras\layers\serialization.py", line 159, in deserialize
File "keras\utils\generic_utils.py", line 668, in deserialize_keras_object
File "keras\engine\sequential.py", line 490, in from_config
File "keras\engine\training.py", line 195, in __new__
File "keras\utils\version_utils.py", line 61, in __new__
File "keras\utils\generic_utils.py", line 1181, in __getattr__
File "keras\utils\generic_utils.py", line 1172, in _load
File "importlib\__init__.py", line 127, in import_module
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'keras.engine.base_layer_v1'
</code>```

I added import keras.engine in the following this post. The python file on it's own still runs well.
However, there are no issues during the creation of .exe file with pyinstaller onefile.spec command:

```<code>90 INFO: PyInstaller: 4.4
90 INFO: Python: 3.8.5 (conda)
90 INFO: Platform: Windows-10-10.0.19041-SP0
90 INFO: UPX is not available.
90 INFO: Extending PYTHONPATH with paths
['path',
'path']
100 INFO: checking Analysis
360 INFO: checking PYZ
490 INFO: checking PKG
490 INFO: Bootloader path\lib\site-packages\PyInstaller\bootloader\Windows-64bit\run.exe
490 INFO: checking EXE
500 INFO: checking COLLECT
WARNING: The output directory "path" and ALL ITS CONTENTS will be REMOVED! Continue? (y/N)y
On your own risk, you can use the option `--noconfirm` to get rid of this question.
2650 INFO: Removing dir C:\Users\ashah\models\Deeplens\Emotions\standalone\dist\onefile
3480 INFO: Building COLLECT COLLECT-00.toc
13630 INFO: Building COLLECT COLLECT-00.toc completed successfully.
</code>```

Here is a part of .spec that was changed:

```<code>from PyInstaller.utils.hooks import collect_submodules
hidden_imports = collect_submodules('h5py') + collect_submodules('tensorflow_core')
block_cipher = None
a = Analysis(['onefile.py'],
         pathex=['C:\\Users\\ashah\\models\\Deeplens\\Emotions\\executable'],
         binaries=[],
         datas=[('complex_model.h5','.')],
         hiddenimports=hidden_imports,
         hookspath=[],
         runtime_hooks=[],
         excludes=[],
         win_no_prefer_redirects=False,
         win_private_assemblies=False,
         cipher=block_cipher,
         noarchive=False)
</code>```

Running out of ideas on how to proceed and get the exe working. I can post the .py code if needed. Any help would be golden. Thanks.

答:
I had the same issue, but the error code was

```<code>ModuleNotFoundError: No module named 'tensorflow.python.keras.engine.base_layer_v1'
</code>```

Resolved it by adding hidden import, either in .spec file:

```<code>hiddenimports=['tensorflow.python.keras.engine.base_layer_v1'],
</code>```

or while compiling .exe :

```<code>--hidden-import=tensorflow.python.keras.engine.base_layer_v1
</code>```

Body:
I am trying to create an executable version of python script that predicts images using .h5 file. The file runs completely fine when on its own in the virtual environment. But when I run the exe after completing the hidden imports following this and data addition in .spec file, when I run the exe it gives the following error:

Traceback (most recent call last):
File "onefile.py", line 11, in <module>
  model = load_model('complex_model.h5')
File "keras\saving\save.py", line 201, in load_model
File "keras\saving\hdf5_format.py", line 180, in load_model_from_hdf5
File "keras\saving\model_config.py", line 59, in model_from_config
File "keras\layers\serialization.py", line 159, in deserialize
File "keras\utils\generic_utils.py", line 668, in deserialize_keras_object
File "keras\engine\sequential.py", line 490, in from_config
File "keras\engine\training.py", line 195, in __new__
File "keras\utils\version_utils.py", line 61, in __new__
File "keras\utils\generic_utils.py", line 1181, in __getattr__
File "keras\utils\generic_utils.py", line 1172, in _load
File "importlib\__init__.py", line 127, in import_module
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'keras.engine.base_layer_v1'

I added import keras.engine in the following this post. The python file on it's own still runs well.
However, there are no issues during the creation of .exe file with pyinstaller onefile.spec command:

90 INFO: PyInstaller: 4.4
90 INFO: Python: 3.8.5 (conda)
90 INFO: Platform: Windows-10-10.0.19041-SP0
90 INFO: UPX is not available.
90 INFO: Extending PYTHONPATH with paths
['path',
'path']
100 INFO: checking Analysis
360 INFO: checking PYZ
490 INFO: checking PKG
490 INFO: Bootloader path\lib\site-packages\PyInstaller\bootloader\Windows-64bit\run.exe
490 INFO: checking EXE
500 INFO: checking COLLECT
WARNING: The output directory "path" and ALL ITS CONTENTS will be REMOVED! Continue? (y/N)y
On your own risk, you can use the option `--noconfirm` to get rid of this question.
2650 INFO: Removing dir C:\Users\ashah\models\Deeplens\Emotions\standalone\dist\onefile
3480 INFO: Building COLLECT COLLECT-00.toc
13630 INFO: Building COLLECT COLLECT-00.toc completed successfully.

Here is a part of .spec that was changed:

from PyInstaller.utils.hooks import collect_submodules
hidden_imports = collect_submodules('h5py') + collect_submodules('tensorflow_core')
block_cipher = None
a = Analysis(['onefile.py'],
         pathex=['C:\\Users\\ashah\\models\\Deeplens\\Emotions\\executable'],
         binaries=[],
         datas=[('complex_model.h5','.')],
         hiddenimports=hidden_imports,
         hookspath=[],
         runtime_hooks=[],
         excludes=[],
         win_no_prefer_redirects=False,
         win_private_assemblies=False,
         cipher=block_cipher,
         noarchive=False)

Running out of ideas on how to proceed and get the exe working. I can post the .py code if needed. Any help would be golden. Thanks.

Body:
I had the same issue, but the error code was

ModuleNotFoundError: No module named 'tensorflow.python.keras.engine.base_layer_v1'

Resolved it by adding hidden import, either in .spec file:

hiddenimports=['tensorflow.python.keras.engine.base_layer_v1'],

or while compiling .exe :

--hidden-import=tensorflow.python.keras.engine.base_layer_v1


问:
Check if paragraph has value with jQuery
I want to check in the checkbox only those that have no value in the paragraph. I don't know where I made a mistake in the code, but when I click the button (Value > 0), it marks all the checkboxes. Where is the mistake?

$("input[id*='btnValue']").click(function() {
  var checked = !$(this).data('checked');
  if ($("p[id*='pCompanyValue']").val() == "") {
    $("input[id*='chkCustomer']").prop('checked', checked);
    $(this).data('checked', checked);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="modal-content" style="background-color:#f2f2f2;">
  <div class="modal-header">
    <h4 class="modal-title">Select customers:</h4>
    <table class="DataTable" border="0" cellpadding="2" cellspacing="0" width="100%">
      <tbody>
        <tr>
          <td class="CellNameButton"><input id="ctl06_repCustomers_ctl00_chkAllCustomers" type="checkbox" name="ctl06$repCustomers$ctl00$chkAllCustomers" onclick="javascript:setTimeout('__doPostBack(\'ctl06$repCustomers$ctl00$chkAllCustomers\',\'\')', 0)"></td>
          <td class="CellNameButton"><span id="ctl06_repCustomers_ctl00_Label7" class="CasualBold">Company name</span></td>
          <td class="CellNameButton"><span id="ctl06_repCustomers_ctl00_Label1" class="CasualBold">Value</span></td>
        </tr>
        <tr>
          <td>
            <input id="ctl06_repCustomers_ctl01_chkCustomer" type="checkbox" name="ctl06$repCustomers$ctl01$chkCustomer" onclick="javascript:setTimeout('__doPostBack(\'ctl06$repCustomers$ctl01$chkCustomer\',\'\')', 0)">
          </td>
          <td id="ctl06_repCustomers_ctl01_trCompanyName" class="CellValue" valign="center">
            <p id="ctl06_repCustomers_ctl01_pCompanyName" class="casual">random</p>
          </td>
          <td id="ctl06_repCustomers_ctl01_trCompanyValue" class="CellValue">
            <p id="ctl06_repCustomers_ctl01_pCompanyValue" class="casualRight">
              48.438,00</p>
          </td>

        </tr>

        <tr>
          <td>
            <input id="ctl06_repCustomers_ctl02_chkCustomer" type="checkbox" name="ctl06$repCustomers$ctl02$chkCustomer" onclick="javascript:setTimeout('__doPostBack(\'ctl06$repCustomers$ctl02$chkCustomer\',\'\')', 0)">

          </td>
          <td id="ctl06_repCustomers_ctl02_trCompanyName" class="CellValue" valign="center">
            <p id="ctl06_repCustomers_ctl02_pCompanyName" class="casual">random2</p>
          </td>

          <td id="ctl06_repCustomers_ctl02_trCompanyValue" class="CellValue">
            <p id="ctl06_repCustomers_ctl02_pCompanyValue" class="casualRight">
              0,00</p>
          </td>

        </tr>

        <tr>
          <td>
            <input id="ctl06_repCustomers_ctl03_chkCustomer" type="checkbox" name="ctl06$repCustomers$ctl03$chkCustomer" onclick="javascript:setTimeout('__doPostBack(\'ctl06$repCustomers$ctl03$chkCustomer\',\'\')', 0)">

          </td>
          <td id="ctl06_repCustomers_ctl03_trCompanyName" class="CellValue" valign="center" style="background-color:#fff0e0;">
            <p id="ctl06_repCustomers_ctl03_pCompanyName" class="casual">Random3</p>
          </td>
          <td id="ctl06_repCustomers_ctl03_trCompanyValue" class="CellValue" style="background-color:#fff0e0;">
            <p id="ctl06_repCustomers_ctl03_pCompanyValue" class="casualRight">
            </p>
          </td>
        </tr>
      </tbody>
    </table>

  </div>
  <div class="modal-footer">
    <table class="modal-body">
      <tbody>
        <tr>
          <td class="CellNameButton">
            <input type="submit" name="ctl06$btnValue" value="Value > 0" id="ctl06_btnValue">
          </td>

        </tr>
      </tbody>
    </table>
    <input type="submit" name="ctl06$btnConfirmCustomers" value="OK" id="ctl06_btnConfirmCustomers" class="CasualForm" check="true">
  </div>
</div></code>```

Unnecessary: This code is done in asp.net that's why it's generated like this with stupid id names.

答:
Here is how you can make checked only those check-boxes which do not have a value.

$("input[id*='btnValue']").click(function() {
  $("p[id*='pCompanyValue']").each(function () {
    var checkId = $(this).attr("id").replace("pCompanyValue", "chkCustomer");
    if ($(this).text().trim().length > 0) {
      $("#"+checkId).attr("checked", true);
    }
  });
});
```

Body:
I want to check in the checkbox only those that have no value in the paragraph. I don't know where I made a mistake in the code, but when I click the button (Value > 0), it marks all the checkboxes. Where is the mistake?

$("input[id*='btnValue']").click(function() {
  var checked = !$(this).data('checked');
  if ($("p[id*='pCompanyValue']").val() == "") {
    $("input[id*='chkCustomer']").prop('checked', checked);
    $(this).data('checked', checked);
  }
});

Select customers:

          <input id="ctl06_repCustomers_ctl00_chkAllCustomers" type="checkbox" name="ctl06$repCustomers$ctl00$chkAllCustomers" onclick="javascript:setTimeout('__doPostBack(\'ctl06$repCustomers$ctl00$chkAllCustomers\',\'\')', 0)">
          Company name
          Value

            <input id="ctl06_repCustomers_ctl01_chkCustomer" type="checkbox" name="ctl06$repCustomers$ctl01$chkCustomer" onclick="javascript:setTimeout('__doPostBack(\'ctl06$repCustomers$ctl01$chkCustomer\',\'\')', 0)">

random

              48.438,00

            <input id="ctl06_repCustomers_ctl02_chkCustomer" type="checkbox" name="ctl06$repCustomers$ctl02$chkCustomer" onclick="javascript:setTimeout('__doPostBack(\'ctl06$repCustomers$ctl02$chkCustomer\',\'\')', 0)">

random2

              0,00

            <input id="ctl06_repCustomers_ctl03_chkCustomer" type="checkbox" name="ctl06$repCustomers$ctl03$chkCustomer" onclick="javascript:setTimeout('__doPostBack(\'ctl06$repCustomers$ctl03$chkCustomer\',\'\')', 0)">

Random3

            <input type="submit" name="ctl06$btnValue" value="Value > 0" id="ctl06_btnValue">

    <input type="submit" name="ctl06$btnConfirmCustomers" value="OK" id="ctl06_btnConfirmCustomers" class="CasualForm" check="true">

Unnecessary: This code is done in asp.net that's why it's generated like this with stupid id names.


问:
how to change ipmi user with one command
i want to change existing user password. i ran this command
ipmitool -I lanplus -H 192.168.1.1 -U USER -P 'PASSWORD' user set password 10 "&UJM2wsx"

i got an error
IPMI command failed: Request data field length limit exceeded
Set User Password command failed (user 10)

when i ran same command without password at the end i was prompted to insert password twice and it worked.
is there a way to echo password twice to ipmitool user set password command?

p.s i tried to delete the user and re create it but there is not delete option from cli only from web gui

答:
This below is incomplete:

"The way to fix this is actually quite simple. Since some time, Supermicro actually does not allow certain passwords for BMC users unless they have the following requirements: use lowercase, capital, numbers and special characters."

How to put your own (and maybe insecure) password:

You need to login in the ipmi webpage with the current password.

Go to 'Configuration>Users>'

Click on the 'here' link:

"For more advanced user settings, please click. here"

Then lower the password security requirements.

That's all.


问:
Custom npm script in ecosystem.config.js
To start a custom npm script start with pm2 as a one-time process, I'd run pm2 start npm -- start, and to move this into the ecosystem.config.js file, my app would be configured as

```<code>...
script: 'npm',
args: 'start',
...
</code>```

But things fall apart when instead of start, I need to run the dev script, like you would in npm run dev. I've tried

```<code>...
script: 'npm run dev',
...
</code>```
```<code>...
script: 'npm',
args: 'run dev',
...
</code>```

and

```<code>...
script: 'npm',
args: 'dev',
...
</code>```

with no luck so far. Could I be missing something, or is there an entirely different approach?

答:
I'm using reactJs + nextJs and I'm also facing the same issue with ecosystem.config.js configuration in PM2, but you can use the following command it's working for me.

```<code>pm2 start "npm run dev" --name YOUR_APP_NAME
</code>```

Body:
To start a custom npm script start with pm2 as a one-time process, I'd run pm2 start npm -- start, and to move this into the ecosystem.config.js file, my app would be configured as

...
script: 'npm',
args: 'start',
...

But things fall apart when instead of start, I need to run the dev script, like you would in npm run dev. I've tried

...
script: 'npm run dev',
...

...
script: 'npm',
args: 'run dev',
...

and

...
script: 'npm',
args: 'dev',
...

with no luck so far. Could I be missing something, or is there an entirely different approach?

Body:
I'm using reactJs + nextJs and I'm also facing the same issue with ecosystem.config.js configuration in PM2, but you can use the following command it's working for me.

pm2 start "npm run dev" --name YOUR_APP_NAME


问:
Membership Provider - only connect to default provider?
In my web config I have 2 membership providers defined, one for sql, one for active directory.  My thought process was that on a release build, I set AD as the default, but while debugging I use sql.  This is because my dev computer does not have access to the domain to authenticate users.

It seems to me however that my web site tries to connect to both sources instead of just the default provider.  So while I have an active directory provider defined, I cannot do development because it fails to connect, even though sql is defined as default.

Is there a way to only connect to the default provider?

My currently broken web config is like so:

```<code><membership defaultProvider="AspNetSqlMembershipProvider">
  <providers>
    <clear/>
    <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="SqlServer" />
    <add name="ActiveDirectoryMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ActiveDirectoryServer" attributeMapUsername="sAMAccountName"/>

  </providers>
</membership>
</code>```

答:
In your web.release.config file, you can just swap out the whole membership section with the AD information and in the web.config you can leave it as it or only have the SQL provider.

For the web.release.config:

```<code><system.web>
  <membership defaultProvider="ActiveDirectoryMembershipProvider" xdt:Transform="Replace">
    <providers>
      <clear/>
      <add name="ActiveDirectoryMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ActiveDirectoryServer" attributeMapUsername="sAMAccountName"/>
    </providers>
  </membership>
</system.web>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my web config I have 2 membership providers defined, one for sql, one for active directory.  My thought process was that on a release build, I set AD as the default, but while debugging I use sql.  This is because my dev computer does not have access to the domain to authenticate users.

It seems to me however that my web site tries to connect to both sources instead of just the default provider.  So while I have an active directory provider defined, I cannot do development because it fails to connect, even though sql is defined as default.

Is there a way to only connect to the default provider?

My currently broken web config is like so:

<membership defaultProvider="AspNetSqlMembershipProvider">
  <providers>
    <clear/>
    <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="SqlServer" />
    <add name="ActiveDirectoryMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ActiveDirectoryServer" attributeMapUsername="sAMAccountName"/>

  </providers>
</membership>

Body:
In your web.release.config file, you can just swap out the whole membership section with the AD information and in the web.config you can leave it as it or only have the SQL provider.

For the web.release.config:

<system.web>
  <membership defaultProvider="ActiveDirectoryMembershipProvider" xdt:Transform="Replace">
    <providers>
      <clear/>
      <add name="ActiveDirectoryMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ActiveDirectoryServer" attributeMapUsername="sAMAccountName"/>
    </providers>
  </membership>
</system.web>


问:
Unexpected result when using list.append(). What am I doing wrong?
I can't understand the following two examples of behaviour of list.append() in Python:

```<code>list_1 = ['A', 'B']
list_2 = ['C', 'D']

copy_l1 = list_1
copy_l1.append(list_2)
</code>```

Example

```<code>print(copy_l1)
</code>```

result: ['A', 'B', ['C', 'D']]

expected: ['A', 'B', 'C', 'D'].

I kind of understand this, but how to get the expected result?

Example

```<code>print(list_1)
</code>```

result: ['A', 'B', ['C', 'D']]

expected: ['A', 'B'].

This is the most puzzling for me. Why does copy_l1.append(list_2) also affect list_1? Due to my backgound in C, this looks to me like I'm working on pointers, but I gather that should not be the case. What means?

答:
You use wrong ways of concatenating and coping lists.

To concatenate lists you can:

```<code>copy_l1.extend(list_2)
copy_l1 += list_2
</code>```

To copy list you can:

```<code>copy_l1 = list_1.copy()
copy_l1 = list_1[:]
copy_l1 = list(list_1)
</code>```

Body:
I can't understand the following two examples of behaviour of list.append() in Python:

list_1 = ['A', 'B']
list_2 = ['C', 'D']

copy_l1 = list_1
copy_l1.append(list_2)

Example

print(copy_l1)

result: ['A', 'B', ['C', 'D']]

expected: ['A', 'B', 'C', 'D'].

I kind of understand this, but how to get the expected result?

Example

print(list_1)

result: ['A', 'B', ['C', 'D']]

expected: ['A', 'B'].

This is the most puzzling for me. Why does copy_l1.append(list_2) also affect list_1? Due to my backgound in C, this looks to me like I'm working on pointers, but I gather that should not be the case. What means?

Body:
You use wrong ways of concatenating and coping lists.

To concatenate lists you can:

copy_l1.extend(list_2)
copy_l1 += list_2

To copy list you can:

copy_l1 = list_1.copy()
copy_l1 = list_1[:]
copy_l1 = list(list_1)


问:
What is a fast async text writer that can be used to log a line of text to a csv file?
I am trying to find a text writer that will not block it's calling thread. It will be called over 400k times a day and will be used for logging lines of text to a csv file. Here is what I have come up with so far:</p>
```<code>public void callWriter()
        {

            textwriter.WriteToFileAsync(LINE_OF_DATA);

            //continue with rest of my program while file gets written to
        }

public async void WriteToFileAsync(string data)
        {
            using (StreamWriter streamWriter =
                new StreamWriter
                (
                    _path,
                    APPEND_FILE,
                    System.Text.Encoding.UTF8,
                    BUFFER_SIZE_IN_BYTES
                ))
            {
                await streamWriter.WriteLineAsync(data);
            }
        }
</code>```

答:
Based on clarifying your need is for logging in the comments, I would suggest using NLog.

Here's a SO post on configuring NLog, for which the question is important, since any buffer for logging is (as others have stated) a queue, which needs to be sized accordingly, otherwise it 'overflows' and messages can be lost.

It is better not to rely on rolling your own solution here. Projects that have been through several public iterations of bug-fixes and dealing with all sorts of scenarios will be more robust and be better performing.

How to configure NLog programmatically for Async target?

You can find performance comparisons of NLog to other .NET logging frameworks/libraries and see that NLog is fastest.

Body:
I am trying to find a text writer that will not block it's calling thread. It will be called over 400k times a day and will be used for logging lines of text to a csv file. Here is what I have come up with so far:

public void callWriter()
        {

            textwriter.WriteToFileAsync(LINE_OF_DATA);

            //continue with rest of my program while file gets written to
        }

public async void WriteToFileAsync(string data)
        {
            using (StreamWriter streamWriter =
                new StreamWriter
                (
                    _path,
                    APPEND_FILE,
                    System.Text.Encoding.UTF8,
                    BUFFER_SIZE_IN_BYTES
                ))
            {
                await streamWriter.WriteLineAsync(data);
            }
        }


问:
.net desktop app installation
I am creating a  C# .Net 4.0 desktop application for a client.  When I sent him the .msi files it requires administration privileges when trying to install.  I realize the reason why is because I am installing the application into the "Program Files" directory.

Is there a way to install an application into an area on the users machine that doesn't require them to install as Administrator?

I'm using .Net 4.0

答:
If you add the manifest file and assign to application then you need to set the Execution level.

Following is the line where you can set the Execution level.

<requestedExecutionLevel  level="asInvoker" uiAccess="false" />

If you want your exe run always run as administator then you need to change the above statement as follow

<requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />

See the following link how to create manifest file.

http://mahesg.wordpress.com/2007/07/30/adding-manifest-to-net-application/

Title: .net desktop app installation


问:
How to resolve "TypeError: mockedAxios.get.mockResolvedValue is not a function" error?
I am using Jest for my TypeScript project. I am trying to mock Axios but keep getting TypeError: mockedAxios.get.mockResolvedValue is not a function error. I have tried several ways as belows but not sure what am I doing wrong here.

I see some articles in this website about similar issue but when I try this on my side, I am unable to reslove it.

References:

Jest mocking: TypeError: axios.get.mockResolvedValue is not a function

Type of Axios mock using jest typescript

Code:

httpRequest.service.ts

```<code>import { injectable } from 'inversify';
import axios from 'axios';

@injectable()
export default class HttpService {
  /**
     * Generic function to make HTTP calls.
     * @template T
     * @param [options]
     * @returns request
     */
  public async request<T>(options: object = {}): Promise<T> {
    return axios.request(options)
      .then((response) => response.data)
      .catch((error) => {
        throw error;
      });
  }
}

</code>```

httpRequest.service.spec.ts

Option-1 = using AxiosResponse from axios

```<code>import 'reflect-metadata';
import HttpService from '../httpRequest.service';
import axios, { AxiosResponse } from 'axios';

describe('httpService', () => {
  let httpService: HttpService;
  let mockedAxios: any;

  beforeEach(() => {
    jest.resetModules();
    jest.resetAllMocks();
    jest.mock('axios');

    mockedAxios = axios as jest.Mocked<typeof axios>;

    httpService = new HttpService();
  });

  describe('request', () => {
    it('successfully returns response', async () => {

      const axiosResponse: AxiosResponse = {
        data: {
          userId: 1,
          id: 1,
          title: 'mock title',
          body: 'mock body',
        },
        status: 200,
        statusText: 'OK',
        config: {},
        headers: {},
      };

      //Mocking axios function rather than a method
      mockedAxios.get.mockResolvedValue(axiosResponse);

      //Act
      const result = await httpService.request();

      //Assert
      expect(result).toBe({
        userId: 1,
        id: 1,
        title: 'mock title',
        body: 'mock body',
      });

    });

  });
});
</code>```

Option-2 = using mocked from ts-jest

```<code>import 'reflect-metadata';
import HttpService from '../httpRequest.service';
import axios, { AxiosResponse } from 'axios';
import { mocked } from 'ts-jest/dist/utils/testing';

describe('httpService', () => {
  let httpService: HttpService;

  beforeEach(() => {
    jest.resetModules();
    jest.resetAllMocks();
    jest.mock('axios');

    httpService = new HttpService();
  });

  describe('request', () => {
    it('successfully returns response', async () => {

      const axiosResponse: AxiosResponse = {
        data: {
          userId: 1,
          id: 1,
          title: 'mock title',
          body: 'mock body',
        },
        status: 200,
        statusText: 'OK',
        config: {},
        headers: {},
      };

      //Mocking axios function rather than a method
      mocked(axios).mockResolvedValue(axiosResponse);
      // mocked.get.mockResolvedValue(axiosResponse);

      //Act
      const result = await httpService.request();

      //Assert
      expect(result).toBe({
        userId: 1,
        id: 1,
        title: 'mock title',
        body: 'mock body',
      });

    });

  });
});
</code>```

Option-3 = using AxiosStatic from axios

```<code>import HttpService from '../httpRequest.service';
import axios, { AxiosStatic } from 'axios';

interface AxiosMock extends AxiosStatic {
  mockResolvedValue: any
  mockRejectedValue: any
}

describe('httpService', () => {
  let httpService: HttpService;
  let mockAxios: any;

  beforeEach(() => {
    jest.resetModules();
    jest.resetAllMocks();
    jest.mock('axios');

    mockAxios = axios as AxiosMock;
    httpService = new HttpService();
  });

  describe('request', () => {
    it('successfully returns response', async () => {

      const axiosResponse: AxiosResponse = {
        data: {
          userId: 1,
          id: 1,
          title: 'mock title',
          body: 'mock body',
        },
        status: 200,
        statusText: 'OK',
        config: {},
        headers: {},
      };

      //Mocking axios function rather than a method
      mockAxios.mockResolvedValue(axiosResponse);

      //Act
      const result = await httpService.request();

      //Assert
      expect(result).toBe({
        userId: 1,
        id: 1,
        title: 'mock title',
        body: 'mock body',
      });

    });

  });
});
</code>```

答:
I was able to resolve this by making 2 changes in my Option-1 solution:

Move jest.mock('axios'); after import statement. I am not sure why it is not working when I declare it inside beforeAll (looking into this).

Change mockedAxios.get.mockResolvedValue(axiosResponse); to mockedAxios.request.mockResolvedValue(axiosResponse);. This is a silly mistake where my function uses .request but I was mocking .get.

Here is full solution.

```<code>import 'reflect-metadata';
import HttpService from '../httpRequest.service';
import axios, { AxiosResponse } from 'axios';
jest.mock('axios');

describe('httpRequest', () => {
  let httpService: HttpService;
  let mockedAxios: any;

  beforeAll(() => {
    jest.resetModules();
    jest.resetAllMocks();

    mockedAxios = axios as jest.Mocked<typeof axios>;
    httpService = new HttpService();

  });

  describe('request', () => {
    it('successful', async () => {

      const mockAxiosData = {
        userId: 1,
        id: 1,
        title: '',
        body: '',
      };

      const axiosResponse: AxiosResponse = {
        data: mockAxiosData,
        status: 200,
        statusText: 'OK',
        config: {},
        headers: {},
      };

      mockedAxios.request.mockResolvedValue(axiosResponse);

      const request = await httpService.request();
      expect(request).toBe(mockAxiosData);

    });
  });

});
</code>```

Body:
I am using Jest for my TypeScript project. I am trying to mock Axios but keep getting TypeError: mockedAxios.get.mockResolvedValue is not a function error. I have tried several ways as belows but not sure what am I doing wrong here.

I see some articles in this website about similar issue but when I try this on my side, I am unable to reslove it.

References:

Jest mocking: TypeError: axios.get.mockResolvedValue is not a function

Type of Axios mock using jest typescript

Code:

httpRequest.service.ts

import { injectable } from 'inversify';
import axios from 'axios';

@injectable()
export default class HttpService {
  /**
     * Generic function to make HTTP calls.
     * @template T
     * @param [options]
     * @returns request
     */
  public async request<T>(options: object = {}): Promise<T> {
    return axios.request(options)
      .then((response) => response.data)
      .catch((error) => {
        throw error;
      });
  }
}

httpRequest.service.spec.ts

Option-1 = using AxiosResponse from axios

import 'reflect-metadata';
import HttpService from '../httpRequest.service';
import axios, { AxiosResponse } from 'axios';

describe('httpService', () => {
  let httpService: HttpService;
  let mockedAxios: any;

  beforeEach(() => {
    jest.resetModules();
    jest.resetAllMocks();
    jest.mock('axios');

    mockedAxios = axios as jest.Mocked<typeof axios>;

    httpService = new HttpService();
  });

  describe('request', () => {
    it('successfully returns response', async () => {

      const axiosResponse: AxiosResponse = {
        data: {
          userId: 1,
          id: 1,
          title: 'mock title',
          body: 'mock body',
        },
        status: 200,
        statusText: 'OK',
        config: {},
        headers: {},
      };

      //Mocking axios function rather than a method
      mockedAxios.get.mockResolvedValue(axiosResponse);

      //Act
      const result = await httpService.request();

      //Assert
      expect(result).toBe({
        userId: 1,
        id: 1,
        title: 'mock title',
        body: 'mock body',
      });

    });

  });
});

Option-2 = using mocked from ts-jest

import 'reflect-metadata';
import HttpService from '../httpRequest.service';
import axios, { AxiosResponse } from 'axios';
import { mocked } from 'ts-jest/dist/utils/testing';

describe('httpService', () => {
  let httpService: HttpService;

  beforeEach(() => {
    jest.resetModules();
    jest.resetAllMocks();
    jest.mock('axios');

    httpService = new HttpService();
  });

  describe('request', () => {
    it('successfully returns response', async () => {

      const axiosResponse: AxiosResponse = {
        data: {
          userId: 1,
          id: 1,
          title: 'mock title',
          body: 'mock body',
        },
        status: 200,
        statusText: 'OK',
        config: {},
        headers: {},
      };

      //Mocking axios function rather than a method
      mocked(axios).mockResolvedValue(axiosResponse);
      // mocked.get.mockResolvedValue(axiosResponse);

      //Act
      const result = await httpService.request();

      //Assert
      expect(result).toBe({
        userId: 1,
        id: 1,
        title: 'mock title',
        body: 'mock body',
      });

    });

  });
});

Option-3 = using AxiosStatic from axios

import HttpService from '../httpRequest.service';
import axios, { AxiosStatic } from 'axios';

interface AxiosMock extends AxiosStatic {
  mockResolvedValue: any
  mockRejectedValue: any
}

describe('httpService', () => {
  let httpService: HttpService;
  let mockAxios: any;

  beforeEach(() => {
    jest.resetModules();
    jest.resetAllMocks();
    jest.mock('axios');

    mockAxios = axios as AxiosMock;
    httpService = new HttpService();
  });

  describe('request', () => {
    it('successfully returns response', async () => {

      const axiosResponse: AxiosResponse = {
        data: {
          userId: 1,
          id: 1,
          title: 'mock title',
          body: 'mock body',
        },
        status: 200,
        statusText: 'OK',
        config: {},
        headers: {},
      };

      //Mocking axios function rather than a method
      mockAxios.mockResolvedValue(axiosResponse);

      //Act
      const result = await httpService.request();

      //Assert
      expect(result).toBe({
        userId: 1,
        id: 1,
        title: 'mock title',
        body: 'mock body',
      });

    });

  });
});

Body:
I was able to resolve this by making 2 changes in my Option-1 solution:

Move jest.mock('axios'); after import statement. I am not sure why it is not working when I declare it inside beforeAll (looking into this).

Change mockedAxios.get.mockResolvedValue(axiosResponse); to mockedAxios.request.mockResolvedValue(axiosResponse);. This is a silly mistake where my function uses .request but I was mocking .get.

Here is full solution.

import 'reflect-metadata';
import HttpService from '../httpRequest.service';
import axios, { AxiosResponse } from 'axios';
jest.mock('axios');

describe('httpRequest', () => {
  let httpService: HttpService;
  let mockedAxios: any;

  beforeAll(() => {
    jest.resetModules();
    jest.resetAllMocks();

    mockedAxios = axios as jest.Mocked<typeof axios>;
    httpService = new HttpService();

  });

  describe('request', () => {
    it('successful', async () => {

      const mockAxiosData = {
        userId: 1,
        id: 1,
        title: '',
        body: '',
      };

      const axiosResponse: AxiosResponse = {
        data: mockAxiosData,
        status: 200,
        statusText: 'OK',
        config: {},
        headers: {},
      };

      mockedAxios.request.mockResolvedValue(axiosResponse);

      const request = await httpService.request();
      expect(request).toBe(mockAxiosData);

    });
  });

});


问:
Multiple Section Hide & Show with HTML & CSS
I have html button that show/hide the inner sections (Not main section) of my page, I have main section inside main section I five inner sections the details of problem and goals are mentioned in detail with code in below.

1. Details about my goal

I want to achieve the hide/show event on the same (single button) without changing its label when user click the button all inner sections should be hidden on the page and again when the user click same button it should show all sections including the one have html button.

2. Expected and actual results

Expected results is same as my goal above and actual result in my code is not giving the idea to put the all 5 section to hide.

What I have tried so far

document.getElementById("Ayat-3").classList.add("hide-section");
document.getElementById("Ayat-4").classList.add("hide-section");
document.getElementById("Ayat-5").classList.add("hide-section");
document.getElementById("Ayat-6").classList.add("hide-section");
document.getElementById("Ayat-7").classList.add("hide-section");

function toggleHide() {
  var section = document.querySelectorAll('.hide-section');
  section.forEach(el => el.classList.toggle('d-none'));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#button {
  color: white;
  background-color: green;
  padding: 12px;
  font-size: 14px;
  width: 25px;
  height: 25px;
  border: 5px;
  border-color: blue;
  cursor: pointer;
  border-radius: 150px;
}

.button:hover,
.button:focus {
  background-color: white;
}

.d-none {
  .display: none;
}</code>```

<button onclick="toggleHide()">Hide/Show Sections</button>```

4. Errors that I am facing

In the above code there is error to hide all mentioned five sections and click on first time its hiding only three sections and same when click second time the different three sections being hidden, i want to hide all five and show up all on second click.

答:
To hide multiple elements with a single button click you can use the querySelectorAll in combination with the forEach command. Then you give all the elements you want to be effected by the script the same class:

function toggleHide() {
  var section = document.querySelectorAll('.hide-section');

  section.forEach(el => el.classList.toggle('d-none'));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.d-none {
  display: none;
}</code>```

Section will not hide

Section will hide

Section will hide

Section will hide

Section will hide

<button onclick="toggleHide()">Hide/Show Sections</button>```

Body:
I have html button that show/hide the inner sections (Not main section) of my page, I have main section inside main section I five inner sections the details of problem and goals are mentioned in detail with code in below.

1. Details about my goal

I want to achieve the hide/show event on the same (single button) without changing its label when user click the button all inner sections should be hidden on the page and again when the user click same button it should show all sections including the one have html button.

2. Expected and actual results

Expected results is same as my goal above and actual result in my code is not giving the idea to put the all 5 section to hide.

What I have tried so far

document.getElementById("Ayat-3").classList.add("hide-section");
document.getElementById("Ayat-4").classList.add("hide-section");
document.getElementById("Ayat-5").classList.add("hide-section");
document.getElementById("Ayat-6").classList.add("hide-section");
document.getElementById("Ayat-7").classList.add("hide-section");

function toggleHide() {
  var section = document.querySelectorAll('.hide-section');
  section.forEach(el => el.classList.toggle('d-none'));
}

#button {
  color: white;
  background-color: green;
  padding: 12px;
  font-size: 14px;
  width: 25px;
  height: 25px;
  border: 5px;
  border-color: blue;
  cursor: pointer;
  border-radius: 150px;
}

.button:hover,
.button:focus {
  background-color: white;
}

.d-none {
  .display: none;
}

<button onclick="toggleHide()">Hide/Show Sections</button>

4. Errors that I am facing

In the above code there is error to hide all mentioned five sections and click on first time its hiding only three sections and same when click second time the different three sections being hidden, i want to hide all five and show up all on second click.

Body:
To hide multiple elements with a single button click you can use the querySelectorAll in combination with the forEach command. Then you give all the elements you want to be effected by the script the same class:

function toggleHide() {
  var section = document.querySelectorAll('.hide-section');

  section.forEach(el => el.classList.toggle('d-none'));
}

.d-none {
  display: none;
}

<section>Section will not hide</section>
<section class="hide-section">Section will hide</section>
<section class="hide-section">Section will hide</section>
<section class="hide-section">Section will hide</section>
<section class="hide-section">Section will hide</section>
<button onclick="toggleHide()">Hide/Show Sections</button>


问:
Why My Deep Learning Model is not changing neither its loss nor its accuracy
I am trying to train a CNN model with 2030 preprocessed eye images. the shape of my input data is (2030, 200,200, 1). At first, the shape of the data was 1527. Then I used imblearn.over_sampling.RandomOverSampler to increase the dataset size. I constructed the model with Keras and here is the summary of my model:

```<code>model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same', activation='relu',
input_shape=(img_cols, img_rows, 1)))
model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (5, 5), padding='same', activation='relu'))
model.add(Conv2D(64, (5, 5), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(3,3)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))

optimizer = tf.keras.optimizers.SGD(learning_rate=0.000001)
model.compile(optimizer=optimizer,loss='binary_crossentropy',
metrics=[tf.keras.metrics.SpecificityAtSensitivity(0.5),
tf.keras.metrics.SensitivityAtSpecificity(0.5),'accuracy'])

# Augmentation

train_datagen = ImageDataGenerator(
    rescale=1./255,
    horizontal_flip=True,
    vertical_flip=True,
    width_shift_range=0.3,
    height_shift_range=0.5,
    rotation_range=10,
    zoom_range=0.2
    )

test_datagen = ImageDataGenerator(rescale=1./255)

train_data = train_datagen.flow(x_train, y_train)
test_data = test_datagen.flow(x_test, y_test)

reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss',
factor=0.9,
                          patience=2, min_lr=0.0000000000000000001)
history=model.fit(train_data, epochs=10, batch_size=32,
validation_data=test_data, callbacks=[reduce_lr])
</code>```

I trained the model with different parameters (with batch sizes 32, 64, 128, 256, 512, 1024, adding 128 and 256 neuron convolution layers, decreasing and increasing learning rate, using callbacks, varying the dense layer size with 32, 64, ..., 1024) but I always get the following learning process:

```<code>*Epoch 1/10
51/51 [==============================] - 14s 238ms/step - loss: 0.6962 - specificity_at_sensitivity_15: 0.4548 - sensitivity_at_specificity_15: 0.4777 - accuracy: 0.4969 - val_loss: 0.6957 - val_specificity_at_sensitivity_15: 0.4112 - val_sensitivity_at_specificity_15: 0.3636 - val_accuracy: 0.4852 - lr: 1.0000e-04
Epoch 2/10
51/51 [==============================] - 12s 226ms/step - loss: 0.6945 - specificity_at_sensitivity_15: 0.4829 - sensitivity_at_specificity_15: 0.4615 - accuracy: 0.5018 - val_loss: 0.6949 - val_specificity_at_sensitivity_15: 0.4467 - val_sensitivity_at_specificity_15: 0.3206 - val_accuracy: 0.4877 - lr: 1.0000e-04
Epoch 3/10
51/51 [==============================] - 12s 227ms/step - loss: 0.6955 - specificity_at_sensitivity_15: 0.4328 - sensitivity_at_specificity_15: 0.4082 - accuracy: 0.5043 - val_loss: 0.6945 - val_specificity_at_sensitivity_15: 0.5584 - val_sensitivity_at_specificity_15: 0.5167 - val_accuracy: 0.4852 - lr: 1.0000e-04
Epoch 4/10
51/51 [==============================] - 12s 226ms/step - loss: 0.6971 - specificity_at_sensitivity_15: 0.4034 - sensitivity_at_specificity_15: 0.4256 - accuracy: 0.5049 - val_loss: 0.6941 - val_specificity_at_sensitivity_15: 0.4010 - val_sensitivity_at_specificity_15: 0.3923 - val_accuracy: 0.4852 - lr: 1.0000e-04
Epoch 5/10
51/51 [==============================] - 12s 226ms/step - loss: 0.6954 - specificity_at_sensitivity_15: 0.4670 - sensitivity_at_specificity_15: 0.4640 - accuracy: 0.4969 - val_loss: 0.6938 - val_specificity_at_sensitivity_15: 0.5584 - val_sensitivity_at_specificity_15: 0.5407 - val_accuracy: 0.4729 - lr: 1.0000e-04
Epoch 6/10
51/51 [==============================] - 12s 227ms/step - loss: 0.6972 - specificity_at_sensitivity_15: 0.4352 - sensitivity_at_specificity_15: 0.3883 - accuracy: 0.4791 - val_loss: 0.6935 - val_specificity_at_sensitivity_15: 0.4772 - val_sensitivity_at_specificity_15: 0.3206 - val_accuracy: 0.4729 - lr: 1.0000e-04
Epoch 7/10
51/51 [==============================] - 12s 227ms/step - loss: 0.6943 - specificity_at_sensitivity_15: 0.4474 - sensitivity_at_specificity_15: 0.4814 - accuracy: 0.5031 - val_loss: 0.6933 - val_specificity_at_sensitivity_15: 0.3604 - val_sensitivity_at_specificity_15: 0.4880 - val_accuracy: 0.4729 - lr: 1.0000e-04
Epoch 8/10
51/51 [==============================] - 12s 225ms/step - loss: 0.6974 - specificity_at_sensitivity_15: 0.4609 - sensitivity_at_specificity_15: 0.4355 - accuracy: 0.4926 - val_loss: 0.6930 - val_specificity_at_sensitivity_15: 0.5279 - val_sensitivity_at_specificity_15: 0.5885 - val_accuracy: 0.4655 - lr: 1.0000e-04
Epoch 9/10
51/51 [==============================] - 12s 226ms/step - loss: 0.6945 - specificity_at_sensitivity_15: 0.4425 - sensitivity_at_specificity_15: 0.4777 - accuracy: 0.5031 - val_loss: 0.6929 - val_specificity_at_sensitivity_15: 0.4619 - val_sensitivity_at_specificity_15: 0.3876 - val_accuracy: 0.4655 - lr: 1.0000e-04
Epoch 10/10
51/51 [==============================] - 12s 226ms/step - loss: 0.6977 - specificity_at_sensitivity_15: 0.4389 - sensitivity_at_specificity_15: 0.4367 - accuracy: 0.4766 - val_loss: 0.6927 - val_specificity_at_sensitivity_15: 0.6091 - val_sensitivity_at_specificity_15: 0.5024 - val_accuracy: 0.4951 - lr: 1.0000e-04*
</code>```

And evaluation with test data generated from x_test data (2 percent of the 2030 images) resulted in:

```<code>13/13 [==============================] - 1s 69ms/step - loss: 0.6927 - specificity_at_sensitivity_15: 0.6091 - sensitivity_at_specificity_15: 0.5024 - accuracy: 0.4951
Accuracy score is : 0.4950738847255707
</code>```

How can I improve my accuracy score? I tried every possible way, but the maximum I could increase was 53%. Similar codes I saw on the internet reached 76%. It is a medical imaging project, I believe it is better to obtain better accuracy.

答:
If you could try with changing optimizer from SGD to Adam, you will get better accuracy along with doing some other changes like adding more convolution layers, increasing learning rate, removing dropout layers as follows:

```<code>model = Sequential()
model.add(Conv2D(16, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(64, (5, 5), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(64, (5, 5), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(128, (5, 5), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(3,3)))

model.add(Flatten())

model.add(Dense(128, activation='relu'))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(1, activation='sigmoid'))

optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
model.compile(optimizer=optimizer,loss='binary_crossentropy',
              metrics=[tf.keras.metrics.SpecificityAtSensitivity(0.5),
                       tf.keras.metrics.SensitivityAtSpecificity(0.5),'accuracy'])

reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss',factor=0.2,
                                                 patience=2, min_lr=0.00001)
history=model.fit(train_dataset, epochs=10, batch_size=32,
                  validation_data=validation_dataset, callbacks=[reduce_lr])
</code>```

Output:

```<code>Epoch 1/10
63/63 [==============================] - 9s 104ms/step - loss: 0.7631 - specificity_at_sensitivity_2: 0.5760 - sensitivity_at_specificity_2: 0.5700 - accuracy: 0.5445 - val_loss: 0.6751 - val_specificity_at_sensitivity_2: 0.7760 - val_sensitivity_at_specificity_2: 0.7460 - val_accuracy: 0.5050 - lr: 0.0010
Epoch 2/10
63/63 [==============================] - 5s 77ms/step - loss: 0.6570 - specificity_at_sensitivity_2: 0.7260 - sensitivity_at_specificity_2: 0.7030 - accuracy: 0.6030 - val_loss: 0.6652 - val_specificity_at_sensitivity_2: 0.7480 - val_sensitivity_at_specificity_2: 0.6920 - val_accuracy: 0.5990 - lr: 0.0010
Epoch 3/10
63/63 [==============================] - 4s 57ms/step - loss: 0.6277 - specificity_at_sensitivity_2: 0.7920 - sensitivity_at_specificity_2: 0.7650 - accuracy: 0.6565 - val_loss: 0.6696 - val_specificity_at_sensitivity_2: 0.6960 - val_sensitivity_at_specificity_2: 0.6820 - val_accuracy: 0.5930 - lr: 0.0010
Epoch 4/10
63/63 [==============================] - 4s 56ms/step - loss: 0.6163 - specificity_at_sensitivity_2: 0.8080 - sensitivity_at_specificity_2: 0.7830 - accuracy: 0.6570 - val_loss: 0.6330 - val_specificity_at_sensitivity_2: 0.8320 - val_sensitivity_at_specificity_2: 0.7840 - val_accuracy: 0.6520 - lr: 0.0010
Epoch 5/10
63/63 [==============================] - 4s 58ms/step - loss: 0.5710 - specificity_at_sensitivity_2: 0.8710 - sensitivity_at_specificity_2: 0.8420 - accuracy: 0.6995 - val_loss: 0.5940 - val_specificity_at_sensitivity_2: 0.8600 - val_sensitivity_at_specificity_2: 0.8420 - val_accuracy: 0.7030 - lr: 0.0010
Epoch 6/10
63/63 [==============================] - 4s 58ms/step - loss: 0.5426 - specificity_at_sensitivity_2: 0.8930 - sensitivity_at_specificity_2: 0.8790 - accuracy: 0.7250 - val_loss: 0.6158 - val_specificity_at_sensitivity_2: 0.8740 - val_sensitivity_at_specificity_2: 0.8360 - val_accuracy: 0.7060 - lr: 0.0010
Epoch 7/10
63/63 [==============================] - 4s 60ms/step - loss: 0.4991 - specificity_at_sensitivity_2: 0.9260 - sensitivity_at_specificity_2: 0.9100 - accuracy: 0.7550 - val_loss: 0.5927 - val_specificity_at_sensitivity_2: 0.8760 - val_sensitivity_at_specificity_2: 0.8460 - val_accuracy: 0.7280 - lr: 0.0010
Epoch 8/10
63/63 [==============================] - 4s 58ms/step - loss: 0.4597 - specificity_at_sensitivity_2: 0.9480 - sensitivity_at_specificity_2: 0.9300 - accuracy: 0.7885 - val_loss: 0.6473 - val_specificity_at_sensitivity_2: 0.8900 - val_sensitivity_at_specificity_2: 0.8260 - val_accuracy: 0.7320 - lr: 0.0010
Epoch 9/10
63/63 [==============================] - 4s 58ms/step - loss: 0.4682 - specificity_at_sensitivity_2: 0.9500 - sensitivity_at_specificity_2: 0.9310 - accuracy: 0.7900 - val_loss: 0.5569 - val_specificity_at_sensitivity_2: 0.9080 - val_sensitivity_at_specificity_2: 0.8880 - val_accuracy: 0.7330 - lr: 0.0010
Epoch 10/10
63/63 [==============================] - 4s 60ms/step - loss: 0.3974 - specificity_at_sensitivity_2: 0.9740 - sensitivity_at_specificity_2: 0.9600 - accuracy: 0.8155 - val_loss: 0.6180 - val_specificity_at_sensitivity_2: 0.9180 - val_sensitivity_at_specificity_2: 0.8940 - val_accuracy: 0.7540 - lr: 0.0010
</code>```

Body:
I am trying to train a CNN model with 2030 preprocessed eye images. the shape of my input data is (2030, 200,200, 1). At first, the shape of the data was 1527. Then I used imblearn.over_sampling.RandomOverSampler to increase the dataset size. I constructed the model with Keras and here is the summary of my model:

model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same', activation='relu',
input_shape=(img_cols, img_rows, 1)))
model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (5, 5), padding='same', activation='relu'))
model.add(Conv2D(64, (5, 5), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(3,3)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))

optimizer = tf.keras.optimizers.SGD(learning_rate=0.000001)
model.compile(optimizer=optimizer,loss='binary_crossentropy',
metrics=[tf.keras.metrics.SpecificityAtSensitivity(0.5),
tf.keras.metrics.SensitivityAtSpecificity(0.5),'accuracy'])

# Augmentation

train_datagen = ImageDataGenerator(
    rescale=1./255,
    horizontal_flip=True,
    vertical_flip=True,
    width_shift_range=0.3,
    height_shift_range=0.5,
    rotation_range=10,
    zoom_range=0.2
    )

test_datagen = ImageDataGenerator(rescale=1./255)

train_data = train_datagen.flow(x_train, y_train)
test_data = test_datagen.flow(x_test, y_test)

reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss',
factor=0.9,
                          patience=2, min_lr=0.0000000000000000001)
history=model.fit(train_data, epochs=10, batch_size=32,
validation_data=test_data, callbacks=[reduce_lr])

I trained the model with different parameters (with batch sizes 32, 64, 128, 256, 512, 1024, adding 128 and 256 neuron convolution layers, decreasing and increasing learning rate, using callbacks, varying the dense layer size with 32, 64, ..., 1024) but I always get the following learning process:

*Epoch 1/10
51/51 [==============================] - 14s 238ms/step - loss: 0.6962 - specificity_at_sensitivity_15: 0.4548 - sensitivity_at_specificity_15: 0.4777 - accuracy: 0.4969 - val_loss: 0.6957 - val_specificity_at_sensitivity_15: 0.4112 - val_sensitivity_at_specificity_15: 0.3636 - val_accuracy: 0.4852 - lr: 1.0000e-04
Epoch 2/10
51/51 [==============================] - 12s 226ms/step - loss: 0.6945 - specificity_at_sensitivity_15: 0.4829 - sensitivity_at_specificity_15: 0.4615 - accuracy: 0.5018 - val_loss: 0.6949 - val_specificity_at_sensitivity_15: 0.4467 - val_sensitivity_at_specificity_15: 0.3206 - val_accuracy: 0.4877 - lr: 1.0000e-04
Epoch 3/10
51/51 [==============================] - 12s 227ms/step - loss: 0.6955 - specificity_at_sensitivity_15: 0.4328 - sensitivity_at_specificity_15: 0.4082 - accuracy: 0.5043 - val_loss: 0.6945 - val_specificity_at_sensitivity_15: 0.5584 - val_sensitivity_at_specificity_15: 0.5167 - val_accuracy: 0.4852 - lr: 1.0000e-04
Epoch 4/10
51/51 [==============================] - 12s 226ms/step - loss: 0.6971 - specificity_at_sensitivity_15: 0.4034 - sensitivity_at_specificity_15: 0.4256 - accuracy: 0.5049 - val_loss: 0.6941 - val_specificity_at_sensitivity_15: 0.4010 - val_sensitivity_at_specificity_15: 0.3923 - val_accuracy: 0.4852 - lr: 1.0000e-04
Epoch 5/10
51/51 [==============================] - 12s 226ms/step - loss: 0.6954 - specificity_at_sensitivity_15: 0.4670 - sensitivity_at_specificity_15: 0.4640 - accuracy: 0.4969 - val_loss: 0.6938 - val_specificity_at_sensitivity_15: 0.5584 - val_sensitivity_at_specificity_15: 0.5407 - val_accuracy: 0.4729 - lr: 1.0000e-04
Epoch 6/10
51/51 [==============================] - 12s 227ms/step - loss: 0.6972 - specificity_at_sensitivity_15: 0.4352 - sensitivity_at_specificity_15: 0.3883 - accuracy: 0.4791 - val_loss: 0.6935 - val_specificity_at_sensitivity_15: 0.4772 - val_sensitivity_at_specificity_15: 0.3206 - val_accuracy: 0.4729 - lr: 1.0000e-04
Epoch 7/10
51/51 [==============================] - 12s 227ms/step - loss: 0.6943 - specificity_at_sensitivity_15: 0.4474 - sensitivity_at_specificity_15: 0.4814 - accuracy: 0.5031 - val_loss: 0.6933 - val_specificity_at_sensitivity_15: 0.3604 - val_sensitivity_at_specificity_15: 0.4880 - val_accuracy: 0.4729 - lr: 1.0000e-04
Epoch 8/10
51/51 [==============================] - 12s 225ms/step - loss: 0.6974 - specificity_at_sensitivity_15: 0.4609 - sensitivity_at_specificity_15: 0.4355 - accuracy: 0.4926 - val_loss: 0.6930 - val_specificity_at_sensitivity_15: 0.5279 - val_sensitivity_at_specificity_15: 0.5885 - val_accuracy: 0.4655 - lr: 1.0000e-04
Epoch 9/10
51/51 [==============================] - 12s 226ms/step - loss: 0.6945 - specificity_at_sensitivity_15: 0.4425 - sensitivity_at_specificity_15: 0.4777 - accuracy: 0.5031 - val_loss: 0.6929 - val_specificity_at_sensitivity_15: 0.4619 - val_sensitivity_at_specificity_15: 0.3876 - val_accuracy: 0.4655 - lr: 1.0000e-04
Epoch 10/10
51/51 [==============================] - 12s 226ms/step - loss: 0.6977 - specificity_at_sensitivity_15: 0.4389 - sensitivity_at_specificity_15: 0.4367 - accuracy: 0.4766 - val_loss: 0.6927 - val_specificity_at_sensitivity_15: 0.6091 - val_sensitivity_at_specificity_15: 0.5024 - val_accuracy: 0.4951 - lr: 1.0000e-04*

And evaluation with test data generated from x_test data (2 percent of the 2030 images) resulted in:

13/13 [==============================] - 1s 69ms/step - loss: 0.6927 - specificity_at_sensitivity_15: 0.6091 - sensitivity_at_specificity_15: 0.5024 - accuracy: 0.4951
Accuracy score is : 0.4950738847255707

How can I improve my accuracy score? I tried every possible way, but the maximum I could increase was 53%. Similar codes I saw on the internet reached 76%. It is a medical imaging project, I believe it is better to obtain better accuracy.

Body:
If you could try with changing optimizer from SGD to Adam, you will get better accuracy along with doing some other changes like adding more convolution layers, increasing learning rate, removing dropout layers as follows:

model = Sequential()
model.add(Conv2D(16, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(64, (5, 5), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(64, (5, 5), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(128, (5, 5), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(3,3)))

model.add(Flatten())

model.add(Dense(128, activation='relu'))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(1, activation='sigmoid'))

optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
model.compile(optimizer=optimizer,loss='binary_crossentropy',
              metrics=[tf.keras.metrics.SpecificityAtSensitivity(0.5),
                       tf.keras.metrics.SensitivityAtSpecificity(0.5),'accuracy'])

reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss',factor=0.2,
                                                 patience=2, min_lr=0.00001)
history=model.fit(train_dataset, epochs=10, batch_size=32,
                  validation_data=validation_dataset, callbacks=[reduce_lr])

Output:

Epoch 1/10
63/63 [==============================] - 9s 104ms/step - loss: 0.7631 - specificity_at_sensitivity_2: 0.5760 - sensitivity_at_specificity_2: 0.5700 - accuracy: 0.5445 - val_loss: 0.6751 - val_specificity_at_sensitivity_2: 0.7760 - val_sensitivity_at_specificity_2: 0.7460 - val_accuracy: 0.5050 - lr: 0.0010
Epoch 2/10
63/63 [==============================] - 5s 77ms/step - loss: 0.6570 - specificity_at_sensitivity_2: 0.7260 - sensitivity_at_specificity_2: 0.7030 - accuracy: 0.6030 - val_loss: 0.6652 - val_specificity_at_sensitivity_2: 0.7480 - val_sensitivity_at_specificity_2: 0.6920 - val_accuracy: 0.5990 - lr: 0.0010
Epoch 3/10
63/63 [==============================] - 4s 57ms/step - loss: 0.6277 - specificity_at_sensitivity_2: 0.7920 - sensitivity_at_specificity_2: 0.7650 - accuracy: 0.6565 - val_loss: 0.6696 - val_specificity_at_sensitivity_2: 0.6960 - val_sensitivity_at_specificity_2: 0.6820 - val_accuracy: 0.5930 - lr: 0.0010
Epoch 4/10
63/63 [==============================] - 4s 56ms/step - loss: 0.6163 - specificity_at_sensitivity_2: 0.8080 - sensitivity_at_specificity_2: 0.7830 - accuracy: 0.6570 - val_loss: 0.6330 - val_specificity_at_sensitivity_2: 0.8320 - val_sensitivity_at_specificity_2: 0.7840 - val_accuracy: 0.6520 - lr: 0.0010
Epoch 5/10
63/63 [==============================] - 4s 58ms/step - loss: 0.5710 - specificity_at_sensitivity_2: 0.8710 - sensitivity_at_specificity_2: 0.8420 - accuracy: 0.6995 - val_loss: 0.5940 - val_specificity_at_sensitivity_2: 0.8600 - val_sensitivity_at_specificity_2: 0.8420 - val_accuracy: 0.7030 - lr: 0.0010
Epoch 6/10
63/63 [==============================] - 4s 58ms/step - loss: 0.5426 - specificity_at_sensitivity_2: 0.8930 - sensitivity_at_specificity_2: 0.8790 - accuracy: 0.7250 - val_loss: 0.6158 - val_specificity_at_sensitivity_2: 0.8740 - val_sensitivity_at_specificity_2: 0.8360 - val_accuracy: 0.7060 - lr: 0.0010
Epoch 7/10
63/63 [==============================] - 4s 60ms/step - loss: 0.4991 - specificity_at_sensitivity_2: 0.9260 - sensitivity_at_specificity_2: 0.9100 - accuracy: 0.7550 - val_loss: 0.5927 - val_specificity_at_sensitivity_2: 0.8760 - val_sensitivity_at_specificity_2: 0.8460 - val_accuracy: 0.7280 - lr: 0.0010
Epoch 8/10
63/63 [==============================] - 4s 58ms/step - loss: 0.4597 - specificity_at_sensitivity_2: 0.9480 - sensitivity_at_specificity_2: 0.9300 - accuracy: 0.7885 - val_loss: 0.6473 - val_specificity_at_sensitivity_2: 0.8900 - val_sensitivity_at_specificity_2: 0.8260 - val_accuracy: 0.7320 - lr: 0.0010
Epoch 9/10
63/63 [==============================] - 4s 58ms/step - loss: 0.4682 - specificity_at_sensitivity_2: 0.9500 - sensitivity_at_specificity_2: 0.9310 - accuracy: 0.7900 - val_loss: 0.5569 - val_specificity_at_sensitivity_2: 0.9080 - val_sensitivity_at_specificity_2: 0.8880 - val_accuracy: 0.7330 - lr: 0.0010
Epoch 10/10
63/63 [==============================] - 4s 60ms/step - loss: 0.3974 - specificity_at_sensitivity_2: 0.9740 - sensitivity_at_specificity_2: 0.9600 - accuracy: 0.8155 - val_loss: 0.6180 - val_specificity_at_sensitivity_2: 0.9180 - val_sensitivity_at_specificity_2: 0.8940 - val_accuracy: 0.7540 - lr: 0.0010


Title: SVG invisible on Safari without height attribute, but issue not recreatable?

Body:
I have an SVG in my website which displays fine on Chrome but isn't visible on Safari and Mobile Safari.

Weirdly, if I copy and paste the SVG into a Codepen page then it works fine, so I'm not able to recreate the issue publicly.

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="22" aria-hidden="true" focusable="false" role="img"><path fill="currentColor" d="M4.686 427.314L104 328l-32.922-31.029C55.958 281.851 66.666 256 88.048 256h112C213.303 256 224 266.745 224 280v112c0 21.382-25.803 32.09-40.922 16.971L152 376l-99.314 99.314c-6.248 6.248-16.379 6.248-22.627 0L4.686 449.941c-6.248-6.248-6.248-16.379 0-22.627zM443.314 84.686L344 184l32.922 31.029c15.12 15.12 4.412 40.971-16.97 40.971h-112C234.697 256 224 245.255 224 232V120c0-21.382 25.803-32.09 40.922-16.971L296 136l99.314-99.314c6.248-6.248 16.379-6.248 22.627 0l25.373 25.373c6.248 6.248 6.248 16.379 0 22.627z"></path></svg>

Setting height 100% as an attribute fixes the issue in Safari and doesn't make it the wrong size or aspect ratio.

What is going on here? Why does this work and is a safe fix? And also why is the issue not reproducible?

UPDATE: Ive now been able to recreate. Safari hides the SVG when it has a parent div with display: flex:

https://codepen.io/adsfdsfhdsafkhdsafjkdhafskjds/pen/yLPgaJx

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="22" aria-hidden="true" focusable="false" role="img"><path fill="currentColor" d="M4.686 427.314L104 328l-32.922-31.029C55.958 281.851 66.666 256 88.048 256h112C213.303 256 224 266.745 224 280v112c0 21.382-25.803 32.09-40.922 16.971L152 376l-99.314 99.314c-6.248 6.248-16.379 6.248-22.627 0L4.686 449.941c-6.248-6.248-6.248-16.379 0-22.627zM443.314 84.686L344 184l32.922 31.029c15.12 15.12 4.412 40.971-16.97 40.971h-112C234.697 256 224 245.255 224 232V120c0-21.382 25.803-32.09 40.922-16.971L296 136l99.314-99.314c6.248-6.248 16.379-6.248 22.627 0l25.373 25.373c6.248 6.248 6.248 16.379 0 22.627z"></path></svg>

If I set the container div to display: block or set a height on the SVG then it comes back.

Body:
You have the height of the SVG twice. In view styles hight="100%" and style="height: auto;"

safari doesn't know which style to prefer, how to scale the SVG, so it doesn't display the image.

Leave one style: width="22" height="auto"

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="22" height="auto" aria-hidden="true" focusable="false" role="img" style="border:1px solid red">
  <path fill="currentColor" d="M4.686 427.314L104 328l-32.922-31.029C55.958 281.851 66.666 256 88.048 256h112C213.303 256 224 266.745 224 280v112c0 21.382-25.803 32.09-40.922 16.971L152 376l-99.314 99.314c-6.248 6.248-16.379 6.248-22.627 0L4.686 449.941c-6.248-6.248-6.248-16.379 0-22.627zM443.314 84.686L344 184l32.922 31.029c15.12 15.12 4.412 40.971-16.97 40.971h-112C234.697 256 224 245.255 224 232V120c0-21.382 25.803-32.09 40.922-16.971L296 136l99.314-99.314c6.248-6.248 16.379-6.248 22.627 0l25.373 25.373c6.248 6.248 6.248 16.379 0 22.627z">
  </path>
 </svg>

Update

Try setting the values of `viewBox="0 32 448 448" according to the dimensions shown by the JS method getBBox()

And also specify fixed width and height viewport width="22" height="22"

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 32 448 448" width="22" height="22" aria-hidden="true" focusable="false" role="img" style="border:1px solid red">
  <path id="path" fill="currentColor" d="M4.686 427.314L104 328l-32.922-31.029C55.958 281.851 66.666 256 88.048 256h112C213.303 256 224 266.745 224 280v112c0 21.382-25.803 32.09-40.922 16.971L152 376l-99.314 99.314c-6.248 6.248-16.379 6.248-22.627 0L4.686 449.941c-6.248-6.248-6.248-16.379 0-22.627zM443.314 84.686L344 184l32.922 31.029c15.12 15.12 4.412 40.971-16.97 40.971h-112C234.697 256 224 245.255 224 232V120c0-21.382 25.803-32.09 40.922-16.971L296 136l99.314-99.314c6.248-6.248 16.379-6.248 22.627 0l25.373 25.373c6.248 6.248 6.248 16.379 0 22.627z">
  </path>
 </svg>
 <script>
   console.log(path.getBBox())
 </script>