问:
On a Concrete PyQt5 Example of Multi-Language Application
Here is a naive application which contains two labels, a button, and a combobox for language selection. If the user changes the language, then every text will be updated to the corresponding language because all the translations are already human prepared in the method  change_language.

```<code>from PyQt5.QtCore import*
from PyQt5.QtWidgets import*
from PyQt5.QtCore import*

class MyWidget(QWidget):
    def __init__(self):
        super().__init__()

        self.language = "English"

        self.setWindowTitle("English Title")
        self.layout = QVBoxLayout()

        self.language_combobox = QComboBox()
        self.language_combobox.addItems(["English", "French", "Chinese"])
        self.layout.addWidget(self.language_combobox)
        self.language_combobox.currentIndexChanged.connect(self.change_language)

        self.label = QLabel("English Label")
        self.layout.addWidget(self.label)

        self.x = 67
        self.label_with_variable = QLabel("English with variable " + str(self.x))
        self.layout.addWidget(self.label_with_variable)

        self.button = QPushButton("English Button")
        self.layout.addWidget(self.button)

        self.setLayout(self.layout)

    def change_language(self):
        self.language = self.language_combobox.currentText()

        if self.language == "English":
            self.setWindowTitle("English Title")
            self.label.setText("English Label")
            self.label_with_variable.setText("English with variable " + str(self.x))
            self.button.setText("English Button")
        elif self.language == "Chinese":
            self.setWindowTitle("中文标题")
            self.label.setText("汉字")
            self.label_with_variable.setText("这句话里有变量 " + str(self.x))
            self.button.setText("中文按钮")
        elif self.language == "French":
            self.setWindowTitle("Titre français")
            self.label.setText("Texte français avec àéîöÆ")
            self.label_with_variable.setText("Voici une variable " + str(self.x))
            self.button.setText("Appuyez ici")

if __name__ == "__main__":
    import sys

    system_app = QApplication(sys.argv)

    license = MyWidget()
    license.show()

    system_app.exec()
</code>```

However, such a naive implementation is obviously inefficient if the project has a large scale. The website https://wiki.qt.io/How_to_create_a_multi_language_application introduces a different way. It uses .qm files and QTranslator. However, after searching online about .qm files and QTranslator, it is just not clear to me what I am supposed to do. Furthermore, the website I give here is not in Python and I am having difficulty understanding it.

Therefore, I ask for a concrete Python example that uses .qm files and QTranslator like in the above website (or any other way suitable for a large project) that does exactly what my code above does .

Body:
Here is a naive application which contains two labels, a button, and a combobox for language selection. If the user changes the language, then every text will be updated to the corresponding language because all the translations are already human prepared in the method  change_language.

from PyQt5.QtCore import*
from PyQt5.QtWidgets import*
from PyQt5.QtCore import*

class MyWidget(QWidget):
    def __init__(self):
        super().__init__()

        self.language = "English"

        self.setWindowTitle("English Title")
        self.layout = QVBoxLayout()

        self.language_combobox = QComboBox()
        self.language_combobox.addItems(["English", "French", "Chinese"])
        self.layout.addWidget(self.language_combobox)
        self.language_combobox.currentIndexChanged.connect(self.change_language)

        self.label = QLabel("English Label")
        self.layout.addWidget(self.label)

        self.x = 67
        self.label_with_variable = QLabel("English with variable " + str(self.x))
        self.layout.addWidget(self.label_with_variable)

        self.button = QPushButton("English Button")
        self.layout.addWidget(self.button)

        self.setLayout(self.layout)

    def change_language(self):
        self.language = self.language_combobox.currentText()

        if self.language == "English":
            self.setWindowTitle("English Title")
            self.label.setText("English Label")
            self.label_with_variable.setText("English with variable " + str(self.x))
            self.button.setText("English Button")
        elif self.language == "Chinese":
            self.setWindowTitle("中文标题")
            self.label.setText("汉字")
            self.label_with_variable.setText("这句话里有变量 " + str(self.x))
            self.button.setText("中文按钮")
        elif self.language == "French":
            self.setWindowTitle("Titre français")
            self.label.setText("Texte français avec àéîöÆ")
            self.label_with_variable.setText("Voici une variable " + str(self.x))
            self.button.setText("Appuyez ici")

if __name__ == "__main__":
    import sys

    system_app = QApplication(sys.argv)

    license = MyWidget()
    license.show()

    system_app.exec()

However, such a naive implementation is obviously inefficient if the project has a large scale. The website https://wiki.qt.io/How_to_create_a_multi_language_application introduces a different way. It uses .qm files and QTranslator. However, after searching online about .qm files and QTranslator, it is just not clear to me what I am supposed to do. Furthermore, the website I give here is not in Python and I am having difficulty understanding it.

Therefore, I ask for a concrete Python example that uses .qm files and QTranslator like in the above website (or any other way suitable for a large project) that does exactly what my code above does .


来源: stackexchange

问:
Macro for using Solver row by row works fine, but cant manage to insert "ValueOf" with cell reference
The Macro works, just need a small adjustment.
So the only part of the code that dosent work is this part:

```<code>ValueOf:="$S$" & i,
</code>```

if i put it like that it dosent work, insted, if i put it like this it dose work:

```<code>ValueOf:=0.1,
</code>```

I want it like the first way because I would like the "value of" to change row by row if  want it to.

```<code>Sub SolverMacro()

Dim LR As Integer
LR = Cells(Rows.Count, "I").End(xlUp).Row

    For i = 2 To LR
    SolverReset
    SolverOk SetCell:="$R$" & i, MaxMinVal:="3", ValueOf:="$S$" & i, ByChange:="$I$" & i, Engine:=1, EngineDesc:="GRG Nonlinear"
    SolverSolve True
    Next

End Sub
</code>```

The idea of my project is for all rows in column R to be 10% by changing values of rows in column I, using the "Value Of" column S.

Before Macro:

After Macro:

ContentLicense: CC BY-SA 4.0

Body:
The Macro works, just need a small adjustment.
So the only part of the code that dosent work is this part:

ValueOf:="$S$" & i,

if i put it like that it dosent work, insted, if i put it like this it dose work:

ValueOf:=0.1,

I want it like the first way because I would like the "value of" to change row by row if  want it to.

Sub SolverMacro()

Dim LR As Integer
LR = Cells(Rows.Count, "I").End(xlUp).Row

    For i = 2 To LR
    SolverReset
    SolverOk SetCell:="$R$" & i, MaxMinVal:="3", ValueOf:="$S$" & i, ByChange:="$I$" & i, Engine:=1, EngineDesc:="GRG Nonlinear"
    SolverSolve True
    Next

End Sub

The idea of my project is for all rows in column R to be 10% by changing values of rows in column I, using the "Value Of" column S.

Before Macro:

After Macro:


问:
How can I show a large map to html?
I'm trying to knit to html a document, but it seems that the map I have created is too big to be knitted, is there a way to fix that?

I have tried to delete all the NA data of all the variables.

Title: How can I show a large map to html?


问:
R Programming - RNN (trainr()) - How to use two inputs on the model to predict stock prices?
I wrote the following code for prediction of the stock market and it is working properly when I use the Adjusted Close Price as input and try to predict the next day Adjusted Close Price.
The file "VALE3.SA.csv" is the historical data from Yahoo Finance from 01/01/2018 to 09/30/2022.

```<code>library("rnn")
library("dplyr")

data <- read.csv("VALE3.SA.csv")
plot(data$Adj.Close)

fechamento_adj <- data$Adj.Close
fechamento_adj_anterior <- lag(fechamento_adj,n=1L)

data_analise <- data.frame(fechamento_adj)
data_analise$fechamento_adj_anterior <- fechamento_adj_anterior
data_analise <- na.omit(data_analise)

x <- data_analise[,2]
y <- data_analise[,1]

X <- matrix(x, nrow = 168)
Y <- matrix(y, nrow = 168)

Yscaled <- (Y - min(Y)) / (max(Y) - min(Y))
Xscaled <- (X - min(X)) / (max(X) - min(X))

Y <- Yscaled
X <- Xscaled

train=1:5
test=6:7

model <- trainr(Y = Y[,train],
                X = X[,train],
                learningrate = 0.05,
                hidden_dim = 15,
                numepochs = 1000,
                network_type = "rnn"
)

Ytrain <- t(matrix(predictr(model, X[,train]),nrow=1))
Yreal <- t(matrix(Y[,train],nrow=1))

rsq <- function(y_actual,y_predict){
  cor(y_actual,y_predict)^2
}

rsq(Yreal,Ytrain)

Ytest=matrix(Y[,test], nrow = 1)
Ytest = t(Ytest)
Yp <- predictr(model, Y[,test])
Ypredicted=matrix(Yp, nrow = 1)
Ypredicted=t(Ypredicted)

result_data <- data.frame(Ytest)
result_data$Ypredicted <- Ypredicted

rsq(result_data$Ytest,result_data$Ypredicted)
mean(result_data$Ytest)
mean(result_data$Ypredicted)
</code>```

The problem is when I tried to utilize two inputs (Adjusted Close price and volume). I tried the following code. The array X at the "trainr" function looks like wrong and also I am getting the error at "Yp <- predictr(model, Y[,test])"
Error in x %*% model$time_synapse[[i]] : non-conformable arguments

```<code>library("rnn")
library("dplyr")

data <- read.csv("VALE3.SA.csv")

fechamento_adj <- data$Adj.Close
volume <- data$Volume

fechamento_adj_anterior <- lag(fechamento_adj,n=1L)
volume_anterior <- lag(volume,n=1L)

data_analise <- data.frame(fechamento_adj)
data_analise$fechamento_adj_anterior <- fechamento_adj_anterior
data_analise$volume_anterior <- volume_anterior

#exclui NA
data_analise <- na.omit(data_analise)

#PEGAR A SEGUNDA COLUNA COMO INPUT
x1 <- data_analise[,2]
x2 <- data_analise[,3]

#PEGAR A PRIMEIRA COLUNA COMO TARGET
y <- data_analise[,1]

X1 <- matrix(x1, nrow = 168)
X2 <- matrix(x2, nrow = 168)
Y <- matrix(y, nrow = 168)

Yscaled <- (Y - min(Y)) / (max(Y) - min(Y))
X1scaled <- (X1 - min(X1)) / (max(X1) - min(X1))
X2scaled <- (X2 - min(X2)) / (max(X2) - min(X2))

Y <- Yscaled

X1 <- X1scaled
X2 <- X2scaled

X <- array( c(X1,X2), dim=c(dim(X1),2) )

train=1:5
test=6:7

model <- trainr(Y = Y[,train],
                X = X[,train,],
                learningrate = 0.05,
                hidden_dim = 15,
                numepochs = 10,
                network_type = "rnn"
)

#no conjunto de treinamento
Ytrain <- t(matrix(predictr(model, X[,train,]),nrow=1))
Yreal <- t(matrix(Y[,train],nrow=1))

#Percentual de variação em uma variável explicada por outra
rsq <- function(y_actual,y_predict){
  cor(y_actual,y_predict)^2
}

rsq(Yreal,Ytrain)

#no conjunto de teste
Ytest=matrix(Y[,test], nrow = 1)
Ytest = t(Ytest)
Yp <- predictr(model, Y[,test])
Ypredicted=matrix(Yp, nrow = 1)
Ypredicted=t(Ypredicted)

result_data <- data.frame(Ytest)
result_data$Ypredicted <- Ypredicted

rsq(result_data$Ytest,result_data$Ypredicted)

mean(result_data$Ytest)
mean(result_data$Ypredicted)
</code>```

Body:
I wrote the following code for prediction of the stock market and it is working properly when I use the Adjusted Close Price as input and try to predict the next day Adjusted Close Price.
The file "VALE3.SA.csv" is the historical data from Yahoo Finance from 01/01/2018 to 09/30/2022.

library("rnn")
library("dplyr")

