问:
How to handle dynamic multiple call of the same function for instance, based on user clicks?
I have the following functions written in JavaScript:

```<code>function getA(color, modelName) {
   console.log("------- getA modelName=", modelName);
   var div = document.getElementById(modelName);
   var myData = div.textContent;
   console.log(myData);
   const myArray = myData.split("|");
   console.log("---ss --- ", myArray[1]);
   const a2 = myArray[1].split(":");
   //for (var i = 0; i < a2.length; i++) { console.log(a2[i]); }
   console.log("------ aaa:", a2[1]);
   //return [color, a2[1]];
   return ["red", a2[1]];
}

function getB(color, modelName){
   var div = document.getElementById(modelName);
   var myData = div.textContent;
   console.log("------- getB =", myData);
   const myArray = myData.split("|");
   console.log("---ss --- ", myArray[2]);
   const a2 = myArray[2].split(":");
   console.log("------ bbb:", a2[1]);
   return ["blue", a2[1]];
}

function getC(color, modelName){

   var div = document.getElementById(modelName);
   var myData = div.textContent;
   console.log("------- getB =", myData);
   const myArray = myData.split("|");
   console.log("---ss --- ", myArray[3]);
   const a2 = myArray[3].split(":");
   console.log("------ ccc:", a2[1]);
   return ["green", a2[1]];
}

function getD(color, modelName){

   var div = document.getElementById(modelName);
   var myData = div.textContent;
   console.log("------- getB =", myData);
   const myArray = myData.split("|");
   console.log("---ss --- ", myArray[4]);
   const a2 = myArray[4].split(":");
   console.log("------ ccc:", a2[1]);
   return ["yellow", a2[1]];
}

function getE(color, modelName){

   var div = document.getElementById(modelName);
   var myData = div.textContent;
   console.log("------- getB =", myData);
   const myArray = myData.split("|");
   console.log("---ss --- ", myArray[5]);
   const a2 = myArray[5].split(":");
   console.log("------ ccc:", a2[1]);
   return ["orange", a2[1]];
}

function getF(color, modelName){

   var div = document.getElementById(modelName);
   var myData = div.textContent;
   console.log("------- getB =", myData);
   const myArray = myData.split("|");
   console.log("---ss --- ", myArray[6]);
   const a2 = myArray[6].split(":");
   console.log("------ ccc:", a2[1]);
   return ["purple", a2[1]];
}

function getL(color, modelName){

   var div = document.getElementById(modelName);
   var myData = div.textContent;
   console.log("------- getB =", myData);
   const myArray = myData.split("|");
   console.log("---ss --- ", myArray[7]);
   const a2 = myArray[7].split(":");
   console.log("------ ccc:", a2[1]);
   return ["cyan", a2[1]];
}
</code>```

Thank you

```<code>I am using these functions with NGL view to display in color amino acids based on their location in the chain A, B, C, ..., etc. These chain names or chain IDs could be identified by capital, small letters or numbers. I am calling these functions in another JS function which display the amino acids in different colors, and basically are an output of large php parser. They are invoked as follows:-

</code>```

var loadpdbfile = function (file, param, filename)

{
var schemeId_A = NGL.ColormakerRegistry.addSelectionScheme([getA("red", filename)]);
var schemeId_B = NGL.ColormakerRegistry.addSelectionScheme([getB("blue", filename)]);
var schemeId_C = NGL.ColormakerRegistry.addSelectionScheme([getC("green", filename)]);
var schemeId_D = NGL.ColormakerRegistry.addSelectionScheme([getD('yellow', filename)]);
var schemeId_E = NGL.ColormakerRegistry.addSelectionScheme([getE('orange', filename)]);
var schemeId_F = NGL.ColormakerRegistry.addSelectionScheme([getF('purple', filename)]);
var schemeId_L = NGL.ColormakerRegistry.addSelectionScheme([getL('cyan', filename)]);

```<code>              pdb.addRepresentation("cartoon", { color: schemeId_A, sele: ":A" });
              pdb.addRepresentation("cartoon", { color: schemeId_B, sele: ":B" });
              pdb.addRepresentation("cartoon", { color: schemeId_C, sele: ":C" });
              pdb.addRepresentation("cartoon", { color: schemeId_D, sele: ":D" });
              pdb.addRepresentation("cartoon", { color: schemeId_E, sele: ":E"  });
              pdb.addRepresentation("cartoon", { color: schemeId_F, sele: ":F"  });
              pdb.addRepresentation("cartoon", { color: schemeId_L, sele: ":L"  });

          return pdb;
</code>```

}

```<code>
But calling the above function in that way is not handy due to nature of the file which is read and that can handle multiple chains with small/upper-case/numeric first character which defines each chain name of the file.`sele: "A"` etc. handles NGL view API (https://nglviewer.org/ngl/api/manual/coloring.html) which is essential to distinguish between different chain name and their colors as well as structural representaion.

My problem is to combine all these function in a single function which candle dynamic call based on the letters/numbers of the chain ID and NGL selection which select specific chain name during function call as shown here:

</code>```
```<code>              pdb.addRepresentation("cartoon", { color: schemeId_A, sele: ":A" });
              pdb.addRepresentation("cartoon", { color: schemeId_B, sele: ":B" });
              pdb.addRepresentation("cartoon", { color: schemeId_C, sele: ":C" });
              pdb.addRepresentation("cartoon", { color: schemeId_D, sele: ":D" });
              pdb.addRepresentation("cartoon", { color: schemeId_E, sele: ":E"  });
              pdb.addRepresentation("cartoon", { color: schemeId_F, sele: ":F"  });
              pdb.addRepresentation("cartoon", { color: schemeId_L, sele: ":L"  });

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

Body:
I have the following functions written in JavaScript:

function getA(color, modelName) {
   console.log("------- getA modelName=", modelName);
   var div = document.getElementById(modelName);
   var myData = div.textContent;
   console.log(myData);
   const myArray = myData.split("|");
   console.log("---ss --- ", myArray[1]);
   const a2 = myArray[1].split(":");
   //for (var i = 0; i < a2.length; i++) { console.log(a2[i]); }
   console.log("------ aaa:", a2[1]);
   //return [color, a2[1]];
   return ["red", a2[1]];
}

function getB(color, modelName){
   var div = document.getElementById(modelName);
   var myData = div.textContent;
   console.log("------- getB =", myData);
   const myArray = myData.split("|");
   console.log("---ss --- ", myArray[2]);
   const a2 = myArray[2].split(":");
   console.log("------ bbb:", a2[1]);
   return ["blue", a2[1]];
}

function getC(color, modelName){

   var div = document.getElementById(modelName);
   var myData = div.textContent;
   console.log("------- getB =", myData);
   const myArray = myData.split("|");
   console.log("---ss --- ", myArray[3]);
   const a2 = myArray[3].split(":");
   console.log("------ ccc:", a2[1]);
   return ["green", a2[1]];
}

function getD(color, modelName){

   var div = document.getElementById(modelName);
   var myData = div.textContent;
   console.log("------- getB =", myData);
   const myArray = myData.split("|");
   console.log("---ss --- ", myArray[4]);
   const a2 = myArray[4].split(":");
   console.log("------ ccc:", a2[1]);
   return ["yellow", a2[1]];
}

function getE(color, modelName){

   var div = document.getElementById(modelName);
   var myData = div.textContent;
   console.log("------- getB =", myData);
   const myArray = myData.split("|");
   console.log("---ss --- ", myArray[5]);
   const a2 = myArray[5].split(":");
   console.log("------ ccc:", a2[1]);
   return ["orange", a2[1]];
}

function getF(color, modelName){

   var div = document.getElementById(modelName);
   var myData = div.textContent;
   console.log("------- getB =", myData);
   const myArray = myData.split("|");
   console.log("---ss --- ", myArray[6]);
   const a2 = myArray[6].split(":");
   console.log("------ ccc:", a2[1]);
   return ["purple", a2[1]];
}

function getL(color, modelName){

   var div = document.getElementById(modelName);
   var myData = div.textContent;
   console.log("------- getB =", myData);
   const myArray = myData.split("|");
   console.log("---ss --- ", myArray[7]);
   const a2 = myArray[7].split(":");
   console.log("------ ccc:", a2[1]);
   return ["cyan", a2[1]];
}

Thank you

I am using these functions with NGL view to display in color amino acids based on their location in the chain A, B, C, ..., etc. These chain names or chain IDs could be identified by capital, small letters or numbers. I am calling these functions in another JS function which display the amino acids in different colors, and basically are an output of large php parser. They are invoked as follows:-

var loadpdbfile = function (file, param, filename)

{
var schemeId_A = NGL.ColormakerRegistry.addSelectionScheme([getA("red", filename)]);
var schemeId_B = NGL.ColormakerRegistry.addSelectionScheme([getB("blue", filename)]);
var schemeId_C = NGL.ColormakerRegistry.addSelectionScheme([getC("green", filename)]);
var schemeId_D = NGL.ColormakerRegistry.addSelectionScheme([getD('yellow', filename)]);
var schemeId_E = NGL.ColormakerRegistry.addSelectionScheme([getE('orange', filename)]);
var schemeId_F = NGL.ColormakerRegistry.addSelectionScheme([getF('purple', filename)]);
var schemeId_L = NGL.ColormakerRegistry.addSelectionScheme([getL('cyan', filename)]);

              pdb.addRepresentation("cartoon", { color: schemeId_A, sele: ":A" });
              pdb.addRepresentation("cartoon", { color: schemeId_B, sele: ":B" });
              pdb.addRepresentation("cartoon", { color: schemeId_C, sele: ":C" });
              pdb.addRepresentation("cartoon", { color: schemeId_D, sele: ":D" });
              pdb.addRepresentation("cartoon", { color: schemeId_E, sele: ":E"  });
              pdb.addRepresentation("cartoon", { color: schemeId_F, sele: ":F"  });
              pdb.addRepresentation("cartoon", { color: schemeId_L, sele: ":L"  });

          return pdb;

}

But calling the above function in that way is not handy due to nature of the file which is read and that can handle multiple chains with small/upper-case/numeric first character which defines each chain name of the file.`sele: "A"` etc. handles NGL view API (https://nglviewer.org/ngl/api/manual/coloring.html) which is essential to distinguish between different chain name and their colors as well as structural representaion.

My problem is to combine all these function in a single function which candle dynamic call based on the letters/numbers of the chain ID and NGL selection which select specific chain name during function call as shown here:

              pdb.addRepresentation("cartoon", { color: schemeId_A, sele: ":A" });
              pdb.addRepresentation("cartoon", { color: schemeId_B, sele: ":B" });
              pdb.addRepresentation("cartoon", { color: schemeId_C, sele: ":C" });
              pdb.addRepresentation("cartoon", { color: schemeId_D, sele: ":D" });
              pdb.addRepresentation("cartoon", { color: schemeId_E, sele: ":E"  });
              pdb.addRepresentation("cartoon", { color: schemeId_F, sele: ":F"  });
              pdb.addRepresentation("cartoon", { color: schemeId_L, sele: ":L"  });

          }
          return pdb;


来源: stackexchange

问:
Round a column in Python
I would like to round one specific column to 1 decimal place. Currently I am using the following code:

scatterLabelsEinkommen['Einkommen'].round(decimals=2)

I get the following error:

loop of ufunc does not support argument 0 of type float which has no callable rint method

Do you know how to overcome this error?

Thank you for your help.

ContentLicense: CC BY-SA 4.0

Title: Round a column in Python


问:
R shiny "variable lengths differ" error with selectInput and dataframe
I have a cancer dataset, so my "keys" are 35 cancer types, and my "values" are 10 metrics for each cancer type (new cases, new deaths, e.t.c.). With this in mind, in the process of trying to adapt a "new cases per cancer type" barplot codeblock I created, to a shiny app, I want to use a "selectInput" sidebar element so the user can select which cancer types they want to be visible in the graph.

I've managed to show the graph, and if I remove cancer types starting from the bottom of the list (meaning alphabetically as presented), or add them back again from top to bottom (meaning in reverse alphabetical order), all is working properly. However, if I try to remove the cancer type with the max/min new cases, or some other random cancer types, I get a "variable lengths differ" error.

```<code>Warning in cancer_data()$cancer_type == input$bar_0_in :
  longer object length is not a multiple of shorter object length
