问:
Error DOMException saying Failed to execute 'replaceChild' on 'Node' while trying to replace all span by input-field in foreach
Like saying, i'm trying to replace all span by input-field in javascript on a foreach.
Here's my code :

```<code> test({params:{idtarif}}){

    let tarifAModifier = document.getElementById('tarif-'+idtarif)
    let listeSpans = Array.from(tarifAModifier.getElementsByTagName("span"))

    listeSpans.forEach(element => {
        let classEl = element.classList.value
        if(classEl){
            let contenuEl = element.textContent
            let inputToDisplay = document.createElement('input')
            inputToDisplay.type = 'text'
            inputToDisplay.maxLength = 50
            inputToDisplay.setAttribute('value', contenuEl)
            inputToDisplay.classList.add(classEl)

            tarifAModifier.replaceChild(inputToDisplay, element)
        }

    });

}
</code>```

Error is always :

```<code>Error invoking action "click->tarifs-administration#test"

DOMException: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.
    at https://127.0.0.1:8000/build/app.js:1810:37
</code>```

Do someone have an idea ?

Body:
Like saying, i'm trying to replace all span by input-field in javascript on a foreach.
Here's my code :

 test({params:{idtarif}}){

    let tarifAModifier = document.getElementById('tarif-'+idtarif)
    let listeSpans = Array.from(tarifAModifier.getElementsByTagName("span"))

    listeSpans.forEach(element => {
        let classEl = element.classList.value
        if(classEl){
            let contenuEl = element.textContent
            let inputToDisplay = document.createElement('input')
            inputToDisplay.type = 'text'
            inputToDisplay.maxLength = 50
            inputToDisplay.setAttribute('value', contenuEl)
            inputToDisplay.classList.add(classEl)

            tarifAModifier.replaceChild(inputToDisplay, element)
        }

    });

}

Error is always :

Error invoking action "click->tarifs-administration#test"

DOMException: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.
    at https://127.0.0.1:8000/build/app.js:1810:37

Do someone have an idea ?


来源: stackexchange

问:
Why is writeValue not returning a Promise
I'm working on mocking the process of writing data to a Web Bluetooth device. I've run into an issue where .writeValue is not returning a promise.

Can somebody either let me know why this isn't working or how I can essentially replace this method to return a promise, I'm not wanting to test the functionality of a depreciated method at the end of the day.

const str2ab = (value: string) => {
  // string to array buffer
}

let chunk = "my message";

let txCharacteristic: BluetoothRemoteGATTCharacteristic;

txCharacteristic
    .writeValue(str2ab(chunk))
    .then(function(){
        // do something
    })

```

I've attempted to see if I can find a way to override this method but have had no luck.

To expand on this the error im receiving is TypeError: Cannot read properties of undefined (reading 'then')

as for the method being depreciated I know, currently I'm just working from a spec and don't have say in changing it.

ContentLicense: CC BY-SA 4.0

Body:
I'm working on mocking the process of writing data to a Web Bluetooth device. I've run into an issue where .writeValue is not returning a promise.

Can somebody either let me know why this isn't working or how I can essentially replace this method to return a promise, I'm not wanting to test the functionality of a depreciated method at the end of the day.

const str2ab = (value: string) => {
  // string to array buffer
}

let chunk = "my message";

let txCharacteristic: BluetoothRemoteGATTCharacteristic;

txCharacteristic
    .writeValue(str2ab(chunk))
    .then(function(){
        // do something
    })

I've attempted to see if I can find a way to override this method but have had no luck.

To expand on this the error im receiving is TypeError: Cannot read properties of undefined (reading 'then')

as for the method being depreciated I know, currently I'm just working from a spec and don't have say in changing it.


问:
How to structure GitHub actions
I'm coming from Travis and am new to GitHub actions, and despite reading a lot of documentation and examples, there's just some aspects I don't understand.

Typically, I have two kinds of jobs: verification and deployment.

For pushes to main, or for pull requests, run verification scripts (unit tests, lint, generate docs, etc etc). This is what should always run first when pushing to main or a PR.

For pushes to certain branches, run deploy jobs after the verification jobs have finished successfully. Different branches should trigger different deploy targets (dev, staging, prod, ...)

I understand that I can create a single workflow with multiple jobs, so that one job could be "verification" and perform those steps, and one job could be "deployment" and perform those jobs. But the triggers are different; deployment jobs should only run for _some branches, and there seems to be no way to use on directives within jobs, only for entire workflow files?

I understand that I could use if to check things like the branch against /ref/heads/master etc, but I think that's very ugly, considering there is a trigger mechanism with on: branches: xxx etc. It doesn't feel right to then resort to a single job with if conditions inside the steps instead. Am I right?

So, should I then create verify.yml and deploy-dev.yml, deploy-staging.yml, deploy-production.yml?
I also understand that I can create a reusable workflow with inputs, so that I could create a deploy.yml workflow which is passed from deploy-dev.yml etc, with inputs like STAGE=dev.
But do I then need to repeat the actions/checkout, actions/setup-node etc for each of my workflows, or is there any relation between different workflow files?

What is the best structure for 1) always running tests etc 2) after tests run deploy to different environments depending on target branch.

Multiple workflow files (with repeated steps for the setup code?)

One workflow with multiple jobs and conditions inside run: steps

Something else?

Title: How to structure GitHub actions


问:
how to fix net:ERR_CERT_AUTHORITY_INVALID error in Unity WebGL
I'm building Unity WebGL game using NodeJS server.
It's working on Unity Editor with Node server but after build webgl it's now working on browser.
When game send request using UnityWebRequest to server, I got net:ERR_CERT_AUTHORITY_INVALID error.
If anybody has knowledge about this issue, Please help me.

```<code>   public IEnumerator SendLogin()
    {
        Debug.Log(Global.WALLET_ADDRESS);
        JObject jsondata = new JObject();
        jsondata.Add("wallet_address", Global.WALLET_ADDRESS);
        using (UnityWebRequest request = UnityWebRequest.Put(URL + "/api/auth/joingame", jsondata.ToString()))
        {
            request.method = UnityWebRequest.kHttpVerbPOST;
            request.SetRequestHeader("Content-Type", "application/json");
            request.SetRequestHeader("Accept", "application/json");
            request.SetRequestHeader("Access-Control-Allow-Origin", URL);
            request.SetRequestHeader("Access-Control-Allow-Methods", "POST");
            request.certificateHandler = new CertHandler();
            yield return request.SendWebRequest();
            Debug.Log(request.downloadHandler.text);
            JObject obj = JObject.Parse(request.downloadHandler.text);
            Global.USER_ID = int.Parse(obj["userId"].ToString());
            Global.ACCESS_TOKEN = obj["accessToken"].ToString();
            MenuController.instance.SetStart(bool.Parse(obj["result"].ToString()));
        }
    }
</code>```

Body:
I'm building Unity WebGL game using NodeJS server.
It's working on Unity Editor with Node server but after build webgl it's now working on browser.
When game send request using UnityWebRequest to server, I got net:ERR_CERT_AUTHORITY_INVALID error.
If anybody has knowledge about this issue, Please help me.

   public IEnumerator SendLogin()
    {
        Debug.Log(Global.WALLET_ADDRESS);
        JObject jsondata = new JObject();
        jsondata.Add("wallet_address", Global.WALLET_ADDRESS);
        using (UnityWebRequest request = UnityWebRequest.Put(URL + "/api/auth/joingame", jsondata.ToString()))
        {
            request.method = UnityWebRequest.kHttpVerbPOST;
            request.SetRequestHeader("Content-Type", "application/json");
            request.SetRequestHeader("Accept", "application/json");
            request.SetRequestHeader("Access-Control-Allow-Origin", URL);
            request.SetRequestHeader("Access-Control-Allow-Methods", "POST");
            request.certificateHandler = new CertHandler();
            yield return request.SendWebRequest();
            Debug.Log(request.downloadHandler.text);
            JObject obj = JObject.Parse(request.downloadHandler.text);
            Global.USER_ID = int.Parse(obj["userId"].ToString());
            Global.ACCESS_TOKEN = obj["accessToken"].ToString();
            MenuController.instance.SetStart(bool.Parse(obj["result"].ToString()));
        }
    }


问:
Google maps autocomplete library loading issue in nextjs
In my application, we are using google search autocomplete and I am facing the below issue on loading the application

As the above image suggested I have referred to the link but not sure how to avoid this issue and it's not a consistent issue to validate it.


问:
how to graphically show bitcoin public key on the curve?
From what i understand private is a point on the Elliptic curve and a public key is x,y co-ordinates on the curve therefore showing them on the graph should be easy to those who knows how to code.
The below code shows the graph using python

```<code>import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = [3, 1, 2, 5]
y = [5, 2, 4, 7]

plt.plot(x, y, 'r*')
plt.axis([0, 6, 0, 20])

for i, j in zip(x, y):
   plt.text(i, j+0.5, '({}, {})'.format(i, j))