data <- read.csv("VALE3.SA.csv")
plot(data$Adj.Close)

fechamento_adj <- data$Adj.Close
fechamento_adj_anterior <- lag(fechamento_adj,n=1L)

data_analise <- data.frame(fechamento_adj)
data_analise$fechamento_adj_anterior <- fechamento_adj_anterior
data_analise <- na.omit(data_analise)

x <- data_analise[,2]
y <- data_analise[,1]

X <- matrix(x, nrow = 168)
Y <- matrix(y, nrow = 168)

Yscaled <- (Y - min(Y)) / (max(Y) - min(Y))
Xscaled <- (X - min(X)) / (max(X) - min(X))

Y <- Yscaled
X <- Xscaled

train=1:5
test=6:7

model <- trainr(Y = Y[,train],
                X = X[,train],
                learningrate = 0.05,
                hidden_dim = 15,
                numepochs = 1000,
                network_type = "rnn"
)

Ytrain <- t(matrix(predictr(model, X[,train]),nrow=1))
Yreal <- t(matrix(Y[,train],nrow=1))

rsq <- function(y_actual,y_predict){
  cor(y_actual,y_predict)^2
}

rsq(Yreal,Ytrain)

Ytest=matrix(Y[,test], nrow = 1)
Ytest = t(Ytest)
Yp <- predictr(model, Y[,test])
Ypredicted=matrix(Yp, nrow = 1)
Ypredicted=t(Ypredicted)

result_data <- data.frame(Ytest)
result_data$Ypredicted <- Ypredicted

rsq(result_data$Ytest,result_data$Ypredicted)
mean(result_data$Ytest)
mean(result_data$Ypredicted)

The problem is when I tried to utilize two inputs (Adjusted Close price and volume). I tried the following code. The array X at the "trainr" function looks like wrong and also I am getting the error at "Yp <- predictr(model, Y[,test])"
Error in x %*% model$time_synapse[[i]] : non-conformable arguments

library("rnn")
library("dplyr")

data <- read.csv("VALE3.SA.csv")

fechamento_adj <- data$Adj.Close
volume <- data$Volume

fechamento_adj_anterior <- lag(fechamento_adj,n=1L)
volume_anterior <- lag(volume,n=1L)

data_analise <- data.frame(fechamento_adj)
data_analise$fechamento_adj_anterior <- fechamento_adj_anterior
data_analise$volume_anterior <- volume_anterior

#exclui NA
data_analise <- na.omit(data_analise)

#PEGAR A SEGUNDA COLUNA COMO INPUT
x1 <- data_analise[,2]
x2 <- data_analise[,3]

#PEGAR A PRIMEIRA COLUNA COMO TARGET
y <- data_analise[,1]

X1 <- matrix(x1, nrow = 168)
X2 <- matrix(x2, nrow = 168)
Y <- matrix(y, nrow = 168)

Yscaled <- (Y - min(Y)) / (max(Y) - min(Y))
X1scaled <- (X1 - min(X1)) / (max(X1) - min(X1))
X2scaled <- (X2 - min(X2)) / (max(X2) - min(X2))

Y <- Yscaled

X1 <- X1scaled
X2 <- X2scaled

X <- array( c(X1,X2), dim=c(dim(X1),2) )

train=1:5
test=6:7

model <- trainr(Y = Y[,train],
                X = X[,train,],
                learningrate = 0.05,
                hidden_dim = 15,
                numepochs = 10,
                network_type = "rnn"
)

#no conjunto de treinamento
Ytrain <- t(matrix(predictr(model, X[,train,]),nrow=1))
Yreal <- t(matrix(Y[,train],nrow=1))

#Percentual de variação em uma variável explicada por outra
rsq <- function(y_actual,y_predict){
  cor(y_actual,y_predict)^2
}

rsq(Yreal,Ytrain)

#no conjunto de teste
Ytest=matrix(Y[,test], nrow = 1)
Ytest = t(Ytest)
Yp <- predictr(model, Y[,test])
Ypredicted=matrix(Yp, nrow = 1)
Ypredicted=t(Ypredicted)

result_data <- data.frame(Ytest)
result_data$Ypredicted <- Ypredicted

rsq(result_data$Ytest,result_data$Ypredicted)

mean(result_data$Ytest)
mean(result_data$Ypredicted)


问:
snapcraft indefinitely hangs on pull step
I am trying to build a snapcraft for my application. It's my first time using snapcraft. The app contains three 'applications' and I can get the point of running the stage for an individual part i.e. snapcraft stage a --use-lxd, but on when I try to run them combined i.e. snapcraft prime --use-lxd the build get's stuck on some 2023-01-08 16:22:11.505 check if Part('websocket'):Step.PULL is outdated \ (31013.8s)

I've tried building the individual parts prior to running a snapcraft prime command and they succeed without noticable errors, so I don't really understand why it doesn't just skip the stages.

I feel like whatever is trying to check if the pull is out of date is in some kind of infinite directory recurssion because even after 31305.6s it still hasn't processed. Any thoughts where I can improve my snapcraft?

name: test
summary: ...
description: ...
confinement: strict
base: core22
grade: stable
version: "1"
architectures:
  - build-on: amd64

apps:
  a:
    command: /usr/share/a/app
    plugs:
      - network
      - home

  b:
    command: /usr/share/b/app
    plugs:
      - network
      - home

  c:
    command: /usr/share/c/app
    plugs:
      - network
      - home