Warning: Error in model.frame.default: variable lengths differ (found for 'input$bar_0_in')
</code>```

I've read about the error, and I understand (also obvious because of the naming) that it happens because of, say, two columns in a data frame with different lengths. That is all well and good, however, for the barplot I have isolated the specific rows of the dataset that correspond to the items of the "selectInput" selected by the user:

```<code>...
 barplot(cancer_data()$new_cases_number[
        cancer_data()$cancer_type ==  input$bar_0_in] ~ input$bar_0_in, ...

</code>```

Here cancer_data is the dataset, and input$bar_0_in is the "selectInput" widget. Obviously, when input$bar_0_in" is created, the choices are generated using cancer_data.

I wanted to debug this, so using an "observeEvent" element, I print both the length and the contents of input$bar_0_in and

```<code>cancer_data()$cancer_type[
    cancer_data()$cancer_type ==  input$bar_0_in
]
</code>```

meaning the cancer types directly from the dataset that match the cancer types from the input$bar_0_in list. As initially all choices are selected in the widget, the length of both lists is 35, and I get this regarding their content:

```<code>[1] "List length:  35 - Condition length: 35"
[1] "List: Anus - Conditional:  Anus"
[2] "List: Bladder - Conditional:  Bladder"
[3] "List: Brain, central nervous system - Conditional:  Brain, central nervous system"
[4] "List: Breast - Conditional:  Breast"
[5] "List: Cervix uteri - Conditional:  Cervix uteri"
[6] "List: Colon - Conditional:  Colon"
[7] "List: Corpus uteri - Conditional:  Corpus uteri"
...
</code>```

e.t.c. (too long, it continues in the same manner). "List:" refers to the "selectInput" content, and "Conditional:" to the filtered cancer_data content.

HOWEVER, if I remove Breast cancer, which has the most new cases, the lengths of the lists become 34 and 3 respectively, and their contents:

```<code>[1] "List length:  34 - Condition length: 3"
[1] "List: Anus - Conditional:  Anus"
[2] "List: Bladder - Conditional:  Bladder"
[3] "List: Brain, central nervous system - Conditional:  Brain, central nervous system"
[4] "List: Cervix uteri - Conditional:  Anus"
[5] "List: Colon - Conditional:  Bladder"
[6] "List: Corpus uteri - Conditional:  Brain, central nervous system"
[7] "List: Gallbladder - Conditional:  Anus"
...
</code>```

The 34 is sensible, one cancer type has been removed, however the 3 does not make any sense. As is visible from the contents, the second list only includes the 3 cancer types before  breast cancer, and are repeated after depletion. Obviously I only removed breast cancer, not touching anything else.

Do you know why this might be happening? I cannot make any sense of it, as everything I did is based on the cancer_data contents, I haven't put anything in by hand.

Thanks a lot for your help. Here is the entirety of my code.

```<code>library(shiny)

if (interactive()) {

  ui <- fluidPage(

    titlePanel("WHO 2020 India Cancer data."),

    sidebarLayout(

      sidebarPanel(
        fileInput(inputId = "uploadData",
                  label = "Select the .csv file with the dataset.",
                  accept = ".csv"),

        checkboxInput(inputId = "showData",
                      label = "Click to show entire dataset."),

        hr(),

        uiOutput("bar_0_cond")
      ),

      mainPanel(
        tableOutput("dataTable"),
        plotOutput("bar_0_out"),
      )
    )
  )

  server <- function(input, output) {

   output$dataTable <- renderTable({
      if (is.null(input$uploadData) || input$showData == FALSE) {
        return()
      } else {
        cancer_data <<- reactive({
          read.csv(input$uploadData$datapath)
        })
        cancer_data()
      }
   })

   output$bar_0_cond <- renderUI({
      if (is.null(input$uploadData)) {
        return(NULL)
      } else {

        selectInput(inputId = "bar_0_in",
                label = "Cases by Cancer Type",
                multiple = TRUE,
                choices = cancer_data()$cancer_type,
                selected = cancer_data()$cancer_type)
      }
   })

   output$bar_0_out <- renderPlot({
    if (is.null(input$uploadData) || is.null(input$bar_0_in)) {
        return(NULL)
      } else {

      barplot(cancer_data()$new_cases_number[
        cancer_data()$cancer_type ==  input$bar_0_in] ~ input$bar_0_in,
          main = "Cases per Cancer Type",
          xlab = "", ylab = "", axes = FALSE,
          las = 2, col = colours,
          cex.names = 0.6,
          mar = c(10, 7, 3, 1)
          )

      axis(side = 2, at = seq(from = 0,
                              to = max(cancer_data()$new_cases_number[
                      cancer_data()$cancer_type ==  input$bar_0_in]),
                              by = max(cancer_data()$new_cases_number[
                      cancer_data()$cancer_type ==  input$bar_0_in]) %/% 5))

      title(ylab = "Number of Cases", line = 5, cex.lab = 1.2, font.lab = 2)
      title(xlab = "Cancer Type", line = 8, cex.lab = 1.2, font.lab = 2)
    }
   })

    # This is entirely for debugging purposes.
    observeEvent(input$bar_0_in, {
      print(paste("List length: ", length(input$bar_0_in),
                  "- Condition length:", length(cancer_data()$new_cases_number[
                      cancer_data()$cancer_type ==  input$bar_0_in])))
      print(paste("List:", input$bar_0_in,
                  "- Conditional: ", cancer_data()$cancer_type[
                              cancer_data()$cancer_type == input$bar_0_in
                  ]))
    })
  }

  shinyApp(ui = ui, server = server)

}

</code>```

Body:
I have a cancer dataset, so my "keys" are 35 cancer types, and my "values" are 10 metrics for each cancer type (new cases, new deaths, e.t.c.). With this in mind, in the process of trying to adapt a "new cases per cancer type" barplot codeblock I created, to a shiny app, I want to use a "selectInput" sidebar element so the user can select which cancer types they want to be visible in the graph.

I've managed to show the graph, and if I remove cancer types starting from the bottom of the list (meaning alphabetically as presented), or add them back again from top to bottom (meaning in reverse alphabetical order), all is working properly. However, if I try to remove the cancer type with the max/min new cases, or some other random cancer types, I get a "variable lengths differ" error.

Warning in cancer_data()$cancer_type == input$bar_0_in :
  longer object length is not a multiple of shorter object length
Warning: Error in model.frame.default: variable lengths differ (found for 'input$bar_0_in')

I've read about the error, and I understand (also obvious because of the naming) that it happens because of, say, two columns in a data frame with different lengths. That is all well and good, however, for the barplot I have isolated the specific rows of the dataset that correspond to the items of the "selectInput" selected by the user:

...
 barplot(cancer_data()$new_cases_number[
        cancer_data()$cancer_type ==  input$bar_0_in] ~ input$bar_0_in, ...

Here cancer_data is the dataset, and input$bar_0_in is the "selectInput" widget. Obviously, when input$bar_0_in" is created, the choices are generated using cancer_data.

I wanted to debug this, so using an "observeEvent" element, I print both the length and the contents of input$bar_0_in and

cancer_data()$cancer_type[
    cancer_data()$cancer_type ==  input$bar_0_in
]

meaning the cancer types directly from the dataset that match the cancer types from the input$bar_0_in list. As initially all choices are selected in the widget, the length of both lists is 35, and I get this regarding their content:

[1] "List length:  35 - Condition length: 35"
[1] "List: Anus - Conditional:  Anus"
[2] "List: Bladder - Conditional:  Bladder"
[3] "List: Brain, central nervous system - Conditional:  Brain, central nervous system"
[4] "List: Breast - Conditional:  Breast"
[5] "List: Cervix uteri - Conditional:  Cervix uteri"
[6] "List: Colon - Conditional:  Colon"
[7] "List: Corpus uteri - Conditional:  Corpus uteri"
...

e.t.c. (too long, it continues in the same manner). "List:" refers to the "selectInput" content, and "Conditional:" to the filtered cancer_data content.

HOWEVER, if I remove Breast cancer, which has the most new cases, the lengths of the lists become 34 and 3 respectively, and their contents:

[1] "List length:  34 - Condition length: 3"
[1] "List: Anus - Conditional:  Anus"
[2] "List: Bladder - Conditional:  Bladder"
[3] "List: Brain, central nervous system - Conditional:  Brain, central nervous system"
[4] "List: Cervix uteri - Conditional:  Anus"
[5] "List: Colon - Conditional:  Bladder"
[6] "List: Corpus uteri - Conditional:  Brain, central nervous system"
[7] "List: Gallbladder - Conditional:  Anus"
...

The 34 is sensible, one cancer type has been removed, however the 3 does not make any sense. As is visible from the contents, the second list only includes the 3 cancer types before  breast cancer, and are repeated after depletion. Obviously I only removed breast cancer, not touching anything else.

Do you know why this might be happening? I cannot make any sense of it, as everything I did is based on the cancer_data contents, I haven't put anything in by hand.

Thanks a lot for your help. Here is the entirety of my code.

library(shiny)

if (interactive()) {

  ui <- fluidPage(

    titlePanel("WHO 2020 India Cancer data."),

    sidebarLayout(

      sidebarPanel(
        fileInput(inputId = "uploadData",
                  label = "Select the .csv file with the dataset.",
                  accept = ".csv"),

        checkboxInput(inputId = "showData",
                      label = "Click to show entire dataset."),

        hr(),

        uiOutput("bar_0_cond")
      ),

      mainPanel(
        tableOutput("dataTable"),
        plotOutput("bar_0_out"),
      )
    )
  )

  server <- function(input, output) {

   output$dataTable <- renderTable({
      if (is.null(input$uploadData) || input$showData == FALSE) {
        return()
      } else {
        cancer_data <<- reactive({
          read.csv(input$uploadData$datapath)
        })
        cancer_data()
      }
   })

   output$bar_0_cond <- renderUI({
      if (is.null(input$uploadData)) {
        return(NULL)
      } else {

        selectInput(inputId = "bar_0_in",
                label = "Cases by Cancer Type",
                multiple = TRUE,
                choices = cancer_data()$cancer_type,
                selected = cancer_data()$cancer_type)
      }
   })

   output$bar_0_out <- renderPlot({
    if (is.null(input$uploadData) || is.null(input$bar_0_in)) {
        return(NULL)
      } else {

      barplot(cancer_data()$new_cases_number[
        cancer_data()$cancer_type ==  input$bar_0_in] ~ input$bar_0_in,
          main = "Cases per Cancer Type",
          xlab = "", ylab = "", axes = FALSE,
          las = 2, col = colours,
          cex.names = 0.6,
          mar = c(10, 7, 3, 1)
          )

      axis(side = 2, at = seq(from = 0,
                              to = max(cancer_data()$new_cases_number[
                      cancer_data()$cancer_type ==  input$bar_0_in]),
                              by = max(cancer_data()$new_cases_number[
                      cancer_data()$cancer_type ==  input$bar_0_in]) %/% 5))

      title(ylab = "Number of Cases", line = 5, cex.lab = 1.2, font.lab = 2)
      title(xlab = "Cancer Type", line = 8, cex.lab = 1.2, font.lab = 2)
    }
   })

    # This is entirely for debugging purposes.
    observeEvent(input$bar_0_in, {
      print(paste("List length: ", length(input$bar_0_in),
                  "- Condition length:", length(cancer_data()$new_cases_number[
                      cancer_data()$cancer_type ==  input$bar_0_in])))
      print(paste("List:", input$bar_0_in,
                  "- Conditional: ", cancer_data()$cancer_type[
                              cancer_data()$cancer_type == input$bar_0_in
                  ]))
    })
  }

  shinyApp(ui = ui, server = server)

}


问:
how to upload the images with the imgur api to my account with python
I am programming a bot for discord and I have a problem and I don't know how to upload an image to my imgur account from python, the way I do it is uploaded anonymously and this way it doesn't work for me, I would like it to be stored within my imgur account

I have read the documentation but I don't understand much, I just started programming

This is the code I'm currently using:

```<code>@bot.command()
async def imgur(ctx):
    headers = {'Authorization': 'Client-ID xxx',}
    params = {'image': base64.b64encode(open('cosmetico.png', 'rb').read())}
    r = requests.post(f'https://api.imgur.com/3/image', headers=headers, data=params)

    data = r.json()["data"]["link"]

    await ctx.send(f"{data}")
</code>```

Could someone help me, thank you very much!

Body:
I am programming a bot for discord and I have a problem and I don't know how to upload an image to my imgur account from python, the way I do it is uploaded anonymously and this way it doesn't work for me, I would like it to be stored within my imgur account

I have read the documentation but I don't understand much, I just started programming

This is the code I'm currently using:

@bot.command()
async def imgur(ctx):
    headers = {'Authorization': 'Client-ID xxx',}
    params = {'image': base64.b64encode(open('cosmetico.png', 'rb').read())}
    r = requests.post(f'https://api.imgur.com/3/image', headers=headers, data=params)

    data = r.json()["data"]["link"]

    await ctx.send(f"{data}")

Could someone help me, thank you very much!


问:
CSS column-count bug break Chrome
I assigned a column-count:2 to a div, but when I test the responsive to the browser (Google Chrome version 108.0.5359.99), it breaks and I need to use the tasks manager to close the window.

Is the column-count because when I comment that style line the browser works fine, and in Firefox column-count works.

Any idea or alternative to column count?

Title: CSS column-count bug break Chrome


问:
Hyperion-rt Python Package OSError
I need to use the hyperion package for python (http://docs.hyperion-rt.org/en/stable/index.html, the three-dimensional dust continuum Monte-Carlo radiative transfer code, not the hyperion by Oracle!).
I installed it and already solved the known error of the wrong import in some of the files (the import six line).
I also created the dust file and have a script for the model.

So now it should be running successfully. Unfortunately, it does not run and gives me the following error:

```<code>
/home/astro/anaconda3/bin/python3 /home/astro/
/yso_code_alpha.py
WARNING: Spectrum is being re-sorted in order of increasing frequency [hyperion.sources.source]
/home/astro/anaconda3/lib/python3.9/site-packages/hyperion/densities/ulrich_envelope.py:435: RuntimeWarning: invalid value encountered in log
  * (np.log((np.sqrt(gamma_1) + 1) / (1. - np.sqrt(gamma_1)))
WARNING: Spacing of inner radial cells is too small, resetting to 1e-08 [hyperion.model.analytical_yso_model]
Traceback (most recent call last):
  File "/home/astro/yso_code_alpha.py", line 95, in <module>
    m.write('alpha_9.rtin') #mass star 8
  File "/home/astro/anaconda3/lib/python3.9/site-packages/hyperion/model/analytical_yso_model.py", line 862, in write
    m = self.to_model(merge_if_possible=merge_if_possible)
  File "/home/astro/anaconda3/lib/python3.9/site-packages/hyperion/model/analytical_yso_model.py", line 729, in to_model
    g = virtual_file()
  File "/home/astro/anaconda3/lib/python3.9/site-packages/hyperion/util/functions.py", line 24, in virtual_file
    return h5py.File(random_id(), driver='core', backing_store=False)
  File "/home/astro/anaconda3/lib/python3.9/site-packages/h5py/_hl/files.py", line 444, in __init__
    fid = make_fid(name, mode, userblock_size,
  File "/home/astro/anaconda3/lib/python3.9/site-packages/h5py/_hl/files.py", line 199, in make_fid
    fid = h5f.open(name, flags, fapl=fapl)
  File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "h5py/h5f.pyx", line 100, in h5py.h5f.open
OSError: Unable to open file (unable to open file)

Process finished with exit code 1

</code>```

I tried to search for solutions online and asked some coworkers, but unfortunately can not find any solution. I also can not even find the path in the last mentioned part (the .../_hl/... path) in my computer.

If that is important: I use Ubuntu.

Anyone any idea or hint on how I could solve it?

Thank you in advance!

Title: Hyperion-rt Python Package OSError

Body:
I need to use the hyperion package for python (http://docs.hyperion-rt.org/en/stable/index.html, the three-dimensional dust continuum Monte-Carlo radiative transfer code, not the hyperion by Oracle!).
I installed it and already solved the known error of the wrong import in some of the files (the import six line).
I also created the dust file and have a script for the model.

So now it should be running successfully. Unfortunately, it does not run and gives me the following error:

/home/astro/anaconda3/bin/python3 /home/astro/
/yso_code_alpha.py
WARNING: Spectrum is being re-sorted in order of increasing frequency [hyperion.sources.source]
/home/astro/anaconda3/lib/python3.9/site-packages/hyperion/densities/ulrich_envelope.py:435: RuntimeWarning: invalid value encountered in log
  * (np.log((np.sqrt(gamma_1) + 1) / (1. - np.sqrt(gamma_1)))
WARNING: Spacing of inner radial cells is too small, resetting to 1e-08 [hyperion.model.analytical_yso_model]
Traceback (most recent call last):
  File "/home/astro/yso_code_alpha.py", line 95, in <module>
    m.write('alpha_9.rtin') #mass star 8
  File "/home/astro/anaconda3/lib/python3.9/site-packages/hyperion/model/analytical_yso_model.py", line 862, in write
    m = self.to_model(merge_if_possible=merge_if_possible)
  File "/home/astro/anaconda3/lib/python3.9/site-packages/hyperion/model/analytical_yso_model.py", line 729, in to_model
    g = virtual_file()
  File "/home/astro/anaconda3/lib/python3.9/site-packages/hyperion/util/functions.py", line 24, in virtual_file
    return h5py.File(random_id(), driver='core', backing_store=False)
  File "/home/astro/anaconda3/lib/python3.9/site-packages/h5py/_hl/files.py", line 444, in __init__
    fid = make_fid(name, mode, userblock_size,
  File "/home/astro/anaconda3/lib/python3.9/site-packages/h5py/_hl/files.py", line 199, in make_fid
    fid = h5f.open(name, flags, fapl=fapl)
  File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "h5py/h5f.pyx", line 100, in h5py.h5f.open
OSError: Unable to open file (unable to open file)

Process finished with exit code 1

I tried to search for solutions online and asked some coworkers, but unfortunately can not find any solution. I also can not even find the path in the last mentioned part (the .../_hl/... path) in my computer.

If that is important: I use Ubuntu.

Anyone any idea or hint on how I could solve it?

Thank you in advance!


问:
Add field to bulk action Product Woocommerce
I want to add a custom date field before the Promotion Price.
enter image description here

I found hook add_action('woocommerce_product_bulk_edit_start', 'custom_date_promo'); but I can't declare the position of the field.


问:
Google Visualization Charts doesn't rendner on iPhone 5s
Does Google Visualization Charts not work on iPhone 5s ?

```<code><script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    function drawVisualization() {

      var data_monthly = google.visualization.arrayToDataTable([
        ['', 'interest', 'principal'],
        [1, 197.26, 166.8],
        ...
        [35, 20.57, 343.49],
        [36, 10.81, 353.25]
      ]);
      var data = data_monthly;
      periods = data['Wf'][data['Wf'].length -  1]['c'][0]['v'];

      let ticks = [0], start = 6; interval = 6;
      if (periods < 20) { start = 1; interval = 1; }
      for (let i = start; i <= periods; i += interval)
      {
        ticks.push(i);
      }
      ticks.push(periods);

      new google.visualization.ColumnChart(document.getElementById('chart')).
          draw(data,
               {
                 title:"",
                  legend: {position: 'top'},
                  vAxis: {title: "Y-Axis Label", viewWindowMode: 'maximized', textPosition: 'none', titleTextStyle: {italic: false}},
                  isStacked: true,
                  hAxis: {title: "X-AXis Label", titleTextStyle: {italic: false}, ticks: ticks},
                  series: {
                    0: {'color': '#87a1cc'},
                    1: {'color': '#d5dce6'}
                  }
               }
           );
    }
    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(drawVisualization);
</script>
</code>```

loader.js itself is 67Kb but I don't think that's the issue - any chance Google Charts doesn't support smaller screen resolutions ?

This is the result on iPhone 5s on browserstack :

Body:
Does Google Visualization Charts not work on iPhone 5s ?

loader.js itself is 67Kb but I don't think that's the issue - any chance Google Charts doesn't support smaller screen resolutions ?

This is the result on iPhone 5s on browserstack :


问:
Quarto toc doesn't recognise ordinary headers
I can't make the table of contents work on my quarto blog. I tried many many times with different possible solutions, but none worked. Below I provide some examples.

Applied toc: true to an individual blog post (i also tried by adding standalone: true after toc: true, since quarto documentation says the table of content doesn't work with standalone: false)

```<code>title: "Dependency management with renv R package"
date: "2022-10-29"
categories: [R, Dependency management]
image: renv_thumbnail.png
format:
  html:
    toc: true
    # standalone: true
    fontsize: 0.9em
    code-tools: true
comments:
    utterances:
      repo:  my_repo
      theme: photon-dark
title-block-banner: false
editor: visual
</code>```

And this is what my post looks like after applying the toc.

I don't know if you can see it, but you might notice the text of my post gets slightly shifted to the left, to make some space for the toc, but no toc actually shows up.

Applied toc: true globally in my main _quarto.yml file (again, I also tried with standalone: true). The result is the same as in step 1, but global.

Repeated step 1 and 2, but I placed toc: true in the first level of my yaml headers/_quarto.yml file. For example.

```<code>title: "Dependency management with renv R package"
date: "2022-10-29"
categories: [R, Dependency management]
image: renv_thumbnail.png
toc: true
# standalone: true
format:
  html:
    fontsize: 0.9em
    code-tools: true
comments:
    utterances:
      repo:  my_repo
      theme: photon-dark
title-block-banner: false
editor: visual
</code>```

Again, I get the same result as in step 1.

What am I doing wrong? Is this a bug? Should I delete my .quarto, _freeze and docs (where I output my rendered pages) folders and re-build my site from scratch, maybe? I'd like to avoid this last solution if possible, since some posts take much time to render.

Body:
I can't make the table of contents work on my quarto blog. I tried many many times with different possible solutions, but none worked. Below I provide some examples.

Applied toc: true to an individual blog post (i also tried by adding standalone: true after toc: true, since quarto documentation says the table of content doesn't work with standalone: false)

title: "Dependency management with renv R package"
date: "2022-10-29"
categories: [R, Dependency management]
image: renv_thumbnail.png
format:
  html:
    toc: true
    # standalone: true
    fontsize: 0.9em
    code-tools: true
comments:
    utterances:
      repo:  my_repo
      theme: photon-dark
title-block-banner: false
editor: visual

And this is what my post looks like after applying the toc.

I don't know if you can see it, but you might notice the text of my post gets slightly shifted to the left, to make some space for the toc, but no toc actually shows up.

Applied toc: true globally in my main _quarto.yml file (again, I also tried with standalone: true). The result is the same as in step 1, but global.

Repeated step 1 and 2, but I placed toc: true in the first level of my yaml headers/_quarto.yml file. For example.

title: "Dependency management with renv R package"
date: "2022-10-29"
categories: [R, Dependency management]
image: renv_thumbnail.png
toc: true
# standalone: true
format:
  html:
    fontsize: 0.9em
    code-tools: true
comments:
    utterances:
      repo:  my_repo
      theme: photon-dark
title-block-banner: false
editor: visual

Again, I get the same result as in step 1.

What am I doing wrong? Is this a bug? Should I delete my .quarto, _freeze and docs (where I output my rendered pages) folders and re-build my site from scratch, maybe? I'd like to avoid this last solution if possible, since some posts take much time to render.


问:
Ads data hub API analysis query
How we can execute all the analysis queries for Ads data hub using API in python as I am able to run single query but data is not saving in Daaset

Added a service account created for this run into Ads data hub Interface user as Super User

I am trying to run all the queries for a customer using API

I tried running a single query using below method

queries=service.customers().analysisQueries().start(

```<code>        name='customer_name',
        body={
            'spec': {
                'adsDataCustomerId': '',
                'timeZone': 'UTC',
                'startDate': {'year': 2022, 'month': 12, 'day': 1},
                'endDate': {'year': 2022, 'month': 12, 'day': 12},
            },
            'destTable' : 'projectName.datasetName.Table'
        }
    ).execute()
</code>```
```<code>After running these queries I am getting response as querymetadata as below

{"name": "": {"@type": "type.googleapis.com/google.ads.adsdatahub.v1.QueryMetadata", "queryResourceName": "", "queryTitle": "title of the query", "customerId": "customerId", "adsDataCustomerId": "adsdatacustomerId", "matchDataCustomerId": "", "parameterValues": {"start_date": {"value": ""}, "end_date": {"value": ""}, "time_zone": {"value": "UTC"}}, "startTime": "", "endTime": "", "destTable": ""}}

But data is not saving in Big query data set
</code>```

Title: Ads data hub API analysis query

Body:
How we can execute all the analysis queries for Ads data hub using API in python as I am able to run single query but data is not saving in Daaset

Added a service account created for this run into Ads data hub Interface user as Super User

I am trying to run all the queries for a customer using API

I tried running a single query using below method

queries=service.customers().analysisQueries().start(

        name='customer_name',
        body={
            'spec': {
                'adsDataCustomerId': '',
                'timeZone': 'UTC',
                'startDate': {'year': 2022, 'month': 12, 'day': 1},
                'endDate': {'year': 2022, 'month': 12, 'day': 12},
            },
            'destTable' : 'projectName.datasetName.Table'
        }
    ).execute()

After running these queries I am getting response as querymetadata as below

{"name": "": {"@type": "type.googleapis.com/google.ads.adsdatahub.v1.QueryMetadata", "queryResourceName": "", "queryTitle": "title of the query", "customerId": "customerId", "adsDataCustomerId": "adsdatacustomerId", "matchDataCustomerId": "", "parameterValues": {"start_date": {"value": ""}, "end_date": {"value": ""}, "time_zone": {"value": "UTC"}}, "startTime": "", "endTime": "", "destTable": ""}}

But data is not saving in Big query data set


问:
JQuery - How to update variable after call function?
I have a timer function, I want to change the value of my variable after the timer reaches 0?

```<code>function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
    var counter = document.getElementById("timer");
    current_minutes = mins - 1
    seconds--;
    counter.innerHTML =
        current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
    if (parseInt(current_minutes) === 0 && parseInt(seconds) === 00) {
        sendAgain.show();
        finalMin = parseInt(current_minutes);
        finalSec = parseInt(seconds);
    }

    if (seconds > 0) {
        timeoutHandle = setTimeout(tick, 1000);
    } else {

        if (mins > 1) {
            // countdown(mins-1);   never reach “00″ issue solved:Contributed by Victor Streithorst
            setTimeout(function () { countdown(mins - 1); }, 1000);

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

}

variables :

```<code>let finalMin = null;
var finalSec = null;
</code>```

I want the variables to be set after the following code is executed?

```<code> if (parseInt(current_minutes) === 0 && parseInt(seconds) === 00) {
        sendAgain.show();
        finalMin = parseInt(current_minutes);
        finalSec = parseInt(seconds);
    }

 countdown(2);
console.log(finalMin); ===== show "0"
</code>```

Body:
I have a timer function, I want to change the value of my variable after the timer reaches 0?

function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
    var counter = document.getElementById("timer");
    current_minutes = mins - 1
    seconds--;
    counter.innerHTML =
        current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
    if (parseInt(current_minutes) === 0 && parseInt(seconds) === 00) {
        sendAgain.show();
        finalMin = parseInt(current_minutes);
        finalSec = parseInt(seconds);
    }

    if (seconds > 0) {
        timeoutHandle = setTimeout(tick, 1000);
    } else {

        if (mins > 1) {
            // countdown(mins-1);   never reach “00″ issue solved:Contributed by Victor Streithorst
            setTimeout(function () { countdown(mins - 1); }, 1000);

        }
    }
}
tick();

}

variables :

let finalMin = null;
var finalSec = null;

I want the variables to be set after the following code is executed?

 if (parseInt(current_minutes) === 0 && parseInt(seconds) === 00) {
        sendAgain.show();
        finalMin = parseInt(current_minutes);
        finalSec = parseInt(seconds);
    }

 countdown(2);
console.log(finalMin); ===== show "0"


问:
Remove empty space from block when width reduced
How to remove this empty space when block reducing width?
It can be flex, doesn't matter.

Here is CodePan

Initial block

When block became smaller

```<code><div class="container">
  <div class="someStuff">someStuff</div>
  <div class="inputs">
    <div class="block">
      <span>Задать шаг: </span>
      <div class="select-container">
        <select>
          <option value="50">50</option>
        </select>
      </div>
    </div>
    <div class="block">
      <span>Цветовая схема: </span>
      <div class="select-container">
        <select>
          <option value="YlOrRd">YlOrRd</option>
        </select>
      </div>
    </div>
  </div>
</div>
</code>```

Body:
How to remove this empty space when block reducing width?
It can be flex, doesn't matter.

Here is CodePan

Initial block

When block became smaller

someStuff

      Задать шаг:

        <select>
          <option value="50">50</option>
        </select>

      Цветовая схема:

        <select>
          <option value="YlOrRd">YlOrRd</option>
        </select>


问:
How to handle SQL parameters with Apache Calcite Planner (Facade Interface)？
I need some help with processing queries using Apache Calcite, I am currently using Planner to process my queries.

My code looks like this:

```<code>// custom config
FrameworkConfig frameworkConfig = Frameworks.newConfigBuilder()
        .parserConfig(parserConfig)
        .defaultSchema(rootSchema)
        .sqlToRelConverterConfig(convertConfig)
        .operatorTable(operatorTable)
        .build();

Planner planner = Frameworks.getPlanner(frameworkConfig);

String sql = "Select id, name from t where id in (?, ?)";
SqlNode parsedSqlNode = planner.parse(sql);
SqlNode validatedSqlNode = planner.validate(parsedSqlNode);
RelRoot relRoot = planner.rel(validatedSqlNode);
PreparedStatement preparedStatement = RelRunners.run(relRoot.rel);
preparedStatement.setLong(1, 11111);
preparedStatement.setLong(2, 22222);

ResultSet resultSet = preparedStatement.executeQuery();
// ....
</code>```

It works fine without SQL parameters, but there are some queries with SQL parameters.

While using SQL parameter and setting the parameter(preparedStatement.setLong), I got the following error message:

```<code>Caused by: java.sql.SQLException: parameter ordinal 1 out of range
    at org.apache.calcite.avatica.Helper.createException(Helper.java:60)
    at org.apache.calcite.avatica.AvaticaPreparedStatement.getParameter(AvaticaPreparedStatement.java:427)
    at org.apache.calcite.avatica.AvaticaPreparedStatement.getSite(AvaticaPreparedStatement.java:434)
    at org.apache.calcite.avatica.AvaticaPreparedStatement.setLong(AvaticaPreparedStatement.java:178)
</code>```

SQL parameters are obviously not being handled correctly. What is the proper way to define and set SQL parameters when using Planner in a case like this?

Body:
I need some help with processing queries using Apache Calcite, I am currently using Planner to process my queries.

My code looks like this:

// custom config
FrameworkConfig frameworkConfig = Frameworks.newConfigBuilder()
        .parserConfig(parserConfig)
        .defaultSchema(rootSchema)
        .sqlToRelConverterConfig(convertConfig)
        .operatorTable(operatorTable)
        .build();

Planner planner = Frameworks.getPlanner(frameworkConfig);

String sql = "Select id, name from t where id in (?, ?)";
SqlNode parsedSqlNode = planner.parse(sql);
SqlNode validatedSqlNode = planner.validate(parsedSqlNode);
RelRoot relRoot = planner.rel(validatedSqlNode);
PreparedStatement preparedStatement = RelRunners.run(relRoot.rel);
preparedStatement.setLong(1, 11111);
preparedStatement.setLong(2, 22222);

ResultSet resultSet = preparedStatement.executeQuery();
// ....

It works fine without SQL parameters, but there are some queries with SQL parameters.

While using SQL parameter and setting the parameter(preparedStatement.setLong), I got the following error message:

Caused by: java.sql.SQLException: parameter ordinal 1 out of range
    at org.apache.calcite.avatica.Helper.createException(Helper.java:60)
    at org.apache.calcite.avatica.AvaticaPreparedStatement.getParameter(AvaticaPreparedStatement.java:427)
    at org.apache.calcite.avatica.AvaticaPreparedStatement.getSite(AvaticaPreparedStatement.java:434)
    at org.apache.calcite.avatica.AvaticaPreparedStatement.setLong(AvaticaPreparedStatement.java:178)

SQL parameters are obviously not being handled correctly. What is the proper way to define and set SQL parameters when using Planner in a case like this?


问:
How to create a validation when importing CSV in Laravel using Maatwebsite?
How to create a validation when importing CSV. I'm using the "maatwebsite/excel": "^3.1" if the imported csv column header name is not exact with the database column it should display some validation. This is my reference LaravelDaily
/
Laravel-8-Import-CSV

Importing CSV

```<code>public function parseImport(CsvImportRequest $request)
{
    if ($request->has('header')) {
        $headings = (new HeadingRowImport)->toArray($request->file('csv_file'));
        $data = Excel::toArray(new AwardeesImport, $request->file('csv_file'))[0];
    } else {
        $data = array_map('str_getcsv', file($request->file('csv_file')->getRealPath()));
    }

    if (count($data) > 0) {
        $csv_data = array_slice($data, 0, 6);

        $csv_data_file = CsvData::create([
            'csv_filename' => $request->file('csv_file')->getClientOriginalName(),
            'csv_header' => $request->has('header'),
            'csv_data' => json_encode($data)
        ]);
    } else {
        return redirect()->back();
    }

    return view('admin.import-csv.import-fields', [
        'headings' => $headings ?? null,
        'csv_data' => $csv_data,
        'csv_data_file' => $csv_data_file
    ])->with('success', 'The CSV file imported successfully');;
}
</code>```

When parsing CSV

```<code>public function processImport(Request $request)
{
    $data = CsvData::find($request->csv_data_file_id);
    $csv_data = json_decode($data->csv_data, true);
    foreach ($csv_data as $row) {
        $awardees = new SIS();
        foreach (config('app.db_fields') as $index => $field) {
            if ($data->csv_header) {
                $awardees->$field = $row[$request->fields[$field]];
            } else {
                $awardees->$field = $row[$request->fields[$index]];
            }
        }
        $awardees->save();
    }
    return redirect()->action([ImportController::class, 'index'])->with('success', 'Import finished.');
}
</code>```

CsvImportRequest

```<code>public function rules()
{
    return [
        'csv_file' => 'required|mimes:csv,txt'
    ];
}
</code>```

config/app.php

```<code>'db_fields' => [
    'email_address',
    'surname',
    'first_name',
    'middle_name',
    'course',
    'year_level',
    'contact_number',
    'gwa_1st',
    'gwa_2nd',
    'applying_for',
    'remarks',
    'comments'
]
</code>```

if one of those field is missing it should show the validation error

Body:
How to create a validation when importing CSV. I'm using the "maatwebsite/excel": "^3.1" if the imported csv column header name is not exact with the database column it should display some validation. This is my reference LaravelDaily
/
Laravel-8-Import-CSV

Importing CSV

public function parseImport(CsvImportRequest $request)
{
    if ($request->has('header')) {
        $headings = (new HeadingRowImport)->toArray($request->file('csv_file'));
        $data = Excel::toArray(new AwardeesImport, $request->file('csv_file'))[0];
    } else {
        $data = array_map('str_getcsv', file($request->file('csv_file')->getRealPath()));
    }

    if (count($data) > 0) {
        $csv_data = array_slice($data, 0, 6);

        $csv_data_file = CsvData::create([
            'csv_filename' => $request->file('csv_file')->getClientOriginalName(),
            'csv_header' => $request->has('header'),
            'csv_data' => json_encode($data)
        ]);
    } else {
        return redirect()->back();
    }

    return view('admin.import-csv.import-fields', [
        'headings' => $headings ?? null,
        'csv_data' => $csv_data,
        'csv_data_file' => $csv_data_file
    ])->with('success', 'The CSV file imported successfully');;
}

When parsing CSV

public function processImport(Request $request)
{
    $data = CsvData::find($request->csv_data_file_id);
    $csv_data = json_decode($data->csv_data, true);
    foreach ($csv_data as $row) {
        $awardees = new SIS();
        foreach (config('app.db_fields') as $index => $field) {
            if ($data->csv_header) {
                $awardees->$field = $row[$request->fields[$field]];
            } else {
                $awardees->$field = $row[$request->fields[$index]];
            }
        }
        $awardees->save();
    }
    return redirect()->action([ImportController::class, 'index'])->with('success', 'Import finished.');
}

CsvImportRequest

public function rules()
{
    return [
        'csv_file' => 'required|mimes:csv,txt'
    ];
}

config/app.php

'db_fields' => [
    'email_address',
    'surname',
    'first_name',
    'middle_name',
    'course',
    'year_level',
    'contact_number',
    'gwa_1st',
    'gwa_2nd',
    'applying_for',
    'remarks',
    'comments'
]

if one of those field is missing it should show the validation error


问:
I have created a sorting visualizer but it's not showing the animation it's sorting the array but no animation
```<code>const n = 10;
const array = [];

init();

function init() {
  for (let i = 0; i < n; i++) {
    // array[i] = Math.floor(Math.random()*10+1);
    array[i] = Math.random();
  }
  showBars();
}

function play() {
  const copy = [...array];
  const swaps= selectionSort(array);
  showBars();
  animate(swaps);

}

function animate(swaps){
  if(swaps.length == 0){
    return;
    showBars(i,j);
  }
  const [i,j] = swaps.shift();
  [array[i],array[j]]= [array[j],array[i]];
  showBars(i,j);
  setTimeout(function(){
     animate(swaps);
   },50);
 }

function change(i,j) {
  var temp = array[j];
  array[j] = array[i];
  array[i] = temp;
  return array[i];
}

function selectionSort(array) {
  const swaps = [];
  do {
    var swapped = false;
    for (let i = 0; i < array.length; i++) {
      var min = i;
      for (let j = i+1; j < array.length; j++) {
        if (array[j] < array[i]) {
          min = j;
          swaps.push([i,j]);
          //
          swapped = true;
          change(i,j);

          //array[i-1],array[i]=array[i],array[i-1];
        }
      }
    }
  } while (swapped);
  return change;
return swaps;
}

function showBars() {
  container.innerHTML = "";
  for (let i = 0; i < array.length; i++) {
    const bar = document.createElement("div");
    bar.style.height = array[i] * 100 + "%";
    bar.classList.add("bar");
    container.appendChild(bar);
  }
}

</code>```

I was expecting an animation of elements getting sorted but didn't get to see.

Body:
const n = 10;
const array = [];

init();

function init() {
  for (let i = 0; i < n; i++) {
    // array[i] = Math.floor(Math.random()*10+1);
    array[i] = Math.random();
  }
  showBars();
}

function play() {
  const copy = [...array];
  const swaps= selectionSort(array);
  showBars();
  animate(swaps);

}

function animate(swaps){
  if(swaps.length == 0){
    return;
    showBars(i,j);
  }
  const [i,j] = swaps.shift();
  [array[i],array[j]]= [array[j],array[i]];
  showBars(i,j);
  setTimeout(function(){
     animate(swaps);
   },50);
 }

function change(i,j) {
  var temp = array[j];
  array[j] = array[i];
  array[i] = temp;
  return array[i];
}

function selectionSort(array) {
  const swaps = [];
  do {
    var swapped = false;
    for (let i = 0; i < array.length; i++) {
      var min = i;
      for (let j = i+1; j < array.length; j++) {
        if (array[j] < array[i]) {
          min = j;
          swaps.push([i,j]);
          //
          swapped = true;
          change(i,j);

          //array[i-1],array[i]=array[i],array[i-1];
        }
      }
    }
  } while (swapped);
  return change;
return swaps;
}

function showBars() {
  container.innerHTML = "";
  for (let i = 0; i < array.length; i++) {
    const bar = document.createElement("div");
    bar.style.height = array[i] * 100 + "%";
    bar.classList.add("bar");
    container.appendChild(bar);
  }
}

I was expecting an animation of elements getting sorted but didn't get to see.


问:
VBA Filter Error If criteria is not available
Im using filter in vba with specific criteria, however im encountering error when the criteria is not available.

If criteria "First" is not available in the summary report, I want the vba to go to the next criteria, "Second". Copy the data and paste in "Second" Tab. So the "First" Tab is blank since criteria is not available in the summary report.

Below is my code...

Range("C1").AutoFilter Field:=3, Criteria1:="First"

```<code>Range("Table6").Select

Selection.SpecialCells(xlCellTypeVisible).Select
Application.CutCopyMode = False
Selection.Copy
Worksheets("First").Select
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, _
    Operation:= xlNone, SkipBlanks:=False, Transpose:=False
Worksheets("ReportTemp").Select
</code>```

Range("C1").AutoFilter Field:=3, Criteria1:= "Second"

```<code>Range("Table6").Select

Selection.SpecialCells(xlCellTypeVisible).Select
Application.CutCopyMode = False
Selection.Copy
Worksheets("Second").Select
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, _
    Operation:= xlNone, SkipBlanks:=False,Transpose:=False`
</code>```

Body:
Im using filter in vba with specific criteria, however im encountering error when the criteria is not available.

If criteria "First" is not available in the summary report, I want the vba to go to the next criteria, "Second". Copy the data and paste in "Second" Tab. So the "First" Tab is blank since criteria is not available in the summary report.

Below is my code...

Range("C1").AutoFilter Field:=3, Criteria1:="First"

Range("Table6").Select

Selection.SpecialCells(xlCellTypeVisible).Select
Application.CutCopyMode = False
Selection.Copy
Worksheets("First").Select
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, _
    Operation:= xlNone, SkipBlanks:=False, Transpose:=False
Worksheets("ReportTemp").Select

Range("C1").AutoFilter Field:=3, Criteria1:= "Second"

Range("Table6").Select

Selection.SpecialCells(xlCellTypeVisible).Select
Application.CutCopyMode = False
Selection.Copy
Worksheets("Second").Select
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, _
    Operation:= xlNone, SkipBlanks:=False,Transpose:=False`


问:
TypeError: unhashable type: 'PngImageFile' - How do you fix this error in Pygame Zero?
I am making a game using pygame zero. I am using replit and getting the following error:

```<code>
</code>```

Traceback (most recent call last):
File "main.py", line 97, in
cell = Actor(cell)
File "/home/runner/Dungeon-Battles-1/venv/lib/python3.8/site-packages/pgzero/actor.py", line 88, in init
self.image = image
File "/home/runner/Dungeon-Battles-1/venv/lib/python3.8/site-packages/pgzero/actor.py", line 103, in setattr
return object.setattr(self, attr, value)
File "/home/runner/Dungeon-Battles-1/venv/lib/python3.8/site-packages/pgzero/actor.py", line 218, in image
self._orig_surf = self._surf = loaders.images.load(image)
File "/home/runner/Dungeon-Battles-1/venv/lib/python3.8/site-packages/pgzero/loaders.py", line 116, in load
if key in self.cache:
TypeError: unhashable type: 'PngImageFile'

```<code>
</code>```

Below are the imports of my code and the part causing the error.

```<code>import random
from pgzero.builtins import Actor, animate, keyboard
import os
os.environ["SDL_VIDEODRIVER"] = "dummy"
import pgzrun
import pgzero
from pgzero import actor
from PIL import Image
</code>```
```<code>
cell = Image.open('border.png') ###Image opening with pillow
</code>```
```<code>cell = Actor(cell) #The error is on this line(line 97)
</code>```

Body:
I am making a game using pygame zero. I am using replit and getting the following error:

Traceback (most recent call last):
File "main.py", line 97, in
cell = Actor(cell)
File "/home/runner/Dungeon-Battles-1/venv/lib/python3.8/site-packages/pgzero/actor.py", line 88, in init
self.image = image
File "/home/runner/Dungeon-Battles-1/venv/lib/python3.8/site-packages/pgzero/actor.py", line 103, in setattr
return object.setattr(self, attr, value)
File "/home/runner/Dungeon-Battles-1/venv/lib/python3.8/site-packages/pgzero/actor.py", line 218, in image
self._orig_surf = self._surf = loaders.images.load(image)
File "/home/runner/Dungeon-Battles-1/venv/lib/python3.8/site-packages/pgzero/loaders.py", line 116, in load
if key in self.cache:
TypeError: unhashable type: 'PngImageFile'

Below are the imports of my code and the part causing the error.

import random
from pgzero.builtins import Actor, animate, keyboard
import os
os.environ["SDL_VIDEODRIVER"] = "dummy"
import pgzrun
import pgzero
from pgzero import actor
from PIL import Image

cell = Image.open('border.png') ###Image opening with pillow

cell = Actor(cell) #The error is on this line(line 97)


问:
duckdb: get some records example from very large parquet file
I'm using duckdb to query parquet files stored on amazon s3. It works fine and I find the tool amazing. However I'm wondering if it exists a quick way to get some random records from a parquet file stored on s3 to have a feel on how the data looked like.

I tried this:

```<code>SELECT * FROM 's3://my-bucket/my_folder.parquet/part.*.parquet' LIMIT 5;
</code>```

And this:

```<code>SELECT * FROM 's3://my-bucket/my_folder.parquet/part.*.parquet' USING SAMPLE 5;
</code>```

But both of them are quite slow. Is there something we can do ? For instance using boto3 directly on s3 file, I can get some example records pretty fast so I'm wondering if there is a way to do so using duck db.

Thank you very much for your help

Body:
I'm using duckdb to query parquet files stored on amazon s3. It works fine and I find the tool amazing. However I'm wondering if it exists a quick way to get some random records from a parquet file stored on s3 to have a feel on how the data looked like.

I tried this:

SELECT * FROM 's3://my-bucket/my_folder.parquet/part.*.parquet' LIMIT 5;

And this:

SELECT * FROM 's3://my-bucket/my_folder.parquet/part.*.parquet' USING SAMPLE 5;

But both of them are quite slow. Is there something we can do ? For instance using boto3 directly on s3 file, I can get some example records pretty fast so I'm wondering if there is a way to do so using duck db.

Thank you very much for your help


问:
What is generation rate in NetSim? How can I calculate it?
Generation rate is a rate of traffic which is generated at the source.

In general its number of packets/sec generated.

Unit is Mbps.

For different type of application there are different formula to calculate Generation rate.

GitLink

Here is a calculator for CBR, Custom, Sensor applications


问:
Separete the graphs to show the ylabel and x label using matplotlib
I have a graph but it is terrible. I want to separete the graphs in parts here is how it is:

The code:

```<code>  def plot_picture(self, tab):
    try:
        self.df = pd.read_csv(self.file)
    except Exception as e:
        messagebox.showerror("Error", "File not found")
    try:
        dyaw=self.df['Flow'].tolist()
        dsurge=self.df['CH4'].tolist()
        dsway=self.df['CO2'].tolist()
        dheave=self.df['O2'].tolist()
        droll=self.df['H2S'].tolist()
        dpitch=self.df['Ap'].tolist()
        dtime=self.df['Time'].tolist()
        fig2, axs2 = plt.subplots(6, sharex=True, sharey=False, gridspec_kw={'hspace': 0})
        fig2.suptitle('RTVGM Data Time History')
        axs2[0].plot(dtime, dsurge)
        axs2[1].plot(dtime, dsway)
        axs2[2].plot(dtime, dheave)
        axs2[3].plot(dtime, droll)
        axs2[4].plot(dtime, dpitch)
        axs2[5].plot(dtime, dyaw)
        axs2[0].set_ylabel('CH4 (%)',fontsize=6)
        axs2[1].set_ylabel('CO2 (%)',fontsize=6)
        axs2[2].set_ylabel('O2 (%)',fontsize=6)
        axs2[3].set_ylabel('H2S (%)',fontsize=6)
        axs2[4].set_ylabel('Ap (mbar)',fontsize=6)
        axs2[5].set_ylabel('Flow (l/pm)',fontsize=6)
        axs2[5].set_xlabel('Time(# of record)',fontsize=6)
        axs2[0].set_ylim(-1,70)
        axs2[1].set_ylim(-1,40)
        axs2[2].set_ylim(-1,25)
        axs2[3].set_ylim(-10,300)
        axs2[4].set_ylim(1000,1020)
        axs2[5].set_ylim(0,0.5)
        self.frame = ttk.Frame(tab, height=500, width=700)
        self.frame.grid(row=0, column=0, sticky='nsew')
        canvas2=FigureCanvasTkAgg(fig2,master=self.frame)
        canvas2.get_tk_widget().place(x=0,y=0,width=600,height=400)
        canvas2.draw()
    except Exception as e:
        print(str(e))
        messagebox.showerror("Error", "Not correct file")
</code>```

I want each graph be separete and have limit in y and x. Can you could help me achive it? Maybe using one axes for each, but i don´t know how do it.

Body:
I have a graph but it is terrible. I want to separete the graphs in parts here is how it is:

The code:

  def plot_picture(self, tab):
    try:
        self.df = pd.read_csv(self.file)
    except Exception as e:
        messagebox.showerror("Error", "File not found")
    try:
        dyaw=self.df['Flow'].tolist()
        dsurge=self.df['CH4'].tolist()
        dsway=self.df['CO2'].tolist()
        dheave=self.df['O2'].tolist()
        droll=self.df['H2S'].tolist()
        dpitch=self.df['Ap'].tolist()
        dtime=self.df['Time'].tolist()
        fig2, axs2 = plt.subplots(6, sharex=True, sharey=False, gridspec_kw={'hspace': 0})
        fig2.suptitle('RTVGM Data Time History')
        axs2[0].plot(dtime, dsurge)
        axs2[1].plot(dtime, dsway)
        axs2[2].plot(dtime, dheave)
        axs2[3].plot(dtime, droll)
        axs2[4].plot(dtime, dpitch)
        axs2[5].plot(dtime, dyaw)
        axs2[0].set_ylabel('CH4 (%)',fontsize=6)
        axs2[1].set_ylabel('CO2 (%)',fontsize=6)
        axs2[2].set_ylabel('O2 (%)',fontsize=6)
        axs2[3].set_ylabel('H2S (%)',fontsize=6)
        axs2[4].set_ylabel('Ap (mbar)',fontsize=6)
        axs2[5].set_ylabel('Flow (l/pm)',fontsize=6)
        axs2[5].set_xlabel('Time(# of record)',fontsize=6)
        axs2[0].set_ylim(-1,70)
        axs2[1].set_ylim(-1,40)
        axs2[2].set_ylim(-1,25)
        axs2[3].set_ylim(-10,300)
        axs2[4].set_ylim(1000,1020)
        axs2[5].set_ylim(0,0.5)
        self.frame = ttk.Frame(tab, height=500, width=700)
        self.frame.grid(row=0, column=0, sticky='nsew')
        canvas2=FigureCanvasTkAgg(fig2,master=self.frame)
        canvas2.get_tk_widget().place(x=0,y=0,width=600,height=400)
        canvas2.draw()
    except Exception as e:
        print(str(e))
        messagebox.showerror("Error", "Not correct file")

I want each graph be separete and have limit in y and x. Can you could help me achive it? Maybe using one axes for each, but i don´t know how do it.


问:
Need a template code to integrate CodeMirror 5 package module into React
I intend to create a YAML editor through React. CodeMirror6 provides no feature to enable YAML linting. So, I am trying to use CodeMirror 5. I am NOT ALLOWED to load the  and  through browser. Hence, I need a template code to integrate CodeMirror 5 inside React along with lint interface. Please help me.

Using React-CodeMirror throws "React/jsx-runtime" error. NOT ALLOWED to upgrade to React 17, so can't fix that too.


问:
Cannot read properties of undefined (reading 'appendchild')
enter image description hereHi i am trying to run a java script in nocode plateform. what i am actually trying to do is i am getting 2 dynamic values from dropdown and adding div according to those values respectively. one dropdown defines length and other one defines width. and i am trying to draw a grid by those values. i am able to add rows but can not add columns in 1st row.

`

```<code><script>
window.onload = function () {
    var MainDiv = document.getElementById("Main");
    var virtualDiv= document.createElement('div');
    virtualDiv.id='Vdiv';
    var Rows = document.getElementById("rows");
    var Columns = document.getElementById("columns");
    var length;
    var width;
    var arrayDivRow = new Array();
    var arrayDivCol = new Array();

    if(Rows){
        Rows.addEventListener('change', function handleChange(event) {

        length = parseInt(event.target.value);
        console.log(length);
            for(var i=0;i<length;i++){
            arrayDivRow[i] = document.createElement('div');
            arrayDivRow[i].id='row'+i;
            arrayDivRow[i].style.backgroundColor = 'yellow';
            arrayDivRow[i].style.height = "100px";
            arrayDivRow[i].style.margin = "5px";
                if(Columns){
                    Columns.addEventListener('change', function                                                                 handleChange(event) {

                    width = parseInt(event.target.value);
                    console.log(width);
                        for(var j=0;j<width;j++){
                            arrayDivCol[j] = document.createElement('div');
                            arrayDivCol[j].id='col'+j;
                            arrayDivCol[j].style.backgroundColor = 'green';
                            arrayDivCol[j].style.height = "100px";
                            arrayDivCol[j].style.margin = "5px";
                            arrayDivRow[i].appendchild(arrayDivCol[j]);
                        }

                    });

                }

            virtualDiv.appendChild(arrayDivRow[i]);
            }

        });
    }
 MainDiv.appendChild(virtualDiv);
};

</script>

</code>```

`
here i am getting error

```<code>Uncaught TypeError: Cannot read properties of undefined (reading 'appendchild')
    at HTMLSelectElement.handleChange (<anonymous>:37:26)
</code>```

in console of a browser

please help me solve this

Body:
enter image description hereHi i am trying to run a java script in nocode plateform. what i am actually trying to do is i am getting 2 dynamic values from dropdown and adding div according to those values respectively. one dropdown defines length and other one defines width. and i am trying to draw a grid by those values. i am able to add rows but can not add columns in 1st row.

`

`
here i am getting error

Uncaught TypeError: Cannot read properties of undefined (reading 'appendchild')
    at HTMLSelectElement.handleChange (<anonymous>:37:26)

in console of a browser

please help me solve this


问:
Having syntax issue for Spring Mongo @Query while trying to validate null values coming from the front end
I am trying to recieve data from the front end and then passing it to my @Query annotation, if the value is null , it would skip it , else it would look for it inside the Mongo database.

So far I have tried this @Query

```<code> @Query("{$and: [{"
            + "            $or: [{"
            + "                $where: '?0 == null'"
            + "            }, {"
            + "                name: '?0'"
            + "            }]"
            + "        }, {"
            + "            $or: [{"
            + "                $where: '?1 == null'"
            + "            }, {"
            + "                batch: '?1'"
            + "            }]"
            + "        }, {"
            + "            $or: [{"
            + "                $where: '?2 == null'"
 `          + "            }, {"
            + "                city: '?2'"
            + "            }]"
            + "        }]}")
