问:
Problem with certificate and ssl on emulator but works on physical device
The error we get on the emulator is:
java.lang.RuntimeException: LayerFactory.retrieveWmsCapabilities: Unable to open connection and read from service address javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

Even though the app works fine on my physical device.

```<code>layerFactory.createFromWmts(
    "https://tiles.geoservice.dlr.de/service/wmts", // WMTS server URL
    "hillshade",                                    // WMTS layer identifier
    object : LayerFactory.Callback {
        override fun creationSucceeded(factory: LayerFactory, layer: Layer) {
            // Add the finished WMTS layer to the WorldWindow.
            wwd.getLayers().addLayer(layer)
            Log.i("gov.nasa.worldwind", "WMTS layer creation succeeded")
        }

        override fun creationFailed(factory: LayerFactory, layer: Layer, ex: Throwable) {
            // Something went wrong connecting to the WMTS server.
            Log.e("gov.nasa.worldwind", "WMTS layer creation failed", ex)
        }
    }
)
</code>```

Working with nasa worldwind library, using the code as they show in their example.

Body:
The error we get on the emulator is:
java.lang.RuntimeException: LayerFactory.retrieveWmsCapabilities: Unable to open connection and read from service address javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

Even though the app works fine on my physical device.

layerFactory.createFromWmts(
    "https://tiles.geoservice.dlr.de/service/wmts", // WMTS server URL
    "hillshade",                                    // WMTS layer identifier
    object : LayerFactory.Callback {
        override fun creationSucceeded(factory: LayerFactory, layer: Layer) {
            // Add the finished WMTS layer to the WorldWindow.
            wwd.getLayers().addLayer(layer)
            Log.i("gov.nasa.worldwind", "WMTS layer creation succeeded")
        }

        override fun creationFailed(factory: LayerFactory, layer: Layer, ex: Throwable) {
            // Something went wrong connecting to the WMTS server.
            Log.e("gov.nasa.worldwind", "WMTS layer creation failed", ex)
        }
    }
)

Working with nasa worldwind library, using the code as they show in their example.


来源: stackexchange

问:
Convert camelCase to snake_case in Excel
How can I convert (without VBA) a camelCaseString into snake_case_string in Excel?

I only find topics about the reverse :)

Thanks a lot for your help

ContentLicense: CC BY-SA 4.0


问:
How to set AzureDevops Pipeline failure in accordance with jfrog Xray scan report
In AzureDevops server, by using Jfrog Extensions I am able to push our custom built  image to Jfrog Docker-local repo as given below.

```<code>- bash: |
    docker image tag myacr.azurecr.io/${{ parameters.imageName }} myartifactory/docker-repo/${{ parameters.imageName }}
  displayName: 'Tag image for jfrog'

- task: ArtifactoryDocker@1
  inputs:
    command: 'push'
    artifactoryService: 'artifact-sc'
    targetRepo: 'docker-repo'
    imageName: 'myartifactory/digital-docker-repo/${{ parameters.imageName }}'
    collectBuildInfo: true
    buildName: '$(Build.DefinitionName)'
    buildNumber: '$(Build.BuildNumber)'
    includeEnvVars: true
</code>```

Now I am looking for below automated items as part of my same pipeline.

1) The Jfrog Scan result need to be visible in the Pipeline dashboard itself so that developers can easily get the scan result.

2)  The Pipeline Build need to be failed if he scan vulnerabilities are identified and should not proceed to further pipeline tasks

3) How to notify the team with the scanned results in automated way.

4) How to create a report dynamically in the Artifactory and share to the team

Tried with below tasks and didn't help me to achieve the above 4 goals.

```<code>- task: JFrogPublishBuildInfo@1
  inputs:
    artifactoryConnection: 'artifact-sc'
    buildName: '$(Build.DefinitionName)'
    buildNumber: '$(Build.BuildNumber)'
    projectKey: 'xxxxxx'

- task: JFrogBuildScan@1
  inputs:
    xrayConnection: 'xray-sc'
    buildName: '$(Build.DefinitionName)'
    buildNumber: '$(Build.BuildNumber)'
    allowFailBuild: true
    vuln: true
</code>```

Body:
In AzureDevops server, by using Jfrog Extensions I am able to push our custom built  image to Jfrog Docker-local repo as given below.

- bash: |
    docker image tag myacr.azurecr.io/${{ parameters.imageName }} myartifactory/docker-repo/${{ parameters.imageName }}
  displayName: 'Tag image for jfrog'

- task: ArtifactoryDocker@1
  inputs:
    command: 'push'
    artifactoryService: 'artifact-sc'
    targetRepo: 'docker-repo'
    imageName: 'myartifactory/digital-docker-repo/${{ parameters.imageName }}'
    collectBuildInfo: true
    buildName: '$(Build.DefinitionName)'
    buildNumber: '$(Build.BuildNumber)'
    includeEnvVars: true

Now I am looking for below automated items as part of my same pipeline.

1) The Jfrog Scan result need to be visible in the Pipeline dashboard itself so that developers can easily get the scan result.

2)  The Pipeline Build need to be failed if he scan vulnerabilities are identified and should not proceed to further pipeline tasks

3) How to notify the team with the scanned results in automated way.

4) How to create a report dynamically in the Artifactory and share to the team

Tried with below tasks and didn't help me to achieve the above 4 goals.

- task: JFrogPublishBuildInfo@1
  inputs:
    artifactoryConnection: 'artifact-sc'
    buildName: '$(Build.DefinitionName)'
    buildNumber: '$(Build.BuildNumber)'
    projectKey: 'xxxxxx'

- task: JFrogBuildScan@1
  inputs:
    xrayConnection: 'xray-sc'
    buildName: '$(Build.DefinitionName)'
    buildNumber: '$(Build.BuildNumber)'
    allowFailBuild: true
    vuln: true


问:
Clases EmbeddedObject con real swift
I am working with Realm swift
In my case I have these models

```<code>class User: Object {
  @Persisted(primaryKey: true) var _id: ObjectId
  @Persisted var name: String
  @Persisted var books: List<Book>
}

class Book: EmbeddedObject {
  @Persisted var name: String
  @Persisted var edition: String
}
</code>```

Adding a book, but now I want to update the name of that book that I add, in the property @Persisted var books: List

Could you guide me how I can update said element of the List @Persisted var books: List of a specific user?

Title: Clases EmbeddedObject con real swift

Body:
I am working with Realm swift
In my case I have these models

class User: Object {
  @Persisted(primaryKey: true) var _id: ObjectId
  @Persisted var name: String
  @Persisted var books: List<Book>
}

class Book: EmbeddedObject {
  @Persisted var name: String
  @Persisted var edition: String
}

Adding a book, but now I want to update the name of that book that I add, in the property @Persisted var books: List

Could you guide me how I can update said element of the List @Persisted var books: List of a specific user?


问:
SwiftUI Menu - how to fire action when clicking on menu with submenus
If I define a Menu with submenus, how do I register a tap when clicking on the menu with submenus?
With the code below, I would like to "print" when clicking on the "menu with submenus". But this is not fired. Instead, the menu opens and displays it's submenus, which is fine. I would just like to add custom code when opening those submenus.</p>
```<code>struct ContentView: View {

    var body: some View {

        Menu {
            Button {
                print("sub1")
            } label: {
                Text("sub1")
            }
            Menu {
                Button {
                    print("sub2")
                } label: {
                    Text("sub2")
                }

            } label: {
                Button {
                    print("menu with submenus")
                } label: {
                    Text("menu with submenus")
                }
            }
        } label: {
            Button {
                print("opening menu")
            } label: {
                Text("open menu")
            }
        }

    }

}
</code>```

Body:
If I define a Menu with submenus, how do I register a tap when clicking on the menu with submenus?
With the code below, I would like to "print" when clicking on the "menu with submenus". But this is not fired. Instead, the menu opens and displays it's submenus, which is fine. I would just like to add custom code when opening those submenus.

struct ContentView: View {

    var body: some View {

        Menu {
            Button {
                print("sub1")
            } label: {
                Text("sub1")
            }
            Menu {
                Button {
                    print("sub2")
                } label: {
                    Text("sub2")
                }

            } label: {
                Button {
                    print("menu with submenus")
                } label: {
                    Text("menu with submenus")
                }
            }
        } label: {
            Button {
                print("opening menu")
            } label: {
                Text("open menu")
            }
        }

    }

}


问:
syslog-ng mysql queue's but never writes
I have a mysql destination that is queueing the logs, but never writing them, I have removed explicit-commits which from my understanding is the part that tells it to enable queueing, but it still does not seem to ever write it

```<code>destination d_sql {
        sql(
                type(mysql)
                host("<MyHost>") username("<MyUser>") password("<MyPassword>")
                database("<Database>")
                table("<Table>")
                columns( "username" , "user_agent" , "message" , "host" , "appointment_code", "os" , "browser", "error_text", "user_id" , "ip" )
                values("${json.username}" , "${json.user_agent}" , "$(format-json --scope dot-nv-pairs)" , "${json.host}" , "${appointment_code}" , "${ua_os}" , "${ua_browser}" , "${error_text}" , "${json.user_id}" , "${json.ip}" )
                flags(dont-create-tables)
        );
};
</code>```

This destination works on our older server ( Ubuntu 18.04 with syslog-ng 3.13 ) But not on the newer server ( Ubuntu 22.04 with syslog-ng 3.35 ) I am not seeing any error's to even start digging into so any pointers would be greatly appreciated

Body:
I have a mysql destination that is queueing the logs, but never writing them, I have removed explicit-commits which from my understanding is the part that tells it to enable queueing, but it still does not seem to ever write it