parts:

  source:
    plugin: nil
    source: https://github.com/flutter/flutter.git
    source-type: "git"
    source-depth: 1
    source-branch: "master"
    build-packages: [clang, cmake, git, ninja-build, pkg-config, libgtk-3-dev, liblzma-dev, curl, unzip]
    stage-packages: [libgtk-3-0, libblkid1, liblzma5]
    override-pull: |
      craftctl default
      git fetch --unshallow
      PATH="$CRAFT_PART_SRC/bin:$PATH" flutter doctor
      PATH="$CRAFT_PART_SRC/bin:$PATH" flutter channel master
      PATH="$CRAFT_PART_SRC/bin:$PATH" flutter precache
    override-build: |
      set -eux
      mkdir -p $CRAFT_PART_INSTALL/usr/bin
      mkdir -p $CRAFT_PART_INSTALL/usr/libexec
      cp -r $CRAFT_PART_SRC $CRAFT_PART_INSTALL/usr/libexec/flutter
      ln -sf $CRAFT_PART_INSTALL/usr/libexec/flutter/bin/flutter $CRAFT_PART_INSTALL/usr/bin/flutter
      ln -sf $CRAFT_PART_INSTALL/usr/libexec/flutter/bin/dart $CRAFT_PART_INSTALL/usr/bin/dart
      export PATH="$CRAFT_PART_INSTALL/usr/bin:$PATH"
    override-prime: ""

  packages:
    source: packages
    source-type: local
    plugin: nil
    build-packages: [rsync]
    override-pull: |
      echo "$(pwd)"
      rsync -r --exclude snap --exclude .git --exclude .vs --exclude .plugin_symlinks --exclude TestResults --exclude releases --exclude .dart_tool --exclude .vscode --exclude node_modules --exclude build $SNAPCRAFT_PROJECT_DIR/packages/* $SNAPCRAFT_PART_SRC/
    override-build: |
      rsync -r $SNAPCRAFT_PART_SRC/* $SNAPCRAFT_PART_INSTALL
    override-stage: ""
    override-prime: ""

  websocket:
    source: websocket
    source-type: local
    plugin: nil
    build-packages: [rsync]
    override-pull: |
      rsync -r --exclude snap --exclude .git --exclude .vs --exclude .plugin_symlinks --exclude TestResults --exclude releases --exclude .dart_tool --exclude .vscode --exclude node_modules --exclude build $SNAPCRAFT_PROJECT_DIR/websocket/* $SNAPCRAFT_PART_SRC/
    override-build: |
      rsync -r $SNAPCRAFT_PART_SRC/* $SNAPCRAFT_PART_INSTALL
    override-stage: ""
    override-prime: ""

  dummy:
    plugin: nil
    build-packages: [rsync]
    build-snaps: [ yq ]
    stage-packages: [dotnet-sdk-6.0, dotnet-runtime-6.0]
    after: [source, packages, websocket]
    override-pull: ""
    override-build: ""
    override-prime: ""

  a:
    source: a_src
    source-type: local
    plugin: nil
    after: [dummy]
    override-pull: |
      mkdir -p packages
      mkdir -p a_src
      mkdir -p websocket
      rsync -r ~/parts/websocket/install/* $SNAPCRAFT_PART_SRC/websocket
      rsync -r ~/parts/packages/install/* $SNAPCRAFT_PART_SRC/packages
      rsync -r --exclude snap --exclude .git --exclude .vs --exclude .plugin_symlinks --exclude TestResults --exclude releases --exclude .dart_tool --exclude .vscode --exclude node_modules --exclude build $SNAPCRAFT_PROJECT_DIR/a_src/* $SNAPCRAFT_PART_SRC/a_src
      #craftctl default
      cd a_src
      flutter clean
      flutter pub get
    override-build: |
      craftctl default
      cd a_src
      flutter build linux
      rsync --mkpath -r build/linux/x64/release/bundle/* $SNAPCRAFT_PART_INSTALL/usr/share/a
    override-stage: |
      rsync –-ignore-existing -r $SNAPCRAFT_PART_INSTALL/* $SNAPCRAFT_STAGE

  b:
    source: b_src
    source-type: local
    plugin: nil
    after: [dummy]
    override-pull: |
      mkdir -p packages
      mkdir -p b_src
      mkdir -p websocket
      rsync -r ~/parts/websocket/install/* $SNAPCRAFT_PART_SRC/websocket
      rsync -r ~/parts/packages/install/* $SNAPCRAFT_PART_SRC/packages
      rsync -r --exclude snap --exclude .git --exclude .vs --exclude .plugin_symlinks --exclude TestResults --exclude releases --exclude .dart_tool --exclude .vscode --exclude node_modules --exclude build $SNAPCRAFT_PROJECT_DIR/b_src/* $SNAPCRAFT_PART_SRC/b_src
      #craftctl default
      cd b_src
      flutter pub get
    override-build: |
      craftctl default
      cd b_src
      flutter build linux
      rsync --mkpath -r build/linux/x64/release/bundle/* $SNAPCRAFT_PART_INSTALL/usr/share/b
    override-stage: |
      rsync –-ignore-existing -r $SNAPCRAFT_PART_INSTALL/* $SNAPCRAFT_STAGE

  c:
    source: c_src
    source-type: local
    plugin: nil
    after: [dummy]
    override-pull: |
      mkdir -p packages
      mkdir -p c_src
      mkdir -p websocket
      rsync -r ~/parts/websocket/install/* $SNAPCRAFT_PART_SRC/websocket
      rsync -r ~/parts/packages/install/* $SNAPCRAFT_PART_SRC/packages
      rsync -r --exclude snap --exclude .git --exclude .vs --exclude .plugin_symlinks --exclude TestResults --exclude releases --exclude .dart_tool --exclude .vscode --exclude node_modules --exclude build $SNAPCRAFT_PROJECT_DIR/c_src/* $SNAPCRAFT_PART_SRC/c_src
      #craftctl default
      cd c_src
      flutter clean
      flutter pub get
    override-build: |
      craftctl default
      cd c_src
      flutter build linux
      rsync --mkpath -r build/linux/x64/release/bundle/* $SNAPCRAFT_PART_INSTALL/usr/share/c
    override-stage: |
      rsync –-ignore-existing -r $SNAPCRAFT_PART_INSTALL/* $SNAPCRAFT_STAGE

  test:
    after: [a, c, b]
    plugin: nil
```


问:
Money is not increased after payment Coinbase
I have a problem
with Coinbase
When recharging the account with $5, for example, the payment process is completed, but the account remains $0

PayPal works without problems. Can you solve this code for me?

```<code>
    elseif($method_id == 24):

           $amount = (double)$amount;

    $insert = $conn->prepare("INSERT INTO payments SET client_id=:c_id, payment_amount=:amount, payment_privatecode=:code, payment_method=:method, payment_mode=:mode, payment_create_date=:date, payment_ip=:ip, payment_extra=:extra");
          $insert->execute(array("c_id" => $user['client_id'], "amount" => $amount, "code" => $paymentCode, "method" => $method_id, "mode" => "", "date" => date("Y.m.d H:i:s"), "ip" => GetIP(), "extra" => $paymentCode));
          $success = 1;
          $successText = "Your payment was initiated successfully, you are being redirected..";

        $data = [
             "redirect_url"=> "https://webhook.site/8c16529b-dab9-4a62-af0e-ea759d1f7abf",
            "business_name" => "Wixout",
            "customer_email" => $user['email'],
            "customer_name" => $user['client_id'].','.$paymentCode.','.$method_id.','.$paymentCode,
            "local_price" => [
                  "amount" => $amount,
                  "currency" => "USD"
               ],
            "memo" => "Balance recharge - ".  $user['email']
         ];
         $fields_string = json_encode($data);
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.commerce.coinbase.com/invoices');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'X-Cc-Api-Key: '.$extra['api_key'];
$headers[] = 'X-Cc-Version: 2018-03-22';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);

//echo $result;

$result=json_decode($result);
header('location:'.$result->data->hosted_url);
exit;

elseif ($method_id == 26):
</code>```

Thank you all

I tried all the solutions because in my experience I didn't find a solution

Body:
I have a problem
with Coinbase
When recharging the account with $5, for example, the payment process is completed, but the account remains $0

PayPal works without problems. Can you solve this code for me?

    elseif($method_id == 24):

           $amount = (double)$amount;

    $insert = $conn->prepare("INSERT INTO payments SET client_id=:c_id, payment_amount=:amount, payment_privatecode=:code, payment_method=:method, payment_mode=:mode, payment_create_date=:date, payment_ip=:ip, payment_extra=:extra");
          $insert->execute(array("c_id" => $user['client_id'], "amount" => $amount, "code" => $paymentCode, "method" => $method_id, "mode" => "", "date" => date("Y.m.d H:i:s"), "ip" => GetIP(), "extra" => $paymentCode));
          $success = 1;
          $successText = "Your payment was initiated successfully, you are being redirected..";

        $data = [
             "redirect_url"=> "https://webhook.site/8c16529b-dab9-4a62-af0e-ea759d1f7abf",
            "business_name" => "Wixout",
            "customer_email" => $user['email'],
            "customer_name" => $user['client_id'].','.$paymentCode.','.$method_id.','.$paymentCode,
            "local_price" => [
                  "amount" => $amount,
                  "currency" => "USD"
               ],
            "memo" => "Balance recharge - ".  $user['email']
         ];
         $fields_string = json_encode($data);
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.commerce.coinbase.com/invoices');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'X-Cc-Api-Key: '.$extra['api_key'];
$headers[] = 'X-Cc-Version: 2018-03-22';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);

//echo $result;

$result=json_decode($result);
header('location:'.$result->data->hosted_url);
exit;

elseif ($method_id == 26):

Thank you all

I tried all the solutions because in my experience I didn't find a solution


问:
Why Isn't Spring Autoconfiguration Working for a Third-Party Library (kie.org kiserver)?
I've created a Spring Boot Starter project using start.spring.io picking the latest (3.0.1 as of this writing) and added org.kie:kie-server-spring-boot-starter-optaplanner:7.73.0.Final as a dependency. This brings along with it several autconfiguration classes (e.g. OptaPlannerKieServerAutoConfiguration.class) in various JARs each having their own META-INF/spring.factories file with what seems to be correct entries for org.springframework.boot.autoconfigure.EnableAutoConfiguration (pointing to the Configuration class).

In the application.properties file in src/main/resources/, I've placed various entries like kieserver.optaplanner.enabled=true, etc.

For some reason, it doesn't appear as if the autoconfiguration classes are being recognized. I'm running the Spring Boot application with debug=true and in the output of UserDetailsServiceAutoConfiguration, I'm not seeing any of the autoconfiguration classes for any of the KIE packages being mentioned.

I tried creating a JUnit test class and forced the loading of the configuration class with ApplicationContextRunner and that seemed to work.

What am I missing in the app to get Spring to pick up the autoconfiguration classes?


问:
What technical difficulty prevents Adobe from implementing auto refresh?
Firstly, sorry if this is not an appropriate question - but it is one that has bothered me for a long time.

I use LaTeX all the time for writing technical documents and while I often convert to ps, there are also situations where converting to pdf is contextually more useful. Since LaTeX is run as an independent process, it (or a related batch file) will update the pdf file on disk. For common ps readers this causes an automatic refresh. But with Adobe Reader, it locks the file and so even prevents updating the pdf file. I have to close Adobe Reader and then recompile the LaTeX and open the Reader again (yes, I am aware of Sumatra PDF - which only makes the Adobe behaviour stranger).

Over the past quite a few years, I have occasionally gone to the Adobe forums and asked about this feature. I see many other people also asking for auto refresh. And the responses from Adobe are always curt and essentially say that such a behaviour is impossible or prohibitive to implement. To the contrary, my own experience suggests that it should be fairly easy to implement. I have heard several comments like - if the file is a gigabyte it cannot be stored in memory - but, my files are never that large, and if the file was too big to auto refresh one could just say that when it was opened. And so on. The reasons given always seem spurious.

My question is - why is Adobe so persistently resistant to having auto refresh?

To clarify - is there some foundational technical problem that would require a strong rewrite? Or is this something to do with a business model?


问:
If the Entry and target profit are on the same candle, it is not taking profit
In the Strategy I wrote to Pine Script, when he enters the position, if the target reaches profit in the same candle, it cannot close the position to take profit.

I couldn't find the reason for this.
Can you help me.

I am attaching sample images and Codes, where is the mistake?

enter image description here

```<code>if yukari_kirilim and window and (allow_longs == true)
    color.new(color.green, 80)
    strategy.entry("long", strategy.long, comment = ( alarm_label_long ), alert_message = (str.tostring(usd)), oca_name="oca_buy")

if asagi_kirilim and window and (allow_shorts == true)
    strategy.entry("short", strategy.short, comment = ( alarm_label_short  ), alert_message = (str.tostring(usd)), oca_name="oca_sell" )

stoploss = input.float( 2 , "LONG Stop Loss percentage" , minval= 0, step = 0.1, group=' StopLoss ' )
short_stoploss = input.float( 2 , "SHORT Stop Loss percentage" , minval= 0, step = 0.1, group=' StopLoss ' )

takeprofit = input.float( 1 , "LONG Take Profit percentage" , minval= 0, step = 0.05, group=' Take Profit ' )
short_takeprofit = input.float( 1 , "SHORT Take Profit percentage" , minval= 0, step = 0.05 , group=' Take Profit ')

trailingstop = input(true , "Trailing Stop", group=' Trailing Stop ')
trail_p = input.float( 0.0 , " LONG Trailing Stop percentage (of entry price)" , minval= 0.0, step = 0.05, group=' Trailing Stop ' )
short_trail_p = input.float( 0.0 , "SHORT Trailing Stop percentage (of entry price)" , minval= 0.0, step = 0.05, group=' Trailing Stop ' )

av_p = strategy.position_avg_price

if trailingstop

    if strategy.position_size > 0 and strategy.position_size[1] <= 0

        mes_pa = "   start trail: "+str.tostring(   av_p + (av_p *  takeprofit/100)    ) +"\n trail offset: "+ str.tostring( av_p *(trail_p/100)   ) +"\n SL: "+ str.tostring( av_p - (av_p *  stoploss/100)    )
        short_mes_pa = "   SHORT start trail: "+str.tostring(   av_p + (av_p *  short_takeprofit/100)    ) +"\n SHORT trail offset: "+ str.tostring( av_p *(short_trail_p/100)   ) +"\n SL: "+ str.tostring( av_p - (av_p *  short_stoploss/100)    )

        ///label.new(bar_index, low - low *(trail_p/100) , mes_pa , style = label.style_label_up , color = color.white ,textcolor = color.black, size = size.normal)

    if  strategy.position_size < 0 and strategy.position_size[1] >= 0

        mes_pa = "   start trail: "+str.tostring(   av_p - (av_p *  takeprofit/100)    ) +"\n trail offset: "+ str.tostring(   av_p *(trail_p/100)     )  +"\n SL: "+ str.tostring( av_p + (av_p *  stoploss/100)    )
        short_mes_pa = "   start trail: "+str.tostring(   av_p - (av_p *  short_takeprofit/100)    ) +"\n trail offset: "+ str.tostring(   av_p *(short_trail_p/100)     )  +"\n SL: "+ str.tostring( av_p + (av_p *  short_stoploss/100)    )

        ///label.new(bar_index, high + high *(trail_p/100) , mes_pa , style = label.style_label_down  , color = color.white ,textcolor = color.black, size = size.normal)

    strategy.exit("exit_buy", "long" ,  when= strategy.position_size > 0  ,  stop  =  av_p - (av_p *  stoploss/100)  ,  trail_price = av_p + (av_p *  takeprofit/100) , trail_offset = av_p *(trail_p/100) *1/syminfo.mintick  , comment = alarm_label_TP_long, alert_message = (str.tostring(usd)) )

    strategy.exit("exit_sell", "short" ,when= strategy.position_size < 0,  stop  =  av_p + (av_p *  short_stoploss/100),  trail_price = av_p - (av_p *  short_takeprofit/100) , trail_offset = av_p *(short_trail_p/100) *1/syminfo.mintick  , comment = alarm_label_TP_short, alert_message = (str.tostring(usd)))

else

    strategy.exit("exit_buy", "long" ,  when= strategy.position_size > 0 ,  stop  =  av_p - (av_p *  stoploss/100)  ,  limit  =  av_p + (av_p *  takeprofit/100) , comment = alarm_label_long_SL, alert_message = (str.tostring(usd)) )

    strategy.exit("exit_sell", "short" ,when= strategy.position_size < 0 ,  stop  =  av_p + (av_p *  short_stoploss/100)   ,  limit  =  av_p - (av_p *  short_takeprofit/100) , comment = alarm_label_short_SL, alert_message = (str.tostring(usd)))

</code>```

Body:
In the Strategy I wrote to Pine Script, when he enters the position, if the target reaches profit in the same candle, it cannot close the position to take profit.

I couldn't find the reason for this.
Can you help me.

I am attaching sample images and Codes, where is the mistake?

enter image description here

if yukari_kirilim and window and (allow_longs == true)
    color.new(color.green, 80)
    strategy.entry("long", strategy.long, comment = ( alarm_label_long ), alert_message = (str.tostring(usd)), oca_name="oca_buy")

if asagi_kirilim and window and (allow_shorts == true)
    strategy.entry("short", strategy.short, comment = ( alarm_label_short  ), alert_message = (str.tostring(usd)), oca_name="oca_sell" )

stoploss = input.float( 2 , "LONG Stop Loss percentage" , minval= 0, step = 0.1, group=' StopLoss ' )
short_stoploss = input.float( 2 , "SHORT Stop Loss percentage" , minval= 0, step = 0.1, group=' StopLoss ' )

takeprofit = input.float( 1 , "LONG Take Profit percentage" , minval= 0, step = 0.05, group=' Take Profit ' )
short_takeprofit = input.float( 1 , "SHORT Take Profit percentage" , minval= 0, step = 0.05 , group=' Take Profit ')

trailingstop = input(true , "Trailing Stop", group=' Trailing Stop ')
trail_p = input.float( 0.0 , " LONG Trailing Stop percentage (of entry price)" , minval= 0.0, step = 0.05, group=' Trailing Stop ' )
short_trail_p = input.float( 0.0 , "SHORT Trailing Stop percentage (of entry price)" , minval= 0.0, step = 0.05, group=' Trailing Stop ' )

av_p = strategy.position_avg_price

if trailingstop

    if strategy.position_size > 0 and strategy.position_size[1] <= 0

        mes_pa = "   start trail: "+str.tostring(   av_p + (av_p *  takeprofit/100)    ) +"\n trail offset: "+ str.tostring( av_p *(trail_p/100)   ) +"\n SL: "+ str.tostring( av_p - (av_p *  stoploss/100)    )
        short_mes_pa = "   SHORT start trail: "+str.tostring(   av_p + (av_p *  short_takeprofit/100)    ) +"\n SHORT trail offset: "+ str.tostring( av_p *(short_trail_p/100)   ) +"\n SL: "+ str.tostring( av_p - (av_p *  short_stoploss/100)    )

        ///label.new(bar_index, low - low *(trail_p/100) , mes_pa , style = label.style_label_up , color = color.white ,textcolor = color.black, size = size.normal)

    if  strategy.position_size < 0 and strategy.position_size[1] >= 0

        mes_pa = "   start trail: "+str.tostring(   av_p - (av_p *  takeprofit/100)    ) +"\n trail offset: "+ str.tostring(   av_p *(trail_p/100)     )  +"\n SL: "+ str.tostring( av_p + (av_p *  stoploss/100)    )
        short_mes_pa = "   start trail: "+str.tostring(   av_p - (av_p *  short_takeprofit/100)    ) +"\n trail offset: "+ str.tostring(   av_p *(short_trail_p/100)     )  +"\n SL: "+ str.tostring( av_p + (av_p *  short_stoploss/100)    )

        ///label.new(bar_index, high + high *(trail_p/100) , mes_pa , style = label.style_label_down  , color = color.white ,textcolor = color.black, size = size.normal)

    strategy.exit("exit_buy", "long" ,  when= strategy.position_size > 0  ,  stop  =  av_p - (av_p *  stoploss/100)  ,  trail_price = av_p + (av_p *  takeprofit/100) , trail_offset = av_p *(trail_p/100) *1/syminfo.mintick  , comment = alarm_label_TP_long, alert_message = (str.tostring(usd)) )

    strategy.exit("exit_sell", "short" ,when= strategy.position_size < 0,  stop  =  av_p + (av_p *  short_stoploss/100),  trail_price = av_p - (av_p *  short_takeprofit/100) , trail_offset = av_p *(short_trail_p/100) *1/syminfo.mintick  , comment = alarm_label_TP_short, alert_message = (str.tostring(usd)))

else

    strategy.exit("exit_buy", "long" ,  when= strategy.position_size > 0 ,  stop  =  av_p - (av_p *  stoploss/100)  ,  limit  =  av_p + (av_p *  takeprofit/100) , comment = alarm_label_long_SL, alert_message = (str.tostring(usd)) )

    strategy.exit("exit_sell", "short" ,when= strategy.position_size < 0 ,  stop  =  av_p + (av_p *  short_stoploss/100)   ,  limit  =  av_p - (av_p *  short_takeprofit/100) , comment = alarm_label_short_SL, alert_message = (str.tostring(usd)))


问:
CSV writing all to one cell and skipping a row
Yes, I know this question has been asked but I have tried the other solutions and also my situation is different, since I am writing to stdout. For example I would type in cmd line python file1.csv file2.csv > results.csv

However, my output.csv file ends up like

```<code>hash,type,file

c02107d09c89bc369a6b6,Misc,items.csv

b20e07d09c89bc369a6b6,Other,items.csv
</code>```

with each row being all in one cell ( the leftmost starting cell )
and skipping a row each time.

My code is this:

```<code>            filenames = argv[1:]
            header = True

            for filename in filenames:
                # Read from file
                with open(filename) as csv_file:
                    # Get the file name from the path
                    filename = os.path.basename(filename)

                    # Get a reader to iterate each csv row
                    csv_reader = csv.reader(csv_file, delimiter=',')

                    # Add the categories header at the top only
                    if header:
                        categories = csv_reader.__next__()
                        categories.append("file")
                        self.results.append(categories)
                        header = False
                    else:
                        csv_reader.__next__()  # Skip type

                    for row in csv_reader:
                        row.append(filename)
                        self.results.append(row)

            # Write CSV output to stdout
            csv_writer = csv.writer(sys.stdout)
            csv_writer.writerows(self.results)

</code>```

I have tried stuff like this with open('file.csv', 'w', newline='') as f: writer = csv.writer(f, delimiter=',') and other things like using with to open as sys.stdout and nothing works. I've also reviewed a dozen other posts of the same topic and nothing works. Please help!

Body:
Yes, I know this question has been asked but I have tried the other solutions and also my situation is different, since I am writing to stdout. For example I would type in cmd line python file1.csv file2.csv > results.csv

However, my output.csv file ends up like

hash,type,file

c02107d09c89bc369a6b6,Misc,items.csv

b20e07d09c89bc369a6b6,Other,items.csv

with each row being all in one cell ( the leftmost starting cell )
and skipping a row each time.

My code is this:

            filenames = argv[1:]
            header = True

            for filename in filenames:
                # Read from file
                with open(filename) as csv_file:
                    # Get the file name from the path
                    filename = os.path.basename(filename)

                    # Get a reader to iterate each csv row
                    csv_reader = csv.reader(csv_file, delimiter=',')

                    # Add the categories header at the top only
                    if header:
                        categories = csv_reader.__next__()
                        categories.append("file")
                        self.results.append(categories)
                        header = False
                    else:
                        csv_reader.__next__()  # Skip type

                    for row in csv_reader:
                        row.append(filename)
                        self.results.append(row)

            # Write CSV output to stdout
            csv_writer = csv.writer(sys.stdout)
            csv_writer.writerows(self.results)

I have tried stuff like this with open('file.csv', 'w', newline='') as f: writer = csv.writer(f, delimiter=',') and other things like using with to open as sys.stdout and nothing works. I've also reviewed a dozen other posts of the same topic and nothing works. Please help!


问:
How to add type to a incoming doc from firebase in typescript?
since am am facing current scalability issues in my app and I am preparing for a major refactor is it possible  to add types for incoming payload form firestore ? in the code below I want to type this docSnap to specific pre defined type, or is the some other solution the could help with this..

await getDoc(docRef).then((docSnap : /*Some pre defined type from front end*/)```
</div>
</div>
</p>
<p>the auto inference type is  :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> docSnap: DocumentSnapshot<DocumentData></code>```