</code>```

Now for the above query i am getting the following syntax issue

SyntaxError: identifier starts immediately after numeric literal on server

Now i know the issue is how i am writing the $where part, but I am not really able to understand it.

Thanks.

```<code></code>```

Body:
I am trying to recieve data from the front end and then passing it to my @Query annotation, if the value is null , it would skip it , else it would look for it inside the Mongo database.

So far I have tried this @Query

 @Query("{$and: [{"
            + "            $or: [{"
            + "                $where: '?0 == null'"
            + "            }, {"
            + "                name: '?0'"
            + "            }]"
            + "        }, {"
            + "            $or: [{"
            + "                $where: '?1 == null'"
            + "            }, {"
            + "                batch: '?1'"
            + "            }]"
            + "        }, {"
            + "            $or: [{"
            + "                $where: '?2 == null'"
 `          + "            }, {"
            + "                city: '?2'"
            + "            }]"
            + "        }]}")

Now for the above query i am getting the following syntax issue

SyntaxError: identifier starts immediately after numeric literal on server

Now i know the issue is how i am writing the $where part, but I am not really able to understand it.

Thanks.


问:
Parsing a JSON response with special characters
I'm currently parsing with javascript a JSON kind of string and I'm struggling with it.

I say JSON kind of string because this string is a response form a JSON Service, with the problem that every apex " is returned as \".
I solved this with an elegant replace

```<code>string = string.replace("\\\"","\"")
</code>```

and everything worked, till the moment I had to face an attribute whose value contained itself some "!

Let me explain with an example:

```<code>JSON response :
\"attr1\":\"value1\",
\"attr2\":\"value2\",
...
</code>```

```<code>After my parsing :
"attr1":"value1",
"attr2":"value2",
...
</code>```

And here everything is fine

Problem : when the response contains attributes like this :

```<code>JSON response :
\"attr1\":\"my name is \"Pippo\"\",
...
</code>```

after my parsing I obviously get an error since the apex before the P ends the value!

```<code>"attr1":"my name is "Pippo"",
</code>```

Any help is kindly appreciated!

Body:
I'm currently parsing with javascript a JSON kind of string and I'm struggling with it.

I say JSON kind of string because this string is a response form a JSON Service, with the problem that every apex " is returned as \".
I solved this with an elegant replace

string = string.replace("\\\"","\"")

and everything worked, till the moment I had to face an attribute whose value contained itself some "!

Let me explain with an example:

JSON response :
\"attr1\":\"value1\",
\"attr2\":\"value2\",
...

After my parsing :
"attr1":"value1",
"attr2":"value2",
...

And here everything is fine

Problem : when the response contains attributes like this :

JSON response :
\"attr1\":\"my name is \"Pippo\"\",
...

after my parsing I obviously get an error since the apex before the P ends the value!

"attr1":"my name is "Pippo"",

Any help is kindly appreciated!


问:
Is there a way to create a Paramiko SSH environment within an already establish Paramiko SSH session?
Currently I have 2 servers A and B. In order to access server B I have to initiate a session towards server A then from there I can access to server B using SSH as well.

Currently I am using python 3.10 and am using Paramiko to do the first SSH and the second server I am accessing it using executing commands on the SSH session as in below code snippet.

```<code>def _init_() -> None:
    self.ssh = paramiko.SSHClient()
    self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def connect(self,IP,port,username,OTP):
    self.ssh.connect(str(IP), str(port), str(username), str(OTP))
    self.chan = self.ssh.invoke_shell()
</code>```

then to reach the other server I am currently using the below

```<code>self.chan.send("ssh " + str(sshphrase) + '\n')
while self.chan.recv_ready():
    self.buff = self.chan.recv(4096).decode("utf-8")
    print (self.buff)
</code>```

Is there a better way to have like another Paramiko instance created based on a previous one instead of doing SSH by sending commands to the initial Paramiko SSHClient?

The above is currently working for me but causing a lot of delays and I am lacking control on sessions especially when I need to perform additional SSH layers within the script.

Body:
Currently I have 2 servers A and B. In order to access server B I have to initiate a session towards server A then from there I can access to server B using SSH as well.

Currently I am using python 3.10 and am using Paramiko to do the first SSH and the second server I am accessing it using executing commands on the SSH session as in below code snippet.

def _init_() -> None:
    self.ssh = paramiko.SSHClient()
    self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def connect(self,IP,port,username,OTP):
    self.ssh.connect(str(IP), str(port), str(username), str(OTP))
    self.chan = self.ssh.invoke_shell()

then to reach the other server I am currently using the below

self.chan.send("ssh " + str(sshphrase) + '\n')
while self.chan.recv_ready():
    self.buff = self.chan.recv(4096).decode("utf-8")
    print (self.buff)

Is there a better way to have like another Paramiko instance created based on a previous one instead of doing SSH by sending commands to the initial Paramiko SSHClient?

The above is currently working for me but causing a lot of delays and I am lacking control on sessions especially when I need to perform additional SSH layers within the script.


问:
Can't retract the needed tag while web scraping a site
What I am trying to do is make a code that converts RUB into PLN using exchange rates of 2 banks, the first one of which is here: https://qiwi.com/payment/exchange
I'm trying to get the selling rate of yuans. What so ever, <p> tags that I extracted seem not to contain it at all, unlike "buying", "selling" and "currency" labels.
What did I do wrong and why is this web page so hard to read?</p>
```<code>#libraries
import mechanicalsoup
from bs4 import BeautifulSoup
import re

#going to the website and extracting tags
browser=mechanicalsoup.Browser()
page=browser.get("https://qiwi.com/payment/exchange")
html=page.soup
print(type(html), '\n\n', page)
indexea=html.find_all('p')
for idx in indexea:
  print(idx)

print(len(indexea))

#variable=indexea[{this is the lien with rubble-yuan exchange rate}]

print()
</code>```

Body:
What I am trying to do is make a code that converts RUB into PLN using exchange rates of 2 banks, the first one of which is here: https://qiwi.com/payment/exchange
I'm trying to get the selling rate of yuans. What so ever,
 tags that I extracted seem not to contain it at all, unlike "buying", "selling" and "currency" labels.
What did I do wrong and why is this web page so hard to read?

#libraries
import mechanicalsoup
from bs4 import BeautifulSoup
import re

#going to the website and extracting tags
browser=mechanicalsoup.Browser()
page=browser.get("https://qiwi.com/payment/exchange")
html=page.soup
print(type(html), '\n\n', page)
indexea=html.find_all('p')
for idx in indexea:
  print(idx)

print(len(indexea))

#variable=indexea[{this is the lien with rubble-yuan exchange rate}]

print()


问:
Flutter : I want to reflect timer variables in the Mac OS system tray
I use a package called system_tray from flutte Mac OS.

I am trying to create a simple countdown timer and want to reflect the timer value in the system tray, but it is not reflected. How can I get it reflected?

This is all code.

```<code>import 'dart:async';

import 'package:flutter/material.dart';
import 'package:system_tray/system_tray.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    super.key,
  });

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Timer? countdownTimer;
  Duration myDuration = Duration(hours: 80);
  var hours;
  var minutes;
  var seconds;

  Future<void> initSystemTray() async {
    final SystemTray systemTray = SystemTray();
    await systemTray.initSystemTray(
      title: '$hours:$minutes:$seconds',
      iconPath: '',
    );
    await Future.delayed(const Duration(seconds: 1));
    print('success');
    setState(() {});
    initSystemTray();
  }

  void startTimer() {
    countdownTimer =
        Timer.periodic(Duration(seconds: 1), (_) => setCountDown());
  }

  void pauseTimer() {
    setState(() => countdownTimer!.cancel());
  }

  void resetTimer() {
    pauseTimer();
    setState(() => myDuration = Duration(hours: 80));
  }

  void setCountDown() {
    final reduceSecondsBy = 1;
    setState(() {
      final seconds = myDuration.inSeconds - reduceSecondsBy;
      if (seconds < 0) {
        countdownTimer!.cancel();
      } else {
        myDuration = Duration(seconds: seconds);
      }
    });
  }

  @override
  void initState() {
    initSystemTray();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    String strDigits(int n) => n.toString().padLeft(2, '0');
    hours = strDigits(myDuration.inHours);
    minutes = strDigits(myDuration.inMinutes.remainder(60));
    seconds = strDigits(myDuration.inSeconds.remainder(60));
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(onPressed: startTimer, icon: Icon(Icons.play_arrow)),
            IconButton(
                onPressed: () {
                  if (countdownTimer == null || countdownTimer!.isActive) {
                    pauseTimer();
                  }
                },
                icon: Icon(Icons.pause)),
            Text(
              '$hours:$minutes:$seconds',
              style: TextStyle(fontSize: 60),
            ),
            IconButton(
                onPressed: () {
                  resetTimer();
                },
                icon: Icon(Icons.restart_alt)),
            // Step 11
          ],
        ),
      ),
    );
  }
}
</code>```

