问:
Terraform get tfvars file from remote repository
I have .tfvars file in remote repository for some other infrastructure. I want to reuse the config file. I am working on new infrastructure but need to use the content of .tfvars. So far tried the following but I am not sure how to read the file I got via http url. Is there a better way of getting remote config?

```<code>data "http" "tfvars" {
  url = "https://some@dev.azure.com/some/_git/sampleinfra?path=/infra/variable_folders.auto.tfvars"
  request_headers = {
    Accept = "application/json"
  }
}
</code>```

I want to add that the content of the file is json array

```<code>    folderList = {
    "main" = {
        process= true
    }
    "base" = {
        process= false
    }
  }
</code>```

Body:
I have .tfvars file in remote repository for some other infrastructure. I want to reuse the config file. I am working on new infrastructure but need to use the content of .tfvars. So far tried the following but I am not sure how to read the file I got via http url. Is there a better way of getting remote config?

data "http" "tfvars" {
  url = "https://some@dev.azure.com/some/_git/sampleinfra?path=/infra/variable_folders.auto.tfvars"
  request_headers = {
    Accept = "application/json"
  }
}

I want to add that the content of the file is json array

    folderList = {
    "main" = {
        process= true
    }
    "base" = {
        process= false
    }
  }


来源: stackexchange

问:
cookie-session, socket.io fails to store socket.id in sessions
server.js

```<code>const express = require("express");
const cookieSession = require("cookie-session");
const socketIo = require("socket.io");

const app = express();

app.use(
  cookieSession({
    name: "session",
    keys: ["key1", "key2"],
  })
);

app.use((req, res, next) => {
  console.log(req.session);
  next();
});

app.get("/", (req, res) => {
  res.sendFile("./index.html", { root: __dirname });
});

app.get("/about", (req, res) => {
  const connectionId = req.session.connectionId;
  res.send(`About. connectionId: ${connectionId}`);
});

const server = app.listen(1234);
const io = socketIo(server);

io.on("connection", (socket) => {
  const connectionId = Math.random().toString(36).substring(2);
  socket.request.session.connectionId = connectionId;
  // socket.request.session.save();
});
</code>```

My problem is that when I call the connect event on the client, but on the server socket.request.session returns undefined so I can't set a unique value in the cookie-session. What is it connected with?

ContentLicense: CC BY-SA 4.0

Body:
server.js

const express = require("express");
const cookieSession = require("cookie-session");
const socketIo = require("socket.io");

const app = express();

app.use(
  cookieSession({
    name: "session",
    keys: ["key1", "key2"],
  })
);

app.use((req, res, next) => {
  console.log(req.session);
  next();
});

app.get("/", (req, res) => {
  res.sendFile("./index.html", { root: __dirname });
});

app.get("/about", (req, res) => {
  const connectionId = req.session.connectionId;
  res.send(`About. connectionId: ${connectionId}`);
});

const server = app.listen(1234);
const io = socketIo(server);

io.on("connection", (socket) => {
  const connectionId = Math.random().toString(36).substring(2);
  socket.request.session.connectionId = connectionId;
  // socket.request.session.save();
});

My problem is that when I call the connect event on the client, but on the server socket.request.session returns undefined so I can't set a unique value in the cookie-session. What is it connected with?


问:
How to implement authorization for function access in Excel dna project
I work on Excel dna project under C# and .NET Core.

I have severals hundreds of Excel functions. I would like to handle authorization on specific class that regoup Excel functions.

For example, if a user is not authenticate, he don't have to get accessed those restricted access functions.

I don't know how to do that. I read this paper: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/secure-data?view=aspnetcore-7.0. But I have some difficulties to see how implement this feature.

Does anyone have en idea?


问:
Facebook: I get "Invalid Page ID" after doing a page merge of two pages that belong to a page structure. Not sure how to proceed
I have a Facebook page structure (parent page and 3 child pages) and we just merged two of the child pages and all seemed ok.
But when going to the "Store locations" page, I see the following message for each of the pages in the structure.
Invalid Page ID ******. Please update your API calls to use Page ID *****

Store_locations screenshot

I don't know what's going on or how to update the API calls.

I tried waiting a few days as I thought the merge was still in process. Also tried searching in Google and Stackoverflow but couldn't find anything related to this situation on a FB page structure.


问:
AWS Amplify React - Deployment and Authentication No Longer Working
I have a React application that I deployed to AWS Amplify which has been working just fine. I deployed the application in September of this year, and decided to make a minor HTML update yesterday. I tried to re-deploy the application but I am facing two issues: (1) First, I keep getting an error in the deployment process. You can see the end of the log of the error below:

```<code>...
...
2022-12-23T12:45:48.274Z [INFO]: npm ERR! code 127
2022-12-23T12:45:48.277Z [INFO]: npm ERR! path
/root/.nvm/versions/node/v16.19.0/lib/node_modules/@aws-amplify/cli/node_modules/babel-runtime/node_modules/core-js
                                 npm ERR! command failed
                                 npm ERR! command sh -c -- node -e "try{require('./postinstall')}catch(e){}"
                                 npm ERR! sh: node: command not found
2022-12-23T12:45:48.277Z [INFO]: npm ERR! A complete log of this run can be found in:
                                 npm ERR!     /root/.npm/_logs/2022-12-23T12_42_58_395Z-debug-0.log
2022-12-23T12:45:48.340Z [WARNING]: Process exited with exit code: 127
2022-12-23T12:45:48.340Z [INFO]: ! Error patching NPM package '@aws-amplify/cli' to version 7.6.19
2022-12-23T12:45:48.346Z [INFO]: # Retrieving cache...
2022-12-23T12:45:55.639Z [INFO]: # Extracting cache...
2022-12-23T12:46:05.281Z [INFO]: # Extraction completed
2022-12-23T12:46:05.469Z [INFO]: # Retrieved cache
2022-12-23T12:46:38.486Z [INFO]: ## Starting Backend Build
                                 # Starting phase: build
                                 ## Running amplify pull to generate aws-exports.js file for frontend
2022-12-23T12:46:43.354Z [INFO]: [31mInvalid feature flag configuration[39m
2022-12-23T12:46:43.356Z [INFO]: [31mThese feature flags are defined in the "amplify/cli.json" configuration file and are unknown to the currently running Amplify CLI:[39m
                                 [31m  - graphqltransformer.showfieldauthnotification[39m
                                 [31mThis issue likely happens when the project has been pushed with a newer version of Amplify CLI, try updating to a newer version.[39m
                                 [31mEnsure that the CI/CD pipeline is not using an older or pinned down version of Amplify CLI.[39m
                                 [31mLearn more about feature flags: https://docs.amplify.aws/cli/reference/feature-flags[39m
2022-12-23T12:46:43.373Z [ERROR]: !!! Build failed
2022-12-23T12:46:43.373Z [ERROR]: !!! Non-Zero Exit Code detected
2022-12-23T12:46:43.373Z [INFO]: # Starting environment caching...
2022-12-23T12:46:43.374Z [INFO]: # Uploading environment cache artifact...
2022-12-23T12:46:43.486Z [INFO]: # Uploaded environment cache artifact
2022-12-23T12:46:43.487Z [INFO]: # Environment caching completed
Terminating logging...
</code>```

...I tried to (1) delete node_modules, and run npm install again, but that was not successful. I noticed that the most recent aws-amplify/cli is a higher version than the one I am using, but I set the 7.6.19 version in the Build parameters in AWS, so I can't imagine that this is the issue. I upgraded the local cli to the current version, but that did not make a difference either.

The (2) second issue I am facing is that user authentication is no longer working when I run the application locally on my machine. I even reverted back to the commit that was working, and even that is not able to allow users to login. Keep in mind the version in production is just fine (and its the same version as the commit I tried locally).

My question is: What do these errors have in common, and can you suggest a path forward to address this?

Body:
I have a React application that I deployed to AWS Amplify which has been working just fine. I deployed the application in September of this year, and decided to make a minor HTML update yesterday. I tried to re-deploy the application but I am facing two issues: (1) First, I keep getting an error in the deployment process. You can see the end of the log of the error below:

...
...
2022-12-23T12:45:48.274Z [INFO]: npm ERR! code 127
2022-12-23T12:45:48.277Z [INFO]: npm ERR! path
/root/.nvm/versions/node/v16.19.0/lib/node_modules/@aws-amplify/cli/node_modules/babel-runtime/node_modules/core-js
                                 npm ERR! command failed
                                 npm ERR! command sh -c -- node -e "try{require('./postinstall')}catch(e){}"
                                 npm ERR! sh: node: command not found
2022-12-23T12:45:48.277Z [INFO]: npm ERR! A complete log of this run can be found in:
                                 npm ERR!     /root/.npm/_logs/2022-12-23T12_42_58_395Z-debug-0.log
2022-12-23T12:45:48.340Z [WARNING]: Process exited with exit code: 127
2022-12-23T12:45:48.340Z [INFO]: ! Error patching NPM package '@aws-amplify/cli' to version 7.6.19
2022-12-23T12:45:48.346Z [INFO]: # Retrieving cache...
2022-12-23T12:45:55.639Z [INFO]: # Extracting cache...
2022-12-23T12:46:05.281Z [INFO]: # Extraction completed
2022-12-23T12:46:05.469Z [INFO]: # Retrieved cache
2022-12-23T12:46:38.486Z [INFO]: ## Starting Backend Build
                                 # Starting phase: build
                                 ## Running amplify pull to generate aws-exports.js file for frontend