destination d_sql {
        sql(
                type(mysql)
                host("<MyHost>") username("<MyUser>") password("<MyPassword>")
                database("<Database>")
                table("
")
                columns( "username" , "user_agent" , "message" , "host" , "appointment_code", "os" , "browser", "error_text", "user_id" , "ip" )
                values("${json.username}" , "${json.user_agent}" , "$(format-json --scope dot-nv-pairs)" , "${json.host}" , "${appointment_code}" , "${ua_os}" , "${ua_browser}" , "${error_text}" , "${json.user_id}" , "${json.ip}" )
                flags(dont-create-tables)
        );
};

This destination works on our older server ( Ubuntu 18.04 with syslog-ng 3.13 ) But not on the newer server ( Ubuntu 22.04 with syslog-ng 3.35 ) I am not seeing any error's to even start digging into so any pointers would be greatly appreciated


问:
gcc inline assembly: how to insert symbol for table address as immediate value
I am trying to implement AES in gcc inline assembly on ARM Cortex M4. AES has many lookups into constant tables. I cannot afford to dedicate a register for the base address of each and every constant table, as there are four of them. How can I get GCC to insert a linker symbol for the immediate value corresponding to a table base address?

Of course, assume we've told the linker to allocate the table within a range and/or alignment that is representable by an immediate value.

As shown below, I tried "m" (memory) but it doesn't seem to work. In fact all "m" seems to do is allocate a register that is preloaded from some data relative to PC, which is exactly the sort of silliness I'm trying to avoid by writing assembly myself in the first place.

```<code>// C model (from openssl)
const int Te0[256] = { ... };
const int Te1[256] = { ... };
const int Te2[256] = { ... };
const int Te3[256] = { ... };
s0 =
  Te0[(t0 >> 24)       ] ^
  Te1[(t1 >> 16) & 0xff] ^
  Te2[(t2 >>  8) & 0xff] ^
  Te3[(t3      ) & 0xff] ^
  rk[0];

// asm implementation
mask = 0x3fc;
__asm("and %[z0], %[mask], %[t0], lsr 22 \n"
  "ldr %[z3], [%[rk], #0] \n"           // z3 = rk[0]

  "ldr %[z0], [%[z0], #0x200] \n"       // z0 = Te0[(t0 >> 24)       ]
  // "ldr %[z0], [%[z0], %[Te0]] \n"    // z0 = Te0[(t0 >> 24)       ]
  // ***** Why doesn't this work? *****
  // Tried binding with:
  //   [Te0] "m" (Te0)
  // Result:
  //   Error: cannot represent T32_OFFSET_IMM relocation in this object file format
  //
  // (same result with "#%[Teo]")

  "and %[z1], %[mask], %[t1], lsr 14 \n"
  "eor %[z0], %[z3] \n"                 // z0 ^= z3
  "ldr %[z1], [%[z1], #0x600] \n"       // z1 = Te1[(t1 >> 16) & 0xff]
  "and %[z2], %[mask], %[t2], lsr  6 \n"
  "ldr %[z2], [%[z2], #0xa00] \n"       // z2 = Te1[(t2 >> 16) & 0xff]
  "eor %[z0], %[z1] \n"                 // z0 ^= z1
  "and %[z3], %[mask], %[t3], lsl  2 \n"
  "ldr %[z3], [%[z3], #0xe00] \n"       // z3 = Te1[(t3 >> 16) & 0xff]
  "eor %[z0], %[z2] \n"                 // z0 ^= z2
  "eor %[z0], %[z3] \n"                 // z0 ^= z3
  :
  [z0] "=&r" (z0),
  [z1] "=&r" (z1),
  [z2] "=&r" (z2),
  [z3] "=&r" (z3)
  :
  [mask] "r" (mask),
  [t0]   "r" (t0),
  [t1]   "r" (t1),
  [t2]   "r" (t2),
  [t3]   "r" (t3),
  [rk]   "r" (rk),

  [Te0] "m" (Te0)
  );

// check the result
assert(s0 == z0);
</code>```

The code works just fine if I pin the tables to absolute addresses and type the addresses directly in the code... But this is 2023. We use symbols in  code. How is it done in GCC?

Update

It was suggested to try the non-inline assembler. Here is a simple example:

```<code># file test.s
# compile with arm-gcc -c test.s
#
# arm-gcc (GNU Arm Embedded Toolchain 9-2020-q2-update) 9.3.1 20200408 (release)

.global Te0

    ldr r0, =Te0
    ldr r0, [r1, r0]
    # Works, but wastes a register (if first instruction is done offline)
    # or adds a load instruction (otherwise)

    ldr r0, [r1, #Te0]
    # Error: internal_relocation (type: OFFSET_IMM) not fixed up

    ldr r0, [r1, #=Te0]
    # Error: bad expression -- `ldr r0,[r1,#=Te0]'

</code>```

Body:
I am trying to implement AES in gcc inline assembly on ARM Cortex M4. AES has many lookups into constant tables. I cannot afford to dedicate a register for the base address of each and every constant table, as there are four of them. How can I get GCC to insert a linker symbol for the immediate value corresponding to a table base address?

Of course, assume we've told the linker to allocate the table within a range and/or alignment that is representable by an immediate value.

As shown below, I tried "m" (memory) but it doesn't seem to work. In fact all "m" seems to do is allocate a register that is preloaded from some data relative to PC, which is exactly the sort of silliness I'm trying to avoid by writing assembly myself in the first place.

// C model (from openssl)
const int Te0[256] = { ... };
const int Te1[256] = { ... };
const int Te2[256] = { ... };
const int Te3[256] = { ... };
s0 =
  Te0[(t0 >> 24)       ] ^
  Te1[(t1 >> 16) & 0xff] ^
  Te2[(t2 >>  8) & 0xff] ^
  Te3[(t3      ) & 0xff] ^
  rk[0];

// asm implementation
mask = 0x3fc;
__asm("and %[z0], %[mask], %[t0], lsr 22 \n"
  "ldr %[z3], [%[rk], #0] \n"           // z3 = rk[0]

  "ldr %[z0], [%[z0], #0x200] \n"       // z0 = Te0[(t0 >> 24)       ]
  // "ldr %[z0], [%[z0], %[Te0]] \n"    // z0 = Te0[(t0 >> 24)       ]
  // ***** Why doesn't this work? *****
  // Tried binding with:
  //   [Te0] "m" (Te0)
  // Result:
  //   Error: cannot represent T32_OFFSET_IMM relocation in this object file format
  //
  // (same result with "#%[Teo]")

  "and %[z1], %[mask], %[t1], lsr 14 \n"
  "eor %[z0], %[z3] \n"                 // z0 ^= z3
  "ldr %[z1], [%[z1], #0x600] \n"       // z1 = Te1[(t1 >> 16) & 0xff]
  "and %[z2], %[mask], %[t2], lsr  6 \n"
  "ldr %[z2], [%[z2], #0xa00] \n"       // z2 = Te1[(t2 >> 16) & 0xff]
  "eor %[z0], %[z1] \n"                 // z0 ^= z1
  "and %[z3], %[mask], %[t3], lsl  2 \n"
  "ldr %[z3], [%[z3], #0xe00] \n"       // z3 = Te1[(t3 >> 16) & 0xff]
  "eor %[z0], %[z2] \n"                 // z0 ^= z2
  "eor %[z0], %[z3] \n"                 // z0 ^= z3
  :
  [z0] "=&r" (z0),
  [z1] "=&r" (z1),
  [z2] "=&r" (z2),
  [z3] "=&r" (z3)
  :
  [mask] "r" (mask),
  [t0]   "r" (t0),
  [t1]   "r" (t1),
  [t2]   "r" (t2),
  [t3]   "r" (t3),
  [rk]   "r" (rk),

  [Te0] "m" (Te0)
  );

// check the result
assert(s0 == z0);

The code works just fine if I pin the tables to absolute addresses and type the addresses directly in the code... But this is 2023. We use symbols in  code. How is it done in GCC?

Update

It was suggested to try the non-inline assembler. Here is a simple example:

# file test.s
# compile with arm-gcc -c test.s
#
# arm-gcc (GNU Arm Embedded Toolchain 9-2020-q2-update) 9.3.1 20200408 (release)

.global Te0

    ldr r0, =Te0
    ldr r0, [r1, r0]
    # Works, but wastes a register (if first instruction is done offline)
    # or adds a load instruction (otherwise)

    ldr r0, [r1, #Te0]
    # Error: internal_relocation (type: OFFSET_IMM) not fixed up

    ldr r0, [r1, #=Te0]
    # Error: bad expression -- `ldr r0,[r1,#=Te0]'


问:
How to customize the alert component in Bootstrap 5.3 using SASS?
I made changes to the $primary and $secondary variables. And that changes all the components I tested like buttons, cards, navbar. But it doesn't change the color of the alerts. This is my custom.sass file:

```<code>$purple-dark:  #9926f0;
$purple-light:  #BB6EF5;
$pink:    #d122e3;

$primary:       $purple-dark;
$secondary:     $pink;

@import "../node_modules/bootstrap/scss/bootstrap.scss";
</code>```

In the documentation about the alert there is a warning box, but it does not explain how to solve it. Or I could not understand!

"Heads up! As of v5.3, the Sass mixin is deprecated. Alert variants now have their CSS variables overridden in the Sass loop. alert-variant()"

https://getbootstrap.com/docs/5.3/components/alerts/

Body:
I made changes to the $primary and $secondary variables. And that changes all the components I tested like buttons, cards, navbar. But it doesn't change the color of the alerts. This is my custom.sass file:

$purple-dark:  #9926f0;
$purple-light:  #BB6EF5;
$pink:    #d122e3;

$primary:       $purple-dark;
$secondary:     $pink;

@import "../node_modules/bootstrap/scss/bootstrap.scss";

In the documentation about the alert there is a warning box, but it does not explain how to solve it. Or I could not understand!

"Heads up! As of v5.3, the Sass mixin is deprecated. Alert variants now have their CSS variables overridden in the Sass loop. alert-variant()"

https://getbootstrap.com/docs/5.3/components/alerts/


问:
XMonad not giving space for Tint2 bar
I am currently setting up my new config for XMonad but I cannot get the docks to work.
https://hastebin.com/eqoliyodat.swift

The tint properties look like this.

```<code>WM_STATE(WM_STATE):
        window state: Normal
        icon window: 0x0
WM_NORMAL_HINTS(WM_SIZE_HINTS):
        program specified location: 1559250944, -874843230
        program specified minimum size: 127 by 42
        program specified maximum size: 127 by 42
WM_CLASS(STRING) = "tint2", "Tint2"
XdndAware(ATOM) = ATOM
_MOTIF_WM_HINTS(_MOTIF_WM_HINTS) = 0x2, 0x0, 0x0, 0x0, 0x0
WM_HINTS(WM_HINTS):
        Client accepts input or input focus: False
        Initial state is Don't Care State.
        window id # to use for icon: 0xe00003
        window id # of group leader: 0xe00003
_NET_WM_STATE(ATOM) = _NET_WM_STATE_SKIP_PAGER, _NET_WM_STATE_SKIP_TASKBAR, _NET_WM_STATE_STICKY, _NET_WM_STATE_ABOVE
_NET_WM_DESKTOP(CARDINAL) = 4294967295
_NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_DOCK
_NET_WM_PID(CARDINAL) = 11648
_NET_WM_ICON_NAME(UTF8_STRING) = "tint2"
_NET_WM_NAME(UTF8_STRING) = "tint2"
WM_ICON_NAME(STRING) = "tint2"
WM_NAME(STRING) = "tint2"
</code>```

I have no idea where this could be coming from, can somebody help me?

I was looking through the current threads, but didnt seem to find any other solution to my problem. I cant use the normal gaps, because I have multiple monitors but a bar only on one screen.

Best regards.

Title: XMonad not giving space for Tint2 bar

Body:
I am currently setting up my new config for XMonad but I cannot get the docks to work.
https://hastebin.com/eqoliyodat.swift

The tint properties look like this.

WM_STATE(WM_STATE):
        window state: Normal
        icon window: 0x0
WM_NORMAL_HINTS(WM_SIZE_HINTS):
        program specified location: 1559250944, -874843230
        program specified minimum size: 127 by 42
        program specified maximum size: 127 by 42
WM_CLASS(STRING) = "tint2", "Tint2"
XdndAware(ATOM) = ATOM
_MOTIF_WM_HINTS(_MOTIF_WM_HINTS) = 0x2, 0x0, 0x0, 0x0, 0x0
WM_HINTS(WM_HINTS):
        Client accepts input or input focus: False
        Initial state is Don't Care State.
        window id # to use for icon: 0xe00003
        window id # of group leader: 0xe00003
_NET_WM_STATE(ATOM) = _NET_WM_STATE_SKIP_PAGER, _NET_WM_STATE_SKIP_TASKBAR, _NET_WM_STATE_STICKY, _NET_WM_STATE_ABOVE
_NET_WM_DESKTOP(CARDINAL) = 4294967295
_NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_DOCK
_NET_WM_PID(CARDINAL) = 11648
_NET_WM_ICON_NAME(UTF8_STRING) = "tint2"
_NET_WM_NAME(UTF8_STRING) = "tint2"
WM_ICON_NAME(STRING) = "tint2"
WM_NAME(STRING) = "tint2"

I have no idea where this could be coming from, can somebody help me?

I was looking through the current threads, but didnt seem to find any other solution to my problem. I cant use the normal gaps, because I have multiple monitors but a bar only on one screen.

Best regards.


问:
Android add buttons on image programmatically
I have an image inside of a Constraint layout, I want to programmatically add buttons to it, so it makes sense with the image. Imagine an image of multiple squares where each square should correspond with a button.

I let it scale the image so it takes up the entire width of the screen.

I know the pixel coordinates of where the button should be located but I'm having trouble placing them correctly on the screen.

I tried converting the pixel location to the location on the screen by getting the width of the screen to calculate the multiplier which should be the same horizontally and vertically as it keeps the aspect ratio. But it's off by quite a bit.

float mult = ((float) x) / ((float) SIZE_IMG.x); # x is the width of the screen
ConstraintLayout viewById = context.findViewById(R.id.constraintLayout);
ConstraintSet constraintSet = new ConstraintSet();

Button button = new Button(context);
button.setId(View.generateViewId());

viewById.addView(button);

constraintSet.clone(viewById);
constraintSet.connect(button.getId(), ConstraintSet.START, R.id.constraintLayout, ConstraintSet.START, (int) (mult * START.x));
constraintSet.connect(button.getId(), ConstraintSet.TOP, R.id.constraintLayout, ConstraintSet.TOP, (int) (mult * START.y));
constraintSet.applyTo(viewById);
```
<p>X is found by</p>
<pre class="lang-java prettyprint-override"><code>ViewTreeObserver vto = viewById.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    public boolean onPreDraw() {
        viewById.getViewTreeObserver().removeOnPreDrawListener(this);
        int finalHeight, finalWidth;
        finalHeight = viewById.getHeight();
        finalWidth = viewById.getWidth();
        yellowScoreBoard.initBoardOn(finalWidth, finalHeight, mainActivity);
        return true;
    }
});
</code>```

Body:
I have an image inside of a Constraint layout, I want to programmatically add buttons to it, so it makes sense with the image. Imagine an image of multiple squares where each square should correspond with a button.

I let it scale the image so it takes up the entire width of the screen.

I know the pixel coordinates of where the button should be located but I'm having trouble placing them correctly on the screen.

I tried converting the pixel location to the location on the screen by getting the width of the screen to calculate the multiplier which should be the same horizontally and vertically as it keeps the aspect ratio. But it's off by quite a bit.

float mult = ((float) x) / ((float) SIZE_IMG.x); # x is the width of the screen
ConstraintLayout viewById = context.findViewById(R.id.constraintLayout);
ConstraintSet constraintSet = new ConstraintSet();

Button button = new Button(context);
button.setId(View.generateViewId());

viewById.addView(button);

constraintSet.clone(viewById);
constraintSet.connect(button.getId(), ConstraintSet.START, R.id.constraintLayout, ConstraintSet.START, (int) (mult * START.x));
constraintSet.connect(button.getId(), ConstraintSet.TOP, R.id.constraintLayout, ConstraintSet.TOP, (int) (mult * START.y));
constraintSet.applyTo(viewById);

X is found by

ViewTreeObserver vto = viewById.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    public boolean onPreDraw() {
        viewById.getViewTreeObserver().removeOnPreDrawListener(this);
        int finalHeight, finalWidth;
        finalHeight = viewById.getHeight();
        finalWidth = viewById.getWidth();
        yellowScoreBoard.initBoardOn(finalWidth, finalHeight, mainActivity);
        return true;
    }
});


问:
How can I redirect traffic from localhost:port to a socks5 proxy?
I am trying to redirect all traffic from localhost with a specific port to a socks5 proxy which has authentication. Kind of like how the Tor proxy works.

I tried usinc ncat, but it does not support socks5 proxies


问:
Error returning a float value from excel - PHP
I'm doing an import with PHP (Laravel) and when I get to a float column in excel it returns this value = 2.0456135709057 and the value in excel is this = 204.561357090573% is there some kind of conversion to get the right value?</p>


问:
DART: attribute of attribute of class
I have a classmodel in dart with a json mapper like

```<code>class DA_Field {
  final String strGROUP;

  DA_Field({
    required this.strGROUP, });

  static DA_Field fromJson(json) => DA_Field(
    strGROUP: json['GROUP'] as String,   );
}
</code>```

and I want to set a attribute of the attribute strGROUP via a function - so that I can call that sub-attribute 'width' for example by:

```<code>intWidth = DA_Field.strGROUP.width
</code>```

My first attempt was to create a setter - but after a lot of google, I only get in touch to create a setter for the whole modelclass, not for all of the single attributes.

The values should be calculated by a function outside of the class - I thought maybe this could be possible by .forEach function - like ?

```<code>DA_Field.forEach((k,v) => k.width = functionxx(k));
</code>```

But i get following errors:

```<code>error: The setter 'width' isn't defined for the type 'DA_Field'. (undefined_setter...)
error: The argument type 'void Function(DA_Field, dynamic)' can't be assigned to the parameter type 'void Function(DA_Field)'. (argument_type_not_assignable)
</code>```

Can anyone give me a suggestion on how to do that?

Thanks..

Title: DART: attribute of attribute of class

Body:
I have a classmodel in dart with a json mapper like

class DA_Field {
  final String strGROUP;

  DA_Field({
    required this.strGROUP, });

  static DA_Field fromJson(json) => DA_Field(
    strGROUP: json['GROUP'] as String,   );
}

and I want to set a attribute of the attribute strGROUP via a function - so that I can call that sub-attribute 'width' for example by:

intWidth = DA_Field.strGROUP.width

My first attempt was to create a setter - but after a lot of google, I only get in touch to create a setter for the whole modelclass, not for all of the single attributes.

The values should be calculated by a function outside of the class - I thought maybe this could be possible by .forEach function - like ?

DA_Field.forEach((k,v) => k.width = functionxx(k));

But i get following errors:

error: The setter 'width' isn't defined for the type 'DA_Field'. (undefined_setter...)
error: The argument type 'void Function(DA_Field, dynamic)' can't be assigned to the parameter type 'void Function(DA_Field)'. (argument_type_not_assignable)

Can anyone give me a suggestion on how to do that?

Thanks..


问:
Python integration aiogram + Socket.IO Server
The question arose how to correctly call the functions seo.edit(), so.and(), sio.call() in the aiogram function.

Is it possible to implement such code somehow:
`

```<code>@dp.message_handler()
async def process_start_command(message: types.Message):
    await sio.send(message.text)
    await message.reply('Готово')

</code>```

`

The connection between the Client and the Server was successfully created.

server.py:

```<code>from aiohttp import web
import socketio

sio = socketio.AsyncServer(logger=True, engineio_logger=True)
app = web.Application()
sio.attach(app)

@sio.on('message')
async def print_message(sid, message):
    print('\n' + "ID: " , sid)
    print(message)

@sio.event()
async def connect(sid, environ):
    print(f'Соединение с {sid} установленно')

if __name__ == '__main__':
    web.run_app(app)

</code>```

client.py:

```<code>import asyncio
import socketio

sio = socketio.AsyncClient(logger=True, engineio_logger=True)

@sio.event
async def message(data):
    print('Получил сообщение ', data)

async def main():
    await sio.connect('http://localhost:8080')
    await sio.wait()

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

Body:
The question arose how to correctly call the functions seo.edit(), so.and(), sio.call() in the aiogram function.

Is it possible to implement such code somehow:
`

@dp.message_handler()
async def process_start_command(message: types.Message):
    await sio.send(message.text)
    await message.reply('Готово')

`

The connection between the Client and the Server was successfully created.

server.py:

from aiohttp import web
import socketio

sio = socketio.AsyncServer(logger=True, engineio_logger=True)
app = web.Application()
sio.attach(app)

@sio.on('message')
async def print_message(sid, message):
    print('\n' + "ID: " , sid)
    print(message)

@sio.event()
async def connect(sid, environ):
    print(f'Соединение с {sid} установленно')

if __name__ == '__main__':
    web.run_app(app)

client.py:

import asyncio
import socketio

sio = socketio.AsyncClient(logger=True, engineio_logger=True)

@sio.event
async def message(data):
    print('Получил сообщение ', data)

async def main():
    await sio.connect('http://localhost:8080')
    await sio.wait()

if __name__ == '__main__':
    asyncio.run(main())


问:
Robinhood API Python Log in error after it used to work
I built a streamlit dashboard showing my robinhood holdings and some other good stuff when I received an error message saying

"Unable to log in with provided credentials".

This happened before during the build process because the API forces a logout in 84600 seconds. To fix it I went into my robinhood settings and messed around with the 2FA method and the issue was resolved.

I now have the same issue, but the quick fix I did before does not work. This is frustrating because the dashboard is fully built, but I cannot log in to even view it. I'm relatively new to python so if it helps my IDE is VSCode and my interpreter is python 3.8.5

Here is the code and the error message associated with the problem. Thank you for your help in advance.

```<code>#log into robinhood

totp = pyotp.TOTP("My2factorAppHere").now()
print("Current OTP:", totp)

login = r.login('config.email' , 'config.password' , store_session= True , mfa_code= totp , expiresIn=86400)``
</code>```

This is the error message:

Exception: Unable to log in with provided credentials.

Body:
I built a streamlit dashboard showing my robinhood holdings and some other good stuff when I received an error message saying

"Unable to log in with provided credentials".

This happened before during the build process because the API forces a logout in 84600 seconds. To fix it I went into my robinhood settings and messed around with the 2FA method and the issue was resolved.

I now have the same issue, but the quick fix I did before does not work. This is frustrating because the dashboard is fully built, but I cannot log in to even view it. I'm relatively new to python so if it helps my IDE is VSCode and my interpreter is python 3.8.5

Here is the code and the error message associated with the problem. Thank you for your help in advance.

#log into robinhood

totp = pyotp.TOTP("My2factorAppHere").now()
print("Current OTP:", totp)

login = r.login('config.email' , 'config.password' , store_session= True , mfa_code= totp , expiresIn=86400)``

This is the error message:

Exception: Unable to log in with provided credentials.


问:
node.send inside RED.httpAdmin.post not working after re-deploy
I'm sending items array by using $.post from frontend to backend. In backend I'm hitting RED.httpAdmin.post route and I can see payload successfully reach backend. I also want to send this items array to the next node by using node.send method inside RED.httpAdmin.post but when I re-deploy app, node.send is stopped working. How can I solve this issue, here is the current code.

HTML:

```
<p>JS:</p>
<pre class="lang-js prettyprint-override"><code>module.exports = function (RED) {
    "use strict";
    var opcua = require('node-opcua');
    var uaclient = require('node-opcua-client');
    const NodeCrawler = require("node-opcua-client-crawler").NodeCrawler;
    const structureSocketInstance = require('./structureSocket.js');
    const axios = require("axios");
    const { v4: uuidv4 } = require("uuid");

    function OpcUaBrowserNode(config) {
        RED.nodes.createNode(this, config);
        this.topic = config.topic || "ns=0;i=85";
        this.plcName = config.plcName;
        this.isRefresh = config.isRefresh;
        this.items = config.items;
        this.checkedItems = config.checkedItems;
        var node = this;
        node.context().set('loading', true);
        node.context().set('checkedItems', []);

        var opcuaEndpoint = RED.nodes.getNode(config.endpoint);

        var connectionOption = {};
        var userIdentity = {};

        if (opcuaEndpoint.securityPolicy) {
            connectionOption.securityPolicy = opcua.SecurityPolicy[opcuaEndpoint.securityPolicy];
        }
        else {
            connectionOption.securityPolicy = opcua.SecurityPolicy.None;
        }
        if (opcuaEndpoint.securityMode) {
            connectionOption.securityMode = opcua.MessageSecurityMode[opcuaEndpoint.securityMode];
        }
        else {
            connectionOption.securityPolicy = opcua.MessageSecurityMode.None;
        }
        connectionOption.endpointMustExist = false;

        if (opcuaEndpoint.login) {
            userIdentity.userName = opcuaEndpoint.credentials.user;
            userIdentity.password = opcuaEndpoint.credentials.password;
            userIdentity.type = uaclient.UserTokenType.UserName; // New TypeScript API parameter
        }

        const startSearching = () => {
            if (this.plcName === '') {
                node.status({
                    fill: "red",
                    shape: "dot",
                    text: "Please fill plc name area.",
                });
            } else {
                setupClient(opcuaEndpoint.endpoint);
            }
        }

        setTimeout(() => {
            if (this.checkedItems.length > 0) {
                node.send({
                    payload: this.checkedItems.map((item) => ({
                        name: item.displayName.text,
                        topic: item.nodeId,
                        datatype: item.dataValue.value.dataType,
                    }))
                }, false);
            }
        }, 500);

        if (node.items.length === 0) {
            startSearching();
        } else {
            node.status({
                fill: "green",
                shape: "dot",
                text: "Successfully found all variables.",
            });
        }

        async function setupClient(url) {
            try {
                const client = opcua.OPCUAClient.create(connectionOption);
                const items = [];
                await client.connect(url);
                const session = await client.createSession(userIdentity);
                var crawler = new NodeCrawler(session);
                node.status({
                    fill: "blue",
                    shape: "dot",
                    text: "Browsing variables in the server.",
                });
                crawler.on("browsed", function (element) {
                    // 2 means variable type
                    if (element.nodeClass === 2 && element.accessLevel === 3) {
                        items.push(element);
                    }
                });
                await crawler.read(node.topic);
                node.context().set(`${node.id}-plc-options`, [...items]);
                node.context().set(`loading`, false);
                node.status({
                    fill: "green",
                    shape: "dot",
                    text: "Successfully found all variables.",
                });
                client.disconnect();
            }
            catch (err) {
                node.status({
                    fill: "red",
                    shape: "dot",
                    text: err,
                });
            }
        }

        const checkedItemListControl = setInterval(() => {
            if (node.context().get('checkListChanged')) {
                node.send({
                    payload: node.context().get('checkedItems').map((item) => ({
                        name: item.displayName.text,
                        topic: item.nodeId,
                        datatype: item.dataValue.value.dataType,
                    }))
                }, false);
                node.context().set('checkListChanged', false);
            }
        }, 1500);

        RED.httpAdmin.get("/plc-options/" + node.id, function (req, res) {
            if (node.context().get('loading')) {
                res.json([]);
            } else {
                res.json(node.context().get(`${node.id}-plc-options`));
            }
        });

        RED.httpAdmin.get("/plc-options/refresh/" + node.id, function (req, res) {
            node.context().set(`loading`, true);
            startSearching();
            res.json("loading");
        });

        RED.httpAdmin.get("/plc-options/checked-items/" + node.id, async function (req, res) {
            const { data } = await axios("http://localhost:8000/api/v1/structure/node-red");
            const structure = JSON.parse(data.nodeRed.replaceAll("'", '"').replaceAll('`', "'"));
            const plcIndex = structure.findIndex(item => item.id === node.id);
            if (plcIndex === -1)
                res.json([]);
            else {
                const childsNodeIds = structure[plcIndex].childs.map((childId) => structure.find((item) => item.id === childId).nodeId);
                res.json(childsNodeIds);
            }
        });

        RED.httpAdmin.post("/plc-options/update/structure/" + node.id, async function (req, res) {
            const { data } = await axios("http://localhost:8000/api/v1/structure/node-red");
            const structure = JSON.parse(data.nodeRed.replaceAll("'", '"').replaceAll('`', "'"));
            const plcIndex = structure.findIndex(item => item.id === node.id);
            const childs = req.body.items.filter((item) => item !== "empty").map((item) => ({
                id: uuidv4(),
                name: item.displayName.text,
                topic: item.nodeId,
                datatype: item.dataValue.value.dataType,
                value: `${req.body.plcName}-${item.displayName.text}`,
                plcName: req.body.plcName,
                childs: [],
                parentId: node.id,
                isOpen: false,
                isShown: plcIndex !== -1 ? structure[plcIndex].isOpen : false,
                type: 10,
            }));
            const parentPlc = {
                id: node.id,
                childs: childs.map((child) => child.id),
                parentId: "2",
                isOpen: plcIndex !== -1 ? structure[plcIndex].isOpen : false,
                isShown: plcIndex !== -1 ? structure[plcIndex].isShown : false,
                name: req.body.plcName,
                type: 9,
            }
            if (!structure[0].childs.includes(node.id)) {
                structure[0].childs.push(node.id)
            }
            if (plcIndex !== -1) {
                let currentIndex = plcIndex + 1;
                //removing childs
                while (structure[currentIndex] && structure[currentIndex].parentId !== '2') {
                    structure.splice(currentIndex, 1);
                    ++currentIndex;
                }
                structure[plcIndex] = parentPlc;
                childs.forEach((child, i) => {
                    structure.splice(plcIndex + i + 1, 0, child);
                })
            } else {
                structure.push(parentPlc);
                childs.forEach(child => {
                    structure.push(child);
                });
            }
            const escapeSingQuote = JSON.stringify(structure).replaceAll("'", '`')
            await axios({
                method: "put",
                url: `http://localhost:8000/api/v1/structure/node-red`,
                data: {
                    nodeRed: escapeSingQuote.replaceAll('"', "'"),
                },
            });
            structureSocketInstance.emit("refetch", () => {
                return "true";
            });
            node.context().set('checkListChanged', true);
            node.context().set('checkedItems', req.body.items.filter((item) => item !== "empty"));
            res.json("success");
        });

        node.on("close", async (removed, done) => {
            clearInterval(checkedItemListControl);
            if (removed) {
                const { data } = await axios("http://localhost:8000/api/v1/structure/node-red");
                const structure = JSON.parse(data.nodeRed.replaceAll("'", '"').replaceAll('`', "'"));
                const plcIndex = structure.findIndex(item => item.id === node.id);
                if (plcIndex !== -1) {
                    structure[0].childs = structure[0].childs.filter((childId) => childId !== node.id)
                    let currentIndex = plcIndex + 1;
                    while (structure[currentIndex] && structure[currentIndex].parentId !== '2') {
                        structure.splice(currentIndex, 1);
                        ++currentIndex;
                    }
                    structure.splice(plcIndex, 1);
                    const escapeSingQuote = JSON.stringify(structure).replaceAll("'", '`')
                    await axios({
                        method: "put",
                        url: `http://localhost:8000/api/v1/structure/node-red`,
                        data: {
                            nodeRed: escapeSingQuote.replaceAll('"', "'"),
                        },
                    });
                    structureSocketInstance.emit("refetch", () => {
                        return "true";
                    });
                    done();
                }
            } else {
                done();
            }
        })
    }
    RED.nodes.registerType("Opcua Browser", OpcUaBrowserNode);
}
</code>```

StructureSocket

const socketio = require("socket.io");

const SOCKET_PORT = 3000;

const structureSocketInstance = socketio(SOCKET_PORT, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"],
        credentials: true,
        transports: ["websocket", "polling"],
    },
});

module.exports = structureSocketInstance;

```

Body:
I'm sending items array by using $.post from frontend to backend. In backend I'm hitting RED.httpAdmin.post route and I can see payload successfully reach backend. I also want to send this items array to the next node by using node.send method inside RED.httpAdmin.post but when I re-deploy app, node.send is stopped working. How can I solve this issue, here is the current code.

HTML:

JS:

module.exports = function (RED) {
    "use strict";
    var opcua = require('node-opcua');
    var uaclient = require('node-opcua-client');
    const NodeCrawler = require("node-opcua-client-crawler").NodeCrawler;
    const structureSocketInstance = require('./structureSocket.js');
    const axios = require("axios");
    const { v4: uuidv4 } = require("uuid");

    function OpcUaBrowserNode(config) {
        RED.nodes.createNode(this, config);
        this.topic = config.topic || "ns=0;i=85";
        this.plcName = config.plcName;
        this.isRefresh = config.isRefresh;
        this.items = config.items;
        this.checkedItems = config.checkedItems;
        var node = this;
        node.context().set('loading', true);
        node.context().set('checkedItems', []);

        var opcuaEndpoint = RED.nodes.getNode(config.endpoint);

        var connectionOption = {};
        var userIdentity = {};

        if (opcuaEndpoint.securityPolicy) {
            connectionOption.securityPolicy = opcua.SecurityPolicy[opcuaEndpoint.securityPolicy];
        }
        else {
            connectionOption.securityPolicy = opcua.SecurityPolicy.None;
        }
        if (opcuaEndpoint.securityMode) {
            connectionOption.securityMode = opcua.MessageSecurityMode[opcuaEndpoint.securityMode];
        }
        else {
            connectionOption.securityPolicy = opcua.MessageSecurityMode.None;
        }
        connectionOption.endpointMustExist = false;

        if (opcuaEndpoint.login) {
            userIdentity.userName = opcuaEndpoint.credentials.user;
            userIdentity.password = opcuaEndpoint.credentials.password;
            userIdentity.type = uaclient.UserTokenType.UserName; // New TypeScript API parameter
        }

        const startSearching = () => {
            if (this.plcName === '') {
                node.status({
                    fill: "red",
                    shape: "dot",
                    text: "Please fill plc name area.",
                });
            } else {
                setupClient(opcuaEndpoint.endpoint);
            }
        }

        setTimeout(() => {
            if (this.checkedItems.length > 0) {
                node.send({
                    payload: this.checkedItems.map((item) => ({
                        name: item.displayName.text,
                        topic: item.nodeId,
                        datatype: item.dataValue.value.dataType,
                    }))
                }, false);
            }
        }, 500);

        if (node.items.length === 0) {
            startSearching();
        } else {
            node.status({
                fill: "green",
                shape: "dot",
                text: "Successfully found all variables.",
            });
        }

        async function setupClient(url) {
            try {
                const client = opcua.OPCUAClient.create(connectionOption);
                const items = [];
                await client.connect(url);
                const session = await client.createSession(userIdentity);
                var crawler = new NodeCrawler(session);
                node.status({
                    fill: "blue",
                    shape: "dot",
                    text: "Browsing variables in the server.",
                });
                crawler.on("browsed", function (element) {
                    // 2 means variable type
                    if (element.nodeClass === 2 && element.accessLevel === 3) {
                        items.push(element);
                    }
                });
                await crawler.read(node.topic);
                node.context().set(`${node.id}-plc-options`, [...items]);
                node.context().set(`loading`, false);
                node.status({
                    fill: "green",
                    shape: "dot",
                    text: "Successfully found all variables.",
                });
                client.disconnect();
            }
            catch (err) {
                node.status({
                    fill: "red",
                    shape: "dot",
                    text: err,
                });
            }
        }

        const checkedItemListControl = setInterval(() => {
            if (node.context().get('checkListChanged')) {
                node.send({
                    payload: node.context().get('checkedItems').map((item) => ({
                        name: item.displayName.text,
                        topic: item.nodeId,
                        datatype: item.dataValue.value.dataType,
                    }))
                }, false);
                node.context().set('checkListChanged', false);
            }
        }, 1500);

        RED.httpAdmin.get("/plc-options/" + node.id, function (req, res) {
            if (node.context().get('loading')) {
                res.json([]);
            } else {
                res.json(node.context().get(`${node.id}-plc-options`));
            }
        });

        RED.httpAdmin.get("/plc-options/refresh/" + node.id, function (req, res) {
            node.context().set(`loading`, true);
            startSearching();
            res.json("loading");
        });

        RED.httpAdmin.get("/plc-options/checked-items/" + node.id, async function (req, res) {
            const { data } = await axios("http://localhost:8000/api/v1/structure/node-red");
            const structure = JSON.parse(data.nodeRed.replaceAll("'", '"').replaceAll('`', "'"));
            const plcIndex = structure.findIndex(item => item.id === node.id);
            if (plcIndex === -1)
                res.json([]);
            else {
                const childsNodeIds = structure[plcIndex].childs.map((childId) => structure.find((item) => item.id === childId).nodeId);
                res.json(childsNodeIds);
            }
        });

        RED.httpAdmin.post("/plc-options/update/structure/" + node.id, async function (req, res) {
            const { data } = await axios("http://localhost:8000/api/v1/structure/node-red");
            const structure = JSON.parse(data.nodeRed.replaceAll("'", '"').replaceAll('`', "'"));
            const plcIndex = structure.findIndex(item => item.id === node.id);
            const childs = req.body.items.filter((item) => item !== "empty").map((item) => ({
                id: uuidv4(),
                name: item.displayName.text,
                topic: item.nodeId,
                datatype: item.dataValue.value.dataType,
                value: `${req.body.plcName}-${item.displayName.text}`,
                plcName: req.body.plcName,
                childs: [],
                parentId: node.id,
                isOpen: false,
                isShown: plcIndex !== -1 ? structure[plcIndex].isOpen : false,
                type: 10,
            }));
            const parentPlc = {
                id: node.id,
                childs: childs.map((child) => child.id),
                parentId: "2",
                isOpen: plcIndex !== -1 ? structure[plcIndex].isOpen : false,
                isShown: plcIndex !== -1 ? structure[plcIndex].isShown : false,
                name: req.body.plcName,
                type: 9,
            }
            if (!structure[0].childs.includes(node.id)) {
                structure[0].childs.push(node.id)
            }
            if (plcIndex !== -1) {
                let currentIndex = plcIndex + 1;
                //removing childs
                while (structure[currentIndex] && structure[currentIndex].parentId !== '2') {
                    structure.splice(currentIndex, 1);
                    ++currentIndex;
                }
                structure[plcIndex] = parentPlc;
                childs.forEach((child, i) => {
                    structure.splice(plcIndex + i + 1, 0, child);
                })
            } else {
                structure.push(parentPlc);
                childs.forEach(child => {
                    structure.push(child);
                });
            }
            const escapeSingQuote = JSON.stringify(structure).replaceAll("'", '`')
            await axios({
                method: "put",
                url: `http://localhost:8000/api/v1/structure/node-red`,
                data: {
                    nodeRed: escapeSingQuote.replaceAll('"', "'"),
                },
            });
            structureSocketInstance.emit("refetch", () => {
                return "true";
            });
            node.context().set('checkListChanged', true);
            node.context().set('checkedItems', req.body.items.filter((item) => item !== "empty"));
            res.json("success");
        });

        node.on("close", async (removed, done) => {
            clearInterval(checkedItemListControl);
            if (removed) {
                const { data } = await axios("http://localhost:8000/api/v1/structure/node-red");
                const structure = JSON.parse(data.nodeRed.replaceAll("'", '"').replaceAll('`', "'"));
                const plcIndex = structure.findIndex(item => item.id === node.id);
                if (plcIndex !== -1) {
                    structure[0].childs = structure[0].childs.filter((childId) => childId !== node.id)
                    let currentIndex = plcIndex + 1;
                    while (structure[currentIndex] && structure[currentIndex].parentId !== '2') {
                        structure.splice(currentIndex, 1);
                        ++currentIndex;
                    }
                    structure.splice(plcIndex, 1);
                    const escapeSingQuote = JSON.stringify(structure).replaceAll("'", '`')
                    await axios({
                        method: "put",
                        url: `http://localhost:8000/api/v1/structure/node-red`,
                        data: {
                            nodeRed: escapeSingQuote.replaceAll('"', "'"),
                        },
                    });
                    structureSocketInstance.emit("refetch", () => {
                        return "true";
                    });
                    done();
                }
            } else {
                done();
            }
        })
    }
    RED.nodes.registerType("Opcua Browser", OpcUaBrowserNode);
}

StructureSocket

const socketio = require("socket.io");

const SOCKET_PORT = 3000;

const structureSocketInstance = socketio(SOCKET_PORT, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"],
        credentials: true,
        transports: ["websocket", "polling"],
    },
});

module.exports = structureSocketInstance;


问:
dyld: Symbol not found
I'm trying to run a keypad software thing but whenever i try to run it it says

```<code>dyld: Symbol not found: __ZTTNSt3__114basic_ifstreamIcNS_11char_traitsIcEEEE
  Referenced from: /Users/nd_admin/Downloads/setting/./Sayo_CLI_Mac_X64 (which was built for Mac OS X 12.0)
  Expected in: /usr/lib/libc++.1.dylib
</code>```

(if it helps this software is supposed to give out an online link with all the keypad drivers and stuff)

I've tried finding the dylib inside the usr file, but it just inputs unreadable characters

Title: dyld: Symbol not found

Body:
I'm trying to run a keypad software thing but whenever i try to run it it says

dyld: Symbol not found: __ZTTNSt3__114basic_ifstreamIcNS_11char_traitsIcEEEE
  Referenced from: /Users/nd_admin/Downloads/setting/./Sayo_CLI_Mac_X64 (which was built for Mac OS X 12.0)
  Expected in: /usr/lib/libc++.1.dylib

(if it helps this software is supposed to give out an online link with all the keypad drivers and stuff)

I've tried finding the dylib inside the usr file, but it just inputs unreadable characters


问:
Odd behavior of `self.size` value of a widget in kivy?
In the code below, self.size of TextPad switches between the size of widget in relation to the kivy window (A), and its size in relation to its parent layout (B). It does this in a pattern where for every two B output, it outputs A, and repeats this over and over. Any reasons why?