Recursive function is executed but null is displayed

How do I get the hours minutes seconds variable reflected in the system tray?

Body:
I use a package called system_tray from flutte Mac OS.

I am trying to create a simple countdown timer and want to reflect the timer value in the system tray, but it is not reflected. How can I get it reflected?

This is all code.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:system_tray/system_tray.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    super.key,
  });

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Timer? countdownTimer;
  Duration myDuration = Duration(hours: 80);
  var hours;
  var minutes;
  var seconds;

  Future<void> initSystemTray() async {
    final SystemTray systemTray = SystemTray();
    await systemTray.initSystemTray(
      title: '$hours:$minutes:$seconds',
      iconPath: '',
    );
    await Future.delayed(const Duration(seconds: 1));
    print('success');
    setState(() {});
    initSystemTray();
  }

  void startTimer() {
    countdownTimer =
        Timer.periodic(Duration(seconds: 1), (_) => setCountDown());
  }

  void pauseTimer() {
    setState(() => countdownTimer!.cancel());
  }

  void resetTimer() {
    pauseTimer();
    setState(() => myDuration = Duration(hours: 80));
  }

  void setCountDown() {
    final reduceSecondsBy = 1;
    setState(() {
      final seconds = myDuration.inSeconds - reduceSecondsBy;
      if (seconds < 0) {
        countdownTimer!.cancel();
      } else {
        myDuration = Duration(seconds: seconds);
      }
    });
  }

  @override
  void initState() {
    initSystemTray();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    String strDigits(int n) => n.toString().padLeft(2, '0');
    hours = strDigits(myDuration.inHours);
    minutes = strDigits(myDuration.inMinutes.remainder(60));
    seconds = strDigits(myDuration.inSeconds.remainder(60));
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(onPressed: startTimer, icon: Icon(Icons.play_arrow)),
            IconButton(
                onPressed: () {
                  if (countdownTimer == null || countdownTimer!.isActive) {
                    pauseTimer();
                  }
                },
                icon: Icon(Icons.pause)),
            Text(
              '$hours:$minutes:$seconds',
              style: TextStyle(fontSize: 60),
            ),
            IconButton(
                onPressed: () {
                  resetTimer();
                },
                icon: Icon(Icons.restart_alt)),
            // Step 11
          ],
        ),
      ),
    );
  }
}

Recursive function is executed but null is displayed

How do I get the hours minutes seconds variable reflected in the system tray?


问:
4D input data in LSTM
I have data with a shape of (11242, 4, 5, 200) where num samples = 11242, sequence = 4, Number of items the sample has= 5, A 200D vectorization of the item= 200
That is, each of 11242 people has five items per sequence, and each item is converted into a vector of 200D.
At this time, I want to use LSTM to receive the above-mentioned 4D data as input.
However, as a result of searching, it seems that in order to use 4D data as input, it is necessary to change 4D data to 3D using flatten(5*200).
The 200D vector should not be combined into 'flatten' because it is a vectorization of each item.
How can I use this data as input for LSTM?

I don't know how to approach it

Title: 4D input data in LSTM