2022-12-23T12:46:43.354Z [INFO]: [31mInvalid feature flag configuration[39m
2022-12-23T12:46:43.356Z [INFO]: [31mThese feature flags are defined in the "amplify/cli.json" configuration file and are unknown to the currently running Amplify CLI:[39m
                                 [31m  - graphqltransformer.showfieldauthnotification[39m
                                 [31mThis issue likely happens when the project has been pushed with a newer version of Amplify CLI, try updating to a newer version.[39m
                                 [31mEnsure that the CI/CD pipeline is not using an older or pinned down version of Amplify CLI.[39m
                                 [31mLearn more about feature flags: https://docs.amplify.aws/cli/reference/feature-flags[39m
2022-12-23T12:46:43.373Z [ERROR]: !!! Build failed
2022-12-23T12:46:43.373Z [ERROR]: !!! Non-Zero Exit Code detected
2022-12-23T12:46:43.373Z [INFO]: # Starting environment caching...
2022-12-23T12:46:43.374Z [INFO]: # Uploading environment cache artifact...
2022-12-23T12:46:43.486Z [INFO]: # Uploaded environment cache artifact
2022-12-23T12:46:43.487Z [INFO]: # Environment caching completed
Terminating logging...

...I tried to (1) delete node_modules, and run npm install again, but that was not successful. I noticed that the most recent aws-amplify/cli is a higher version than the one I am using, but I set the 7.6.19 version in the Build parameters in AWS, so I can't imagine that this is the issue. I upgraded the local cli to the current version, but that did not make a difference either.

The (2) second issue I am facing is that user authentication is no longer working when I run the application locally on my machine. I even reverted back to the commit that was working, and even that is not able to allow users to login. Keep in mind the version in production is just fine (and its the same version as the commit I tried locally).

My question is: What do these errors have in common, and can you suggest a path forward to address this?


问:
How to turn a ch to int in assembly?
I have as an assignment to make an assembly program that reads the users input as postfix and when you input '=' it gives you the result, and to do that I'm required to use a stack. The problem is that the stack I use has character type inputs and I don't know how to turn them to integers to do the required operations.

That's what I have done till now:

```<code>.text
.globl main

main:
    #Preload the operations
    li $s1, '+'
    li $s2, '-'
    li $s3, '*'
    li $s4, '/'
    li $s5, '='

    li $v0,4
    la $a0,prompt
    syscall

    li $v0, 12
    syscall
    move $t0, $v0

    sub $sp, $sp, 4
    sw $t0, ($sp)

    bne $t0, '=', loop

    li $v0, 4
    la $a0, error
    syscall

    li $v0, 10
    syscall
loop:

    li $v0,4
    la $a0, prompt
    syscall

    li $v0,12
    syscall
    move $t1, $v0

    beq $t1, '=', result_process
    beq $t1, ' ', loop

    sub $sp, $sp, 4
    sw $t1, ($sp)

    blt $t1, '0', operations
    bgt $t1, '9', operations
    j loop

    li $v0, 10
    syscall

operations:
    lw $t2, ($sp)
    add $sp, $sp, 4

    lw $t3, ($sp)
    add $sp, $sp, 4

    beq $t1, '+', add_process
    beq $t1, '-', sub_process
    beq $t1, '*', mul_process
    beq $t1, '/', div_process

add_process:
    add $t4, $t2, $t3

    sub $sp, $sp, 4
    sw $t4, ($sp)

    j loop

sub_process:
    sub $t4, $t2, $t3

    sub $sp, $sp, 4
    sw $t4, ($sp)

    j loop

mul_process:
    mul $t4, $t2, $t3

    sub $sp, $sp, 4
    sw $t4, ($sp)

    j loop

div_process:
    beq $t3, '0', error_div
    div $t4, $t2, $t3

    sub $sp, $sp, 4
    sw $t4, ($sp)

    j loop

result_process:
    lw $t5, ($sp)
    add $sp, $sp, 4

    li $v0,4
    la $a0, result
    syscall

    move $a0, $t5
    li $v0, 11
    syscall

    li $v0,10
    syscall

error_div:
    li $v0,4
    la $a0, div_error
    syscall

    li $v0, 10
    syscall

.data
prompt: .asciiz "\nPostfix (input): "
error: .asciiz "\nInvalid Postfix!"
div_error: .asciiz "\nDivide by zero!"
test: .asciiz  "\nWorks!"
result: .asciiz "\nPostfix evaluation: "
</code>```

My only question is how do I turn a character input to integer in assembly, like is there a command ?(I know it stills need work btw) thanks in advance for any information!

Title: How to turn a ch to int in assembly?

Body:
I have as an assignment to make an assembly program that reads the users input as postfix and when you input '=' it gives you the result, and to do that I'm required to use a stack. The problem is that the stack I use has character type inputs and I don't know how to turn them to integers to do the required operations.

That's what I have done till now:

.text
.globl main

main:
    #Preload the operations
    li $s1, '+'
    li $s2, '-'
    li $s3, '*'
    li $s4, '/'
    li $s5, '='

    li $v0,4
    la $a0,prompt
    syscall

    li $v0, 12
    syscall
    move $t0, $v0

    sub $sp, $sp, 4
    sw $t0, ($sp)

    bne $t0, '=', loop

    li $v0, 4
    la $a0, error
    syscall

    li $v0, 10
    syscall
loop:

    li $v0,4
    la $a0, prompt
    syscall

    li $v0,12
    syscall
    move $t1, $v0

    beq $t1, '=', result_process
    beq $t1, ' ', loop

    sub $sp, $sp, 4
    sw $t1, ($sp)

    blt $t1, '0', operations
    bgt $t1, '9', operations
    j loop

    li $v0, 10
    syscall

operations:
    lw $t2, ($sp)
    add $sp, $sp, 4

    lw $t3, ($sp)
    add $sp, $sp, 4

    beq $t1, '+', add_process
    beq $t1, '-', sub_process
    beq $t1, '*', mul_process
    beq $t1, '/', div_process

add_process:
    add $t4, $t2, $t3

    sub $sp, $sp, 4
    sw $t4, ($sp)

    j loop

sub_process:
    sub $t4, $t2, $t3

    sub $sp, $sp, 4
    sw $t4, ($sp)

    j loop

mul_process:
    mul $t4, $t2, $t3

    sub $sp, $sp, 4
    sw $t4, ($sp)

    j loop

div_process:
    beq $t3, '0', error_div
    div $t4, $t2, $t3

    sub $sp, $sp, 4
    sw $t4, ($sp)

    j loop

result_process:
    lw $t5, ($sp)
    add $sp, $sp, 4

    li $v0,4
    la $a0, result
    syscall

    move $a0, $t5
    li $v0, 11
    syscall

    li $v0,10
    syscall

error_div:
    li $v0,4
    la $a0, div_error
    syscall

    li $v0, 10
    syscall

.data
prompt: .asciiz "\nPostfix (input): "
error: .asciiz "\nInvalid Postfix!"
div_error: .asciiz "\nDivide by zero!"
test: .asciiz  "\nWorks!"
result: .asciiz "\nPostfix evaluation: "

My only question is how do I turn a character input to integer in assembly, like is there a command ?(I know it stills need work btw) thanks in advance for any information!


问:
Return value from dropdown button in kivy
I currently have a code that runs a dropdown button in kivy. I would like to send the value 1,2,3,4 into the main class when the value is selected.

Specifying chain of events:

click dropdown button

four options are displayed

select one of the four options ==> this is when the value gets sent back to the main class

dropdown button text replaced with the selection

I have tried using get_screen(), which is equivalent to get_running_app when using windows, but this was delayed. I also tried creating an external variable but this was delayed too.

Below is my code. Thanks.

'''

```<code>from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.dropdown import DropDown

class WindowManager(ScreenManager):
    pass

class Drop_down(DropDown):
   pass

class MenuWindow(Screen):
    General_select_button_size = (100, 100)
    General_select_button_pos = (400, 400)

class GeneralWindow(Screen):

    drop_size = (100,100)
    drop_pos = (400,400)

    xax=''
    def on_touch_up(self,touch):
        app = self.manager.get_screen('General')
        print('use get',app.ids['btn'].text)
        print('use variable',self.xax)

KV = Builder.load_string("""

WindowManager:
    MenuWindow:
    GeneralWindow:

<MenuWIndow>:
    name: 'Menu'
    RelativeLayout:
        Button:
            allow_stretch: True
            keep_ratio: True
            size_hint: None,None
            id: general_select_button
            text: 'move to general mode'
            size: root.General_select_button_size
            pos: root.General_select_button_pos
            on_release:
                app.root.current = "General"
                root.manager.transition.direction = "left"

<GeneralWindow>:
    name: 'General'

    RelativeLayout:
        Button:
            allow_stretch: True
            keep_ratio: True
            size_hint: None,None
            id: btn
            text: 'select number'
            size: root.drop_size
            pos: root.drop_pos
            on_parent: drop_content.dismiss()
            on_release:
                drop_content.open(self)
                root.xax=btn.text

        DropDown:
            id: drop_content
            on_select: btn.text = '{}'.format(args[1])

            Button:
                id: btn1
                text: '1'
                size_hint_y: None
                height: 30
                on_release: drop_content.select('1')
            Button:
                id: btn2
                text:'2'
                size_hint_y: None
                height: 30
                on_release: drop_content.select('2')
            Button:
                id: btn3
                text: '3'
                size_hint_y: None
                height: 30
                on_release: drop_content.select('3')
            Button:
                id: btn4
                text: '4'
                size_hint_y: None
                height: 30
                on_release: drop_content.select('4')

""")

class ImageChangeApp(App):

    def build(self):
        return KV

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

'''

Body:
I currently have a code that runs a dropdown button in kivy. I would like to send the value 1,2,3,4 into the main class when the value is selected.

Specifying chain of events:

click dropdown button

four options are displayed

select one of the four options ==> this is when the value gets sent back to the main class

dropdown button text replaced with the selection

I have tried using get_screen(), which is equivalent to get_running_app when using windows, but this was delayed. I also tried creating an external variable but this was delayed too.

Below is my code. Thanks.

'''

from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.dropdown import DropDown

class WindowManager(ScreenManager):
    pass

class Drop_down(DropDown):
   pass

class MenuWindow(Screen):
    General_select_button_size = (100, 100)
    General_select_button_pos = (400, 400)

class GeneralWindow(Screen):

    drop_size = (100,100)
    drop_pos = (400,400)

    xax=''
    def on_touch_up(self,touch):
        app = self.manager.get_screen('General')
        print('use get',app.ids['btn'].text)
        print('use variable',self.xax)

KV = Builder.load_string("""

WindowManager:
    MenuWindow:
    GeneralWindow:

<MenuWIndow>:
    name: 'Menu'
    RelativeLayout:
        Button:
            allow_stretch: True
            keep_ratio: True
            size_hint: None,None
            id: general_select_button
            text: 'move to general mode'
            size: root.General_select_button_size
            pos: root.General_select_button_pos
            on_release:
                app.root.current = "General"
                root.manager.transition.direction = "left"

<GeneralWindow>:
    name: 'General'

    RelativeLayout:
        Button:
            allow_stretch: True
            keep_ratio: True
            size_hint: None,None
            id: btn
            text: 'select number'
            size: root.drop_size
            pos: root.drop_pos
            on_parent: drop_content.dismiss()
            on_release:
                drop_content.open(self)
                root.xax=btn.text

        DropDown:
            id: drop_content
            on_select: btn.text = '{}'.format(args[1])

            Button:
                id: btn1
                text: '1'
                size_hint_y: None
                height: 30
                on_release: drop_content.select('1')
            Button:
                id: btn2
                text:'2'
                size_hint_y: None
                height: 30
                on_release: drop_content.select('2')
            Button:
                id: btn3
                text: '3'
                size_hint_y: None
                height: 30
                on_release: drop_content.select('3')
            Button:
                id: btn4
                text: '4'
                size_hint_y: None
                height: 30
                on_release: drop_content.select('4')

""")

class ImageChangeApp(App):

    def build(self):
        return KV

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

'''


问:
MySQL won't let me run scripts
I have a problem with MySQL. When I try to run the script, I get one of two errors:

Preparing... [WinError 32] The process cannot access the file because it is being used by another process:

The first one I get if I don't select default schema. That makes some sense, but I get a different one when I do select default schema:

sequence item 6: expected str instance, bytes found

If I try to open script to run it, I get this window:

I checked on different machine and the encoding was utf8, but on my machine I can only open it with latin1 encoding and that way data in database gets corrupted.

This is what I get if I choose utf8 or any other encoding:
The file contents could not be converted from 'utf8' to UTF-8: Invalid byte sequence in conversion input

This happens with any script I try, no matter the content in it.

Here is an example of a script that doesn't work:

SET @organizationId = 34299;

SET @userId = (SELECT max(user.id) FROM user);

INSERT IGNORE INTO user (id, uuid, username, password, first_name, last_name, email, owner_organization_id, sign_app_port) VALUES (@userId + 1, uuid(),'test@gmail.rs','$2a$10$Gt/hIHyrP2NNzDoC5bbu5K9CKlyZJXEy', 'Test', 'Test','test@gmail.rs', @organizationId, 8086);
INSERT IGNORE INTO user (id, uuid, username, password, first_name, last_name, email, owner_organization_id, sign_app_port) VALUES (@userId + 2, uuid(),'test2@gmail.rs','$2a$10$dva/lg08AtbWfDoC5bbuzmhfB0F.9hMi', 'Test', 'Test','test2@gmail.rs', @organizationId, 8086);
```

I couldn't find similar problems on the internet nor anything helpful. I tried installing mysql again, even tried some older versions, but that didn't work either (OS is Windows 10 professional).
Thank you in advance for anything helpful.

Title: MySQL won't let me run scripts

Body:
I have a problem with MySQL. When I try to run the script, I get one of two errors:

Preparing... [WinError 32] The process cannot access the file because it is being used by another process:

The first one I get if I don't select default schema. That makes some sense, but I get a different one when I do select default schema:

sequence item 6: expected str instance, bytes found

If I try to open script to run it, I get this window:

I checked on different machine and the encoding was utf8, but on my machine I can only open it with latin1 encoding and that way data in database gets corrupted.

This is what I get if I choose utf8 or any other encoding:
The file contents could not be converted from 'utf8' to UTF-8: Invalid byte sequence in conversion input

This happens with any script I try, no matter the content in it.

Here is an example of a script that doesn't work:

SET @organizationId = 34299;

SET @userId = (SELECT max(user.id) FROM user);

INSERT IGNORE INTO user (id, uuid, username, password, first_name, last_name, email, owner_organization_id, sign_app_port) VALUES (@userId + 1, uuid(),'test@gmail.rs','$2a$10$Gt/hIHyrP2NNzDoC5bbu5K9CKlyZJXEy', 'Test', 'Test','test@gmail.rs', @organizationId, 8086);
INSERT IGNORE INTO user (id, uuid, username, password, first_name, last_name, email, owner_organization_id, sign_app_port) VALUES (@userId + 2, uuid(),'test2@gmail.rs','$2a$10$dva/lg08AtbWfDoC5bbuzmhfB0F.9hMi', 'Test', 'Test','test2@gmail.rs', @organizationId, 8086);

I couldn't find similar problems on the internet nor anything helpful. I tried installing mysql again, even tried some older versions, but that didn't work either (OS is Windows 10 professional).
Thank you in advance for anything helpful.


问:
How to make play an animation from current frame until N seconds en Rive
I have an animation and an input, I want to play my animation N seconds from current frame every time  my input change his value

I was using scrub function but that only jumps between frames, that help to has controll over the animation but it seem a little laggy


问:
Replace column text of gridView in vb6
I want to replace all the columns in a gridview having a text value of "," with blank. How do I do that?

I try to just to give string value to the particular index column:

```<code>GridviewName.Columns.Item(3).text=""
</code>```

But that generates this error:

```<code>Error with dataType mismatch while updating field
</code>```

Title: Replace column text of gridView in vb6

Body:
I want to replace all the columns in a gridview having a text value of "," with blank. How do I do that?

I try to just to give string value to the particular index column:

GridviewName.Columns.Item(3).text=""

But that generates this error:

Error with dataType mismatch while updating field


问:
How do I build this query in yii2; myField like "firstname%lastname"
I have been using the Query builder in Yii2. When trying to make a filter like this:

```<code>      where myaddress like 'avenue%12%espe'
</code>```

When I tried this:

```<code>andWhere('like','myaddress', 'avenue%12%espe')
</code>```

The constructor detect % caracter and inserts escape wildcards automatically and ignores them, help please

Regards

Body:
I have been using the Query builder in Yii2. When trying to make a filter like this:

      where myaddress like 'avenue%12%espe'

When I tried this:

andWhere('like','myaddress', 'avenue%12%espe')

The constructor detect % caracter and inserts escape wildcards automatically and ignores them, help please

Regards


问:
No output in the UI on button click, in console log, response is showing 200 - ReactJS
I have the following piece of code, where on button click the UI should render question where user can select the right answer:

```<code>import React, { Component } from 'react';
import { Configuration, OpenAIApi } from 'openai';

class QuizApp extends Component {
  constructor(props) {
    super(props);

    this.state = {
      bookName: '', // name of the book the user enters
      questions: [], // array of questions to display to the user
      currentQuestionIndex: 0, // index of the current question being displayed
      userAnswer: null, // the answer the user has selected
      correctAnswer: null, // the correct answer to the current question
      feedback: '' // feedback to show the user if their answer was correct or not
    };
  }

  // function to handle changes to the book name input
  handleBookNameChange = (event) => {
    this.setState({ bookName: event.target.value });
  }

  // function to handle the user selecting an answer
  handleAnswerSelection = (event) => {
    this.setState({ userAnswer: event.target.value }, () => {
      // check if the user's answer is correct
      if (this.state.userAnswer === this.state.correctAnswer) {
        this.setState({ feedback: 'Correct!' });
      } else {
        this.setState({ feedback: 'Incorrect :(' });
      }
    });
  }

  handleNextButtonClick = () => {
    this.setState((prevState) => {
      if (prevState.currentQuestionIndex + 1 < this.state.questions.length) {
        return {
          currentQuestionIndex: prevState.currentQuestionIndex + 1,
          userAnswer: null,
          correctAnswer: this.state.questions[prevState.currentQuestionIndex + 1].correctAnswer,
          feedback: ''
        };
      }
    });
  };

  // function to generate questions using the GPT-3 API
  generateQuestions = async () => {
    // set up openai with your API key and the name of the model you want to use
    const configuration = new Configuration({
      apiKey: 'someapikey',
    });
    const openai = new OpenAIApi(configuration);

    // use GPT-3 to generate 5 questions based on the book name
    const response = await openai.createCompletion({
      model: 'text-davinci-003',
      prompt: `Generate 5 quiz questions about ${this.state.bookName}`,
      max_tokens: 2048,
      n: 5,
      stop: 'Q:',
      temperature: 0.5
    });
    console.log(response);

    // parse the response and extract the questions and answers
    const questions = response.data.choices[0].text.split('\nQ:').map((question) => {
        const [text, ...choices] = question.split('\nA:');
        const correctAnswer = choices.find((choice) => choice.startsWith('*'));
        if (correctAnswer) {
            console.log(text);
          console.log(choices);
          console.log(correctAnswer);
          return {
            text,
            choices: choices.map((choice) => choice.replace('*', '').trim()),
            correctAnswer: correctAnswer.replace('*', '').trim()
          };
        }
      }).filter(Boolean);

      if (questions.length > 0) {
        // set the questions array and currentQuestion variable with the data from the API response
        this.setState({ questions, currentQuestion: questions[0] });
      }}
  render() {
    const { bookName, questions, currentQuestionIndex, userAnswer, correctAnswer = '', feedback } = this.state;
    const currentQuestion = questions[currentQuestionIndex];

    return (
        <div>
        {/* input field for the book name */}
        <label htmlFor="book-name-input">Enter a book name:</label>
        <input
          id="book-name-input"
          type="text"
          value={bookName}
          onChange={this.handleBookNameChange}
        />
        <button onClick={this.generateQuestions}>Generate Questions</button>
        {questions.length > 0 ? (
          <>
            {/* display the current question and the choices */}
            <div>{currentQuestion.text}</div>
            {currentQuestion.choices.map((choice) => (
              <div key={choice}>
                <input
                  type="radio"
                  value={choice}
                  checked={userAnswer === choice}
                  onChange={this.handleAnswerSelection}
                />
                {choice}
              </div>
            ))}
            {/* display the feedback and next button if the user has answered the question */}
            {userAnswer !== null && (
              <>
                <div>{feedback}</div>
                <button onClick={this.handleNextButtonClick}>Next</button>
              </>
            )}
          </>
        ) : (
          <div>Enter a book name and click the "Generate Questions" button to get started.</div>
        )}
      </div>
    );
  }
}

export default QuizApp;
</code>```

However, on the button click, on the UI side, nothing is showing. If I check the console, I can see that the request is returned with a 200.

```<code>{data: {…}, status: 200, statusText: '', headers: {…}, config: {…}, …}
config
:
{transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
data
:
{id: 'cmpl-6QdVYvHhURjNVlXRugMrWe2DEawT3', object: 'text_completion', created: 1671806416, model: 'text-davinci-003', choices: Array(5), …}
headers
:
{cache-control: 'no-cache, must-revalidate', content-length: '2485', content-type: 'application/json'}
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status
:
200
statusText
:
""
[[Prototype]]
:
Object
</code>```

I messed something up for sure, however, I can't seem to figure out what. Any help is appreciated!

Body:
I have the following piece of code, where on button click the UI should render question where user can select the right answer:

import React, { Component } from 'react';
import { Configuration, OpenAIApi } from 'openai';

class QuizApp extends Component {
  constructor(props) {
    super(props);

    this.state = {
      bookName: '', // name of the book the user enters
      questions: [], // array of questions to display to the user
      currentQuestionIndex: 0, // index of the current question being displayed
      userAnswer: null, // the answer the user has selected
      correctAnswer: null, // the correct answer to the current question
      feedback: '' // feedback to show the user if their answer was correct or not
    };
  }

  // function to handle changes to the book name input
  handleBookNameChange = (event) => {
    this.setState({ bookName: event.target.value });
  }

  // function to handle the user selecting an answer
  handleAnswerSelection = (event) => {
    this.setState({ userAnswer: event.target.value }, () => {
      // check if the user's answer is correct
      if (this.state.userAnswer === this.state.correctAnswer) {
        this.setState({ feedback: 'Correct!' });
      } else {
        this.setState({ feedback: 'Incorrect :(' });
      }
    });
  }

  handleNextButtonClick = () => {
    this.setState((prevState) => {
      if (prevState.currentQuestionIndex + 1 < this.state.questions.length) {
        return {
          currentQuestionIndex: prevState.currentQuestionIndex + 1,
          userAnswer: null,
          correctAnswer: this.state.questions[prevState.currentQuestionIndex + 1].correctAnswer,
          feedback: ''
        };
      }
    });
  };

  // function to generate questions using the GPT-3 API
  generateQuestions = async () => {
    // set up openai with your API key and the name of the model you want to use
    const configuration = new Configuration({
      apiKey: 'someapikey',
    });
    const openai = new OpenAIApi(configuration);

    // use GPT-3 to generate 5 questions based on the book name
    const response = await openai.createCompletion({
      model: 'text-davinci-003',
      prompt: `Generate 5 quiz questions about ${this.state.bookName}`,
      max_tokens: 2048,
      n: 5,
      stop: 'Q:',
      temperature: 0.5
    });
    console.log(response);

    // parse the response and extract the questions and answers
    const questions = response.data.choices[0].text.split('\nQ:').map((question) => {
        const [text, ...choices] = question.split('\nA:');
        const correctAnswer = choices.find((choice) => choice.startsWith('*'));
        if (correctAnswer) {
            console.log(text);
          console.log(choices);
          console.log(correctAnswer);
          return {
            text,
            choices: choices.map((choice) => choice.replace('*', '').trim()),
            correctAnswer: correctAnswer.replace('*', '').trim()
          };
        }
      }).filter(Boolean);

      if (questions.length > 0) {
        // set the questions array and currentQuestion variable with the data from the API response
        this.setState({ questions, currentQuestion: questions[0] });
      }}
  render() {
    const { bookName, questions, currentQuestionIndex, userAnswer, correctAnswer = '', feedback } = this.state;
    const currentQuestion = questions[currentQuestionIndex];

    return (

        {/* input field for the book name */}
        Enter a book name:
        <input
          id="book-name-input"
          type="text"
          value={bookName}
          onChange={this.handleBookNameChange}
        />
        <button onClick={this.generateQuestions}>Generate Questions</button>
        {questions.length > 0 ? (
          <>
            {/* display the current question and the choices */}

{currentQuestion.text}

            {currentQuestion.choices.map((choice) => (

                <input
                  type="radio"
                  value={choice}
                  checked={userAnswer === choice}
                  onChange={this.handleAnswerSelection}
                />
                {choice}

            ))}
            {/* display the feedback and next button if the user has answered the question */}
            {userAnswer !== null && (
              <>

{feedback}

                <button onClick={this.handleNextButtonClick}>Next</button>
              </>
            )}
          </>
        ) : (

Enter a book name and click the "Generate Questions" button to get started.

        )}

    );
  }
}

export default QuizApp;

However, on the button click, on the UI side, nothing is showing. If I check the console, I can see that the request is returned with a 200.

{data: {…}, status: 200, statusText: '', headers: {…}, config: {…}, …}
config
:
{transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
data
:
{id: 'cmpl-6QdVYvHhURjNVlXRugMrWe2DEawT3', object: 'text_completion', created: 1671806416, model: 'text-davinci-003', choices: Array(5), …}
headers
:
{cache-control: 'no-cache, must-revalidate', content-length: '2485', content-type: 'application/json'}
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status
:
200
statusText
:
""
[[Prototype]]
:
Object

I messed something up for sure, however, I can't seem to figure out what. Any help is appreciated!


问:
Is there a method to hide a JFrame from Print-Screen or Screen Recording?
I'm developing a virtual keyboard and would like to know what is the best approach to hide it from print-screen and screen recording.

I've found examples while researching the web, but the results are for Android - even if I put JFrame as a must have on the search query. Mostly, what I have found is something like: getWindow().WindowManager.LayoutParams.FLAG_SECURE - but like I said, it doesn't seems to be applicable for a desktop environment Java application (I think).

Thanks in advance for your for the help!

All my attempts were relying on "half measures" like creating a ClipboardMonitor (java.util.Observable, etc) - but this just gets me to avoid print-screens by flushing the clipboard.

What I'm aiming for is to hide the JFrame or make it black if a user tries to capture the screen with a print-screen command, a snip or screen record application.


问:
CarPlay: make a settings screen with toggle rows
I am trying to make a settings screen with rows that have a toggle inside, like the one in the picture.

I have been trying with CPListTemplate and CPListItem, but I don't manage to show any toggle inside the item.

Have anyone managed to do it?


问:
Configure yarn to pick version from version range based on supported engine
I develop a package. That package has a dependency, which is listed as a version range: ^1.0.0 || ^2.0.0

The versions of the dependency within that version range support different node versions. In v2 support for node 12 has been dropped. Beside that there are no differences. I want to support both to prevent dependency hell on consumers if several of their dependencies rely on the same transitive package.

My package itself still supports node 12. I want to run tests in CI with node 12 to avoid accidentally dropping support for it.

How can I configure Yarn to pick a version within the version range based on the supported node version? In my example I want yarn to pick the latest v1 version to run my tests as that still supports node 12.

The project is using yarn v1.


问:
How to deploy streamlit application in mobile app
In mobile I need to open streamlit app which I have developed but I don't have any idea how to do that because I was new to both python and streamlit.

I developed one streamlit app in windows in that I will crop the images which was captured by laptop camera and preview the same...now the problem is I need to deploy it in mobile....so that whenever I opened app in mobile I can take the pictures and crop it in rectangle and I can view the same


问:
How to wrap multiple different innerhtml values at once in a variable
I'm working on a international country code selection section for my project and for that I have used innerHTML to inject the SVG flag icons of every country (within a SPAN tag) in every option. and the problem I'm facing is that innerHTML is super slow and that is slowed down my website performance.

Because the Option tag does not support any other HTML tag, that's why I have created a div tag for every single option or country (using JS) to render the country flag. and for that I have used the innerHTML upto 240 times for 240 countries. which decreased my page loading speed upto 3-4 seconds.

Is there are any way to wrap all the innerHTML in a single variable so that we can declear it once only, that speed up the performance of my site.

Please have a look on my JS Snippet.

  // Autoclick on the parent div to hide the Dropdown after loading a page (Bug)
  window.addEventListener('load', () => {
      document.querySelector(".country-code-selector").click();
  });

  document.addEventListener('DOMContentLoaded', () => {

      const head = document.getElementsByTagName('head')[0];
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.type = 'text/css';
      link.href = 'https://amitdutta.co.in/flag/css/flag-icon.css';
      head.appendChild(link);

      // Get dropdowns and form
      const dropdowns = document.querySelectorAll('[cc-data-dropdown]');
      const form = document.querySelector('.country-code-selector form');

      // Check if dropdowns exist on page
      if (dropdowns.length > 0) {
          // Loop through dropdowns and create custom dropdown for each select element
          dropdowns.forEach(dropdown => {
              createCustomDropdown(dropdown);
          });
      }

      // Check if form element exist on page
      if (form !== null) {
          // When form is submitted console log the value of the select field
          form.addEventListener('submit', (e) => {
              e.preventDefault();
              console.log('Selected country:', form.querySelector('[name="country"]').value);
          });
      }

      // Create custom dropdown
      function createCustomDropdown(dropdown) {
          // Get all options and convert them from nodelist to array
          const options = dropdown.querySelectorAll('option');
          const optionsArr = Array.prototype.slice.call(options);

          optionsArr[0].innerHTML = ' Afganistan (+69)';
          optionsArr[1].innerHTML = ' Albania (+355)';
          optionsArr[2].innerHTML = ' Algeria (+213)';
          optionsArr[3].innerHTML = ' American Samoa (+1-684)';
          optionsArr[4].innerHTML = ' Andorra (+376)';
          optionsArr[5].innerHTML = ' Angola (+244)';
          optionsArr[6].innerHTML = ' Anguilla (+1-264)';
          optionsArr[7].innerHTML = ' Antarctica (+672)';
          optionsArr[8].innerHTML = ' Antigua and Barbuda (+1-268)';
          optionsArr[9].innerHTML = ' Argentina (+54)';
          optionsArr[10].innerHTML = ' Armenia (+374)';
          optionsArr[11].innerHTML = ' Aruba (+297)';
          optionsArr[12].innerHTML = ' Australia (+61)';
          optionsArr[13].innerHTML = ' Austria (+43)';
          optionsArr[14].innerHTML = ' Azerbaijan (+994)';
          optionsArr[15].innerHTML = ' Bahamas (+1-242)';
          optionsArr[16].innerHTML = ' Bahrain (+973)';
          optionsArr[17].innerHTML = ' Bangladesh (+880)';
          optionsArr[18].innerHTML = ' Barbados (+1-246)';
          optionsArr[19].innerHTML = ' Belarus (+375)';
          optionsArr[20].innerHTML = ' Belgium (+32)';
          optionsArr[21].innerHTML = ' Belize (+501)';
          optionsArr[22].innerHTML = ' Benin (+229)';
          optionsArr[23].innerHTML = ' Bermuda (+1-441)';
          optionsArr[24].innerHTML = ' Bhutan (+975)';
          optionsArr[25].innerHTML = ' Bolivia (+591)';
          optionsArr[26].innerHTML = ' Bosnia and Herzegovina (+387)';
          optionsArr[27].innerHTML = ' Botswana (+267)';
          optionsArr[28].innerHTML = ' Brazil (+55)';
          optionsArr[29].innerHTML = ' British Indian Ocean Territory (+246)';
          optionsArr[30].innerHTML = ' British Virgin Islands (+1-284)';
          optionsArr[31].innerHTML = ' Brunei (+673)';
          optionsArr[32].innerHTML = ' Bulgaria (+359)';
          optionsArr[33].innerHTML = ' Burkina Faso (+226)';
          optionsArr[34].innerHTML = ' Burundi (+257)';
          optionsArr[35].innerHTML = ' Cambodia (+855)';
          optionsArr[36].innerHTML = ' Cameroon (+237)';
          optionsArr[37].innerHTML = ' Canada (+1)';
          optionsArr[38].innerHTML = ' Cape Verde (+238)';
          optionsArr[39].innerHTML = ' Cayman Islands (+1-345)';
          optionsArr[40].innerHTML = ' Central African Republic (+236)';
          optionsArr[41].innerHTML = ' Chad (+235)';
          optionsArr[42].innerHTML = ' Chile (+56)';
          optionsArr[43].innerHTML = ' China (+86)';
          optionsArr[44].innerHTML = ' Christmas Island (+61)';
          optionsArr[45].innerHTML = ' Cocos Islands (+61)';
          optionsArr[46].innerHTML = ' Colombia (+57)';
          optionsArr[47].innerHTML = ' Comoros (+269)';
          optionsArr[48].innerHTML = ' Cook Islands (+682)';
          optionsArr[49].innerHTML = ' Costa Rica (+506)';
          optionsArr[50].innerHTML = ' Croatia (+385)';
          optionsArr[51].innerHTML = ' Cuba (+53)';
          optionsArr[52].innerHTML = ' Curacao (+599)';
          optionsArr[53].innerHTML = ' Cyprus (+357)';
          optionsArr[54].innerHTML = ' Czech Republic (+420)';
          optionsArr[55].innerHTML = ' Democratic Republic of the Congo (+243)';
          optionsArr[56].innerHTML = ' Denmark (+45)';
          optionsArr[57].innerHTML = ' Djibouti (+253)';
          optionsArr[58].innerHTML = ' Dominica (+1-767)';
          optionsArr[59].innerHTML = ' Dominican Republic (+1-809)';
          optionsArr[60].innerHTML = ' East Timor (+670)';
          optionsArr[61].innerHTML = ' Ecuador (+593)';
          optionsArr[62].innerHTML = ' Egypt (+20)';
          optionsArr[63].innerHTML = ' El Salvador (+503)';
          optionsArr[64].innerHTML = ' Equatorial Guinea (+240)';
          optionsArr[65].innerHTML = ' Eritrea (+291)';
          optionsArr[66].innerHTML = ' Estonia (+372)';
          optionsArr[67].innerHTML = ' Ethiopia (+251)';
          optionsArr[68].innerHTML = ' Falkland Islands (+500)';
          optionsArr[69].innerHTML = ' Faroe Islands (+298)';
          optionsArr[70].innerHTML = ' Fiji (+679)';
          // More 169 Countries (Currently not added here to shortner the code) -
          optionsArr[71].innerHTML = 'No Data Found';

          // Create custom dropdown element and add class dropdown to it
          // Insert it in the DOM after the select field
          const customDropdown = document.createElement('div');
          customDropdown.classList.add('cc-dropdown');
          dropdown.insertAdjacentElement('afterend', customDropdown);

          // Create element for selected option
          // Add class to this element, text from the first option in select field and append it to custom dropdown
          const selected = document.createElement('div');
          selected.classList.add('cc-dropdown-selected');
          selected.innerHTML = 'Tel-Code';
          customDropdown.appendChild(selected);

          // Create element for dropdown menu, add class to it and append it to custom dropdown
          // Add click event to selected element to toggle dropdown menu
          const menu = document.createElement('div');
          menu.classList.add('cc-dropdown-menu');
          customDropdown.appendChild(menu);
          selected.addEventListener('click', toggleDropdown.bind(menu));

          // Create serach input element
          // Add class, type and placeholder to this element and append it to menu element
          const search = document.createElement('input');
          search.placeholder = 'Search Your Country...';
          search.type = 'text';
          search.classList.add('cc-dropdown-menu-search');
          menu.appendChild(search);

          // Create wrapper element for menu items, add class to it and append to menu element
          const menuItemsWrapper = document.createElement('div');
          menuItemsWrapper.classList.add('cc-dropdown-menu-items');
          menu.appendChild(menuItemsWrapper);

          // Loop through all options and create custom option for each option and append it to items wrapper element
          // Add click event for each custom option to set clicked option as selected option
          optionsArr.forEach(option => {
              const item = document.createElement('div');
              item.classList.add('cc-dropdown-menu-item');
              item.dataset.value = option.value;
              item.innerHTML = option.innerHTML;
              menuItemsWrapper.appendChild(item);

              item.addEventListener('click', setSelected.bind(item, selected, dropdown, menu));
          });

          // Add selected class to first custom option
          // menuItemsWrapper.querySelector('div').classList.add('selected');

          // Add input event to search input element to filter items
          // Add click event to document element to close custom dropdown if clicked outside of it
          // Hide original dropdown(select)
          search.addEventListener('input', filterItems.bind(search, optionsArr, menu));
          document.addEventListener('click', closeIfClickedOutside.bind(customDropdown, menu));
          dropdown.style.display = 'none';

      }

      // Toggle dropdown
      function toggleDropdown() {
          // Check if dropdown is opened and if it is close it, otherwise open it and focus search input

          if (this.offsetParent !== null) {
              this.style.display = 'none';
          } else {
              this.style.display = 'block';
              this.querySelector('input').focus();
          }
      }

      // Set selected option
      function setSelected(selected, dropdown, menu) {
          // Get value and label from clicked custom option
          const value = this.dataset.value;
          const label = this.innerHTML;

          // Change the text on selected element
          // Change the value on select field

          filterDate = /(<span\b[^<>]*><\/span>\s*)\w+(?:\s+\w+)*\s*\((\+[\d-]+)\)/g;
          selected.innerHTML = label.replace(filterDate, `$1$2`);
          dropdown.value = value;

          // Close the menu
          // Reset search input value
          // Remove selected class from previously selected option and show all divs if they were filtered
          // Add selected class to clicked option
          menu.style.display = 'none';
          menu.querySelector('input').value = '';
          menu.querySelectorAll('div').forEach(div => {
              if (div.classList.contains('selected')) {
                  div.classList.remove('selected');
              }
              if (div.offsetParent === null) {
                  div.style.display = 'block';
              }
          });
          this.classList.add('selected');
      }

      // Filter items
      function filterItems(itemsArr, menu) {
          // Get all custom options
          // Get the value of search input and convert it to all lowercase characters
          // Get filtered items
          // Get the indexes of filtered items
          const customOptions = menu.querySelectorAll('.cc-dropdown-menu-items div');
          const value = this.value.toLowerCase();
          const filteredItems = itemsArr.filter(item => item.value.toLowerCase().includes(value));
          const indexesArr = filteredItems.map(item => itemsArr.indexOf(item));

          // Check if option is not inside indexes array and hide it and if it is inside indexes array and it is hidden show it

          var options = itemsArr.length;
          itemsArr.forEach(option => {
              if (!indexesArr.includes(itemsArr.indexOf(option))) {
                  customOptions[itemsArr.indexOf(option)].style.display = 'none';
                  options -= 1;
                  if (options <= 0) {
                      customOptions[itemsArr.length - 1].style.display = 'block';
                  }
              } else {
                  if (customOptions[itemsArr.indexOf(option)].offsetParent === null) {
                      customOptions[itemsArr.indexOf(option)].style.display = 'block';
                  }
              }
          });
      }

      // Close dropdown if clicked outside dropdown element
      function closeIfClickedOutside(menu, e) {
          if (e.target.closest('.cc-dropdown') === null && e.target !== this && menu.offsetParent !== null) {
              menu.style.display = 'none';
          }
      }

  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .cc-dropdown-menu-items::-webkit-scrollbar-track {
     background-color: #323757;
     width: 2px;
}
 .cc-dropdown-menu-items::-webkit-scrollbar {
     background-color: #323757;
     width: 14px;
}
 .cc-dropdown-menu-items::-webkit-scrollbar-thumb {
     background-color: #e8576f;
     border: 4px solid #323757;
     z-index: -1;
     width: 2px;
     min-height: 50px;
}
 #phone-number {
     width: calc(100% - 120px);
     margin-left: 120px;
}
 .frm div:nth-child(3) .inputBox .tx {
     margin-left: 120px;
}
 .frm div:nth-child(3) .inputBox {
     display: flex;
}
 .frm div:nth-child(3) .inputBox .ln {
     margin-left: 120px;
     width: calc(100% - 120px);
}
 .cc-dropdown {
     position: relative;
}
 .cc-dropdown-selected {
     display: flex;
     align-items: center;
     justify-content: center;
     width: 116px;
     height: 40px;
     padding: 0 20px 0 10px;
     position: relative;
     cursor: pointer;
     transition: box-shadow .3s ease;
     background-color: #323757;
     border-radius: 3px;
     font-size: 15px;
     color: #fff;
}
 .cc-dropdown-selected::after {
     top: calc(50% - 2px);
     right: 10px;
     border: solid transparent;
     content: '';
     height: 0;
     width: 0;
     position: absolute;
     border-top-color:#000;
     border-width: 4px;
     margin-left: -4px;
}
 .cc-dropdown-selected:hover {
     box-shadow: 0 0 5px rgba(0,0,0,0.1);
}
 .cc-dropdown-menu {
     position: absolute;
     top: 100%;
     left: 0;
     width: 273px;
     border: 3px solid #323757;
     margin-right: -2px;
     border-top: 0;
     background-color: #fff;
     z-index: +9;
     margin-top: 10px;
}
 .cc-dropdown-menu-items {
     max-height: 200px;
     width: 270px;
     overflow-y: auto;
     overflow-x: hidden;
     z-index: +9;
}
 .cc-dropdown-menu-search {
     display: block;
     width: 260px;
     border: 0;
     border-right: 3px solid #323757;
     padding: 14px 0px 14px 10px;
     font-size: 15px;
     font-weight: 550;
     color: #fff;
     outline: 0;
     background-color: #323757;
}
 .cc-dropdown-menu-search::placeholder {
     color: rgb(214, 214, 214)!important;
}
 .cc-dropdown-menu-item {
     width: 267px;
     border-bottom: 1px solid #323757a6;
     font-size: 14px;
     font-weight: 550;
     cursor: pointer;
     z-index: +9;
     user-select: none;
     padding: 10px 18px 10px 10px;
}
 .cc-dropdown-menu-items .flag-icon {
     height: 15px;
     width: 26px;
     margin-right: 3px;
}
 .cc-dropdown-menu-item:last-child {
     border-bottom: 0;
}
 .cc-dropdown-menu-item:hover {
     background-color: rgb(228, 228, 228);
}
 .cc-dropdown-menu-item.selected {
     border: none;
}
 .cc-dropdown-selected .flag-icon {
     margin-right: 5px!important;
}
 .cc-dropdown-menu-item.selected, .cc-dropdown-menu-item.selected:hover {
     background-color: #323757c2;
     color: #ffffff;
}
 .cc-dropdown-menu-item:last-child {
     pointer-events: none;
}</code>```

   <form class="cc-form">

         <select id="country" name="country" cc-data-dropdown>
            <option value="Afganistan"></option>
            <option value="Albania"></option>
            <option value="Algeria"></option>
            <option value="American Samoa"></option>
            <option value="Andorra"></option>
            <option value="Angola"></option>
            <option value="Anguilla"></option>
            <option value="Antarctica"></option>
            <option value="Antigua and Barbuda"></option>
            <option value="Argentina"></option>
            <option value="Armenia"></option>
            <option value="Aruba"></option>
            <option value="Australia"></option>
            <option value="Austria"></option>
            <option value="Azerbaijan"></option>
            <option value="Bahamas"></option>
            <option value="Bahrain"></option>
            <option value="Bangladesh"></option>
            <option value="Barbados"></option>
            <option value="Belarus"></option>
            <option value="Belgium"></option>
            <option value="Belize"></option>
            <option value="Benin"></option>
            <option value="Bermuda"></option>
            <option value="Bhutan"></option>
            <option value="Bolivia"></option>
            <option value="Bosnia and Herzegovina"></option>
            <option value="Botswana"></option>
            <option value="Brazil"></option>
            <option value="British Indian Ocean Territory"></option>
            <option value="British Virgin Islands"></option>
            <option value="Brunei"></option>
            <option value="Bulgaria"></option>
            <option value="Burkina Faso"></option>
            <option value="Burundi"></option>
            <option value="Cambodia"></option>
            <option value="Cameroon"></option>
            <option value="Canada"></option>
            <option value="Cape Verde"></option>
            <option value="Cayman Islands"></option>
            <option value="Central African Republic"></option>
            <option value="Chad"></option>
            <option value="Chile"></option>
            <option value="China"></option>
            <option value="Christmas Island"></option>
            <option value="Cocos Islands"></option>
            <option value="Colombia"></option>
            <option value="Comoros"></option>
            <option value="Cook Islands"></option>
            <option value="Costa Rica"></option>
            <option value="Croatia"></option>
            <option value="Cuba"></option>
            <option value="Curacao"></option>
            <option value="Cyprus"></option>
            <option value="Czech Republic"></option>
            <option value="Democratic Republic of the Congo"></option>
            <option value="Denmark"></option>
            <option value="Djibouti"></option>
            <option value="Dominica"></option>
            <option value="Dominican Republic"></option>
            <option value="East Timor"></option>
            <option value="Ecuador"></option>
            <option value="Egypt"></option>
            <option value="El Salvador"></option>
            <option value="Equatorial Guinea"></option>
            <option value="Eritrea"></option>
            <option value="Estonia"></option>
            <option value="Ethiopia"></option>
            <option value="Falkland Islands"></option>
            <option value="Faroe Islands"></option>
            <option value="Fiji"></option>
            <option></option>
         </select>

   </form>

```

Body:
I'm working on a international country code selection section for my project and for that I have used innerHTML to inject the SVG flag icons of every country (within a SPAN tag) in every option. and the problem I'm facing is that innerHTML is super slow and that is slowed down my website performance.

Because the Option tag does not support any other HTML tag, that's why I have created a div tag for every single option or country (using JS) to render the country flag. and for that I have used the innerHTML upto 240 times for 240 countries. which decreased my page loading speed upto 3-4 seconds.

Is there are any way to wrap all the innerHTML in a single variable so that we can declear it once only, that speed up the performance of my site.

Please have a look on my JS Snippet.

  // Autoclick on the parent div to hide the Dropdown after loading a page (Bug)
  window.addEventListener('load', () => {
      document.querySelector(".country-code-selector").click();
  });

  document.addEventListener('DOMContentLoaded', () => {

      const head = document.getElementsByTagName('head')[0];
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.type = 'text/css';
      link.href = 'https://amitdutta.co.in/flag/css/flag-icon.css';
      head.appendChild(link);

      // Get dropdowns and form
      const dropdowns = document.querySelectorAll('[cc-data-dropdown]');
      const form = document.querySelector('.country-code-selector form');

      // Check if dropdowns exist on page
      if (dropdowns.length > 0) {
          // Loop through dropdowns and create custom dropdown for each select element
          dropdowns.forEach(dropdown => {
              createCustomDropdown(dropdown);
          });
      }

      // Check if form element exist on page
      if (form !== null) {
          // When form is submitted console log the value of the select field
          form.addEventListener('submit', (e) => {
              e.preventDefault();
              console.log('Selected country:', form.querySelector('[name="country"]').value);
          });
      }

      // Create custom dropdown
      function createCustomDropdown(dropdown) {
          // Get all options and convert them from nodelist to array
          const options = dropdown.querySelectorAll('option');
          const optionsArr = Array.prototype.slice.call(options);

          optionsArr[0].innerHTML = ' Afganistan (+69)';
          optionsArr[1].innerHTML = ' Albania (+355)';
          optionsArr[2].innerHTML = ' Algeria (+213)';
          optionsArr[3].innerHTML = ' American Samoa (+1-684)';
          optionsArr[4].innerHTML = ' Andorra (+376)';
          optionsArr[5].innerHTML = ' Angola (+244)';
          optionsArr[6].innerHTML = ' Anguilla (+1-264)';
          optionsArr[7].innerHTML = ' Antarctica (+672)';
          optionsArr[8].innerHTML = ' Antigua and Barbuda (+1-268)';
          optionsArr[9].innerHTML = ' Argentina (+54)';
          optionsArr[10].innerHTML = ' Armenia (+374)';
          optionsArr[11].innerHTML = ' Aruba (+297)';
          optionsArr[12].innerHTML = ' Australia (+61)';
          optionsArr[13].innerHTML = ' Austria (+43)';
          optionsArr[14].innerHTML = ' Azerbaijan (+994)';
          optionsArr[15].innerHTML = ' Bahamas (+1-242)';
          optionsArr[16].innerHTML = ' Bahrain (+973)';
          optionsArr[17].innerHTML = ' Bangladesh (+880)';
          optionsArr[18].innerHTML = ' Barbados (+1-246)';
          optionsArr[19].innerHTML = ' Belarus (+375)';
          optionsArr[20].innerHTML = ' Belgium (+32)';
          optionsArr[21].innerHTML = ' Belize (+501)';
          optionsArr[22].innerHTML = ' Benin (+229)';
          optionsArr[23].innerHTML = ' Bermuda (+1-441)';
          optionsArr[24].innerHTML = ' Bhutan (+975)';
          optionsArr[25].innerHTML = ' Bolivia (+591)';
          optionsArr[26].innerHTML = ' Bosnia and Herzegovina (+387)';
          optionsArr[27].innerHTML = ' Botswana (+267)';
          optionsArr[28].innerHTML = ' Brazil (+55)';
          optionsArr[29].innerHTML = ' British Indian Ocean Territory (+246)';
          optionsArr[30].innerHTML = ' British Virgin Islands (+1-284)';
          optionsArr[31].innerHTML = ' Brunei (+673)';
          optionsArr[32].innerHTML = ' Bulgaria (+359)';
          optionsArr[33].innerHTML = ' Burkina Faso (+226)';
          optionsArr[34].innerHTML = ' Burundi (+257)';
          optionsArr[35].innerHTML = ' Cambodia (+855)';
          optionsArr[36].innerHTML = ' Cameroon (+237)';
          optionsArr[37].innerHTML = ' Canada (+1)';
          optionsArr[38].innerHTML = ' Cape Verde (+238)';
          optionsArr[39].innerHTML = ' Cayman Islands (+1-345)';
          optionsArr[40].innerHTML = ' Central African Republic (+236)';
          optionsArr[41].innerHTML = ' Chad (+235)';
          optionsArr[42].innerHTML = ' Chile (+56)';
          optionsArr[43].innerHTML = ' China (+86)';
          optionsArr[44].innerHTML = ' Christmas Island (+61)';
          optionsArr[45].innerHTML = ' Cocos Islands (+61)';
          optionsArr[46].innerHTML = ' Colombia (+57)';
          optionsArr[47].innerHTML = ' Comoros (+269)';
          optionsArr[48].innerHTML = ' Cook Islands (+682)';
          optionsArr[49].innerHTML = ' Costa Rica (+506)';
          optionsArr[50].innerHTML = ' Croatia (+385)';
          optionsArr[51].innerHTML = ' Cuba (+53)';
          optionsArr[52].innerHTML = ' Curacao (+599)';
          optionsArr[53].innerHTML = ' Cyprus (+357)';
          optionsArr[54].innerHTML = ' Czech Republic (+420)';
          optionsArr[55].innerHTML = ' Democratic Republic of the Congo (+243)';
          optionsArr[56].innerHTML = ' Denmark (+45)';
          optionsArr[57].innerHTML = ' Djibouti (+253)';
          optionsArr[58].innerHTML = ' Dominica (+1-767)';
          optionsArr[59].innerHTML = ' Dominican Republic (+1-809)';
          optionsArr[60].innerHTML = ' East Timor (+670)';
          optionsArr[61].innerHTML = ' Ecuador (+593)';
          optionsArr[62].innerHTML = ' Egypt (+20)';
          optionsArr[63].innerHTML = ' El Salvador (+503)';
          optionsArr[64].innerHTML = ' Equatorial Guinea (+240)';
          optionsArr[65].innerHTML = ' Eritrea (+291)';
          optionsArr[66].innerHTML = ' Estonia (+372)';
          optionsArr[67].innerHTML = ' Ethiopia (+251)';
          optionsArr[68].innerHTML = ' Falkland Islands (+500)';
          optionsArr[69].innerHTML = ' Faroe Islands (+298)';
          optionsArr[70].innerHTML = ' Fiji (+679)';
          // More 169 Countries (Currently not added here to shortner the code) -
          optionsArr[71].innerHTML = 'No Data Found';

          // Create custom dropdown element and add class dropdown to it
          // Insert it in the DOM after the select field
          const customDropdown = document.createElement('div');
          customDropdown.classList.add('cc-dropdown');
          dropdown.insertAdjacentElement('afterend', customDropdown);

          // Create element for selected option
          // Add class to this element, text from the first option in select field and append it to custom dropdown
          const selected = document.createElement('div');
          selected.classList.add('cc-dropdown-selected');
          selected.innerHTML = 'Tel-Code';
          customDropdown.appendChild(selected);

          // Create element for dropdown menu, add class to it and append it to custom dropdown
          // Add click event to selected element to toggle dropdown menu
          const menu = document.createElement('div');
          menu.classList.add('cc-dropdown-menu');
          customDropdown.appendChild(menu);
          selected.addEventListener('click', toggleDropdown.bind(menu));

          // Create serach input element
          // Add class, type and placeholder to this element and append it to menu element
          const search = document.createElement('input');
          search.placeholder = 'Search Your Country...';
          search.type = 'text';
          search.classList.add('cc-dropdown-menu-search');
          menu.appendChild(search);

          // Create wrapper element for menu items, add class to it and append to menu element
          const menuItemsWrapper = document.createElement('div');
          menuItemsWrapper.classList.add('cc-dropdown-menu-items');
          menu.appendChild(menuItemsWrapper);

          // Loop through all options and create custom option for each option and append it to items wrapper element
          // Add click event for each custom option to set clicked option as selected option
          optionsArr.forEach(option => {
              const item = document.createElement('div');
              item.classList.add('cc-dropdown-menu-item');
              item.dataset.value = option.value;
              item.innerHTML = option.innerHTML;
              menuItemsWrapper.appendChild(item);

              item.addEventListener('click', setSelected.bind(item, selected, dropdown, menu));
          });

          // Add selected class to first custom option
          // menuItemsWrapper.querySelector('div').classList.add('selected');

          // Add input event to search input element to filter items
          // Add click event to document element to close custom dropdown if clicked outside of it
          // Hide original dropdown(select)
          search.addEventListener('input', filterItems.bind(search, optionsArr, menu));
          document.addEventListener('click', closeIfClickedOutside.bind(customDropdown, menu));
          dropdown.style.display = 'none';

      }

      // Toggle dropdown
      function toggleDropdown() {
          // Check if dropdown is opened and if it is close it, otherwise open it and focus search input

          if (this.offsetParent !== null) {
              this.style.display = 'none';
          } else {
              this.style.display = 'block';
              this.querySelector('input').focus();
          }
      }

      // Set selected option
      function setSelected(selected, dropdown, menu) {
          // Get value and label from clicked custom option
          const value = this.dataset.value;
          const label = this.innerHTML;

          // Change the text on selected element
          // Change the value on select field

          filterDate = /(<span\b[^<>]*><\/span>\s*)\w+(?:\s+\w+)*\s*\((\+[\d-]+)\)/g;
          selected.innerHTML = label.replace(filterDate, `$1$2`);
          dropdown.value = value;

          // Close the menu
          // Reset search input value
          // Remove selected class from previously selected option and show all divs if they were filtered
          // Add selected class to clicked option
          menu.style.display = 'none';
          menu.querySelector('input').value = '';
          menu.querySelectorAll('div').forEach(div => {
              if (div.classList.contains('selected')) {
                  div.classList.remove('selected');
              }
              if (div.offsetParent === null) {
                  div.style.display = 'block';
              }
          });
          this.classList.add('selected');
      }

      // Filter items
      function filterItems(itemsArr, menu) {
          // Get all custom options
          // Get the value of search input and convert it to all lowercase characters
          // Get filtered items
          // Get the indexes of filtered items
          const customOptions = menu.querySelectorAll('.cc-dropdown-menu-items div');
          const value = this.value.toLowerCase();
          const filteredItems = itemsArr.filter(item => item.value.toLowerCase().includes(value));
          const indexesArr = filteredItems.map(item => itemsArr.indexOf(item));

          // Check if option is not inside indexes array and hide it and if it is inside indexes array and it is hidden show it

          var options = itemsArr.length;
          itemsArr.forEach(option => {
              if (!indexesArr.includes(itemsArr.indexOf(option))) {
                  customOptions[itemsArr.indexOf(option)].style.display = 'none';
                  options -= 1;
                  if (options <= 0) {
                      customOptions[itemsArr.length - 1].style.display = 'block';
                  }
              } else {
                  if (customOptions[itemsArr.indexOf(option)].offsetParent === null) {
                      customOptions[itemsArr.indexOf(option)].style.display = 'block';
                  }
              }
          });
      }

      // Close dropdown if clicked outside dropdown element
      function closeIfClickedOutside(menu, e) {
          if (e.target.closest('.cc-dropdown') === null && e.target !== this && menu.offsetParent !== null) {
              menu.style.display = 'none';
          }
      }

  });

 .cc-dropdown-menu-items::-webkit-scrollbar-track {
     background-color: #323757;
     width: 2px;
}
 .cc-dropdown-menu-items::-webkit-scrollbar {
     background-color: #323757;
     width: 14px;
}
 .cc-dropdown-menu-items::-webkit-scrollbar-thumb {
     background-color: #e8576f;
     border: 4px solid #323757;
     z-index: -1;
     width: 2px;
     min-height: 50px;
}
 #phone-number {
     width: calc(100% - 120px);
     margin-left: 120px;
}
 .frm div:nth-child(3) .inputBox .tx {
     margin-left: 120px;
}
 .frm div:nth-child(3) .inputBox {
     display: flex;
}
 .frm div:nth-child(3) .inputBox .ln {
     margin-left: 120px;
     width: calc(100% - 120px);
}
 .cc-dropdown {
     position: relative;
}
 .cc-dropdown-selected {
     display: flex;
     align-items: center;
     justify-content: center;
     width: 116px;
     height: 40px;
     padding: 0 20px 0 10px;
     position: relative;
     cursor: pointer;
     transition: box-shadow .3s ease;
     background-color: #323757;
     border-radius: 3px;
     font-size: 15px;
     color: #fff;
}
 .cc-dropdown-selected::after {
     top: calc(50% - 2px);
     right: 10px;
     border: solid transparent;
     content: '';
     height: 0;
     width: 0;
     position: absolute;
     border-top-color:#000;
     border-width: 4px;
     margin-left: -4px;
}
 .cc-dropdown-selected:hover {
     box-shadow: 0 0 5px rgba(0,0,0,0.1);
}
 .cc-dropdown-menu {
     position: absolute;
     top: 100%;
     left: 0;
     width: 273px;
     border: 3px solid #323757;
     margin-right: -2px;
     border-top: 0;
     background-color: #fff;
     z-index: +9;
     margin-top: 10px;
}
 .cc-dropdown-menu-items {
     max-height: 200px;
     width: 270px;
     overflow-y: auto;
     overflow-x: hidden;
     z-index: +9;
}
 .cc-dropdown-menu-search {
     display: block;
     width: 260px;
     border: 0;
     border-right: 3px solid #323757;
     padding: 14px 0px 14px 10px;
     font-size: 15px;
     font-weight: 550;
     color: #fff;
     outline: 0;
     background-color: #323757;
}
 .cc-dropdown-menu-search::placeholder {
     color: rgb(214, 214, 214)!important;
}
 .cc-dropdown-menu-item {
     width: 267px;
     border-bottom: 1px solid #323757a6;
     font-size: 14px;
     font-weight: 550;
     cursor: pointer;
     z-index: +9;
     user-select: none;
     padding: 10px 18px 10px 10px;
}
 .cc-dropdown-menu-items .flag-icon {
     height: 15px;
     width: 26px;
     margin-right: 3px;
}
 .cc-dropdown-menu-item:last-child {
     border-bottom: 0;
}
 .cc-dropdown-menu-item:hover {
     background-color: rgb(228, 228, 228);
}
 .cc-dropdown-menu-item.selected {
     border: none;
}
 .cc-dropdown-selected .flag-icon {
     margin-right: 5px!important;
}
 .cc-dropdown-menu-item.selected, .cc-dropdown-menu-item.selected:hover {
     background-color: #323757c2;
     color: #ffffff;
}
 .cc-dropdown-menu-item:last-child {
     pointer-events: none;
}

   <form class="cc-form">

         <select id="country" name="country" cc-data-dropdown>
            <option value="Afganistan"></option>
            <option value="Albania"></option>
            <option value="Algeria"></option>
            <option value="American Samoa"></option>
            <option value="Andorra"></option>
            <option value="Angola"></option>
            <option value="Anguilla"></option>
            <option value="Antarctica"></option>
            <option value="Antigua and Barbuda"></option>
            <option value="Argentina"></option>
            <option value="Armenia"></option>
            <option value="Aruba"></option>
            <option value="Australia"></option>
            <option value="Austria"></option>
            <option value="Azerbaijan"></option>
            <option value="Bahamas"></option>
            <option value="Bahrain"></option>
            <option value="Bangladesh"></option>
            <option value="Barbados"></option>
            <option value="Belarus"></option>
            <option value="Belgium"></option>
            <option value="Belize"></option>
            <option value="Benin"></option>
            <option value="Bermuda"></option>
            <option value="Bhutan"></option>
            <option value="Bolivia"></option>
            <option value="Bosnia and Herzegovina"></option>
            <option value="Botswana"></option>
            <option value="Brazil"></option>
            <option value="British Indian Ocean Territory"></option>
            <option value="British Virgin Islands"></option>
            <option value="Brunei"></option>
            <option value="Bulgaria"></option>
            <option value="Burkina Faso"></option>
            <option value="Burundi"></option>
            <option value="Cambodia"></option>
            <option value="Cameroon"></option>
            <option value="Canada"></option>
            <option value="Cape Verde"></option>
            <option value="Cayman Islands"></option>
            <option value="Central African Republic"></option>
            <option value="Chad"></option>
            <option value="Chile"></option>
            <option value="China"></option>
            <option value="Christmas Island"></option>
            <option value="Cocos Islands"></option>
            <option value="Colombia"></option>
            <option value="Comoros"></option>
            <option value="Cook Islands"></option>
            <option value="Costa Rica"></option>
            <option value="Croatia"></option>
            <option value="Cuba"></option>
            <option value="Curacao"></option>
            <option value="Cyprus"></option>
            <option value="Czech Republic"></option>
            <option value="Democratic Republic of the Congo"></option>
            <option value="Denmark"></option>
            <option value="Djibouti"></option>
            <option value="Dominica"></option>
            <option value="Dominican Republic"></option>
            <option value="East Timor"></option>
            <option value="Ecuador"></option>
            <option value="Egypt"></option>
            <option value="El Salvador"></option>
            <option value="Equatorial Guinea"></option>
            <option value="Eritrea"></option>
            <option value="Estonia"></option>
            <option value="Ethiopia"></option>
            <option value="Falkland Islands"></option>
            <option value="Faroe Islands"></option>
            <option value="Fiji"></option>
            <option></option>
         </select>

   </form>


问:
“tm extra text field” add to the “woocommernce order_note/order_comment”?
Is there a way to automatically add the text entered in the “tm extra text field” to the “woocommernce order_note/order_comment”? Just to make the text entered here available via the woocommerce API? Thanks

I have not tried.


问:
C# LPUTF8Str string marshaling does not appear to read string correctly from memory
LPUTF8Str string marshaling in C# simply does not work for me. I feel like I'm can't be understanding its use case correctly, but after poring over the documentation and doing various other tests, I'm not sure what I'm doing wrong.

Context

First of all, to state my base (possibly incorrect) understanding of character encodings and why C# needs to convert them, in case something is wrong here:

Standard C/C++ strings (const char* and std::string respectively) use single-byte characters by default, on Windows and elsewhere. You can have strings with two-byte characters, but these are only used if you choose to use std::wstring (which I am not doing).

The default Windows single-byte character encoding is ANSI (7-bit ASCII + an extra set of characters that uses the 8th bit).

Unicode is the mapping of printable characters to code points (ie. to unique numbers). Strings of Unicode code points are commonly encoded using conventions such as:

UTF-8: mostly one byte per character for English, with special bytes specifying where a chain of more than one byte should form a single character (for the more funky ones). 7-bit ASCII is a subset of the UTF-8 encoding.

UTF-16: two bytes per character, with similar (but rarer) continuation patterns for the really funky characters.

UTF-32: four bytes per character, which is basically never used for English and adjacent languages because it's not a very memory-efficient encoding.

To write non-ASCII characters in C/C++ strings, you can encode the literal UTF-8 bytes using \xhh, where hh is the hex encoding of the bytes. Eg. "\xF0\x9F\xA4\xA0" equates to "".

C# encodes all managed strings using two-byte characters - I'm unsure if this is explicitly UTF-16, or some other Microsoft encoding. When a C/C++ string is passed to C#, it needs to be converted from single-byte (narrow) characters to two-byte (wide) characters.

Microsoft abuses the term "Unicode". They refer to two-byte character strings as "Unicode strings" in the C# documentation, thereby implying (incorrectly) that any strings that aren't two bytes per character are not Unicode. As we know from the UTF-8 encoding, this is not necessarily true - just because a string is represented as a const char* does not mean that it is not formed of Unicode characters. Colour me "\xF0\x9F\x98\x92" => ""

The actual issue

So, for a C++ program, it must expose strings to C# using const char* pointers, and a C# application must marshal these strings by converting them to wide characters. Let's say I have the following C++ function, which for the sake of demonstrating C# marshaling, passes data out via a struct:

// Header:
extern "C"
{
    struct Library_Output
    {
        const char* str;
    };

    API_FUNC void Library_GetString(Library_Output* out);
}

// Source:
extern "C"
{
    void Library_GetString(Library_Output* out)
    {
        if ( out )
        {
            // Static string literal:
            out->str = "This is a UTF-8 string. \xF0\x9F\xA4\xA0";
        }
    }
}
```
<p>In C#, I call the function like so:</p>
<pre class="lang-cs prettyprint-override"><code>public class Program
{
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct Library_Output
    {
        // This is where the marshaling type is defined.
        // C# will convert the const char* pointer to
        // a string automatically.
        [MarshalAs(UnmanagedType.LPUTF8Str)]
        public string str;
    }

    [DllImport("Library.dll")]
    static extern void Library_GetString(IntPtr output);

    private static void Main()
    {
        int structSize = Marshal.SizeOf(typeof(Library_Output));
        IntPtr structPtr = Marshal.AllocHGlobal(structSize);

        Library_GetString(structPtr);

        // Tell C# to convert the data in the unmanaged memory
        // buffer to a managed object.
        Library_Output outputStruct =
            (Library_Output)Marshal.PtrToStructure(structPtr, typeof(Library_Output));

        Console.WriteLine(outputStruct.str);

        Marshal.FreeHGlobal(structPtr);
    }
}
</code>```

Instead of printing the string to the console, what the application actually prints out is:

```<code>���n�
</code>```

However, if I change the marshaling type to be UnmanagedType.LPStr rather than UnmanagedType.LPUTF8Str, I get:

```<code>This is a UTF-8 string.
</code>```

This is confusing to me, because the documentation for string marshaling of structure members states:

UnmanagedType.LPStr: A pointer to a null-terminated array of ANSI characters.

UnmanagedType.LPUTF8Str: A pointer to a null-terminated array of UTF-8 encoded characters.

So ANSI string marshaling prints a UTF-8 (non-ANSI) string, but UTF-8 string marshaling prints garbage? To work out where the garbage was coming from, I had a look at what the data being printed actually was, and it appeared to be the value of the pointer itself.

Either the UTF-8 marshaling routine is treating the memory where the string pointer value resides as the string itself, or I'm misunderstanding something crucial about this process. My question, fundamentally, is twofold: firstly, why does the UTF-8 marshaling process not follow the string pointer properly, and secondly, what is actually the proper way to marshal UTF-8 strings from C++ to C#? Is it to use LPUTF8Str, or something else?

Body:
LPUTF8Str string marshaling in C# simply does not work for me. I feel like I'm can't be understanding its use case correctly, but after poring over the documentation and doing various other tests, I'm not sure what I'm doing wrong.

Context

First of all, to state my base (possibly incorrect) understanding of character encodings and why C# needs to convert them, in case something is wrong here:

Standard C/C++ strings (const char* and std::string respectively) use single-byte characters by default, on Windows and elsewhere. You can have strings with two-byte characters, but these are only used if you choose to use std::wstring (which I am not doing).

The default Windows single-byte character encoding is ANSI (7-bit ASCII + an extra set of characters that uses the 8th bit).

Unicode is the mapping of printable characters to code points (ie. to unique numbers). Strings of Unicode code points are commonly encoded using conventions such as:

UTF-8: mostly one byte per character for English, with special bytes specifying where a chain of more than one byte should form a single character (for the more funky ones). 7-bit ASCII is a subset of the UTF-8 encoding.

UTF-16: two bytes per character, with similar (but rarer) continuation patterns for the really funky characters.

UTF-32: four bytes per character, which is basically never used for English and adjacent languages because it's not a very memory-efficient encoding.

To write non-ASCII characters in C/C++ strings, you can encode the literal UTF-8 bytes using \xhh, where hh is the hex encoding of the bytes. Eg. "\xF0\x9F\xA4\xA0" equates to "".

C# encodes all managed strings using two-byte characters - I'm unsure if this is explicitly UTF-16, or some other Microsoft encoding. When a C/C++ string is passed to C#, it needs to be converted from single-byte (narrow) characters to two-byte (wide) characters.

Microsoft abuses the term "Unicode". They refer to two-byte character strings as "Unicode strings" in the C# documentation, thereby implying (incorrectly) that any strings that aren't two bytes per character are not Unicode. As we know from the UTF-8 encoding, this is not necessarily true - just because a string is represented as a const char* does not mean that it is not formed of Unicode characters. Colour me "\xF0\x9F\x98\x92" => ""

The actual issue

So, for a C++ program, it must expose strings to C# using const char* pointers, and a C# application must marshal these strings by converting them to wide characters. Let's say I have the following C++ function, which for the sake of demonstrating C# marshaling, passes data out via a struct:

// Header:
extern "C"
{
    struct Library_Output
    {
        const char* str;
    };

    API_FUNC void Library_GetString(Library_Output* out);
}

// Source:
extern "C"
{
    void Library_GetString(Library_Output* out)
    {
        if ( out )
        {
            // Static string literal:
            out->str = "This is a UTF-8 string. \xF0\x9F\xA4\xA0";
        }
    }
}

In C#, I call the function like so:

public class Program
{
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct Library_Output
    {
        // This is where the marshaling type is defined.
        // C# will convert the const char* pointer to
        // a string automatically.
        [MarshalAs(UnmanagedType.LPUTF8Str)]
        public string str;
    }

    [DllImport("Library.dll")]
    static extern void Library_GetString(IntPtr output);

    private static void Main()
    {
        int structSize = Marshal.SizeOf(typeof(Library_Output));
        IntPtr structPtr = Marshal.AllocHGlobal(structSize);

        Library_GetString(structPtr);

        // Tell C# to convert the data in the unmanaged memory
        // buffer to a managed object.
        Library_Output outputStruct =
            (Library_Output)Marshal.PtrToStructure(structPtr, typeof(Library_Output));

        Console.WriteLine(outputStruct.str);

        Marshal.FreeHGlobal(structPtr);
    }
}

Instead of printing the string to the console, what the application actually prints out is:

���n�

However, if I change the marshaling type to be UnmanagedType.LPStr rather than UnmanagedType.LPUTF8Str, I get:

This is a UTF-8 string.

This is confusing to me, because the documentation for string marshaling of structure members states:

UnmanagedType.LPStr: A pointer to a null-terminated array of ANSI characters.

UnmanagedType.LPUTF8Str: A pointer to a null-terminated array of UTF-8 encoded characters.

So ANSI string marshaling prints a UTF-8 (non-ANSI) string, but UTF-8 string marshaling prints garbage? To work out where the garbage was coming from, I had a look at what the data being printed actually was, and it appeared to be the value of the pointer itself.

Either the UTF-8 marshaling routine is treating the memory where the string pointer value resides as the string itself, or I'm misunderstanding something crucial about this process. My question, fundamentally, is twofold: firstly, why does the UTF-8 marshaling process not follow the string pointer properly, and secondly, what is actually the proper way to marshal UTF-8 strings from C++ to C#? Is it to use LPUTF8Str, or something else?


问:
How to detect when Zebra PS20 personal shopper is removed from cradle
How to discover when Zebra PS20J personal shopper is taken from smart cradle when cradle is unlocked?

Zebra Enterprise Browser 2 is used in Android 8.

I tried in javascript in browser

const unlockparam = {
  "ledOnDuration": 1000,
  "ledOffDuration": 1000,
  "timeout": 10,
  "smoothingEffect": true
};

EB.SmartCradle.unlockEx(unlockparam, function () {
  console.write('Device is taken from Cradle');
});
```
<p>But unlock callback fires immediately after unlocking, not after device is taken.</p>
<p>How to detect device detach from cradle? I tried to poll cradle wallId property using:</p>
<pre class="lang-js prettyprint-override"><code>EB.SmartCradle.getProperty("wallId") !== 0
</code>```

But wallId returns value even after PS20 is removed from cradle.
Haven't found any description about it in Zebra SmartCradle API reference in https://techdocs.zebra.com/enterprise-browser/latest/api/smartcradle/

Getting device from cradle stops charging. Is it possible/reasonable to check charging state to dedect removal using API like https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API?

I posted this also in Zebra developers forum in https://developer.zebra.com/content/how-dedect-when-ps20j-removed-cradle but havent got response.

Body:
How to discover when Zebra PS20J personal shopper is taken from smart cradle when cradle is unlocked?

Zebra Enterprise Browser 2 is used in Android 8.

I tried in javascript in browser

const unlockparam = {
  "ledOnDuration": 1000,
  "ledOffDuration": 1000,
  "timeout": 10,
  "smoothingEffect": true
};

EB.SmartCradle.unlockEx(unlockparam, function () {
  console.write('Device is taken from Cradle');
});

But unlock callback fires immediately after unlocking, not after device is taken.

How to detect device detach from cradle? I tried to poll cradle wallId property using:

EB.SmartCradle.getProperty("wallId") !== 0

But wallId returns value even after PS20 is removed from cradle.
Haven't found any description about it in Zebra SmartCradle API reference in https://techdocs.zebra.com/enterprise-browser/latest/api/smartcradle/

Getting device from cradle stops charging. Is it possible/reasonable to check charging state to dedect removal using API like https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API?

I posted this also in Zebra developers forum in https://developer.zebra.com/content/how-dedect-when-ps20j-removed-cradle but havent got response.


问:
angular project .js file generation configuration option
Please see this image. I see a constants.js file and "js.map" file under the constants.ts file. while I see no js file for other ts files. I understand that the type script compiler will generate the js file for each ts file. I am not sure why I can not see all the js files. I am not sure which configuration setting is affecting this. project is under source control. I only want to commit to the .ts files. I need to stop any ".js" or "js.map" files from being generated. not sure why it is only happening for one file. This is .Net core project with angular frontend.


问:
Generating Invoices xml - Items found listed under root node & not contained within a collection node
I am trying to generate an Invoice xml for tax services, which contains one or many InvoiceLine elements.
The example xml lists "child" elements in the same level, under the root element, instead of being listed within a collection node.

For sake of simplicity I have removed some topic irrelevant nodes.

```<code><Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"    xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2">
    <cbc:ID>TEST</cbc:ID>
    <cac:InvoicePeriod>
        <cbc:StartDate>2009-11-01</cbc:StartDate>
        <cbc:EndDate>2009-11-30</cbc:EndDate>
    </cac:InvoicePeriod>

    <cac:InvoiceLine>
        <cbc:ID>1</cbc:ID>
        <cbc:Note>Item1</cbc:Note>
    </cac:InvoiceLine>

    <cac:InvoiceLine>
        <cbc:ID>2</cbc:ID>
        <cbc:Note>Item2</cbc:Note>
    </cac:InvoiceLine>

</Invoice>
</code>```

In the meantime, I have created data classes from the XSD files but, the InvoiceLine can only appear once in the resulting xml.

Can I replicate this behaviour using the xml serializer or i would have to build the whole xml from scratch using XmlWriter?

Body:
I am trying to generate an Invoice xml for tax services, which contains one or many InvoiceLine elements.
The example xml lists "child" elements in the same level, under the root element, instead of being listed within a collection node.

For sake of simplicity I have removed some topic irrelevant nodes.

<Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"    xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2">
    <cbc:ID>TEST</cbc:ID>
    <cac:InvoicePeriod>
        <cbc:StartDate>2009-11-01</cbc:StartDate>
        <cbc:EndDate>2009-11-30</cbc:EndDate>
    </cac:InvoicePeriod>

    <cac:InvoiceLine>
        <cbc:ID>1</cbc:ID>
        <cbc:Note>Item1</cbc:Note>
    </cac:InvoiceLine>

    <cac:InvoiceLine>
        <cbc:ID>2</cbc:ID>
        <cbc:Note>Item2</cbc:Note>
    </cac:InvoiceLine>

</Invoice>

In the meantime, I have created data classes from the XSD files but, the InvoiceLine can only appear once in the resulting xml.

Can I replicate this behaviour using the xml serializer or i would have to build the whole xml from scratch using XmlWriter?


问:
React native build failure on `/bin/sh -c ... appname.build/Script-....sh`
I am attempting to launch npm run ios my react native app (fresh except for i installed Sentry), and the build fails at Bundle React Native code and images

```<code>...
export __CODE_SIGNING_ALLOWED_iphoneos\=NO
export __CODE_SIGNING_ALLOWED_watchos\=NO
export arch\=undefined_arch
export variant\=normal
/bin/sh -c /Users/jackcrane/Library/Developer/Xcode/DerivedData/ftcqa-enyxcqcflhsddwapetsdxzogrqbo/Build/Intermediates.noindex/ftcqa.build/Debug iphonesimulator/ftcqa.build/Script-00DD1BFF1BD5951E006B06BC.sh
</code>```

And fails with

```<code>error: No such file or directory (os error 2)
</code>```

I have not been able to find anything about this online. Any tips? Thanks

Body:
I am attempting to launch npm run ios my react native app (fresh except for i installed Sentry), and the build fails at Bundle React Native code and images

...
export __CODE_SIGNING_ALLOWED_iphoneos\=NO
export __CODE_SIGNING_ALLOWED_watchos\=NO
export arch\=undefined_arch
export variant\=normal
/bin/sh -c /Users/jackcrane/Library/Developer/Xcode/DerivedData/ftcqa-enyxcqcflhsddwapetsdxzogrqbo/Build/Intermediates.noindex/ftcqa.build/Debug iphonesimulator/ftcqa.build/Script-00DD1BFF1BD5951E006B06BC.sh

And fails with

error: No such file or directory (os error 2)

I have not been able to find anything about this online. Any tips? Thanks