output snippet:

```<code>widget size: [800, 600] | window size: (800, 600)  # A
widget size: [100, 100] | window size: (800, 600)
widget size: [100, 100] | window size: (800, 600)
widget size: [800, 600] | window size: (800, 600)  # A
widget size: [100, 100] | window size: (800, 600)
widget size: [100, 100] | window size: (800, 600)
widget size: [800, 600] | window size: (800, 600)  # A
widget size: [100, 100] | window size: (800, 600)
widget size: [100, 100] | window size: (800, 600)
</code>```

main.py

import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.textinput import TextInput
from kivy.core.window import Window

kivy.require("2.1.0")

class ScreenManger(ScreenManager):
    pass

class MainScreen(Screen):
    pass

class TextPad(TextInput):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        Window.bind(mouse_pos=self.on_mouse_motion)  # run callback when mouse moves in window

    def on_mouse_motion(self, window, pos):
        print("widget size:", self.size, "| window size:", Window.size)

kv = Builder.load_file("main.kv")

class MainApp(App):
    def build(self):
        return kv

if __name__ == '__main__':
    MainApp().run()
```
<p>main.kv:</p>
<pre class="lang-py prettyprint-override"><code>#:kivy 2.1.0

ScreenManager:
    MainScreen:

<MainScreen>:
    TextPad:
</code>```

Body:
In the code below, self.size of TextPad switches between the size of widget in relation to the kivy window (A), and its size in relation to its parent layout (B). It does this in a pattern where for every two B output, it outputs A, and repeats this over and over. Any reasons why?

output snippet:

widget size: [800, 600] | window size: (800, 600)  # A
widget size: [100, 100] | window size: (800, 600)
widget size: [100, 100] | window size: (800, 600)
widget size: [800, 600] | window size: (800, 600)  # A
widget size: [100, 100] | window size: (800, 600)
widget size: [100, 100] | window size: (800, 600)
widget size: [800, 600] | window size: (800, 600)  # A
widget size: [100, 100] | window size: (800, 600)
widget size: [100, 100] | window size: (800, 600)

main.py

import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.textinput import TextInput
from kivy.core.window import Window

kivy.require("2.1.0")

class ScreenManger(ScreenManager):
    pass

class MainScreen(Screen):
    pass

class TextPad(TextInput):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        Window.bind(mouse_pos=self.on_mouse_motion)  # run callback when mouse moves in window

    def on_mouse_motion(self, window, pos):
        print("widget size:", self.size, "| window size:", Window.size)

kv = Builder.load_file("main.kv")

class MainApp(App):
    def build(self):
        return kv

if __name__ == '__main__':
    MainApp().run()

main.kv:

#:kivy 2.1.0

ScreenManager:
    MainScreen:

<MainScreen>:
    TextPad:


问:
How to use a JavaScript file that needs another JavaScript file (incl. modules) on the frontend of my node.js server?
Currently, I am working on a smart home system at home, but my frontend won't work properly. What should happen: Frontend sends RSA-Encrypted data to my apache2 server, which runs also node.js. Then the server should decrypt the data and execute the proper function of the request so that the frontend receives a proper response (the server works as intended, I tested it with a program called "Insomnia" which can generate any kind of request, in my case there are POST-Request which contains JSON-Objects in the body section).

Below you will find an example of my project.

Frontend
index.html

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="./index.css">
  <title>Smart Home</title>
</head>
<body>
...
<button id="btn1" class="numPad-btn">btn1</button>
...
</body>
<script type="module" src="connection.js"></script>
</html>
</code>```

connectio.js

```<code>import * as _crypto from './Crypto.js';

const btn1 = document.getElementById('btn1')
btn1.addEventListener('click', post)

async function post(e) {
    e.preventDefault();

    const data = JSON.stringify({request: _crypto.Encrypt('S', "<Text>")});

    const res = await fetch('http://<IP>:<Port>/', {
        method: 'POST',
        headers: {
            "Content-Type": 'application/json',
        },
        body: data
    });
console.log(res.body);              //for troubleshooting
console.log(_crypto.Decrypt('C', res.body));    //for troubleshooting
}
</code>```

Backend
server.js

```<code>import * as _databaseJS from './database.js';
import * as _crypto from './Crypto.js';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const express = require('express');
const cors=require("cors");
const app = express();
const port = 8383;
const corsOptions ={
   origin:'*',
   credentials:true,
   optionSuccessStatus:200,
};

app.use(cors(corsOptions));
app.use(express.json());

app.post('/', (req, res) => {
    const cryptedRequest = req.body;
    const request = _crypto.Decrypt(cryptedRequest.request);

    let _response="";
    let _output="";
    let _status=0;
    switch (request) {

        case "methode1":
            _output = _databaseJS.GetUser();

            _response = JSON.stringify({
                "reply":_crypto.Encrypt(_output.response)
            });

            _status=_output.status;
        break;

        case "methode2":
            _output = _databaseJS.GetUser();

            _response = JSON.stringify({
                "reply":_crypto.Encrypt(_output.response)
            });

            _status=_output.status;
        break;

        default:
            _response = JSON.stringify({
                "reply": _crypto.Encrypt("Methode not found")
            })

            _status=500;
        break;
      }

      console.log(_response);

      res.status(_status).send(_response);
});
</code>```

Crypto.js

```<code>import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const execSync = require('child_process').execSync;
const NodeRSA = require('node-rsa');

function ExecuteInTerminal(query)
{
        const output = execSync(query, { encoding: 'utf-8' });
        return output;
}

function Encrypt(whichOne, message)
{
    const key = new NodeRSA();

    switch (whichOne) {
        case 'C':
            key.importKey(ExecuteInTerminal(`sudo cat /path/to/key/publicRsaKeyClient.key`), 'pkcs8-public-pem');
        break;

        case 'S':
            key.importKey(ExecuteInTerminal(`sudo cat /path/to/key/publicRsaKey.key`), 'pkcs8-public-pem');
        break;

        default:
        break;
    }

    const encrypted = key.encrypt(message, 'base64');
    return encrypted;
}

function Decrypt(whichOne, message)
{
    const key = new NodeRSA();

    switch (whichOne) {
        case 'C':
            key.importKey(ExecuteInTermianal(`sudo cat /path/to/key/publicRsaKeyClient.key`), 'pkcs1-pem');
        break;

        case 'S':
            key.importKey(ExecuteInTerminal(`sudo cat /path/to/key/privateRsaKey.key`), 'pkcs1-pem');
        break;

        default:
        break;
    }

    const decryptedString = key.decrypt(message, 'utf8');
    return decryptedString;
}

export { Encrypt, Decrypt };
</code>```

First, I tried first to write

```<code><script type="application/javascript" src="connection.js"></script>
</code>```

instead of

```<code><script type="module" src="connection.js"></script>
</code>```

, but in browsers development tools an error occurred. Error: "Uncaught SyntaxError: Cannot use import statement outside a module".

After that I tried to write

```<code><script type="module" src="connection.js"></script>
</code>```

,but even there an error occurred. Error: "Uncaught TypeError: Failed to resolve module specifier "module". Relative references must start with either "/", "./", or "../".".

Then I tried instead of "module": "/module", "./module", "../module" and "module/", but I realized that the frontend, no matter what I add to the module, the browser doesn't use the connection.js file. The HTML file only uses the css.

I tried to edit all in the HTML file in the  section. Unfortunately, nothing changes.

Body:
Currently, I am working on a smart home system at home, but my frontend won't work properly. What should happen: Frontend sends RSA-Encrypted data to my apache2 server, which runs also node.js. Then the server should decrypt the data and execute the proper function of the request so that the frontend receives a proper response (the server works as intended, I tested it with a program called "Insomnia" which can generate any kind of request, in my case there are POST-Request which contains JSON-Objects in the body section).

Below you will find an example of my project.

Frontend
index.html

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="./index.css">
  <title>Smart Home</title>

...
<button id="btn1" class="numPad-btn">btn1</button>
...

connectio.js

import * as _crypto from './Crypto.js';

const btn1 = document.getElementById('btn1')
btn1.addEventListener('click', post)

async function post(e) {
    e.preventDefault();

    const data = JSON.stringify({request: _crypto.Encrypt('S', "<Text>")});

    const res = await fetch('http://<IP>:<Port>/', {
        method: 'POST',
        headers: {
            "Content-Type": 'application/json',
        },
        body: data
    });
console.log(res.body);              //for troubleshooting
console.log(_crypto.Decrypt('C', res.body));    //for troubleshooting
}

Backend
server.js

import * as _databaseJS from './database.js';
import * as _crypto from './Crypto.js';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const express = require('express');
const cors=require("cors");
const app = express();
const port = 8383;
const corsOptions ={
   origin:'*',
   credentials:true,
   optionSuccessStatus:200,
};

app.use(cors(corsOptions));
app.use(express.json());

app.post('/', (req, res) => {
    const cryptedRequest = req.body;
    const request = _crypto.Decrypt(cryptedRequest.request);

    let _response="";
    let _output="";
    let _status=0;
    switch (request) {

        case "methode1":
            _output = _databaseJS.GetUser();

            _response = JSON.stringify({
                "reply":_crypto.Encrypt(_output.response)
            });

            _status=_output.status;
        break;

        case "methode2":
            _output = _databaseJS.GetUser();

            _response = JSON.stringify({
                "reply":_crypto.Encrypt(_output.response)
            });

            _status=_output.status;
        break;

        default:
            _response = JSON.stringify({
                "reply": _crypto.Encrypt("Methode not found")
            })

            _status=500;
        break;
      }

      console.log(_response);

      res.status(_status).send(_response);
});

Crypto.js

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const execSync = require('child_process').execSync;
const NodeRSA = require('node-rsa');

function ExecuteInTerminal(query)
{
        const output = execSync(query, { encoding: 'utf-8' });
        return output;
}

function Encrypt(whichOne, message)
{
    const key = new NodeRSA();

    switch (whichOne) {
        case 'C':
            key.importKey(ExecuteInTerminal(`sudo cat /path/to/key/publicRsaKeyClient.key`), 'pkcs8-public-pem');
        break;

        case 'S':
            key.importKey(ExecuteInTerminal(`sudo cat /path/to/key/publicRsaKey.key`), 'pkcs8-public-pem');
        break;

        default:
        break;
    }

    const encrypted = key.encrypt(message, 'base64');
    return encrypted;
}

function Decrypt(whichOne, message)
{
    const key = new NodeRSA();

    switch (whichOne) {
        case 'C':
            key.importKey(ExecuteInTermianal(`sudo cat /path/to/key/publicRsaKeyClient.key`), 'pkcs1-pem');
        break;

        case 'S':
            key.importKey(ExecuteInTerminal(`sudo cat /path/to/key/privateRsaKey.key`), 'pkcs1-pem');
        break;

        default:
        break;
    }

    const decryptedString = key.decrypt(message, 'utf8');
    return decryptedString;
}

export { Encrypt, Decrypt };

First, I tried first to write

instead of

, but in browsers development tools an error occurred. Error: "Uncaught SyntaxError: Cannot use import statement outside a module".

After that I tried to write

,but even there an error occurred. Error: "Uncaught TypeError: Failed to resolve module specifier "module". Relative references must start with either "/", "./", or "../".".

Then I tried instead of "module": "/module", "./module", "../module" and "module/", but I realized that the frontend, no matter what I add to the module, the browser doesn't use the connection.js file. The HTML file only uses the css.

I tried to edit all in the HTML file in the  section. Unfortunately, nothing changes.


问:
Tastypie: ending empty POST with no request, and to a path parameter URL
I need to create two POST request with url:

/create with raw body: {some JSON}, I'm able to do this,
with a obj_create method provided by tastypie.

/create/4, I'm stuck at this, which has the same endpoint but with a path parameter and no body.

I've the following questions for which I could not figure out answers from documentation/stack overflow:

Is is possible to send POST request in tastypie without a body

this post request does not goes to obj_create, what is the corresponding method in tastypie to receive such post requests with path parameter and no body.

Thanks for the help.


问:
How to put images on Y axis of line chart in Chart.js?
I'm trying to put images on the vertical axis of my chart using Chart.js but I can't figure out how...

For now the data in my chart is hard coded and it is supposed to show the emotions of a person during the week.

Here is what I have tried:

```<code>import Chart from 'chart.js/auto'
(async function () {
const EMOTIONS = ["Angry.png", "Sad.png", "Normal.png", "Happy.png"];
const DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
const data = [
    {day: DAYS[0], i: 2},
    {day: DAYS[1], i: 3},
    {day: DAYS[2], i: 1},
    {day: DAYS[3], i: 2},
    {day: DAYS[4], i: 3},
    {day: DAYS[5], i: 2},
    {day: DAYS[6], i: 0},
];
var ctx = document.getElementById('feel-graph').getContext('2d');
new Chart(
    ctx,
    {
        type: 'line',
        data: {
            labels: data.map(row => row.day),
            datasets: [
                {
                    label: 'Your emotions throughout the week',
                    data: data.map(row => row.i)
                }
            ]

        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: 'Personal Statistics'
                }
            },
            scales: {
                y: {
                    ticks: {
                        callback: function (val) {
                            var image = new Image()
                            image.src= EMOTIONS[val]
                            return image
//I also tried to return the image element as a string but it doesn't work...
                            //return `<image data-src="${EMOTIONS[val]}">`
                        }
                    }
                }
            }
        }
    }
);
})();
</code>```

Is it even possible to do it? I have searched a lot on the internet and I have found nothing that comes close to what I search...

Body:
I'm trying to put images on the vertical axis of my chart using Chart.js but I can't figure out how...

For now the data in my chart is hard coded and it is supposed to show the emotions of a person during the week.

Here is what I have tried:

import Chart from 'chart.js/auto'
(async function () {
const EMOTIONS = ["Angry.png", "Sad.png", "Normal.png", "Happy.png"];
const DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
const data = [
    {day: DAYS[0], i: 2},
    {day: DAYS[1], i: 3},
    {day: DAYS[2], i: 1},
    {day: DAYS[3], i: 2},
    {day: DAYS[4], i: 3},
    {day: DAYS[5], i: 2},
    {day: DAYS[6], i: 0},
];
var ctx = document.getElementById('feel-graph').getContext('2d');
new Chart(
    ctx,
    {
        type: 'line',
        data: {
            labels: data.map(row => row.day),
            datasets: [
                {
                    label: 'Your emotions throughout the week',
                    data: data.map(row => row.i)
                }
            ]

        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: 'Personal Statistics'
                }
            },
            scales: {
                y: {
                    ticks: {
                        callback: function (val) {
                            var image = new Image()
                            image.src= EMOTIONS[val]
                            return image
//I also tried to return the image element as a string but it doesn't work...
                            //return `<image data-src="${EMOTIONS[val]}">`
                        }
                    }
                }
            }
        }
    }
);
})();

Is it even possible to do it? I have searched a lot on the internet and I have found nothing that comes close to what I search...


问:
How to remove an element in a list which is present another time in the list?(Python)
Let's say we have the following list:
list = ['a','b','c','a'] and we want to remove the second 'a'.
With list.remove('a') the first 'a' will be removed.How can we remove the second 'a'?

I tried what I wrote and did not work!Can this be solved with index()?


问:
How to add a class when another class is active
I have an anchor menu and when the anchor link is active it adds a class to that link. I'm trying to add an additional class to each anchor link individually when it's active, so I can make different changes to each one.
Following is my anchor menu html:

```<code><div class="anchor-menu" id="background">
      <div><a href="#service1" class="anchor1 nav-link" id="grey"></a></div>
      <div><a href="#service2" class="anchor2 nav-link" id="grey1"></a></div>
      <div><a href="#service3" class="anchor3 nav-link" id="grey2"></a></div>
      <div><a href="#service4" class="anchor4 nav-link" id="grey3"></a></div>
    </div>
</code>```

Following is the jquery that adds the class 'active' to the active anchor link.

```<code> <script>
    $(document).ready(function () {

      var sectionIds = $('a.nav-link');

      $(document).scroll(function () {
        sectionIds.each(function () {
          var container = $(this).attr('href');
          var containerOffset = $(container).offset().top - 300;
          var containerHeight = $(container).outerHeight();
          var containerBottom = containerOffset + containerHeight;
          var scrollPosition = $(document).scrollTop();

          if (scrollPosition < containerBottom && scrollPosition >= containerOffset) {
            $(this).addClass('active');
          } else {
            $(this).removeClass('active');
          }
        });
      });
    });
  </script>
</code>```

So basically what I'm trying to do is that when id=grey has the class active added to it it should add an additional class to it. And so on for all the other anchor links. So I should be able to set styling for each element that becomes active seperately.

Body:
I have an anchor menu and when the anchor link is active it adds a class to that link. I'm trying to add an additional class to each anchor link individually when it's active, so I can make different changes to each one.
Following is my anchor menu html:

Following is the jquery that adds the class 'active' to the active anchor link.

So basically what I'm trying to do is that when id=grey has the class active added to it it should add an additional class to it. And so on for all the other anchor links. So I should be able to set styling for each element that becomes active seperately.


问:
Are new created Github secrets available to existing workflows that failed before?
I have some private repositories installed in my project, one of them is Laravel Nova. I need to provide a username and password when running my Github actions (workflows). An example piece of code from my workflow is:

- name: Install Dependencies
  env:
        COMPOSER_AUTH: '{"github-oauth": {"github.com": "${{secrets.COMPOSER_AUTH}}"} }'
  run: |
        composer config "http-basic.nova.laravel.com" "${{ secrets.NOVA_USERNAME }}" "${{ secrets.NOVA_PASSWORD }}"
        composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist
```

As you can see I am using three different secrets here. This workflow runs perfect when I create a PR myself. However, when Dependabot created a PR it failed, because it didn't had access to these credentials.

I found out that I have to create separate secrets for Dependabot as described here. So I created those credentials and tried re-running the failed workflows manually. But that resulted in the same error:

Your github oauth token for github.com contains invalid characters: ""

So it seems that the credentials are still not available. I named the secrets exactly the same as in my so called 'action secrets'.

I would like to re-run the failed workflows from the Dependabot PR to make sure it doesn't break anything. Can anyone confirm that these credentials are not available in the old workflow, because they weren't available at that time yet? Thanks!

Body:
I have some private repositories installed in my project, one of them is Laravel Nova. I need to provide a username and password when running my Github actions (workflows). An example piece of code from my workflow is:

- name: Install Dependencies
  env:
        COMPOSER_AUTH: '{"github-oauth": {"github.com": "${{secrets.COMPOSER_AUTH}}"} }'
  run: |
        composer config "http-basic.nova.laravel.com" "${{ secrets.NOVA_USERNAME }}" "${{ secrets.NOVA_PASSWORD }}"
        composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist

As you can see I am using three different secrets here. This workflow runs perfect when I create a PR myself. However, when Dependabot created a PR it failed, because it didn't had access to these credentials.

I found out that I have to create separate secrets for Dependabot as described here. So I created those credentials and tried re-running the failed workflows manually. But that resulted in the same error:

Your github oauth token for github.com contains invalid characters: ""

So it seems that the credentials are still not available. I named the secrets exactly the same as in my so called 'action secrets'.

I would like to re-run the failed workflows from the Dependabot PR to make sure it doesn't break anything. Can anyone confirm that these credentials are not available in the old workflow, because they weren't available at that time yet? Thanks!


问:
Stripe popup not opening on mobile
I have a website on MERN STACK in which I have Stripe implemented, the problem is when I try to pay through Stripe on a desktop/PC it works fine but when I try the same thing on a browser using mobile it redirects me to Stripe website and says an error occurred.

Image

This image shows the redirected link when using Stripe payment on mobile.

Below is the code for Stripe:

The request:

```<code>  const [stripeToken, setStripeToken] = useState(null);
  //  const navigate = useNavigate();
  const onToken = (token) => {
    setStripeToken(token);
    // console.log(token);
  };

  useEffect(() => {
    const makeRequest = async () => {
      try {
        const res = await userRequest.post("/checkout/payment", {
          tokenId: stripeToken.id,
          // amount: order.totalPrice,
          amount: 172500,
        });

        history.push("/success", {
          stripeData: res.data,
          // products: cart,
        });
      } catch (err) {
        console.log(err);
      }
    };
    stripeToken && makeRequest();
  }, [stripeToken, history]);

  const orderId = match.params.id;

<StripeCheckout
 name="CCBS Shop"
 billingAddress
 shippingAddress
 description={`Your total is ${order.totalPrice}`}
 amount={172500}
 token={onToken}
 stripeKey={KEY}
>
</code>```

Title: Stripe popup not opening on mobile

Body:
I have a website on MERN STACK in which I have Stripe implemented, the problem is when I try to pay through Stripe on a desktop/PC it works fine but when I try the same thing on a browser using mobile it redirects me to Stripe website and says an error occurred.

Image

This image shows the redirected link when using Stripe payment on mobile.

Below is the code for Stripe:

The request:

  const [stripeToken, setStripeToken] = useState(null);
  //  const navigate = useNavigate();
  const onToken = (token) => {
    setStripeToken(token);
    // console.log(token);
  };

  useEffect(() => {
    const makeRequest = async () => {
      try {
        const res = await userRequest.post("/checkout/payment", {
          tokenId: stripeToken.id,
          // amount: order.totalPrice,
          amount: 172500,
        });

        history.push("/success", {
          stripeData: res.data,
          // products: cart,
        });
      } catch (err) {
        console.log(err);
      }
    };
    stripeToken && makeRequest();
  }, [stripeToken, history]);

  const orderId = match.params.id;

<StripeCheckout
 name="CCBS Shop"
 billingAddress
 shippingAddress
 description={`Your total is ${order.totalPrice}`}
 amount={172500}
 token={onToken}
 stripeKey={KEY}
>


问:
How to mock a return inside the testing method in Spring Boot
Problem: I need to test method to throw the exception in order to do that I need to return empty ArrayList from the method cryptoService.findAll(). How can I mock it?

The test class CSVServiceTests

```<code>class CSVServiceTests {

    @Autowired
    private CSVService csvService;

    @Test
    public void generateCSVReportWithEmptyDB() {

        Throwable t = Assertions.assertThrows(DataNotFoundException.class,
                () -> csvService.generateCSVReport());

        assertEquals("...", t.getMessage());
    }
}

</code>```

The class and method which is testing. I need to mock cryptoService.findAll() to return new ArrayList()

```<code>@Service
public class CSVServiceImpl implements CSVService {

    private final CryptoService cryptoService;

    public ByteArrayInputStream generateCSVReport() {
        List<Crypto> cryptos = cryptoService.findAll();
        // cryptoService.findAll().size() == 6
        if (cryptos.size() == 0)
            throw new DataNotFoundException("There is not enough data to create a CSV: The DB is empty");

        ...
    }
}

</code>```

And bellow a method that should be mocked, but this approach doesn't work inside csvService.generateCSVReport().

```<code>@Mock
private CryptoService cryptoService;

@Test
public void generateCSVReportWithEmptyDB() {
 Mockito.when(cryptoService.findAll()).thenReturn(new ArrayList<>());

 // cryptoService.findAll().size() == 0
 // it will print zero size here, but it doesn't work inside the
 // method `csvService.generateCSVReport()`

 Throwable t = Assertions.assertThrows(DataNotFoundException.class,
                () -> csvService.generateCSVReport());
 assertEquals("...", t.getMessage());
}
</code>```

I tried to mock it, but I couldn't achieve that correctly. I will appreciate your help

Body:
Problem: I need to test method to throw the exception in order to do that I need to return empty ArrayList from the method cryptoService.findAll(). How can I mock it?

The test class CSVServiceTests

class CSVServiceTests {

    @Autowired
    private CSVService csvService;

    @Test
    public void generateCSVReportWithEmptyDB() {

        Throwable t = Assertions.assertThrows(DataNotFoundException.class,
                () -> csvService.generateCSVReport());

        assertEquals("...", t.getMessage());
    }
}

The class and method which is testing. I need to mock cryptoService.findAll() to return new ArrayList()

@Service
public class CSVServiceImpl implements CSVService {

    private final CryptoService cryptoService;

    public ByteArrayInputStream generateCSVReport() {
        List<Crypto> cryptos = cryptoService.findAll();
        // cryptoService.findAll().size() == 6
        if (cryptos.size() == 0)
            throw new DataNotFoundException("There is not enough data to create a CSV: The DB is empty");

        ...
    }
}

And bellow a method that should be mocked, but this approach doesn't work inside csvService.generateCSVReport().

@Mock
private CryptoService cryptoService;

@Test
public void generateCSVReportWithEmptyDB() {
 Mockito.when(cryptoService.findAll()).thenReturn(new ArrayList<>());

 // cryptoService.findAll().size() == 0
 // it will print zero size here, but it doesn't work inside the
 // method `csvService.generateCSVReport()`

 Throwable t = Assertions.assertThrows(DataNotFoundException.class,
                () -> csvService.generateCSVReport());
 assertEquals("...", t.getMessage());
}

I tried to mock it, but I couldn't achieve that correctly. I will appreciate your help


问:
How to avoid the small page movement in a react component at first load
There is a reusable Radio Group component which works fine but it has a small issue, first time it is loaded and the user selects an options it moves fast (maybe re-renders?).

After that it doesn't have the issue anymore but cannot find its root cause.

Here is the code:

radio-button.stories.tsx

```<code>import { ComponentMeta } from '@storybook/react';
import { useState } from 'react';

import RadioButtonGroup from './radio-button-group';
import { IOptionGroup } from './radio-button.types';

export default {
  title: 'Components/RadioButton',
  component: RadioButtonGroup,
} as ComponentMeta<typeof RadioButtonGroup>;

const Template = ({ ...args }: IOptionGroup) => {
  const options = [
    {
      label: 'Coffee',
      name: 'button-types',
    },
    {
      label: 'Tea',
      name: 'button-types',
    },
    {
      label: 'Disabled option',
      name: 'button-types',
      disabled: true,
    },
  ];

  const [selectedValue, setSelectedValue] = useState<string>(options[0].label);

  function radioGroupHandler(event: React.ChangeEvent<HTMLInputElement>) {
    setSelectedValue(event.target.value);
  }

  console.log('selectedValue: ', selectedValue);

  const label = 'Select an option:';

  return (
    <RadioButtonGroup
      {...args}
      options={options}
      label={label}
      onChange={radioGroupHandler}
      horizontal
    />
  );
};

export const button = Template.bind({});
</code>```

radio-button-group.tsx

```<code>import RadioButton from './radio-button';
import { Legend, Fieldset, Horizontal, Vertical } from './radio-button.styles';
import { IOption, IOptionGroup } from './radio-button.types';

export const RadioButtonGroup = ({ label, options, horizontal, onChange }: IOptionGroup) => {
  function getRenderedOptions() {
    return options.map(({ label, name, disabled }: IOption, index) => {
      const shortenedOptionLabel = label.replace(/\s+/g, '');
      const optionId = `radio-option-${shortenedOptionLabel}`;

      return (
        <RadioButton
          value={label}
          label={label}
          key={`${optionId}-${index}`}
          id={optionId}
          name={name}
          disabled={disabled}
          defaultChecked={index === 0}
          onChange={onChange}
        />
      );
    });
  }

  const renderedOptions = horizontal ? (
    <Horizontal>{getRenderedOptions()}</Horizontal>
  ) : (
    <Vertical>{getRenderedOptions()}</Vertical>
  );

  return (
    <Fieldset>
      <Legend>{label}</Legend>
      {renderedOptions}
    </Fieldset>
  );
};
export default RadioButtonGroup;
</code>```

radio-button.tsx

```<code>import { StyledRadioButton, Radio, Wrapper } from './radio-button.styles';
import { RadioButtonProps } from './radio-button.types';

export const RadioButton = ({ label, id, disabled, ...rest }: RadioButtonProps) => {
  return (
    <Wrapper>
      <Radio type="radio" id={id} disabled={disabled} {...rest} />
      <StyledRadioButton htmlFor={id}>{label}</StyledRadioButton>
    </Wrapper>
  );
};

RadioButton.displayName = 'RadioButton';

export default RadioButton;
</code>```

radio-button.types.ts

```<code>import { InputHTMLAttributes } from 'react';

export type option = string | number;
export interface RadioButtonProps extends InputHTMLAttributes<HTMLInputElement> {
  label: string;
  id: string;
  key: string | number;
  disabled?: boolean;
}

export interface IOption {
  label: string;
  name?: string;
  disabled?: boolean;
}

export interface IOptionGroup {
  label: string;
  options: IOption[];
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  horizontal?: boolean;
}
</code>```

radio-button.styles.ts

```<code>import styled from 'styled-components';

export const Fieldset = styled.fieldset`
  border: none;
`;

export const Vertical = styled.div``;

export const Horizontal = styled.div`
  display: flex;
  gap: 1rem;
`;

export const StyledRadioButton = styled.label<{ disabled?: boolean }>`
  font-weight: 400;
  font-size: 16px;
  color: black;
`;

export const Legend = styled.legend`
  font-weight: 400;
  font-size: 16px;
  color: black;
`;

export const Wrapper = styled.div`
  display: flex;
  gap: 1rem;
  margin-top: 0.5rem;
  margin-bottom: 0.5rem;
  align-items: center;
`;

export const Radio = styled.input`
  -webkit-appearance: none;
  appearance: none;
  margin: 0;
  width: 1.5em;
  height: 1.5em;
  border: 1px solid grey;
  font-size: 16px;
  font-style: normal;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.1s ease-in-out;
  ::after {
    content: '';
    display: block;
    border-radius: 50%;
    width: 0.75em;
    height: 0.75em;
    margin: 4.26px;
  }
  :checked {
    ::after {
      background-color: blue;
    }
    border: 1px solid green;
  }
  :hover {
    border: 1px solid red;
  }
  border: 1px solid red;
  :disabled {
    cursor: not-allowed;
    border: 1px solid grey;
    background-color: grey;
    :checked {
      ::after {
        background-color: grey;
      }
    }
  }
`;
</code>```

Here is a video of the issue: https://www.dropbox.com/s/j5nx2vpiscmbvxm/Screen%20Recording%202023-01-02%20at%2022.28.45.mov?dl=0

Body:
There is a reusable Radio Group component which works fine but it has a small issue, first time it is loaded and the user selects an options it moves fast (maybe re-renders?).

After that it doesn't have the issue anymore but cannot find its root cause.

Here is the code:

radio-button.stories.tsx

import { ComponentMeta } from '@storybook/react';
import { useState } from 'react';

import RadioButtonGroup from './radio-button-group';
import { IOptionGroup } from './radio-button.types';

export default {
  title: 'Components/RadioButton',
  component: RadioButtonGroup,
} as ComponentMeta<typeof RadioButtonGroup>;

const Template = ({ ...args }: IOptionGroup) => {
  const options = [
    {
      label: 'Coffee',
      name: 'button-types',
    },
    {
      label: 'Tea',
      name: 'button-types',
    },
    {
      label: 'Disabled option',
      name: 'button-types',
      disabled: true,
    },
  ];

  const [selectedValue, setSelectedValue] = useState<string>(options[0].label);

  function radioGroupHandler(event: React.ChangeEvent<HTMLInputElement>) {
    setSelectedValue(event.target.value);
  }

  console.log('selectedValue: ', selectedValue);

  const label = 'Select an option:';

  return (
    <RadioButtonGroup
      {...args}
      options={options}
      label={label}
      onChange={radioGroupHandler}
      horizontal
    />
  );
};

export const button = Template.bind({});

radio-button-group.tsx

import RadioButton from './radio-button';
import { Legend, Fieldset, Horizontal, Vertical } from './radio-button.styles';
import { IOption, IOptionGroup } from './radio-button.types';

export const RadioButtonGroup = ({ label, options, horizontal, onChange }: IOptionGroup) => {
  function getRenderedOptions() {
    return options.map(({ label, name, disabled }: IOption, index) => {
      const shortenedOptionLabel = label.replace(/\s+/g, '');
      const optionId = `radio-option-${shortenedOptionLabel}`;

      return (
        <RadioButton
          value={label}
          label={label}
          key={`${optionId}-${index}`}
          id={optionId}
          name={name}
          disabled={disabled}
          defaultChecked={index === 0}
          onChange={onChange}
        />
      );
    });
  }

  const renderedOptions = horizontal ? (
    <Horizontal>{getRenderedOptions()}</Horizontal>
  ) : (
    <Vertical>{getRenderedOptions()}</Vertical>
  );

  return (
    <Fieldset>
      <Legend>{label}</Legend>
      {renderedOptions}
    </Fieldset>
  );
};
export default RadioButtonGroup;

radio-button.tsx

import { StyledRadioButton, Radio, Wrapper } from './radio-button.styles';
import { RadioButtonProps } from './radio-button.types';

export const RadioButton = ({ label, id, disabled, ...rest }: RadioButtonProps) => {
  return (
    <Wrapper>
      <Radio type="radio" id={id} disabled={disabled} {...rest} />

    </Wrapper>
  );
};

RadioButton.displayName = 'RadioButton';

export default RadioButton;

radio-button.types.ts

import { InputHTMLAttributes } from 'react';

export type option = string | number;
export interface RadioButtonProps extends InputHTMLAttributes<HTMLInputElement> {
  label: string;
  id: string;
  key: string | number;
  disabled?: boolean;
}

export interface IOption {
  label: string;
  name?: string;
  disabled?: boolean;
}

export interface IOptionGroup {
  label: string;
  options: IOption[];
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  horizontal?: boolean;
}

radio-button.styles.ts

import styled from 'styled-components';

export const Fieldset = styled.fieldset`
  border: none;
`;

export const Vertical = styled.div``;

export const Horizontal = styled.div`
  display: flex;
  gap: 1rem;
`;

export const StyledRadioButton = styled.label<{ disabled?: boolean }>`
  font-weight: 400;
  font-size: 16px;
  color: black;
`;

export const Legend = styled.legend`
  font-weight: 400;
  font-size: 16px;
  color: black;
`;

export const Wrapper = styled.div`
  display: flex;
  gap: 1rem;
  margin-top: 0.5rem;
  margin-bottom: 0.5rem;
  align-items: center;
`;

export const Radio = styled.input`
  -webkit-appearance: none;
  appearance: none;
  margin: 0;
  width: 1.5em;
  height: 1.5em;
  border: 1px solid grey;
  font-size: 16px;
  font-style: normal;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.1s ease-in-out;
  ::after {
    content: '';
    display: block;
    border-radius: 50%;
    width: 0.75em;
    height: 0.75em;
    margin: 4.26px;
  }
  :checked {
    ::after {
      background-color: blue;
    }
    border: 1px solid green;
  }
  :hover {
    border: 1px solid red;
  }
  border: 1px solid red;
  :disabled {
    cursor: not-allowed;
    border: 1px solid grey;
    background-color: grey;
    :checked {
      ::after {
        background-color: grey;
      }
    }
  }
`;

Here is a video of the issue: https://www.dropbox.com/s/j5nx2vpiscmbvxm/Screen%20Recording%202023-01-02%20at%2022.28.45.mov?dl=0


问:
How can I make the word document orientation to be a landscape?
Below is the VBA code I use. I tried to add .PageSetup.Orientation = wdOrientLandscape without a success.

```<code>Sub Export_EU_Quote()

Dim WdObj As Object

Set WdObj = CreateObject("Word.Application")
WdObj.Visible = True
Range("A1:E50").Select
Selection.Copy 'Your Copy Range
WdObj.Documents.Add

WdObj.Selection.PasteExcelTable _
    LinkedToExcel:=False, _
    WordFormatting:=False, _
    RTF:=False

WdObj.ActiveDocument.Range.ParagraphFormat.SpaceAfter = 0

Application.CutCopyMode = False

Set WdObj = Nothing
End Sub
</code>```

I would like to export an excel page to word in landscape page format since the columns do not fit a portrait page

Body:
Below is the VBA code I use. I tried to add .PageSetup.Orientation = wdOrientLandscape without a success.

Sub Export_EU_Quote()

Dim WdObj As Object

Set WdObj = CreateObject("Word.Application")
WdObj.Visible = True
Range("A1:E50").Select
Selection.Copy 'Your Copy Range
WdObj.Documents.Add

WdObj.Selection.PasteExcelTable _
    LinkedToExcel:=False, _
    WordFormatting:=False, _
    RTF:=False

WdObj.ActiveDocument.Range.ParagraphFormat.SpaceAfter = 0

Application.CutCopyMode = False

Set WdObj = Nothing
End Sub

I would like to export an excel page to word in landscape page format since the columns do not fit a portrait page