plt.show()
</code>```

I need to do the same but with Elliptic curve and x,y co-ordinates of public key.
My goal is to find the relationship between 2 public key with bitcoin addresses that share the 8 first characters, so it would be easy if i see them on a curve.

i have read Scalar multiplication HERE

can someone show me how to show public and private key on the curve using python?

The below code is a sample from HERE

```<code>import numpy as np
import matplotlib.pyplot as plt

def main():
    a = -1
    b = 1

    y, x = np.ogrid[-5:5:100j, -5:5:100j]
    plt.contour(x.ravel(), y.ravel(), pow(y, 2) - pow(x, 3) - x * a - b, [0])
    plt.grid()
    plt.show()

if __name__ == '__main__':
    main()
</code>```

I am still learning python.

Body:
From what i understand private is a point on the Elliptic curve and a public key is x,y co-ordinates on the curve therefore showing them on the graph should be easy to those who knows how to code.
The below code shows the graph using python

import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = [3, 1, 2, 5]
y = [5, 2, 4, 7]

plt.plot(x, y, 'r*')
plt.axis([0, 6, 0, 20])

for i, j in zip(x, y):
   plt.text(i, j+0.5, '({}, {})'.format(i, j))

plt.show()

I need to do the same but with Elliptic curve and x,y co-ordinates of public key.
My goal is to find the relationship between 2 public key with bitcoin addresses that share the 8 first characters, so it would be easy if i see them on a curve.

i have read Scalar multiplication HERE

can someone show me how to show public and private key on the curve using python?

The below code is a sample from HERE

import numpy as np
import matplotlib.pyplot as plt

def main():
    a = -1
    b = 1

    y, x = np.ogrid[-5:5:100j, -5:5:100j]
    plt.contour(x.ravel(), y.ravel(), pow(y, 2) - pow(x, 3) - x * a - b, [0])
    plt.grid()
    plt.show()

if __name__ == '__main__':
    main()

I am still learning python.


问:
Virtual machine status is not ready
Virtual machine agent is not ready

Virtual machine status is not ready. What could be the possible reasons for this?

Title: Virtual machine status is not ready


问:
XeroApi missing ability to assign TaxNumberType
We update user's contact information from our site, and use the TaxNumber field.

I assume it guesses the TaxNumberType, a field available in the user UI, based on the format of the value passed in. We have people change from using SSN to EIN because their mode of business changes. This throws an error "Social security number must be 9 digits and in the format xxx-xx-xxxx."

This should be a field accepted through the API.


问:
Set gulp-usemin task to build the content of src folder, but not create another src folder into dist
So, I have the follow project structure

```<code>├── gulpfile.js
├── output.txt
├── package-lock.json
├── package.json
└── src
   ├── assets
   |  ├── css
   |  ├── img
   |  ├── js
   |  └── pages
   └── index.html
</code>```

And the follow gulp tasks

gulp.task("imagemin", function () {
    return gulp
        .src("./src/assets/img/*", { base: "." })
        .pipe(
            imagemin({
                optmizationLevel: 1,
                progressive: true,
                interlaced: true
            })
        )
        .pipe(gulp.dest("dist/"));
});

gulp.task("usemin", function () {
    return gulp
        .src("./src/*.html", { base: "." })
        .pipe(
            flatmap(function (stream, file) {
                return stream.pipe(
                    usemin({
                        css: [cleanCss(), rev()],
                        html: [
                            function () {
                                return htmlmin({
                                    collapseWhitespace: true
                                });
                            }
                        ],
                        js: [uglify(), rev()],
                        inlinejs: [uglify()],
                        inlinecss: [cleanCss(), "concat"]
                    })
                );
            })
        )
        .pipe(gulp.dest("dist/"));
});

gulp.task("build", gulp.series("clean", gulp.parallel("imagemin", "usemin")));

```
<p>When I run <code>build</code>, I get the follow structure:</p>
```├── dist
|  └── src
|     ├── assets
|     └── index.html
├── gulpfile.js
├── output.txt
├── package-lock.json
├── package.json
└── src
   ├── assets
   |  ├── css
   |  ├── img
   |  ├── js
   |  └── pages
   └── index.html
```

But I don't want another src folder into the dist folder, just it's content. How do I do that?

I tried to set ´root: ./src` as usemin task option, but I get the same result.

OBS: The pages folder into assets have more html files.

Body:
So, I have the follow project structure

├── gulpfile.js
├── output.txt
├── package-lock.json
├── package.json
└── src
   ├── assets
   |  ├── css
   |  ├── img
   |  ├── js
   |  └── pages
   └── index.html

And the follow gulp tasks

gulp.task("imagemin", function () {
    return gulp
        .src("./src/assets/img/*", { base: "." })
        .pipe(
            imagemin({
                optmizationLevel: 1,
                progressive: true,
                interlaced: true
            })
        )
        .pipe(gulp.dest("dist/"));
});

gulp.task("usemin", function () {
    return gulp
        .src("./src/*.html", { base: "." })
        .pipe(
            flatmap(function (stream, file) {
                return stream.pipe(
                    usemin({
                        css: [cleanCss(), rev()],
                        html: [
                            function () {
                                return htmlmin({
                                    collapseWhitespace: true
                                });
                            }
                        ],
                        js: [uglify(), rev()],
                        inlinejs: [uglify()],
                        inlinecss: [cleanCss(), "concat"]
                    })
                );
            })
        )
        .pipe(gulp.dest("dist/"));
});

gulp.task("build", gulp.series("clean", gulp.parallel("imagemin", "usemin")));

When I run build, I get the follow structure:

├── dist
|  └── src
|     ├── assets
|     └── index.html
├── gulpfile.js
├── output.txt
├── package-lock.json
├── package.json
└── src
   ├── assets
   |  ├── css
   |  ├── img
   |  ├── js
   |  └── pages
   └── index.html

But I don't want another src folder into the dist folder, just it's content. How do I do that?

I tried to set ´root: ./src` as usemin task option, but I get the same result.

OBS: The pages folder into assets have more html files.


问:
BottomSheetModalProvider when navigate to screen when modal is active the modal is always open
I use BottomSheetModal and when I open my modal and I have a button to navigate to a screen then if I press the button and I navigate to a screen the modal is always showing. How can I make that the modal is only inside the current screen showing ?

Look at the video

App.tsx

```<code>     <SafeAreaProvider>
      <SafeAreaView style={s.rootView}>
        <GestureHandlerRootView style={s.rootView}>
          <NavigationContainer onReady={onLayoutRootView}>
            <BottomSheetModalProvider>
                <NativeStackWrapper />
            </BottomSheetModalProvider>
            <Toast position='bottom' config={ToastConfig} />
          </NavigationContainer>
          </GestureHandlerRootView>
        </SafeAreaView>
      </SafeAreaProvider>
</code>```

Video

Body:
I use BottomSheetModal and when I open my modal and I have a button to navigate to a screen then if I press the button and I navigate to a screen the modal is always showing. How can I make that the modal is only inside the current screen showing ?

Look at the video

App.tsx

     <SafeAreaProvider>
      <SafeAreaView style={s.rootView}>
        <GestureHandlerRootView style={s.rootView}>
          <NavigationContainer onReady={onLayoutRootView}>
            <BottomSheetModalProvider>
                <NativeStackWrapper />
            </BottomSheetModalProvider>
            <Toast position='bottom' config={ToastConfig} />
          </NavigationContainer>
          </GestureHandlerRootView>
        </SafeAreaView>
      </SafeAreaProvider>

Video


问:
Failed to load class "org.slf4j.impl.StaticLoggerBinder" - trying to add Bootstrap to a Spring project
I tried adding bootstrap to my spring project. I added the thymeleaf reference in the html tag and now i get this error. Failed to load class "org.slf4j.impl.StaticLoggerBinder". Does anyone have any idea why this is happening?

```<code></code>```
```<code>\<!DOCTYPE html\>
\<html lang="en" xmlns:th="https://thymeleaf.org"\>
\<head\>
\<meta charset="UTF-8"\>
\<title\>Welcome to my Application\</title\>

\</head\>
\<body\>
\<h1\>Welcome to my Application\</h1\>
\</body\>
\</html\>
</code>```
```<code></code>```

This is the whole log

```<code>`SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:119)
    at java.base/java.lang.reflect.Method.invoke(Method.java:578)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.IllegalArgumentException: LoggerFactory is not a Logback LoggerContext but Logback is on the classpath. Either remove Logback or the competing implementation (class org.slf4j.helpers.NOPLoggerFactory loaded from file:/C:/Users/Ariciu/.m2/repository/org/slf4j/slf4j-api/1.7.7/slf4j-api-1.7.7.jar). If you are using WebLogic you will need to add 'org.slf4j' to prefer-application-packages in WEB-INF/weblogic.xml: org.slf4j.helpers.NOPLoggerFactory
    at org.springframework.util.Assert.instanceCheckFailed(Assert.java:713)
    at org.springframework.util.Assert.isInstanceOf(Assert.java:632)
    at org.springframework.boot.logging.logback.LogbackLoggingSystem.getLoggerContext(LogbackLoggingSystem.java:369)
    at org.springframework.boot.logging.logback.LogbackLoggingSystem.beforeInitialize(LogbackLoggingSystem.java:121)
    at org.springframework.boot.context.logging.LoggingApplicationListener.onApplicationStartingEvent(LoggingApplicationListener.java:238)
    at org.springframework.boot.context.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:220)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:131)
    at org.springframework.boot.context.event.EventPublishingRunListener.multicastInitialEvent(EventPublishingRunListener.java:136)
    at org.springframework.boot.context.event.EventPublishingRunListener.starting(EventPublishingRunListener.java:75)
    at org.springframework.boot.SpringApplicationRunListeners.lambda$starting$0(SpringApplicationRunListeners.java:54)
    at java.base/java.lang.Iterable.forEach(Iterable.java:75)
    at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:118)
    at org.springframework.boot.SpringApplicationRunListeners.starting(SpringApplicationRunListeners.java:54)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:300)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291)
    at com.vladlaudat.java_crud_app.JavaCrudAppApplication.main(JavaCrudAppApplication.java:10)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    ... 2 more`
</code>```

Body:
I tried adding bootstrap to my spring project. I added the thymeleaf reference in the html tag and now i get this error. Failed to load class "org.slf4j.impl.StaticLoggerBinder". Does anyone have any idea why this is happening?

\<!DOCTYPE html\>
\
\
\<meta charset="UTF-8"\>
\<title\>Welcome to my Application\</title\>

\
\
\
Welcome to my Application\

\
\

This is the whole log

`SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:119)
    at java.base/java.lang.reflect.Method.invoke(Method.java:578)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.IllegalArgumentException: LoggerFactory is not a Logback LoggerContext but Logback is on the classpath. Either remove Logback or the competing implementation (class org.slf4j.helpers.NOPLoggerFactory loaded from file:/C:/Users/Ariciu/.m2/repository/org/slf4j/slf4j-api/1.7.7/slf4j-api-1.7.7.jar). If you are using WebLogic you will need to add 'org.slf4j' to prefer-application-packages in WEB-INF/weblogic.xml: org.slf4j.helpers.NOPLoggerFactory
    at org.springframework.util.Assert.instanceCheckFailed(Assert.java:713)
    at org.springframework.util.Assert.isInstanceOf(Assert.java:632)
    at org.springframework.boot.logging.logback.LogbackLoggingSystem.getLoggerContext(LogbackLoggingSystem.java:369)
    at org.springframework.boot.logging.logback.LogbackLoggingSystem.beforeInitialize(LogbackLoggingSystem.java:121)
    at org.springframework.boot.context.logging.LoggingApplicationListener.onApplicationStartingEvent(LoggingApplicationListener.java:238)
    at org.springframework.boot.context.logging.LoggingApplicationListener.onApplicationEvent(LoggingApplicationListener.java:220)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:131)
    at org.springframework.boot.context.event.EventPublishingRunListener.multicastInitialEvent(EventPublishingRunListener.java:136)
    at org.springframework.boot.context.event.EventPublishingRunListener.starting(EventPublishingRunListener.java:75)
    at org.springframework.boot.SpringApplicationRunListeners.lambda$starting$0(SpringApplicationRunListeners.java:54)
    at java.base/java.lang.Iterable.forEach(Iterable.java:75)
    at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:118)
    at org.springframework.boot.SpringApplicationRunListeners.starting(SpringApplicationRunListeners.java:54)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:300)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291)
    at com.vladlaudat.java_crud_app.JavaCrudAppApplication.main(JavaCrudAppApplication.java:10)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    ... 2 more`


问:
How to do Zoom in/out using mouse wheel/pinch
I want to add zoom in/out functionality in the middle div (yellow are as shown in fig) the content inside the inner div should increase in size while zoom.

const DocContainer = () => {

```<code>const scale = useRef() as React.MutableRefObject<HTMLDivElement>;

let scale1 = 1;
const handleZoomIn = () => {

    let zoomScale = Math.round(parseFloat(scale.current.style.scale) * 100);
    if (zoomScale == 200)
        return;
    scale.current.style.scale = (parseFloat(scale.current.style.scale) + 0.05).toString();
    let elem = document.getElementById('txtZoomVal') as HTMLInputElement;
    elem.value = Math.round(parseFloat(scale.current.style.scale) * 100) + '%';

    console.log(scale);
    console.log(scale.current.getBoundingClientRect());
}
const handleZoomOut = () => {
    let zoomScale = Math.round(parseFloat(scale.current.style.scale) * 100);
    if (zoomScale == 50)
        return;
    scale.current.style.scale = (parseFloat(scale.current.style.scale) - 0.05).toString();
    let elem = document.getElementById('txtZoomVal') as HTMLInputElement;
    elem.value = Math.round(parseFloat(scale.current.style.scale) * 100) + '%';
}

return (<>
    <div className="row g-0">
        <div className="col-md-2">
            <div className="card rounded-0 shadow-0 border border-info">
                <div className="card-header py-1">
                    <span className="card-title h4">Components</span>
                </div>
                <div className="card-body p-1">
                    <MDBListGroup light>
                        <MDBListGroupItem tag='button' action type='button' className='px-3'>
                            <MDBIcon className="me-2 fa fa-tag"></MDBIcon>
                            <span id="lbl" className="lbl"> Label</span>
                        </MDBListGroupItem>
                        <MDBListGroupItem tag='button' action type='button' className='px-3'>
                            <MDBIcon className="me-2 fa fa-pen-to-square"></MDBIcon>
                            <span>Input</span>
                        </MDBListGroupItem>
                        <MDBListGroupItem tag='button' action type='button' className='px-3'>
                            <MDBIcon className="me-2 fa fa-table"></MDBIcon>
                            <span>Table</span>
                        </MDBListGroupItem>
                        <MDBListGroupItem tag='button' action type='button' className='px-3'>
                            <MDBIcon className="me-2 fa fa-grip-lines"></MDBIcon>
                            <span>H-Line</span>
                        </MDBListGroupItem>
                        <MDBListGroupItem tag='button' action type='button' className='px-3'>
                            <MDBIcon className="me-3 fa fa-grip-lines-vertical"></MDBIcon>
                            <span>V-Line</span>
                        </MDBListGroupItem>
                        <MDBListGroupItem tag='button' action type='button' className='px-3'>
                            <MDBIcon className="me-2 fa fa-image"></MDBIcon>
                            <span>Image</span>
                        </MDBListGroupItem>
                    </MDBListGroup>
                </div>
            </div>
        </div>
        <div className="col-md-8">
            <div className="card rounded-0 shadow-0 border border-warning">
                <div className="card-header py-1">
                    <span className="card-title">
                        <MDBBtn className="p-2">
                            <MDBIcon className="me-2 fa fa-square-plus"></MDBIcon>Add Page
                        </MDBBtn>
                    </span>
                    <span className="card-title ms-2">
                        <MDBBtn className="p-2">
                            <MDBIcon className="me-2 fa fa-border-all"></MDBIcon>Set Margin
                        </MDBBtn>
                    </span>
                    <span className="card-title ms-2">
                        <MDBBtn className="p-2" onClick={handleZoomIn}>
                            <MDBIcon className="me-2 fa fa-plus"></MDBIcon> Zoom In
                        </MDBBtn>
                    </span>
                    <span className="card-title ms-2">
                        <input id="txtZoomVal" type="text" readOnly title="zoom value" value={parseFloat(scale.current?.style.scale ?? 1) * 100 + '%'} style={{ width: '50px' }}></input>
                    </span>
                    <span className="card-title ms-2">
                        <MDBBtn className="p-2" onClick={handleZoomOut}>
                            <MDBIcon className="me-2 fa fa-minus"></MDBIcon> Zoom Out
                        </MDBBtn>
                    </span>
                </div>
                <div className="p-0 card-body rounded-0 shadow-0 bg-dark" style={{ height: '86vh', overflowY: 'scroll' }}>
                    <div className="bg-warning d-flex justify-content-center" ref={scale} style={{scale:'1'}}>
                        <div id="doc-container" className="my-3 position-relative">
                            <div id="doc1" className="bg-white mb-3">
                                <canvas id="canvas1" className="bg-info"  height={842} width={595}></canvas>
                                <div className="pdf-components">
                                <span style={{ left: '0px', top: '0px', position: 'absolute', cursor: 'move' }}>Label</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div className="col-md-2">
            <div className="card rounded-0 shadow-0 border border-danger">
                <div className="card-header py-1">
                    <span className="card-title h4">Properties</span>
                </div>
                <div className="card-body">
                    <div className="row g-0">

                    </div>
                </div>
            </div>
        </div>
    </div>
</>)
</code>```

}
I want zoom functionality as shown in this https://mozilla.github.io/pdf.js/web/viewer.html
consider document is as my inner div.

Body:
I want to add zoom in/out functionality in the middle div (yellow are as shown in fig) the content inside the inner div should increase in size while zoom.

const DocContainer = () => {

const scale = useRef() as React.MutableRefObject<HTMLDivElement>;

let scale1 = 1;
const handleZoomIn = () => {

    let zoomScale = Math.round(parseFloat(scale.current.style.scale) * 100);
    if (zoomScale == 200)
        return;
    scale.current.style.scale = (parseFloat(scale.current.style.scale) + 0.05).toString();
    let elem = document.getElementById('txtZoomVal') as HTMLInputElement;
    elem.value = Math.round(parseFloat(scale.current.style.scale) * 100) + '%';

    console.log(scale);
    console.log(scale.current.getBoundingClientRect());
}
const handleZoomOut = () => {
    let zoomScale = Math.round(parseFloat(scale.current.style.scale) * 100);
    if (zoomScale == 50)
        return;
    scale.current.style.scale = (parseFloat(scale.current.style.scale) - 0.05).toString();
    let elem = document.getElementById('txtZoomVal') as HTMLInputElement;
    elem.value = Math.round(parseFloat(scale.current.style.scale) * 100) + '%';
}

return (<>

                    Components

                    <MDBListGroup light>
                        <MDBListGroupItem tag='button' action type='button' className='px-3'>
                            <MDBIcon className="me-2 fa fa-tag"></MDBIcon>
                             Label
                        </MDBListGroupItem>
                        <MDBListGroupItem tag='button' action type='button' className='px-3'>
                            <MDBIcon className="me-2 fa fa-pen-to-square"></MDBIcon>
                            Input
                        </MDBListGroupItem>
                        <MDBListGroupItem tag='button' action type='button' className='px-3'>
                            <MDBIcon className="me-2 fa fa-table"></MDBIcon>
                            Table
                        </MDBListGroupItem>
                        <MDBListGroupItem tag='button' action type='button' className='px-3'>
                            <MDBIcon className="me-2 fa fa-grip-lines"></MDBIcon>
                            H-Line
                        </MDBListGroupItem>
                        <MDBListGroupItem tag='button' action type='button' className='px-3'>
                            <MDBIcon className="me-3 fa fa-grip-lines-vertical"></MDBIcon>
                            V-Line
                        </MDBListGroupItem>
                        <MDBListGroupItem tag='button' action type='button' className='px-3'>
                            <MDBIcon className="me-2 fa fa-image"></MDBIcon>
                            Image
                        </MDBListGroupItem>
                    </MDBListGroup>

                        <MDBBtn className="p-2">
                            <MDBIcon className="me-2 fa fa-square-plus"></MDBIcon>Add Page
                        </MDBBtn>

                        <MDBBtn className="p-2">
                            <MDBIcon className="me-2 fa fa-border-all"></MDBIcon>Set Margin
                        </MDBBtn>

                        <MDBBtn className="p-2" onClick={handleZoomIn}>
                            <MDBIcon className="me-2 fa fa-plus"></MDBIcon> Zoom In
                        </MDBBtn>

                        <input id="txtZoomVal" type="text" readOnly title="zoom value" value={parseFloat(scale.current?.style.scale ?? 1) * 100 + '%'} style={{ width: '50px' }}></input>

                        <MDBBtn className="p-2" onClick={handleZoomOut}>
                            <MDBIcon className="me-2 fa fa-minus"></MDBIcon> Zoom Out
                        </MDBBtn>

                                <canvas id="canvas1" className="bg-info"  height={842} width={595}></canvas>

                                Label

                    Properties

</>)

}
I want zoom functionality as shown in this https://mozilla.github.io/pdf.js/web/viewer.html
consider document is as my inner div.


问:
Duplicate data after using update_or_create
In my project I retrieve data from an API that I save on my database created in parallel, the problem is that the initial data is duplicated each time I refresh the page that executes the API

models.py

```<code>class Empl(models.Model):
    code=models.CharField(max_length=10,blank=True,null=True)
    age=models.CharField(max_length=255,blank=True,null=True)
    service=models.CharField(max_length=255,blank=True,null=True)
</code>```

views.py

```<code>url='http://myAPI/Empl/GetEmpl'
x=requests.get(url)
content=x.json()
for data in content:
    emp , _ = Empl.objects.update_or_create(code=data['code'],age=data['age'],service=data['service'])
    emp.save()
</code>```

At the level of my project when I look for an employee on the search bar, several employees with the same data. And this every time I refresh the page that executes the API, the initial data is duplicated and so on.
Oddly when I perform a filter on an employee through her code in Mysql Base I get a single tuple, I don't understand?

Body:
In my project I retrieve data from an API that I save on my database created in parallel, the problem is that the initial data is duplicated each time I refresh the page that executes the API

models.py

class Empl(models.Model):
    code=models.CharField(max_length=10,blank=True,null=True)
    age=models.CharField(max_length=255,blank=True,null=True)
    service=models.CharField(max_length=255,blank=True,null=True)

views.py

url='http://myAPI/Empl/GetEmpl'
x=requests.get(url)
content=x.json()
for data in content:
    emp , _ = Empl.objects.update_or_create(code=data['code'],age=data['age'],service=data['service'])
    emp.save()

At the level of my project when I look for an employee on the search bar, several employees with the same data. And this every time I refresh the page that executes the API, the initial data is duplicated and so on.
Oddly when I perform a filter on an employee through her code in Mysql Base I get a single tuple, I don't understand?


问:
State of a Web application
im wondering how can i save the state of a web application during a session?

i have a functioning java code , but it dont dave the state of the web app when i restart it!

@Controller
@SessionAttributes("character")
public class CreationController {

```<code>@ModelAttribute
public CharacterInfo characterInfo(){
    return new CharacterInfo("character");
}
</code>```

}

Expected: the inputs in the frontend are saved!

Title: State of a Web application

Body:
im wondering how can i save the state of a web application during a session?

i have a functioning java code , but it dont dave the state of the web app when i restart it!

@Controller
@SessionAttributes("character")
public class CreationController {

@ModelAttribute
public CharacterInfo characterInfo(){
    return new CharacterInfo("character");
}

}

Expected: the inputs in the frontend are saved!


问:
merge two list of dfs into list of dfs first by dfs name, than by columnname R
I do have two lists of a dataframe extract2_HW and extract_hw_help.
I used to bind both list of dfs by rbind_labelled (rdhs library), similar to rbind. Afterwards I preformed an merge by:

```<code>Results <- merge(comb_extract_hw_help,
                              comb_extract_HW,  by.x = c("hhid", "hvidx", "SurveyId"),
                              by.y =c("hwhhid", "hwline", "SurveyId"), all.x = TRUE)
</code>```

However, I would prefer to contain the lists structure and want to first merge the two lists by dataframe names (SurveyId) and afterwards preform a join like:

```<code>Results <- merge(`extract_hw_help[[corresponding names]]`,
                                  `extract2_HW[[corresponding names]]`,  by.x = c("hhid","hvidx"),
                                  by.y =c("hwhhid", "hwline"), all.x = TRUE)
</code>```

Where the corresponding names are Equal to the SurveyID .The Ouput should be a list of dataframes of SurveyIDs, where the different dfs of the lists are merged.
How could I do that?
Some example dput

```<code>dput(extract2_hw_help[[1]][1:2,1:20])
structure(list(hhid = c("        1 17", "        1 17"), hvidx = c(1,
2), hv001 = c(1, 1), hv002 = c(17, 17), hv005 = c(1894033, 1894033
), hv006 = c(11, 11), hv007 = c(1997, 1997), hv021 = c(1, 1),
    hv023 = structure(c(5, 5), label = "Sample domain", format.spss = "F2.0", display_width = 5L, labels = c(`Tigray - rural` = 1,
    `Tigray - urban` = 2, `Afar - rural` = 3, `Afar - urban` = 4,
    `Amhara - rural` = 5, `Amhara - urban` = 6, `Oromiya - rural` = 7,
    `Oromiya - urban` = 8, `Somali - rural` = 9, `Somali - urban` = 10,
    `Ben-Gumz - rural` = 11, `Ben-Gumz - urban` = 12, `SNNP - rural` = 13,
    `SNNP - urban` = 14, `Gambela - rural` = 15, `Gambela - urban` = 16,
    `Harari - rural` = 17, `Harari - urban` = 18, `Addis Ababa - rural` = 19,
    `Addis Ababa - urban` = 20, `Dire Dawa - rural` = 21, `Dire Dawa - urban` = 22
    ), class = c("haven_labelled", "vctrs_vctr", "double")),
    hv024 = structure(c(3, 3), label = "Region", format.spss = "F2.0", display_width = 5L, labels = c(Tigray = 1,
    Afar = 2, Amhara = 3, Oromiya = 4, Somali = 5, `Ben-Gumz` = 6,
    SNNP = 7, Gambela = 12, Harari = 13, `Addis Abeba` = 14,
    `Dire Dawa` = 15), class = c("haven_labelled", "vctrs_vctr",
    "double")), hv025 = structure(c(2, 2), label = "Type of place of residence", format.spss = "F1.0", display_width = 5L, labels = c(Urban = 1,
    Rural = 2), class = c("haven_labelled", "vctrs_vctr", "double"
    )), hv103 = structure(c(1, 1), label = "Slept last night", na_values = 9, format.spss = "F1.0", display_width = 5L, labels = c(No = 0,
    Yes = 1), class = c("haven_labelled_spss", "haven_labelled",
    "vctrs_vctr", "double")), hc1 = c(NA_real_, NA_real_), CLUSTER = c(1,
    1), ALT_DEM = c(2314L, 2314L), LATNUM = c(10.889096, 10.889096
    ), LONGNUM = c(37.269565, 37.269565), ADM1NAME = c("amhara",
    "amhara"), DHSREGNA = c("amhara", "amhara"), SurveyId = c("ET2005DHS",
    "ET2005DHS")), row.names = 1:2, class = "data.frame")
> dput(extract2_HW[[1]][1:2,1:7])
structure(list(hwhhid = structure(c("        1 17", "        1 32"
), label = "case identification", format.stata = "%12s"), hwline = structure(c(4,
7), label = "line", format.stata = "%8.0g"), hwlevel = structure(c(1,
1), label = "data from hh or individual", format.stata = "%8.0g", labels = c(`from household` = 1,
`from individual questionnaire` = 2), class = c("haven_labelled",
"vctrs_vctr", "double")), hc70 = structure(c(-121, -212), label = "ht/a standard deviations (according to who)", format.stata = "%8.0g", labels = c(`height out of plausible limits` = 9996,
`age in days out of plausible limits` = 9997, `flagged cases` = 9998
), class = c("haven_labelled", "vctrs_vctr", "double")), hc71 = structure(c(-54,
-331), label = "wt/a standard deviations (according to who)", format.stata = "%8.0g", labels = c(`height out of plausible limits` = 9996,
`age in days out of plausible limits` = 9997, `flagged cases` = 9998
), class = c("haven_labelled", "vctrs_vctr", "double")), hc72 = structure(c(0,
-319), label = "wt/ht standard deviations (according to who)", format.stata = "%8.0g", labels = c(`height out of plausible limits` = 9996,
`age in days out of plausible limits` = 9997, `flagged cases` = 9998
), class = c("haven_labelled", "vctrs_vctr", "double")), hc73 = structure(c(26,
-312), label = "bmi standard deviations (according to who)", format.stata = "%8.0g", labels = c(`height out of plausible limits` = 9996,
`age in days out of plausible limits` = 9997, `flagged cases` = 9998
), class = c("haven_labelled", "vctrs_vctr", "double"))), row.names = c(NA,
-2L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

Body:
I do have two lists of a dataframe extract2_HW and extract_hw_help.
I used to bind both list of dfs by rbind_labelled (rdhs library), similar to rbind. Afterwards I preformed an merge by:

Results <- merge(comb_extract_hw_help,
                              comb_extract_HW,  by.x = c("hhid", "hvidx", "SurveyId"),
                              by.y =c("hwhhid", "hwline", "SurveyId"), all.x = TRUE)

However, I would prefer to contain the lists structure and want to first merge the two lists by dataframe names (SurveyId) and afterwards preform a join like:

Results <- merge(`extract_hw_help[[corresponding names]]`,
                                  `extract2_HW[[corresponding names]]`,  by.x = c("hhid","hvidx"),
                                  by.y =c("hwhhid", "hwline"), all.x = TRUE)

Where the corresponding names are Equal to the SurveyID .The Ouput should be a list of dataframes of SurveyIDs, where the different dfs of the lists are merged.
How could I do that?
Some example dput

dput(extract2_hw_help[[1]][1:2,1:20])
structure(list(hhid = c("        1 17", "        1 17"), hvidx = c(1,
2), hv001 = c(1, 1), hv002 = c(17, 17), hv005 = c(1894033, 1894033
), hv006 = c(11, 11), hv007 = c(1997, 1997), hv021 = c(1, 1),
    hv023 = structure(c(5, 5), label = "Sample domain", format.spss = "F2.0", display_width = 5L, labels = c(`Tigray - rural` = 1,
    `Tigray - urban` = 2, `Afar - rural` = 3, `Afar - urban` = 4,
    `Amhara - rural` = 5, `Amhara - urban` = 6, `Oromiya - rural` = 7,
    `Oromiya - urban` = 8, `Somali - rural` = 9, `Somali - urban` = 10,
    `Ben-Gumz - rural` = 11, `Ben-Gumz - urban` = 12, `SNNP - rural` = 13,
    `SNNP - urban` = 14, `Gambela - rural` = 15, `Gambela - urban` = 16,
    `Harari - rural` = 17, `Harari - urban` = 18, `Addis Ababa - rural` = 19,
    `Addis Ababa - urban` = 20, `Dire Dawa - rural` = 21, `Dire Dawa - urban` = 22
    ), class = c("haven_labelled", "vctrs_vctr", "double")),
    hv024 = structure(c(3, 3), label = "Region", format.spss = "F2.0", display_width = 5L, labels = c(Tigray = 1,
    Afar = 2, Amhara = 3, Oromiya = 4, Somali = 5, `Ben-Gumz` = 6,
    SNNP = 7, Gambela = 12, Harari = 13, `Addis Abeba` = 14,
    `Dire Dawa` = 15), class = c("haven_labelled", "vctrs_vctr",
    "double")), hv025 = structure(c(2, 2), label = "Type of place of residence", format.spss = "F1.0", display_width = 5L, labels = c(Urban = 1,
    Rural = 2), class = c("haven_labelled", "vctrs_vctr", "double"
    )), hv103 = structure(c(1, 1), label = "Slept last night", na_values = 9, format.spss = "F1.0", display_width = 5L, labels = c(No = 0,
    Yes = 1), class = c("haven_labelled_spss", "haven_labelled",
    "vctrs_vctr", "double")), hc1 = c(NA_real_, NA_real_), CLUSTER = c(1,
    1), ALT_DEM = c(2314L, 2314L), LATNUM = c(10.889096, 10.889096
    ), LONGNUM = c(37.269565, 37.269565), ADM1NAME = c("amhara",
    "amhara"), DHSREGNA = c("amhara", "amhara"), SurveyId = c("ET2005DHS",
    "ET2005DHS")), row.names = 1:2, class = "data.frame")
> dput(extract2_HW[[1]][1:2,1:7])
structure(list(hwhhid = structure(c("        1 17", "        1 32"
), label = "case identification", format.stata = "%12s"), hwline = structure(c(4,
7), label = "line", format.stata = "%8.0g"), hwlevel = structure(c(1,
1), label = "data from hh or individual", format.stata = "%8.0g", labels = c(`from household` = 1,
`from individual questionnaire` = 2), class = c("haven_labelled",
"vctrs_vctr", "double")), hc70 = structure(c(-121, -212), label = "ht/a standard deviations (according to who)", format.stata = "%8.0g", labels = c(`height out of plausible limits` = 9996,
`age in days out of plausible limits` = 9997, `flagged cases` = 9998
), class = c("haven_labelled", "vctrs_vctr", "double")), hc71 = structure(c(-54,
-331), label = "wt/a standard deviations (according to who)", format.stata = "%8.0g", labels = c(`height out of plausible limits` = 9996,
`age in days out of plausible limits` = 9997, `flagged cases` = 9998
), class = c("haven_labelled", "vctrs_vctr", "double")), hc72 = structure(c(0,
-319), label = "wt/ht standard deviations (according to who)", format.stata = "%8.0g", labels = c(`height out of plausible limits` = 9996,
`age in days out of plausible limits` = 9997, `flagged cases` = 9998
), class = c("haven_labelled", "vctrs_vctr", "double")), hc73 = structure(c(26,
-312), label = "bmi standard deviations (according to who)", format.stata = "%8.0g", labels = c(`height out of plausible limits` = 9996,
`age in days out of plausible limits` = 9997, `flagged cases` = 9998
), class = c("haven_labelled", "vctrs_vctr", "double"))), row.names = c(NA,
-2L), class = c("tbl_df", "tbl", "data.frame"))


问:
CosmosDB Emulator - Losing data after deleting Docker Container
I am building a CosmosDB Emulator container via a docker-compose.yml file.

```<code>version: '3.4'

services:
  cosmosdb:
    container_name: cosmosdb
    image: "mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest"
    tty: true
    mem_limit: 2G
    cpu_count: 2
    environment:
      - AZURE_COSMOS_EMULATOR_PARTITION_COUNT=10
      - AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE=true
    ports:
      - '8081:8081'
      #- '8900:8900'
      #- '8901:8901'
      #- '8902:8902'
      #- '10250:10250'
      #- '10251:10251'
      #- '10252:10252'
      #- '10253:10253'
      #- '10254:10254'
      #- '10255:10255'
      #- '10256:10256'
      #- '10350:10350'
    volumes:
       - vol_cosmos:/data/db

volumes:
  vol_cosmos:
</code>```

I then generate some data in it via the CosmosDB Emulator Explorer. However, if I delete the container I lose all the data, even though the container uses the specified volume, and the volume is not deleted ever.

Either I don't understand how volumes work, or something else is wrong, but I am looking for a way to persists the data even after deleting the container. A new one should just use the volume with the specified name if it exists, or create a new one if it doesn't, right?

The data stays intact after container and/or OS restarts. It just doesn't persist after deleting the container.

Body:
I am building a CosmosDB Emulator container via a docker-compose.yml file.

version: '3.4'

services:
  cosmosdb:
    container_name: cosmosdb
    image: "mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest"
    tty: true
    mem_limit: 2G
    cpu_count: 2
    environment:
      - AZURE_COSMOS_EMULATOR_PARTITION_COUNT=10
      - AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE=true
    ports:
      - '8081:8081'
      #- '8900:8900'
      #- '8901:8901'
      #- '8902:8902'
      #- '10250:10250'
      #- '10251:10251'
      #- '10252:10252'
      #- '10253:10253'
      #- '10254:10254'
      #- '10255:10255'
      #- '10256:10256'
      #- '10350:10350'
    volumes:
       - vol_cosmos:/data/db

volumes:
  vol_cosmos:

I then generate some data in it via the CosmosDB Emulator Explorer. However, if I delete the container I lose all the data, even though the container uses the specified volume, and the volume is not deleted ever.

Either I don't understand how volumes work, or something else is wrong, but I am looking for a way to persists the data even after deleting the container. A new one should just use the volume with the specified name if it exists, or create a new one if it doesn't, right?

The data stays intact after container and/or OS restarts. It just doesn't persist after deleting the container.


问:
Cannot assign variables inside backtracking base condition
I want to implement a backtrack algorithm to find a minimum hamiltonian path, but I ran into a question: why I cannot assign a variable to a value inside the "if" in the code below?

```<code>cycle = [0]
start = 0
visited = set()
num_nodes = graph.number_of_nodes()

def backtrack(u, total_distance, shortest_distance):
    if len(cycle) == num_nodes and u == 0 and total_distance < shortest_distance:
        shortest_distance = total_distance ## CANNOT ASSIGN
        return

    # for all neighbours
    for v in range(num_nodes):
        if u != v and v not in visited:
            cycle.append(v)
            visited.add(v)
            total_distance += graph[u][v]['distance']

            backtrack(v, total_distance)

            cycle.pop()
            visited.remove(v)
            total_distance -= graph[u][v]['distance']

backtrack(start, 0, float('inf'))
</code>```

You can easily solve this by saving all minimum distances in a globally defined array, but what I didn't understand is why I cannot do like that: shortest_distance = total_distance?

Body:
I want to implement a backtrack algorithm to find a minimum hamiltonian path, but I ran into a question: why I cannot assign a variable to a value inside the "if" in the code below?

cycle = [0]
start = 0
visited = set()
num_nodes = graph.number_of_nodes()

def backtrack(u, total_distance, shortest_distance):
    if len(cycle) == num_nodes and u == 0 and total_distance < shortest_distance:
        shortest_distance = total_distance ## CANNOT ASSIGN
        return

    # for all neighbours
    for v in range(num_nodes):
        if u != v and v not in visited:
            cycle.append(v)
            visited.add(v)
            total_distance += graph[u][v]['distance']

            backtrack(v, total_distance)

            cycle.pop()
            visited.remove(v)
            total_distance -= graph[u][v]['distance']

backtrack(start, 0, float('inf'))

You can easily solve this by saving all minimum distances in a globally defined array, but what I didn't understand is why I cannot do like that: shortest_distance = total_distance?


问:
Can I use AJAX or Fetch API to my backend, then use the backend to redirect to nginx to fetch data then send back data to the frontend?
I need to fetch private images uploaded by users. Each user has his private images.
For that I plan to use nginx X-Accel.

But I also need to validate the request in my backend before that to check if the user is allowed to fetch these images (with PHP, Laravel)

I initiate the fetch call using AJAX or Fetch API from my frontend.

It means that the flow would look like that:

Fetch/AJAX call from frontend -> backend validation with PHP -> use nginx X-Accel to get protected images -> send images back to frontend

Is such flow even possible? Or I am doing it wrong?


问:
pdf() function not producing an output
I am trying to save a ggplot figure as a pdf, or even png, any way to save a figure as a file will do, but when i run it there does not a ppear to be any pdf made or any other form of output. There are no error signals and the code appears in the console, juut nothing happens.

I've tried both pdf and png, i've used dev.off() and have also used print(penguinplot1) as its a ggplot.

input
#save figure as a vector so as not to compromise resolution
pdf("penguinplot1.pdf")
print(penguinplot1)
penguinplot1
dev.off()

output

```<code>> #save figure as a vector so as not to compromise resolution
> pdf("penguinplot1.pdf")
> print(penguinplot1)
`geom_smooth()` using formula = 'y ~ x'
> penguinplot1
`geom_smooth()` using formula = 'y ~ x'
> dev.off()
pdf
  3
</code>```

Title: pdf() function not producing an output

Body:
I am trying to save a ggplot figure as a pdf, or even png, any way to save a figure as a file will do, but when i run it there does not a ppear to be any pdf made or any other form of output. There are no error signals and the code appears in the console, juut nothing happens.

I've tried both pdf and png, i've used dev.off() and have also used print(penguinplot1) as its a ggplot.

input
#save figure as a vector so as not to compromise resolution
pdf("penguinplot1.pdf")
print(penguinplot1)
penguinplot1
dev.off()

output

> #save figure as a vector so as not to compromise resolution
> pdf("penguinplot1.pdf")
> print(penguinplot1)
`geom_smooth()` using formula = 'y ~ x'
> penguinplot1
`geom_smooth()` using formula = 'y ~ x'
> dev.off()
pdf
  3


问:
can not publish config.json under angular application domain
I need to publish my config.json file with angular.json under my application domain. config.json is located in src folder. I expose one of my module as mfe, which uses this config.json, i have not access to that file in shell, so i need this file to be available from shell.

i tried to publish it as styles, in angular.json i wrote
{
input: path to the file,
bundleName: any name,
inject: false,
}
but that does not works. i get cors error when i make a request, because it is not hosted.


问:
Quoting an external stage pathname
I need to query data from an external stage @s3data in the prefix runs/2022/12/01/15:33:03. However, if I run this query in Snowflake, it returns 0 results:

SELECT * FROM @s3data/runs/2022/12/01/15:33:03/
```
<p>But if I run this, I can see all the files with key prefix <code>runs/2022/12/01/15:33:03/</code>:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT * FROM @s3data/runs/2022/12/01/
</code>```

Apparently, Snowflake does not like the 15:33:03 part of the name. Is there some way to "quote" this name in order to allow Snowflake to read from specifically that prefix?

Title: Quoting an external stage pathname

Body:
I need to query data from an external stage @s3data in the prefix runs/2022/12/01/15:33:03. However, if I run this query in Snowflake, it returns 0 results:

SELECT * FROM @s3data/runs/2022/12/01/15:33:03/

But if I run this, I can see all the files with key prefix runs/2022/12/01/15:33:03/:

SELECT * FROM @s3data/runs/2022/12/01/

Apparently, Snowflake does not like the 15:33:03 part of the name. Is there some way to "quote" this name in order to allow Snowflake to read from specifically that prefix?


问:
Seaborn implicitly adds legend to graph, but only sometimes
I have two functions which convert Pandas dataFrames into graphs using Seaborn. First one works, the second one does not, and they are virtually the same.

Here is the first one:

This is how my first dataFrame, vis, looks like:

Here it is by using vis.head(16).to_clipboard(sep=',', index=True)

```<code>,region,Viditeľnosť,Počet
0,JHC,v noci - nezhoršená,4863
1,PHA,v noci - nezhoršená,20459
2,PLK,v noci - nezhoršená,5144
3,STC,v noci - nezhoršená,22586
4,JHC,v noci - zhoršená,683
5,PHA,v noci - zhoršená,1102
6,PLK,v noci - zhoršená,607
7,STC,v noci - zhoršená,2226
8,JHC,ve dne - nezhoršená,18452
9,PHA,ve dne - nezhoršená,95753
10,PLK,ve dne - nezhoršená,14899
11,STC,ve dne - nezhoršená,55308
12,JHC,ve dne - zhoršená,1989
13,PHA,ve dne - zhoršená,7254
14,PLK,ve dne - zhoršená,1701
15,STC,ve dne - zhoršená,8196
</code>```

And here is the code to render its graph:

```<code>ax = sns.catplot(x='region', hue='region', y='Počet',col='Viditeľnosť', data=vis, kind='bar', palette='hls',col_wrap=2,sharex=False, dodge=False)

for axis in ax.axes:
    axis.bar_label(axis.containers[0])
    axis.bar_label(axis.containers[1])
    axis.bar_label(axis.containers[2])
    axis.bar_label(axis.containers[3])
    axis.set_xlabel('Kraj')

ax.fig.tight_layout()
ax.add_legend()
</code>```

The resulting graph looks like this (and if I don't use add_legend, no legend is added to the graph):

Then there's a second graph, its dataFrame, vis, looks like this:

The code to render a graph from it is this:

```<code>ax = sns.catplot(x='month', hue='Druh srážky', y='Počet',col='region', data=dir, kind='bar', palette='hls',col_wrap=2,sharex=False)
ax.set_titles(col_template="Kraj: {col_name}")
ax.fig.tight_layout()
ax.add_legend()
</code>```

The resulting graph looks like this - it has its legend doubled for no apparent reason:

Why is this happening? The two graphs are both a catplot, yet the first one does not add a legend implicitly, while the second does. How do I fix this?

Body:
I have two functions which convert Pandas dataFrames into graphs using Seaborn. First one works, the second one does not, and they are virtually the same.

Here is the first one:

This is how my first dataFrame, vis, looks like:

Here it is by using vis.head(16).to_clipboard(sep=',', index=True)

,region,Viditeľnosť,Počet
0,JHC,v noci - nezhoršená,4863
1,PHA,v noci - nezhoršená,20459
2,PLK,v noci - nezhoršená,5144
3,STC,v noci - nezhoršená,22586
4,JHC,v noci - zhoršená,683
5,PHA,v noci - zhoršená,1102
6,PLK,v noci - zhoršená,607
7,STC,v noci - zhoršená,2226
8,JHC,ve dne - nezhoršená,18452
9,PHA,ve dne - nezhoršená,95753
10,PLK,ve dne - nezhoršená,14899
11,STC,ve dne - nezhoršená,55308
12,JHC,ve dne - zhoršená,1989
13,PHA,ve dne - zhoršená,7254
14,PLK,ve dne - zhoršená,1701
15,STC,ve dne - zhoršená,8196

And here is the code to render its graph:

ax = sns.catplot(x='region', hue='region', y='Počet',col='Viditeľnosť', data=vis, kind='bar', palette='hls',col_wrap=2,sharex=False, dodge=False)

for axis in ax.axes:
    axis.bar_label(axis.containers[0])
    axis.bar_label(axis.containers[1])
    axis.bar_label(axis.containers[2])
    axis.bar_label(axis.containers[3])
    axis.set_xlabel('Kraj')

ax.fig.tight_layout()
ax.add_legend()

The resulting graph looks like this (and if I don't use add_legend, no legend is added to the graph):

Then there's a second graph, its dataFrame, vis, looks like this:

The code to render a graph from it is this:

ax = sns.catplot(x='month', hue='Druh srážky', y='Počet',col='region', data=dir, kind='bar', palette='hls',col_wrap=2,sharex=False)
ax.set_titles(col_template="Kraj: {col_name}")
ax.fig.tight_layout()
ax.add_legend()

The resulting graph looks like this - it has its legend doubled for no apparent reason:

Why is this happening? The two graphs are both a catplot, yet the first one does not add a legend implicitly, while the second does. How do I fix this?


问:
Check if one row of an array is present in another array and if so, extract the array
So I have two large Numpy arrays. One array has size [6, ~1000000] and the other array is [6, ~900000]. My arrays have rows which are identical but I don't know which ones. I want to find out which rows are identical in each array and then either extract the rows or obtain their index.

I have tried a few things. If my arrays are called g_data and p_data then I have tried:

```<code>(g_data==p_data[:,None]).all(-1).any()
</code>```

but I get the error:

```<code>Python: AttributeError: 'bool' object has no attribute 'all'
</code>```

I have also tried

```<code>check = any(map(lambda x: x in g_data, p_data))
</code>```

however this just returns a single 'True'. I think it is more difficult as the two arrays don't have the same size. I would like to either extract the identical rows to a new matrix or at least have the index of the identical rows. Please help! I'm not interested in performance so even a slow solution doesn't matter if it works.

Thanks in advance.

Body:
So I have two large Numpy arrays. One array has size [6, ~1000000] and the other array is [6, ~900000]. My arrays have rows which are identical but I don't know which ones. I want to find out which rows are identical in each array and then either extract the rows or obtain their index.

I have tried a few things. If my arrays are called g_data and p_data then I have tried:

(g_data==p_data[:,None]).all(-1).any()

but I get the error:

Python: AttributeError: 'bool' object has no attribute 'all'

I have also tried

check = any(map(lambda x: x in g_data, p_data))

however this just returns a single 'True'. I think it is more difficult as the two arrays don't have the same size. I would like to either extract the identical rows to a new matrix or at least have the index of the identical rows. Please help! I'm not interested in performance so even a slow solution doesn't matter if it works.

Thanks in advance.


问:
How to optimize the function query
I have a query that has an index on the where clause column, but MySQL doesn't pick up the index; I'm not sure what the issue is. Is there any way to optimize this query?

```<code>SELECT
  cart_medicine_detail._id AS _id,
  cart_medicine_detail.cartId AS cartId,
  cart_medicine_detail.medicineId AS medicineId,
  cart_medicine_detail.distributorId AS distributorId,
  cart_medicine_detail.quantity AS quantity,
  cart_medicine_detail.name AS name,
  cart_medicine_detail.itemCode AS itemCode,
  cart_medicine_detail.dealType AS dealType,
  cart_medicine_detail.reason AS reason,
  cart_medicine_detail.isDeleted AS isDeleted,
  cart_medicine_detail.actualPrice AS actualPrice,
  cart_medicine_detail.source AS source,
  from_unixtime(
    (
      cart_medicine_detail.createdTimestamp / 1000
    )
  ) AS createdTimestamp,
  from_unixtime(
    (
      cart_medicine_detail.updatedTimestamp / 1000
    )
  ) AS updatedTimestamp,
  cart_medicine_detail.medicineCategory AS medicineCategory,
  cart_medicine_detail.medicineSubCategory AS medicineSubCategory
FROM
  saveo_prod.cart_medicine_detail
WHERE
  cart_medicine_detail.createdTimestamp >= unix_timestamp(
    date_add(
      now(6),
      INTERVAL -7 day
    )
  )
</code>```

explain plan

```<code>*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: cart_medicine_detail
   partitions: NULL
         type: ALL
possible_keys: idx_createdTimestamp
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 12031730
     filtered: 50.00
        Extra: Using where
</code>```

Please  share your thoughts; it would be helpful for a large amount of data.

Title: How to optimize the function query

Body:
I have a query that has an index on the where clause column, but MySQL doesn't pick up the index; I'm not sure what the issue is. Is there any way to optimize this query?

SELECT
  cart_medicine_detail._id AS _id,
  cart_medicine_detail.cartId AS cartId,
  cart_medicine_detail.medicineId AS medicineId,
  cart_medicine_detail.distributorId AS distributorId,
  cart_medicine_detail.quantity AS quantity,
  cart_medicine_detail.name AS name,
  cart_medicine_detail.itemCode AS itemCode,
  cart_medicine_detail.dealType AS dealType,
  cart_medicine_detail.reason AS reason,
  cart_medicine_detail.isDeleted AS isDeleted,
  cart_medicine_detail.actualPrice AS actualPrice,
  cart_medicine_detail.source AS source,
  from_unixtime(
    (
      cart_medicine_detail.createdTimestamp / 1000
    )
  ) AS createdTimestamp,
  from_unixtime(
    (
      cart_medicine_detail.updatedTimestamp / 1000
    )
  ) AS updatedTimestamp,
  cart_medicine_detail.medicineCategory AS medicineCategory,
  cart_medicine_detail.medicineSubCategory AS medicineSubCategory
FROM
  saveo_prod.cart_medicine_detail
WHERE
  cart_medicine_detail.createdTimestamp >= unix_timestamp(
    date_add(
      now(6),
      INTERVAL -7 day
    )
  )

explain plan

*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: cart_medicine_detail
   partitions: NULL
         type: ALL
possible_keys: idx_createdTimestamp
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 12031730
     filtered: 50.00
        Extra: Using where

Please  share your thoughts; it would be helpful for a large amount of data.


问:
Connecting to AWS Document DB (MongoDB) with rails mongoid
I am trying to connect to AWS Document DB (MongoDB) in rails using "mongoid" gem (7.5.1) which internally uses mongo gem (2.18)

```<code>dev:
  clients:
    default:
      database: my_database_name
      hosts:
        - docdb.dev.mysite.internal:27017
      options:
        read:
          mode: :primary
        auth_mech: :aws
        max_pool_size: 1
</code>```

I followed the documentation for both mongoid and mongo gem and they have mandated to use auth_mechanism as "aws" when we want to provide authentication credentials using AWS IAM.
With the above config/mongoid.yml , when I try to connect , getting below error

```<code>User  (mechanism: aws) is not authorized to access my_database_name (auth source: $external, used mechanism: MONGODB-AWS, used server: docdb.dev.mysite.internal:27017 (PRIMARY)): [73]:
Invalid character $ in database name: $external (modern retry, attempt 1) (Mongo::Auth::Unauthorized)
</code>```

Seems like when auth_mech is set to aws, mongo gem sets the auth_source as $external. Based on the documentation here https://www.mongodb.com/docs/ruby-driver/current/reference/authentication/#authentication-mechanisms , auth source is the database where users authentication credentials are stored.

Please suggest the way to make it work.

Body:
I am trying to connect to AWS Document DB (MongoDB) in rails using "mongoid" gem (7.5.1) which internally uses mongo gem (2.18)

dev:
  clients:
    default:
      database: my_database_name
      hosts:
        - docdb.dev.mysite.internal:27017
      options:
        read:
          mode: :primary
        auth_mech: :aws
        max_pool_size: 1

I followed the documentation for both mongoid and mongo gem and they have mandated to use auth_mechanism as "aws" when we want to provide authentication credentials using AWS IAM.
With the above config/mongoid.yml , when I try to connect , getting below error

User  (mechanism: aws) is not authorized to access my_database_name (auth source: $external, used mechanism: MONGODB-AWS, used server: docdb.dev.mysite.internal:27017 (PRIMARY)): [73]:
Invalid character $ in database name: $external (modern retry, attempt 1) (Mongo::Auth::Unauthorized)

Seems like when auth_mech is set to aws, mongo gem sets the auth_source as $external. Based on the documentation here https://www.mongodb.com/docs/ruby-driver/current/reference/authentication/#authentication-mechanisms , auth source is the database where users authentication credentials are stored.

Please suggest the way to make it work.


问:
How to avoid Firefox `CSP` with violentmonkey script while staying compatible with Tampermonkey
Expecting:

conditionally add // ==UserScript== comments or

other ways to use this script injected into conetnt only if firefox and
Why?

Firefox has CSP issues while using Violentmonkey and the script i'm using.

What works:
//@inject-into content works but my issue occurs when cross compatibility of my script around Tampermonkey & Violentmonkey

Case:

We're looking at a GM API called //@inject-into content which is Violentmonkey API and doesn't exist at this time of writing on Tampermonkey. So,in order to allow //@inject-into content to exist on script, if/else conditions are met. Again i just need my script to get working with Firefox CSP

// ==UserScript==
// @name        com-hCaptcha Captcha Solver by noCaptchaAi
// @inject-into content
// ==/UserScript==
```
<p>How to achieve  something like this? Also i gu</p>
<pre class="lang-js prettyprint-override"><code>// ==UserScript==
// @name        com-hCaptcha Captcha Solver by noCaptchaAi

if(if_Violentmonkey && if_Firefox){
// @inject-into content
}

// ==/UserScript==
</code>```
```<code>if(if_Violentmonkey && if_Firefox){
// @inject-into content
}
</code>```

Body:
Expecting:

conditionally add // ==UserScript== comments or

other ways to use this script injected into conetnt only if firefox and
Why?

Firefox has CSP issues while using Violentmonkey and the script i'm using.

What works:
//@inject-into content works but my issue occurs when cross compatibility of my script around Tampermonkey & Violentmonkey

Case:

We're looking at a GM API called //@inject-into content which is Violentmonkey API and doesn't exist at this time of writing on Tampermonkey. So,in order to allow //@inject-into content to exist on script, if/else conditions are met. Again i just need my script to get working with Firefox CSP

// ==UserScript==
// @name        com-hCaptcha Captcha Solver by noCaptchaAi
// @inject-into content
// ==/UserScript==

How to achieve  something like this? Also i gu

// ==UserScript==
// @name        com-hCaptcha Captcha Solver by noCaptchaAi

if(if_Violentmonkey && if_Firefox){
// @inject-into content
}

// ==/UserScript==

if(if_Violentmonkey && if_Firefox){
// @inject-into content
}


问:
Frequency count of characters in String for a given start and end index in Java
How to determine the numbers of characters found in a String between a given begin and end index in O(1) time complexity?

There can be a pre-processing step like storing in HashMap which can have O(n) time complexity.

Can anyone suggest how to retrieve the character count using 0(1) time complexity after pre-processing? The O(1) time complexity is for retrieving the count of any input character with a start and end index

Eg: String stackoverflow.
Character count a between index 1 and 6 is 1
Character count o between index 1 and 6 is 1
Character count o between index 7 and 12 is 1
Character count o between index 0 and 12 is 2

All these must be retrieved using 0(1) time complexity.


问:
How to Iterate over PDF field labels using Python?
I'm trying to change a TON of field labels in multiple PDFs by hand currently.
an example would be: "name" -> "Full_name_1"

How can I iterate over every field label, change it if I need to, and then save the pdf with my changes?

I've tried playing with the "PyPDF2" library but it doesn't seem to directly support what I'm trying to achieve.

reader.getFields() gets the fields, but it returns a Dict of them.
How can I update them in-place?

Thanks in advance for any help you can provide. :)


问:
Powershell add user to group only works intermittently
I have dumbed down a script I have.  Basically print out the current groups a user is a member of.  Add them to a group.  Print out the list of the updated group list a user is a member of.  I'm not sure if this is a threading issue or what because it will print out before membership update then after membership update then the group list twice, WITHOUT adding in the new group. See image:

My code is as follows:

```<code>$CopyToUsername='clippy'
write-host 'before membership update'
Get-ADPrincipalGroupMembership $CopyToUsername | select name
get-aduser $CopyToUsername |ForEach {add-adgroupmember -identity 'PlaceholderGroup' -members $_.samaccountname}
write-host 'after membership update'
Get-ADPrincipalGroupMembership $CopyToUsername | select name
</code>```

Body:
I have dumbed down a script I have.  Basically print out the current groups a user is a member of.  Add them to a group.  Print out the list of the updated group list a user is a member of.  I'm not sure if this is a threading issue or what because it will print out before membership update then after membership update then the group list twice, WITHOUT adding in the new group. See image:

My code is as follows:

$CopyToUsername='clippy'
write-host 'before membership update'
Get-ADPrincipalGroupMembership $CopyToUsername | select name
get-aduser $CopyToUsername |ForEach {add-adgroupmember -identity 'PlaceholderGroup' -members $_.samaccountname}
write-host 'after membership update'
Get-ADPrincipalGroupMembership $CopyToUsername | select name


问:
Scaling editable JTextPane
I want to scale the JTextPane for inline text editing. User can zoom/pan the text and double click on a JLabel to edit it. The editor should scale to the current zoom level.

I extended JTextPane and painted by scaling the component graphics. However editing does not work at scale different than 1.

How to scale a editable JTextPane?

Any solutions/pointers would be helpful. Thanks in advance.

I do not find the related question useful.

Following only scales the component and paints at different scale. However editing is not scaled.

```<code>public class ScaledJTextPane extends JTextPane {

      private double scale = 0;

      public ScaledJTextPane () {
        this.scale = 1;
      }

      protected void paintComponent(Graphics g) {
        Graphics2D g2 = null;
        g2 = (Graphics2D) g;
        g2.scale(this.scale, this.scale);

        super.paintComponent(g2);
      }

      public double getScale() {
        return this.scale;
      }

      public boolean setScale(double xscale) {
        boolean status = true;
        status = (xscale != 0.0 && xscale != Float.NaN);
        if (status) this.scale = xscale;

        return status;
      }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Scaling editable JTextPane

Body:
I want to scale the JTextPane for inline text editing. User can zoom/pan the text and double click on a JLabel to edit it. The editor should scale to the current zoom level.

I extended JTextPane and painted by scaling the component graphics. However editing does not work at scale different than 1.

How to scale a editable JTextPane?

Any solutions/pointers would be helpful. Thanks in advance.

I do not find the related question useful.

Following only scales the component and paints at different scale. However editing is not scaled.

public class ScaledJTextPane extends JTextPane {

      private double scale = 0;

      public ScaledJTextPane () {
        this.scale = 1;
      }

      protected void paintComponent(Graphics g) {
        Graphics2D g2 = null;
        g2 = (Graphics2D) g;
        g2.scale(this.scale, this.scale);

        super.paintComponent(g2);
      }

      public double getScale() {
        return this.scale;
      }

      public boolean setScale(double xscale) {
        boolean status = true;
        status = (xscale != 0.0 && xscale != Float.NaN);
        if (status) this.scale = xscale;

        return status;
      }
    }