Body:
since am am facing current scalability issues in my app and I am preparing for a major refactor is it possible  to add types for incoming payload form firestore ? in the code below I want to type this docSnap to specific pre defined type, or is the some other solution the could help with this..

await getDoc(docRef).then((docSnap : /*Some pre defined type from front end*/)

the auto inference type is  :

 docSnap: DocumentSnapshot<DocumentData>


问:
Choosing correct component type based on runtime condition
I am looking for some guidance on how best to accomplish my goal. Essentially, I want to choose the correct component type based on a runtime condition(someCondition). However, I am getting the issue below. I am sure I am overlooking something simple. I imagine I need some factory to produce the correct type(not sure why I am having trouble coming up with one ).

I would appreciate it if someone would explain the best way to approach this problem for future reference! Thank you in advance!

Types of construct signatures are incompatible.   Type 'new <T>(props: Props<T>) => BComp<T>' is not assignable to type 'new <T>(props: Props<T>) => AComp<T>'.     Construct signature return types 'BComp<T>' and 'AComp<T>' are incompatible.       The types of 'getState' are incompatible between these types.         Type '(s: BState) => BState' is not assignable to type '(s: AState) => AState'.           Types of parameters 's' and 's' are incompatible.             Property 'b' is missing in type 'AState' but required in type 'BState'.ts(2419) typescript_advance_types.ts(23, 5): 'b' is declared here.

Components:

interface Props<T> {
    items: T[];
}
interface ComponentState {}

abstract class Component<T, S extends ComponentState> {
    constructor(readonly props: Props<T>){}

    abstract getState(s:S):S;
}

interface AState extends ComponentState {
    a: boolean;
}

class AComp<T> extends Component<T, AState>{
    getState(s: AState): AState {
        throw new Error("Method not implemented.");
    }
}

interface BState extends ComponentState {
    b: boolean;
}
class BComp<T> extends Component<T, BState>{
    getState(s: BState): BState {
        throw new Error("Method not implemented.");
    }
}
```
<p>Conditionally choosing type:</p>
<pre class="lang-js prettyprint-override"><code>let someCondition = false;
let component  = AComp;

if(someCondition){
    component = BComp; // issue
}

export const FinalComponent = component;
</code>```

Body:
I am looking for some guidance on how best to accomplish my goal. Essentially, I want to choose the correct component type based on a runtime condition(someCondition). However, I am getting the issue below. I am sure I am overlooking something simple. I imagine I need some factory to produce the correct type(not sure why I am having trouble coming up with one ).

I would appreciate it if someone would explain the best way to approach this problem for future reference! Thank you in advance!

Types of construct signatures are incompatible.   Type 'new <T>(props: Props<T>) => BComp<T>' is not assignable to type 'new <T>(props: Props<T>) => AComp<T>'.     Construct signature return types 'BComp<T>' and 'AComp<T>' are incompatible.       The types of 'getState' are incompatible between these types.         Type '(s: BState) => BState' is not assignable to type '(s: AState) => AState'.           Types of parameters 's' and 's' are incompatible.             Property 'b' is missing in type 'AState' but required in type 'BState'.ts(2419) typescript_advance_types.ts(23, 5): 'b' is declared here.

Components:

interface Props<T> {
    items: T[];
}
interface ComponentState {}

abstract class Component<T, S extends ComponentState> {
    constructor(readonly props: Props<T>){}

    abstract getState(s:S):S;
}

interface AState extends ComponentState {
    a: boolean;
}

class AComp<T> extends Component<T, AState>{
    getState(s: AState): AState {
        throw new Error("Method not implemented.");
    }
}

interface BState extends ComponentState {
    b: boolean;
}
class BComp<T> extends Component<T, BState>{
    getState(s: BState): BState {
        throw new Error("Method not implemented.");
    }
}

Conditionally choosing type:

let someCondition = false;
let component  = AComp;

if(someCondition){
    component = BComp; // issue
}

export const FinalComponent = component;


问:
Python - How to rename duplicated keys in a nested 'dict' while keeping their order
I'm curious how one would go about renaming duplicated key names in a Python dict containing potentially multiple nested dicts.

I have a dictionary that will be used to dynamically populate a UI. Each key's value is a list containing an identifier int at v[0], and depending on the identifier, subsequent items at v[n>0]. The general format of this dict is as follows:

```<code>MenuItems = {

    'Title': [0], #Text
    '---': [1], #Separator

    'MenuItem 1': [3, { #Dropdown Submenu

        'SubItem 1': [2, 1000], #Submenu Items that return a value
        '---': [1],
        'SubItem 2': [2, 2000],
        '---': [1],
        'SubItem 3': [2, 3000]

        }],

    '---': [1],
    'MenuItem2': [2, 4000]

    }
</code>```

I've written a recursive function to then traverse this dictionary and add the different menu items to the UI, however unfortunately I overlooked the fact that each separator has the same key name. As a result when the UI is built, only the first separator is shown in each UI level corresponding to the dict's level, like so:

```<code>Title
---
MenuItem 1
    SubItem 1
    ---
    SubItem 2
    SubItem 3
MenuItem2
</code>```

Interestingly, and (for me) surprisingly, it is the first separator that is displayed in each UI level. I was under the assumption that as the duplicated key names overwrite each other from top to bottom, that it would be the last separator that would be shown, however it seems as though the first key's position is maintained, however it inherits the values of subsequent duplicate keys.

From reading up on python dicts further I understand that they may not be the best structure to use for data that is order-dependent (as is a UI builder), however their legibility and ease of iteration via for k, v in dict.items() means that ideally I'd like to continue with them if possible, rather than swapping to a list-based structure.

As renaming keys in a dict that's being looped over gives an error, to tackle the issue I've instead tried recursively iterating through each key in the dict and adding it to a new empty dict. The idea behind this is that for each entry in the original dict, its k & v is copied to the new dict one at a time, and if one of the duplicated '---' keys is reached, its name is changed to 'Separator ' + a count number. I'd then be able to use this new dictionary with my original function. Unfortunately I haven't been able to get this working and although the keys are copied and renamed correctly, again only the first separator key from each nested dict is included. The function looks like this:

```<code>old_dict = {#The same dict as in the original code block above}
new_dict = {}
global_count = 1

def prepare_dict(old, new):

    global global_count

    for k, v in old.items():
        if v[0] == 0:
            new.update({k:v})

        elif v[0] == 1:
            new["Seperator %s" % global_count] = old[k]
            global_count += 1

        elif v[0] == 2:
            new.update({k:v})

        elif v[0] == 3:

            new_dict = {}
            prepare_dict(v[1], new_dict)
            new.update({k:(v[0], new_dict)})

        else: pass

prepare_dict(old_dict, new_dict)
print(new_dict)

</code>```

This results in (where the commented lines are what I'd expect/hope to be included):

```<code>{'Title': [0],
'Seperator 1': [1],
'MenuItem 1': (3, {
    'SubItem 1': [2, 1000],
    'Seperator 2': [1],
    'SubItem 2': [2, 2000],
    #'Seperator 3': [1],
    'SubItem 3': [2, 3000]}),
#'Seperator 4': [1],
'MenuItem2': [2, 4000]}
</code>```

Any ideas or suggestions would be very much appreciated, I have looked at a number of similar questions but none have quite brought me to the right answer yet. It seems like there should be a way to go through the raw dictionary line-by-line only while looking at the key at the current iteration and without the duplicated keys affecting their predecessors, but obviously I'm open to recommendations if there really is no way to achieve what I'm trying to do with dicts! Thanks :)

Body:
I'm curious how one would go about renaming duplicated key names in a Python dict containing potentially multiple nested dicts.

I have a dictionary that will be used to dynamically populate a UI. Each key's value is a list containing an identifier int at v[0], and depending on the identifier, subsequent items at v[n>0]. The general format of this dict is as follows:

MenuItems = {

    'Title': [0], #Text
    '---': [1], #Separator

    'MenuItem 1': [3, { #Dropdown Submenu

        'SubItem 1': [2, 1000], #Submenu Items that return a value
        '---': [1],
        'SubItem 2': [2, 2000],
        '---': [1],
        'SubItem 3': [2, 3000]

        }],

    '---': [1],
    'MenuItem2': [2, 4000]

    }

I've written a recursive function to then traverse this dictionary and add the different menu items to the UI, however unfortunately I overlooked the fact that each separator has the same key name. As a result when the UI is built, only the first separator is shown in each UI level corresponding to the dict's level, like so:

Title
---
MenuItem 1
    SubItem 1
    ---
    SubItem 2
    SubItem 3
MenuItem2

Interestingly, and (for me) surprisingly, it is the first separator that is displayed in each UI level. I was under the assumption that as the duplicated key names overwrite each other from top to bottom, that it would be the last separator that would be shown, however it seems as though the first key's position is maintained, however it inherits the values of subsequent duplicate keys.

From reading up on python dicts further I understand that they may not be the best structure to use for data that is order-dependent (as is a UI builder), however their legibility and ease of iteration via for k, v in dict.items() means that ideally I'd like to continue with them if possible, rather than swapping to a list-based structure.

As renaming keys in a dict that's being looped over gives an error, to tackle the issue I've instead tried recursively iterating through each key in the dict and adding it to a new empty dict. The idea behind this is that for each entry in the original dict, its k & v is copied to the new dict one at a time, and if one of the duplicated '---' keys is reached, its name is changed to 'Separator ' + a count number. I'd then be able to use this new dictionary with my original function. Unfortunately I haven't been able to get this working and although the keys are copied and renamed correctly, again only the first separator key from each nested dict is included. The function looks like this:

old_dict = {#The same dict as in the original code block above}
new_dict = {}
global_count = 1

def prepare_dict(old, new):

    global global_count

    for k, v in old.items():
        if v[0] == 0:
            new.update({k:v})

        elif v[0] == 1:
            new["Seperator %s" % global_count] = old[k]
            global_count += 1

        elif v[0] == 2:
            new.update({k:v})

        elif v[0] == 3:

            new_dict = {}
            prepare_dict(v[1], new_dict)
            new.update({k:(v[0], new_dict)})

        else: pass

prepare_dict(old_dict, new_dict)
print(new_dict)

This results in (where the commented lines are what I'd expect/hope to be included):

{'Title': [0],
'Seperator 1': [1],
'MenuItem 1': (3, {
    'SubItem 1': [2, 1000],
    'Seperator 2': [1],
    'SubItem 2': [2, 2000],
    #'Seperator 3': [1],
    'SubItem 3': [2, 3000]}),
#'Seperator 4': [1],
'MenuItem2': [2, 4000]}

Any ideas or suggestions would be very much appreciated, I have looked at a number of similar questions but none have quite brought me to the right answer yet. It seems like there should be a way to go through the raw dictionary line-by-line only while looking at the key at the current iteration and without the duplicated keys affecting their predecessors, but obviously I'm open to recommendations if there really is no way to achieve what I'm trying to do with dicts! Thanks :)


问:
Johnny-five sensor (pin, freq=100) equivalent for Raspberry Pi 4
I need to read data on the Raspberry PI 4 gpio input pins. The javascript I have uses johnny-five (because this script was used on the Arduino YUN) and now I am running same script on Raspberry Pi 4. But, I am using nodejs``onoff to control the gpio pins. I understood that onoff is more powerful and advanced than the johnny-five.

Presently, the script reads input data of a physical pin at 100 ms frequency.

```<code>var five = require("johnny-five");
var readData = new five.Sensor({ pin:"A0", freq:100});
</code>```

Equivalent code for Raspberry Pi 4:

```<code>var gpio = require('onoff').Gpio;
var pin_17_in = new gpio(17,'in')
var readData = setInterval(pin_17_in, 100);
</code>```

Present output:

```<code>Timeout {
  _called: false,
  _idleTimeout: 100,
  _idlePrev: [TimersList],
  _idleNext: [TimersList],
  _idleStart: 57250,
  _onTimeout: [Function],
  _timerArgs: undefined,
  _repeat: 100,
  _destroyed: false,
  [Symbol(unrefed)]: false,
  [Symbol(asyncId)]: 9,
  [Symbol(triggerId)]: 5 }
</code>```

I was expecting 0 output, since, nothing is connected to the pin. However, I am seeing this dictionary list. Is this the correct one? is there a direct function available to read data every 100 ms using onoff package?

Body:
I need to read data on the Raspberry PI 4 gpio input pins. The javascript I have uses johnny-five (because this script was used on the Arduino YUN) and now I am running same script on Raspberry Pi 4. But, I am using nodejs``onoff to control the gpio pins. I understood that onoff is more powerful and advanced than the johnny-five.

Presently, the script reads input data of a physical pin at 100 ms frequency.

var five = require("johnny-five");
var readData = new five.Sensor({ pin:"A0", freq:100});

Equivalent code for Raspberry Pi 4:

var gpio = require('onoff').Gpio;
var pin_17_in = new gpio(17,'in')
var readData = setInterval(pin_17_in, 100);

Present output:

Timeout {
  _called: false,
  _idleTimeout: 100,
  _idlePrev: [TimersList],
  _idleNext: [TimersList],
  _idleStart: 57250,
  _onTimeout: [Function],
  _timerArgs: undefined,
  _repeat: 100,
  _destroyed: false,
  [Symbol(unrefed)]: false,
  [Symbol(asyncId)]: 9,
  [Symbol(triggerId)]: 5 }

I was expecting 0 output, since, nothing is connected to the pin. However, I am seeing this dictionary list. Is this the correct one? is there a direct function available to read data every 100 ms using onoff package?


问:
Safari does not always draw an svg line when its position is changed
I have an SVG element with a line:

```<code><svg viewBox="0 0 1 1" preserveAspectRatio="none">
  <line x1="0" y1="0.5" x2="1" y2="0.5" />
</svg>
</code>```

I want to move the line vertically when the user presses left mouse button on the image and drags the mouse while holding the button. When dragging the mouse cursor, the line is not always shown by Safari (the line is flickering). However, it works fine in Chrome and Firefox. Why is it not working in Safari?

A workaround is to add a border to the svg element. Why does this workaround work? Is there another way to fix it?

I'm using Safari Version 16.1 (18614.2.9.1.12) on macOS 13.0.1 (22A400).

To view the demo, click "Run code snippet" button and click near the vertical line to move it and drag the mouse cursor while holding the left mouse button.

class Input {
  constructor($element, $line) {
    this.$element = $element;
    this.$line = $line;

    // Function that is called when user clicks the fundus is moved,
    // passing position as argument
    this.onChange = null;

    // True if the user holds left mouse bottom, which
    // indicates that frame is being changed.
    // False by default or when the left mouse button is released.
    this.active = false;

    this.addEventListeners();
  }

  addEventListeners() {
    let $element = this.$element;

    // Start changing brightness
    // -----------------

    $element.onmousedown = (e) => {
      if (e.button !== 0) return; // Not a left mouse button
      this.active = true;
      e.preventDefault();
      this.handleClick(e);
    };

    $element.addEventListener("touchstart", (e) => {
      this.active = true;
      e.preventDefault();
      this.handleClick(e);
    });

    // End changing brightness
    // -----------------

    document.addEventListener("mouseup", () => {
      this.active = false;
    });

    document.addEventListener("touchend", () => {
      this.active = false;
    });

    // Drag the pointer over the bar
    // -----------------

    document.addEventListener("mousemove", (e) => {
      if (!this.active) return;
      this.handleClick(e);
    });

    document.addEventListener("touchmove", (e) => {
      if (!this.active) return;
      this.handleClick(e);
    });
  }

  handleClick(e) {
    let position = this.positionFromCursor(e);
    this.$line.setAttribute("y1", position);
    this.$line.setAttribute("y2", position);
  }

  // Returns a number from 0 to 1 corresponding to the
  // position of the cursor relative to the bscan box on fundus image
  positionFromCursor(e) {
    let $element = this.$element;
    // Vertical position of the click relative to the viewport.
    var pointerY = e.clientY;

    if (e.touches && e.touches.length > 0) {
      pointerY = e.touches[0].clientY;
    }

    var elementTop = $element.getBoundingClientRect().top;
    pointerY = pointerY - elementTop;
    let height = $element.getBoundingClientRect().bottom - elementTop;

    if (pointerY > height) {
      // Can not be larger than size of the element
      pointerY = height;
    }

    if (pointerY < 0) {
      // Can not be negative
      pointerY = 0;
    }

    return pointerY / height;
  }
}

document.addEventListener("DOMContentLoaded", function () {
  const $svgElement = document.querySelector(".Svg");
  const $svgLine = document.querySelector(".Svg-line");
  new Input($svgElement, $svgLine);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.Svg {
  width: 150px;
  height: 150px;
  /* Workaround for Safari to show the line */
  /* border: 5px solid red; */
  cursor: pointer;
}

.Svg-line {
  stroke: black;
  stroke-width: 0.02px;
}</code>```

<svg class="Svg" viewBox="0 0 1 1" preserveAspectRatio="none">
  <line class="Svg-line" x1="0" y1="0.5" x2="1" y2="0.5" />
</svg>```

Body:
I have an SVG element with a line:

<svg viewBox="0 0 1 1" preserveAspectRatio="none">
  <line x1="0" y1="0.5" x2="1" y2="0.5" />
</svg>

I want to move the line vertically when the user presses left mouse button on the image and drags the mouse while holding the button. When dragging the mouse cursor, the line is not always shown by Safari (the line is flickering). However, it works fine in Chrome and Firefox. Why is it not working in Safari?

A workaround is to add a border to the svg element. Why does this workaround work? Is there another way to fix it?

I'm using Safari Version 16.1 (18614.2.9.1.12) on macOS 13.0.1 (22A400).

To view the demo, click "Run code snippet" button and click near the vertical line to move it and drag the mouse cursor while holding the left mouse button.

class Input {
  constructor($element, $line) {
    this.$element = $element;
    this.$line = $line;

    // Function that is called when user clicks the fundus is moved,
    // passing position as argument
    this.onChange = null;

    // True if the user holds left mouse bottom, which
    // indicates that frame is being changed.
    // False by default or when the left mouse button is released.
    this.active = false;

    this.addEventListeners();
  }

  addEventListeners() {
    let $element = this.$element;

    // Start changing brightness
    // -----------------

    $element.onmousedown = (e) => {
      if (e.button !== 0) return; // Not a left mouse button
      this.active = true;
      e.preventDefault();
      this.handleClick(e);
    };

    $element.addEventListener("touchstart", (e) => {
      this.active = true;
      e.preventDefault();
      this.handleClick(e);
    });

    // End changing brightness
    // -----------------

    document.addEventListener("mouseup", () => {
      this.active = false;
    });

    document.addEventListener("touchend", () => {
      this.active = false;
    });

    // Drag the pointer over the bar
    // -----------------

    document.addEventListener("mousemove", (e) => {
      if (!this.active) return;
      this.handleClick(e);
    });

    document.addEventListener("touchmove", (e) => {
      if (!this.active) return;
      this.handleClick(e);
    });
  }

  handleClick(e) {
    let position = this.positionFromCursor(e);
    this.$line.setAttribute("y1", position);
    this.$line.setAttribute("y2", position);
  }

  // Returns a number from 0 to 1 corresponding to the
  // position of the cursor relative to the bscan box on fundus image
  positionFromCursor(e) {
    let $element = this.$element;
    // Vertical position of the click relative to the viewport.
    var pointerY = e.clientY;

    if (e.touches && e.touches.length > 0) {
      pointerY = e.touches[0].clientY;
    }

    var elementTop = $element.getBoundingClientRect().top;
    pointerY = pointerY - elementTop;
    let height = $element.getBoundingClientRect().bottom - elementTop;

    if (pointerY > height) {
      // Can not be larger than size of the element
      pointerY = height;
    }

    if (pointerY < 0) {
      // Can not be negative
      pointerY = 0;
    }

    return pointerY / height;
  }
}

document.addEventListener("DOMContentLoaded", function () {
  const $svgElement = document.querySelector(".Svg");
  const $svgLine = document.querySelector(".Svg-line");
  new Input($svgElement, $svgLine);
});

.Svg {
  width: 150px;
  height: 150px;
  /* Workaround for Safari to show the line */
  /* border: 5px solid red; */
  cursor: pointer;
}

.Svg-line {
  stroke: black;
  stroke-width: 0.02px;
}

<svg class="Svg" viewBox="0 0 1 1" preserveAspectRatio="none">
  <line class="Svg-line" x1="0" y1="0.5" x2="1" y2="0.5" />
</svg>


问:
Why are some resources still cached even after a hard refresh in Chrome?
Some resources are still cached after performing a hard refresh on a page (CTRL + SHIFT + R) in Chrome.

Using the 'disable caching' option in dev tools returns all of the page resources.

Is this something to do with the cache-control headers? Or something to do with Chrome itself?

I've compared the cached files using hard refresh vs. CTRL + SHIFT + R


问:
I'm trying to do 3 questions, and save each answer in a different variable
Well, first of all I'm using JUST javascript, so no html, it's only a js file that I'm runnning in console because I'm trying to practice. (I've also installed nodejs)
The thing is, When I run the code, It just doesn't let me input anything, and ends up with nan values in each variable.
I tried 2 variants but I just get almost the same result.

```<code>function ejercicio1_4() {

    let km;
    let pr
    let kml
    for(i=0; i<3; i++) {

        if(i==1) {
            console.log("Write your car km: ")
            process.stdin.on('data', function(data) {
                km = data;
                process.exit()
            })
        }else if (i==2) {
            console.log("Write the gas price: ")
            process.stdin.on('data', function(data) {
                pr = data;
                process.exit()
            })
        }else if (i==3) {
            console.log("Write how much km your car drives for each gas liter: ")
            process.stdin.on('data', function(data) {
                kml = data;
                process.exit()
            })
        }

    }
    let liters_consumed = (km/kml)
    let money_spent = pr/liters_consumed
    console.log("you've consumed: " + liters_consumed + "liters of gas. And you've spent: " + money_spent + "dollars in total.")

    // console.log("Write your car km: ")
    // process.stdin.on('kmm', function(kmm) {
    //     km = kmm.toNumber()
    //     process.exit()
    // })
    // console.log("Write the gas price: ")
    // process.stdin.on('prr', function(prr) {
    //     pr = prr.toNumber()
    //     process.exit()
    // })
    // console.log("Write how much km your car drives for each gas liter: ")
    // process.stdin.on('kmll', function(kmll) {
    //     kml = kmll.toNumber()
    //     process.exit()
    // })
    // let liters_consumed = (km/kml)
    // let money_spent = pr/liters_consumed
    // console.log("you've consumed: " + liters_consumed + "liters of gas. And you've spent: " + money_spent + "dollars in total.")
}
ejercicio1_4()
</code>```

I post the output pictures: Output after using the first script
Second script: Output after using the second script

Body:
Well, first of all I'm using JUST javascript, so no html, it's only a js file that I'm runnning in console because I'm trying to practice. (I've also installed nodejs)
The thing is, When I run the code, It just doesn't let me input anything, and ends up with nan values in each variable.
I tried 2 variants but I just get almost the same result.

function ejercicio1_4() {

    let km;
    let pr
    let kml
    for(i=0; i<3; i++) {

        if(i==1) {
            console.log("Write your car km: ")
            process.stdin.on('data', function(data) {
                km = data;
                process.exit()
            })
        }else if (i==2) {
            console.log("Write the gas price: ")
            process.stdin.on('data', function(data) {
                pr = data;
                process.exit()
            })
        }else if (i==3) {
            console.log("Write how much km your car drives for each gas liter: ")
            process.stdin.on('data', function(data) {
                kml = data;
                process.exit()
            })
        }

    }
    let liters_consumed = (km/kml)
    let money_spent = pr/liters_consumed
    console.log("you've consumed: " + liters_consumed + "liters of gas. And you've spent: " + money_spent + "dollars in total.")

    // console.log("Write your car km: ")
    // process.stdin.on('kmm', function(kmm) {
    //     km = kmm.toNumber()
    //     process.exit()
    // })
    // console.log("Write the gas price: ")
    // process.stdin.on('prr', function(prr) {
    //     pr = prr.toNumber()
    //     process.exit()
    // })
    // console.log("Write how much km your car drives for each gas liter: ")
    // process.stdin.on('kmll', function(kmll) {
    //     kml = kmll.toNumber()
    //     process.exit()
    // })
    // let liters_consumed = (km/kml)
    // let money_spent = pr/liters_consumed
    // console.log("you've consumed: " + liters_consumed + "liters of gas. And you've spent: " + money_spent + "dollars in total.")
}
ejercicio1_4()

I post the output pictures: Output after using the first script
Second script: Output after using the second script


问:
c# get the matched value from an string array of a string
i have a long string that I want to see if it  matches anything from a string array

```<code>string line = "this is a banana testing quote.";
string[] searchList = new string[4] {"b", "quote", "tee", "obb"};
</code>```

I will first need to find if the line contains any string from the searchList.

```<code>if(searchList.Any(line.Contains))
</code>```

and it can check if there is any match from the searchList, in this case, it should be "quote". but the checking can only check if it contains without knowing which exact string from the string array is matched.

Is there any better way to get the matched value, eg: string matchedValue = "serachList[2] or string matchedValue = "quote" other than looping the whole string for checking again?

I cannot loop through the string array searchList one by one as I am reading a big log, I think it is faster and better to use.Any()

Body:
i have a long string that I want to see if it  matches anything from a string array

string line = "this is a banana testing quote.";
string[] searchList = new string[4] {"b", "quote", "tee", "obb"};

I will first need to find if the line contains any string from the searchList.

if(searchList.Any(line.Contains))

and it can check if there is any match from the searchList, in this case, it should be "quote". but the checking can only check if it contains without knowing which exact string from the string array is matched.

Is there any better way to get the matched value, eg: string matchedValue = "serachList[2] or string matchedValue = "quote" other than looping the whole string for checking again?

I cannot loop through the string array searchList one by one as I am reading a big log, I think it is faster and better to use.Any()


问:
Hide certain product variation from store if is_purchasable = false in Woocommerce
I'm trying to hide from visitors from seeing certain product variation by uncheck the Enabled field. As currently when uncheck the Enabled field, the variation is grey out from store front, is there any way can add function to totally hide the certain variation from store front instead of grey out?

Example: i have product with variation XS, X, M, L
variation XS is disabled (uncheck the Enabled field), at store front, visitors will only see the selection for X, M, L, XS will be totally hidden (not grey out). While admin still able to see it from backend create order.


问:
Private slash commands
How can I make this command have permissions that nobody but me can use and see. Like the images img 1 img 2

```<code>const Discord = require("discord.js");

module.exports = {
  name: "ping",
  description: "nada",
  type: Discord.ApplicationCommandType.ChatInput,
  run: async (client, interaction) => {
    interaction.reply({ content: `Pong ${Math.round(client.ws.ping)}` })
  }
}
</code>```

I've tried this:

```<code>const Discord = require("discord.js");

module.exports = {
  name: "ping",
  description: "nada",
  type: Discord.ApplicationCommandType.ChatInput,
  default_member_permissions: 0,
  run: async (client, interaction) => {
    interaction.reply({ content: `Pong ${Math.round(client.ws.ping)}` })
  }
}
</code>```

default_member_permissions: 0, it's permission for administrators, but how do I make sure they don't even see it?

Title: Private slash commands

Body:
How can I make this command have permissions that nobody but me can use and see. Like the images img 1 img 2

const Discord = require("discord.js");

module.exports = {
  name: "ping",
  description: "nada",
  type: Discord.ApplicationCommandType.ChatInput,
  run: async (client, interaction) => {
    interaction.reply({ content: `Pong ${Math.round(client.ws.ping)}` })
  }
}

I've tried this:

const Discord = require("discord.js");

module.exports = {
  name: "ping",
  description: "nada",
  type: Discord.ApplicationCommandType.ChatInput,
  default_member_permissions: 0,
  run: async (client, interaction) => {
    interaction.reply({ content: `Pong ${Math.round(client.ws.ping)}` })
  }
}

default_member_permissions: 0, it's permission for administrators, but how do I make sure they don't even see it?


问:
WooCommerce v2 - echo order quantity
I am manipulating a table that shows orders.

I have managed to show some data from this using the below example (getting their phone number)

```<code>$order = new WC_Order( $item['order_id'] );
$phone = $order->billing_phone;
</code>```

I have tried $order->quantity but that returns nothing - so not sure what variable I need to use.

Can someone assist?

Title: WooCommerce v2 - echo order quantity

Body:
I am manipulating a table that shows orders.

I have managed to show some data from this using the below example (getting their phone number)

$order = new WC_Order( $item['order_id'] );
$phone = $order->billing_phone;

I have tried $order->quantity but that returns nothing - so not sure what variable I need to use.

Can someone assist?


问:
Where and how should CSRF token be stored for sending back and fro from server to client and client to server?
I have read a lot of posts/comments saying that CSRF token can be used for improving security for a Web application or an API but I cannot find information how CSRF token is implemented.

I assume on the server side one can store CSRF tokens in a memory cache, SQL server, etc I assume the client sends the token back in a POST request, in the header but how does the server sends a token to a client securely and where does the client store the token (some posts say don't store the token in the session cookie and some say don't store it in a hidden field but do not state the alternative)? Furthermore, does the server generate different tokens during a session (ie. a new token per request)?


问:
GlassFish v2 - How to externalize deployment descriptor sun-ejb-jar.xml?
When deploying my application I need to separate my configurations. This way any configuration changes does not require a new build.

My application has

app.ear

|---- app-ejb.jar

```<code>     |---- sun-ejb-jar.xml
</code>```

I need to remove sun-ejb-jar.xml out of app-ejb.jar and also app.ear, so when I make configuration changes in sun-ejb-jar.xml, I do not need to build and deploy, but only restart the application.

Is this possible with Glassfish v2 ?

Body:
When deploying my application I need to separate my configurations. This way any configuration changes does not require a new build.

My application has

app.ear

|---- app-ejb.jar

     |---- sun-ejb-jar.xml

I need to remove sun-ejb-jar.xml out of app-ejb.jar and also app.ear, so when I make configuration changes in sun-ejb-jar.xml, I do not need to build and deploy, but only restart the application.

Is this possible with Glassfish v2 ?


问:
DOMException Blocked A Frame / Cross Origin Frame, Unable to Solve
We are experiencing an issue on a domain that calls a web viewer server component on the same domain:8443 (so a different port) for users to view an uploaded file before placing an order for printing.

We're occasionally getting DOMException: Blocked a frame with origin \https://posterprintshop.com\ from accessing a cross-origin frame. error (when customers report it).  Strangely, it only happens in about 3 out of 10 users, only in Chrome on Windows, and not every user.

Our developer claims to have followed the advice from @MarcoBonelli in this article:

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

to use window.postMessage for communication, but the issue still occurs, and we know we're losing countless business from regular users who leave the site thinking their file won't upload because this error is buried in the console, and few customers tell us about it.  The fact it doesn't occur for everyone in Chrome makes it difficult to pinpoint and solve.

Issue happens when uploading a file in Chrome at https://posterprintshop.com/order-wizard

What is our developer missing?

Here is the description of what is happening on the page, with the code being used provided by our developer, you can see in the bottom code he's attempted to implement the postMessage solutions suggested in other articles, yet still this is not working:

A customer starts on our 'order-wizard' page at https://posterprintshop.com/order-wizard where they choose a file to upload.  After successful upload, this triggers the load of our /webv/ page where the web viewer is supposed to load the uploaded image and display it in an iframe from the PDFTRon server.  This is where the problem rears its head - for most users, all is fine, but for 50% of Chrome users, we get the cross-domain error.

webv page code includes div element with ID "viewer" where WebViewer/PDFTron performs the display of uploaded image.

HTML Snippets:

```<code><div id="viewer" class="viewer" style="background: url( <?php echo get_stylesheet_directory_uri() . '/images/pattern.jpg'; ?> ) repeat;"></div>
</code>```

JS Snippets:

```<code>var viewerElement = document.getElementById( 'viewer' );
</code>```

Under the div element with ID "viewer", WebViewer/PDFTron injecting an iframe with ID "webviewer-1" and it will show the uploaded image.

Snippets:

```<code><iframe id="webviewer-1" src=https://posterprintshop.com/wp-content/themes/hello-child/WebViewer/lib/./ui/index.html#d=https%3A%2F%2Fposterprintshop.com%2Fwp-content%2Fthemes%2Fhello-child%2Fpdftest.pdf&preloadWorker=pdf&a=1&css=https%3A%2F%2Fposterprintshop.com%2Fwp-content%2Fthemes%2Fhello-child%2Fcss%2Fwebviewer.css&filepicker=0&pdfnet=0&enableRedaction=0&enableMeasurement=0&pageHistory=1&notesInLeftPanel=0&useDownloader=0&selectAnnotationOnCreation=0&id=1 title="webviewer" frameborder="0" width="100%" height="100%" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>
</code>```

JS Snippets:

```<code>WebViewer( {
    path: '<?php echo get_stylesheet_directory_uri() .'/' ?>WebViewer/lib',
    licenseKey: '<License Key>',
    initialDoc: '<?php echo get_stylesheet_directory_uri() .'/' ?>pdftest.pdf',
    documentType: 'pdf',
    useDownloader: false,
    mobileRedirect: false,
    // fullAPI: true,
    css: '<?php echo get_stylesheet_directory_uri() .'/' ?>css/webviewer.css',
    }, viewerElement )
    .then( async ( instance ) => {
    console.log( '==> [pdf.php] Instance object ', instance );

    const iframeDoc = instance.iframeWindow.document;
    const iframe = document.getElementById( 'webviewer-1' ).contentWindow;
    iframe.postMessage( 'iframeTriggerJS', 'https://posterprintshop.com' );
    window.addEventListener( 'message', function( event ) {
        console.log( '==> [pdf.php] Listener triggering from JS' );
        console.log( '==> [pdf.php] Event object ', event );
        const origin = event.origin;
        if ( origin === 'https://posterprintshop.com' ) {
            console.log( '==> [pdf.php] Listening...' );
            console.log( '==> [pdf.php] Event Data object ', event.data );
        }
    } );

} );
</code>```

I have added below snippets in WebV page Snippets:

```<code><script>
    $ = jQuery.noConflict();
    $( function( $ ) {
        window.addEventListener( 'message', function( event ) {
            console.log( '==> [pdf.php] Listener triggering from WEBV' );
            console.log( '==> [pdf.php] Event object ', event );
            const origin = event.origin;
            if ( origin.startsWith( 'https://posterprintshop.com' ) ) {
                console.log( '==> [pdf.php] Listening...' );
                console.log( '==> [pdf.php] Event Data object ', event.data );
            }
        } );
    } );
</script>
</code>```

Also, added below snippets in JS Snippets:

```<code>const iframe = document.getElementById( 'webviewer-1' ).contentWindow;
iframe.postMessage( 'iframeTriggerJS', 'https://posterprintshop.com' );
window.addEventListener( 'message', function( event ) {
    console.log( '==> [pdf.php] Listener triggering from JS' );
    console.log( '==> [pdf.php] Event object ', event );
    const origin = event.origin;
    if ( origin === 'https://posterprintshop.com' ) {
        console.log( '==> [pdf.php] Listening...' );
        console.log( '==> [pdf.php] Event Data object ', event.data );
    }
} );
</code>```

Hoping someone can analyze this chain of events to point us in the direction of what we're missing?

Body:
We are experiencing an issue on a domain that calls a web viewer server component on the same domain:8443 (so a different port) for users to view an uploaded file before placing an order for printing.

We're occasionally getting DOMException: Blocked a frame with origin \https://posterprintshop.com\ from accessing a cross-origin frame. error (when customers report it).  Strangely, it only happens in about 3 out of 10 users, only in Chrome on Windows, and not every user.

Our developer claims to have followed the advice from @MarcoBonelli in this article:

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

to use window.postMessage for communication, but the issue still occurs, and we know we're losing countless business from regular users who leave the site thinking their file won't upload because this error is buried in the console, and few customers tell us about it.  The fact it doesn't occur for everyone in Chrome makes it difficult to pinpoint and solve.

Issue happens when uploading a file in Chrome at https://posterprintshop.com/order-wizard

What is our developer missing?

Here is the description of what is happening on the page, with the code being used provided by our developer, you can see in the bottom code he's attempted to implement the postMessage solutions suggested in other articles, yet still this is not working:

A customer starts on our 'order-wizard' page at https://posterprintshop.com/order-wizard where they choose a file to upload.  After successful upload, this triggers the load of our /webv/ page where the web viewer is supposed to load the uploaded image and display it in an iframe from the PDFTRon server.  This is where the problem rears its head - for most users, all is fine, but for 50% of Chrome users, we get the cross-domain error.

webv page code includes div element with ID "viewer" where WebViewer/PDFTron performs the display of uploaded image.

HTML Snippets:

<div id="viewer" class="viewer" style="background: url( <?php echo get_stylesheet_directory_uri() . '/images/pattern.jpg'; ?> ) repeat;">

JS Snippets:

var viewerElement = document.getElementById( 'viewer' );

Under the div element with ID "viewer", WebViewer/PDFTron injecting an iframe with ID "webviewer-1" and it will show the uploaded image.

Snippets:

<iframe id="webviewer-1" src=https://posterprintshop.com/wp-content/themes/hello-child/WebViewer/lib/./ui/index.html#d=https%3A%2F%2Fposterprintshop.com%2Fwp-content%2Fthemes%2Fhello-child%2Fpdftest.pdf&preloadWorker=pdf&a=1&css=https%3A%2F%2Fposterprintshop.com%2Fwp-content%2Fthemes%2Fhello-child%2Fcss%2Fwebviewer.css&filepicker=0&pdfnet=0&enableRedaction=0&enableMeasurement=0&pageHistory=1&notesInLeftPanel=0&useDownloader=0&selectAnnotationOnCreation=0&id=1 title="webviewer" frameborder="0" width="100%" height="100%" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true">

JS Snippets:

WebViewer( {
    path: '<?php echo get_stylesheet_directory_uri() .'/' ?>WebViewer/lib',
    licenseKey: '<License Key>',
    initialDoc: '<?php echo get_stylesheet_directory_uri() .'/' ?>pdftest.pdf',
    documentType: 'pdf',
    useDownloader: false,
    mobileRedirect: false,
    // fullAPI: true,
    css: '<?php echo get_stylesheet_directory_uri() .'/' ?>css/webviewer.css',
    }, viewerElement )
    .then( async ( instance ) => {
    console.log( '==> [pdf.php] Instance object ', instance );

    const iframeDoc = instance.iframeWindow.document;
    const iframe = document.getElementById( 'webviewer-1' ).contentWindow;
    iframe.postMessage( 'iframeTriggerJS', 'https://posterprintshop.com' );
    window.addEventListener( 'message', function( event ) {
        console.log( '==> [pdf.php] Listener triggering from JS' );
        console.log( '==> [pdf.php] Event object ', event );
        const origin = event.origin;
        if ( origin === 'https://posterprintshop.com' ) {
            console.log( '==> [pdf.php] Listening...' );
            console.log( '==> [pdf.php] Event Data object ', event.data );
        }
    } );

} );

I have added below snippets in WebV page Snippets:

Also, added below snippets in JS Snippets:

const iframe = document.getElementById( 'webviewer-1' ).contentWindow;
iframe.postMessage( 'iframeTriggerJS', 'https://posterprintshop.com' );
window.addEventListener( 'message', function( event ) {
    console.log( '==> [pdf.php] Listener triggering from JS' );
    console.log( '==> [pdf.php] Event object ', event );
    const origin = event.origin;
    if ( origin === 'https://posterprintshop.com' ) {
        console.log( '==> [pdf.php] Listening...' );
        console.log( '==> [pdf.php] Event Data object ', event.data );
    }
} );

Hoping someone can analyze this chain of events to point us in the direction of what we're missing?


问:
You want a bot like voicemaster. but it doesn't work. Deleting a channel doesn't work as expected
There is an error in the channel deletion part. I want to create a new dedicated channel when I enter a certain channel and delete that channel when I leave that channel. However, the function to be deleted when entering and exiting a voice room is applied to all voice channels. I'm sorry for my lack of English skills.</p>
```<code>async def on_voice_state_update(member, before, after):
    guild = bot.get_guild(guildid)
    category = get(guild.categories, name="╭────  gameroom  ────╮")
    try:
        if after.channel.id == 1015799007995510868:
          global channel
          channel = await guild.create_voice_channel(str(member).split("#")[0] + "'s channel", category = category, overwrites = {member: discord.PermissionOverwrite(manage_channels=True)})
          await member.move_to(channel)
    except:
      if len(before.channel.members) == 0:
        try: await bot.get_channel(before.channel.id).delete()
        except: pass```
</code>```

Body:
There is an error in the channel deletion part. I want to create a new dedicated channel when I enter a certain channel and delete that channel when I leave that channel. However, the function to be deleted when entering and exiting a voice room is applied to all voice channels. I'm sorry for my lack of English skills.

async def on_voice_state_update(member, before, after):
    guild = bot.get_guild(guildid)
    category = get(guild.categories, name="╭────  gameroom  ────╮")
    try:
        if after.channel.id == 1015799007995510868:
          global channel
          channel = await guild.create_voice_channel(str(member).split("#")[0] + "'s channel", category = category, overwrites = {member: discord.PermissionOverwrite(manage_channels=True)})
          await member.move_to(channel)
    except:
      if len(before.channel.members) == 0:
        try: await bot.get_channel(before.channel.id).delete()
        except: pass```


问:
cp949 error occurred while using smop. how do i solve it?
I searched for smop cp949 on stackoverflow, but didn't get any results, so I'm posting a question.

Traceback (most recent call last):
File "C:\Users\avern.conda\envs\ML\lib\site-packages\smop\main.py", line 58, in main
buf = open(options.filename).read()
UnicodeDecodeError: 'cp949' codec can't decode byte 0xec in position 2: illegal multibyte sequence
Errors: 1

```<code>clc; clear; close all;

refPath = 'D:\220119 Stroke Segmentation_transUnet\Walin\phoresults_CharSeg';        %'./[1] NeungUK';
savPath = 'D:\220104 Stroke Segmentation\wallin\Pho\classifiedChar3'; %./[3-5] Classification results(nuk)';

refPath = 'D:\programming\Stroke segmentation\TransUNet\data\sukbo_06_300\seg_chrpho2';
savPath = 'D:\programming\Stroke segmentation\TransUNet\data\sukbo_06_300\cls_chrpho3';

refPath = 'D:\programming\Stroke segmentation\TransUNet\data\sukbo_06_300\seg_chrpho2';
savPath = 'D:\programming\Stroke segmentation\TransUNet\data\sukbo_06_300\cls_chrpho3';

refPath = 'D:\programming\Stroke segmentation\TransUNet\data\neungumgyoung_08_600\seg_chrpho';
savPath = 'D:\programming\Stroke segmentation\TransUNet\data\neungumgyoung_08_600\cls_chrpho';

load('net_checkpoint_220124_jamo_ep20.mat','net')

dirImage   = dir( fullfile( refPath, '*.png' ));
group_labels = [];

jaumCode = string([ '1100';'1101';'1102';'1103';'1104';'1105';'1106';'1107';'1108';'1109';'110A';...
    '110B';'110C';'110D';'110E';'110F';'1110';'1111';'1112';'1115';'111A';'111D';'1120';...
    '1121';'1122';'1123';'1127';'112B';'112D';'112F';'1132';'1140';'1145';'1147';'114C';...
    '1158';'1159';'115B';'115C';'115D';'11B0';'11B1';'11B2';'11B3';'11B5';'11DD' ]);
moumCode = string([ '11A1';'116A';'116B';'116C';'116D';'116E';'116F';'119E';'1161';'1162';'1163';...
    '1165';'1166';'1167';'1168';'1169';'1170';'1171';'1172';'1173';'1174';'1175';'1188';...
    '1191';'1192';'1194';'D7C4';'D7C5' ]);
mkdir( fullfile( savPath, 'fail' ));

%%
for n = 1 : size( dirImage, 1 )

    [ ~, name, ~ ] = fileparts( fullfile(refPath, dirImage(n).name ));
    file =  fullfile( dirImage(n).folder, dirImage(n).name );

    img = imread( file );

    initPho = img( :, :, 2 ) | img( :, :, 3 );
    midPho  = img( :, :, 1 ) | img( :, :, 3 );
    finPho  = img( :, :, 1 ) | img( :, :, 2 );

    initPho = resize64_Pho(initPho);
    midPho = resize64_Pho(midPho);
    finPho = resize64_Pho(finPho);

    initPred = classify(net, initPho);
    midPred = classify(net, midPho);
    finPred = classify(net, finPho);

    label = join( string([ initPred, midPred, finPred ]), "" );
    savdir = fullfile( savPath, label );

    ja_Idx1 = find(moumCode == string(initPred));
    ja_Idx2 = find(moumCode == string(finPred));
    mo_Idx = find(jaumCode == string(midPred));

    if ~isempty(ja_Idx1) || ~isempty(ja_Idx2) || ~isempty(mo_Idx)
        imwrite( img, fullfile( savPath, 'fail', join([ name '.png' ],"" )), 'png')
    else
        if any( strcmp( label, group_labels ))
            imwrite( img, fullfile( savdir, join([ name '.png' ],"" )), 'png' );
        else
            assert( ~exist( fullfile( savPath, label ), 'dir' ))
            mkdir( fullfile( savPath, label ));
            imwrite( img, fullfile( savdir, join([ name '.png' ],"" )), 'png' );
            group_labels = vertcat( group_labels, label );
        end
    end
    label = [];
    if mod(n,1000)
        continue
    end
    disp([num2str(n)])
end
</code>```

Body:
I searched for smop cp949 on stackoverflow, but didn't get any results, so I'm posting a question.

Traceback (most recent call last):
File "C:\Users\avern.conda\envs\ML\lib\site-packages\smop\main.py", line 58, in main
buf = open(options.filename).read()
UnicodeDecodeError: 'cp949' codec can't decode byte 0xec in position 2: illegal multibyte sequence
Errors: 1

clc; clear; close all;

refPath = 'D:\220119 Stroke Segmentation_transUnet\Walin\phoresults_CharSeg';        %'./[1] NeungUK';
savPath = 'D:\220104 Stroke Segmentation\wallin\Pho\classifiedChar3'; %./[3-5] Classification results(nuk)';

refPath = 'D:\programming\Stroke segmentation\TransUNet\data\sukbo_06_300\seg_chrpho2';
savPath = 'D:\programming\Stroke segmentation\TransUNet\data\sukbo_06_300\cls_chrpho3';

refPath = 'D:\programming\Stroke segmentation\TransUNet\data\sukbo_06_300\seg_chrpho2';
savPath = 'D:\programming\Stroke segmentation\TransUNet\data\sukbo_06_300\cls_chrpho3';

refPath = 'D:\programming\Stroke segmentation\TransUNet\data\neungumgyoung_08_600\seg_chrpho';
savPath = 'D:\programming\Stroke segmentation\TransUNet\data\neungumgyoung_08_600\cls_chrpho';

load('net_checkpoint_220124_jamo_ep20.mat','net')

dirImage   = dir( fullfile( refPath, '*.png' ));
group_labels = [];

jaumCode = string([ '1100';'1101';'1102';'1103';'1104';'1105';'1106';'1107';'1108';'1109';'110A';...
    '110B';'110C';'110D';'110E';'110F';'1110';'1111';'1112';'1115';'111A';'111D';'1120';...
    '1121';'1122';'1123';'1127';'112B';'112D';'112F';'1132';'1140';'1145';'1147';'114C';...
    '1158';'1159';'115B';'115C';'115D';'11B0';'11B1';'11B2';'11B3';'11B5';'11DD' ]);
moumCode = string([ '11A1';'116A';'116B';'116C';'116D';'116E';'116F';'119E';'1161';'1162';'1163';...
    '1165';'1166';'1167';'1168';'1169';'1170';'1171';'1172';'1173';'1174';'1175';'1188';...
    '1191';'1192';'1194';'D7C4';'D7C5' ]);
mkdir( fullfile( savPath, 'fail' ));

%%
for n = 1 : size( dirImage, 1 )

    [ ~, name, ~ ] = fileparts( fullfile(refPath, dirImage(n).name ));
    file =  fullfile( dirImage(n).folder, dirImage(n).name );

    img = imread( file );

    initPho = img( :, :, 2 ) | img( :, :, 3 );
    midPho  = img( :, :, 1 ) | img( :, :, 3 );
    finPho  = img( :, :, 1 ) | img( :, :, 2 );

    initPho = resize64_Pho(initPho);
    midPho = resize64_Pho(midPho);
    finPho = resize64_Pho(finPho);

    initPred = classify(net, initPho);
    midPred = classify(net, midPho);
    finPred = classify(net, finPho);

    label = join( string([ initPred, midPred, finPred ]), "" );
    savdir = fullfile( savPath, label );

    ja_Idx1 = find(moumCode == string(initPred));
    ja_Idx2 = find(moumCode == string(finPred));
    mo_Idx = find(jaumCode == string(midPred));

    if ~isempty(ja_Idx1) || ~isempty(ja_Idx2) || ~isempty(mo_Idx)
        imwrite( img, fullfile( savPath, 'fail', join([ name '.png' ],"" )), 'png')
    else
        if any( strcmp( label, group_labels ))
            imwrite( img, fullfile( savdir, join([ name '.png' ],"" )), 'png' );
        else
            assert( ~exist( fullfile( savPath, label ), 'dir' ))
            mkdir( fullfile( savPath, label ));
            imwrite( img, fullfile( savdir, join([ name '.png' ],"" )), 'png' );
            group_labels = vertcat( group_labels, label );
        end
    end
    label = [];
    if mod(n,1000)
        continue
    end
    disp([num2str(n)])
end


问:
Getting index out of bounds error trying to make a method that adds an int to an array in java
Doing some school stuff and I basically need to create a Method that "pushes" an integer to an array at the last position (basically recreating the Stack.push() method).

```<code>public class IntegerStack {

    int[] storage;
    int height;

    public IntegerStack(int i) {
        this.storage = new int[i];
        this.height = 0;
    }

    public void push(int i) {
        if(height == 0) {
            storage[height] = i;
            height++;
        } else {

            int[] tempArr = new int[storage.length + 1];

            for(int j = 0; j < storage.length - 1 ; j++) {
                tempArr[j] = storage[j];
            }
                tempArr[tempArr.length] = i;
                storage = tempArr;
                height++;

        }
    }
</code>```

I tried to create a Temporary array that has the same stuff as the original one + add the integer from the method at last position and then replace the original one with the temporary one, but I keep getting this error and I'm really stuck so I need some help

```<code>java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
</code>```

Body:
Doing some school stuff and I basically need to create a Method that "pushes" an integer to an array at the last position (basically recreating the Stack.push() method).

public class IntegerStack {

    int[] storage;
    int height;

    public IntegerStack(int i) {
        this.storage = new int[i];
        this.height = 0;
    }

    public void push(int i) {
        if(height == 0) {
            storage[height] = i;
            height++;
        } else {

            int[] tempArr = new int[storage.length + 1];

            for(int j = 0; j < storage.length - 1 ; j++) {
                tempArr[j] = storage[j];
            }
                tempArr[tempArr.length] = i;
                storage = tempArr;
                height++;

        }
    }

I tried to create a Temporary array that has the same stuff as the original one + add the integer from the method at last position and then replace the original one with the temporary one, but I keep getting this error and I'm really stuck so I need some help

java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4


问:
How can I get the word "Menu" from the current String.xml?
<string name="item_first1">MENU</string>

Currently name can be fetched.
How do I get the word "Menu" from this string.xml file?

My sources are:

```<code>try {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(xml.url);

    NodeList tagList = doc.getElementsByTagName("string");
    for(int i = 0; i < tagList.getLength(); ++i) {
             String name = tagList.item(i).getAttributes().getNamedItem("name").getNodeValue();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }`
</code>```

Body:
<string name="item_first1">MENU</string>

Currently name can be fetched.
How do I get the word "Menu" from this string.xml file?

My sources are:

try {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(xml.url);

    NodeList tagList = doc.getElementsByTagName("string");
    for(int i = 0; i < tagList.getLength(); ++i) {
             String name = tagList.item(i).getAttributes().getNamedItem("name").getNodeValue();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }`