问:
How to calculate and return result of specific R function in a Shiny app?
I'm trying to use a R function in my shiny app but in vain...
This function is called "procedure_finale_shiny" and takes many arguments :

```<code>procedure_finale_shiny(0.3,0.3,0.1,0.1,0.2,c(30,50,60,70,80),c(1,2,3,4))
</code>```

and it returns a list of two elements.

And for information :

```<code>str(formals(procedure_finale_shiny))
</code>```

returns

```<code>Dotted pair list of 7
 $ alpha_1      : symbol
 $ alpha_2      : symbol
 $ alpha_3      : symbol
 $ alpha_4      : symbol
 $ alpha_5      : symbol
 $ choix_ratios : symbol
 $ choix_modeles: symbol
</code>```

I would like that the shiny app calculate and returns those 2 elements. The arguments (parameters) would be chosen by the user (but not the database for now just the parameters called "Choix des paramètres" in the UI).

I'm for the moment just working on the first tabPanel (1st page of the app).

Here is my user interface :  https://milesfrancois.shinyapps.io/shiny/

And here is my code (shiny app) :

```<code>library(dplyr)
library(ggplot2)
library(shiny)
library(DT)
library(ggrepel)
library(tidyr)
library(shinycssloaders)
library(shinythemes)
library(SwimmeR)
library(rsconnect)

button_color_css <- "
#DivCompClear, #FinderClear, #EnterTimes{
/* Change the background color of the update button
to blue. */
background: DodgerBlue;

/* Change the text size to 15 pixels. */
font-size: 15px;
}"

# Define UI
ui <- fluidPage(

  #Navbar structure for UI
  navbarPage("Selection de modeles", theme = shinytheme("slate"),
             tabPanel("Programme", fluid = TRUE, icon = icon("spinner"),
                      tags$style(button_color_css),
                      # Sidebar layout with a input and output definitions
                      sidebarLayout(
                        sidebarPanel(

                          h3("Chargement des donnees"),

                          fileInput("file", "Charger un jeu de donnees :"),

                          checkboxGroupInput(inputId = "DataExemple",
                                             label = "Utiliser les donnees de base :",
                                             choices = c("Donnees de base" = "D1")),

                          hr(),

                          actionButton(inputId = "DeleteData", label = "Supprimer les donnees", icon = icon("trash-alt")),

                          hr(),

                          h3("Implementation de la procedure de selection"),
                          #shinythemes::themeSelector(),

                          # Select modele
                          checkboxGroupInput(inputId = "ModeleFinder",
                                             label = "Choix des modele(s):",
                                             choices = c("Modele 1" = c(1), "Modele 2 " = c(2),"Modele 3 " = c(3),"Modele 4 " = c(4)),
                                             selected = "M1"),

                          hr(),

                          # Select ratio 1
                          sliderInput(inputId = "SliderRatio1",
                                      label = "Choix ratio 1",
                                      min = 0, max = 100, 30
                          ),

                          # Select ratio 2
                          sliderInput(inputId = "SliderRatio2",
                                      label = "Choix ratio 2",
                                      min = 0, max = 100, 30
                          ),

                          # Select ratio 3
                          sliderInput(inputId = "SliderRatio3",
                                      label = "Choix ratio 3",
                                      min = 0, max = 100, 30
                          ),

                          # Select ratio 4
                          sliderInput(inputId = "SliderRatio4",
                                      label = "Choix ratio 4",
                                      min = 0, max = 100, 30
                          ),

                          # Select ratio 5
                          sliderInput(inputId = "SliderRatio5",
                                      label = "Choix ratio 5",
                                      min = 0, max = 100, 30
                          ),

                          hr(),
                          hr(),

                          # Select alpha 1
                          sliderInput(inputId = "SliderAlpha1",
                                      label = "Importance du ratio",
                                      min = 0, max = 1, 0.3
                          ),

                          # Select alpha 2
                          sliderInput(inputId = "SliderAlpha2",
                                      label = "Importance de l'erreur d'apprentissage",
                                      min = 0, max = 1, 0.3
                          ),

                          # Select alpha 3
                          sliderInput(inputId = "SliderAlpha3",
                                      label = "Importance de l'erreur test",
                                      min = 0, max = 1, 0.3
                          ),

                          # Select alpha 4
                          sliderInput(inputId = "SliderAlpha4",
                                      label = "Importance du temps de calcul",
                                      min = 0, max = 1, 0.3
                          ),

                          # Select alpha 5
                          sliderInput(inputId = "SliderAlpha5",
                                      label = "Importance de la complexite du modele",
                                      min = 0, max = 1, 0.3
                          ),

                          hr(),
                          actionButton(inputId = "calculate", label = "Calculer", icon = icon("check")),
                          hr(),

                          h3("Sauvegarder les resultats"),

                          selectInput(inputId = "Export1",
                                      label = "Choisir le format",
                                      choices = c("csv", "texte","PDF","xlsx","SPSS","SAS","Stata"),
                                      selected = "csv"),

                          downloadButton("downloadData1", "Download")

                        ),

                        mainPanel(

                          ### add your style inline css values here

                          ### added a line of code here too `.dataTables_wrapper .dataTables_paginate .paginate_button.current:hover `###
                          tags$style(HTML("
                                          .dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing, .dataTables_wrapper .dataTables_paginate, .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover {
                                          color: #ffffff;
                                          }
                                          ### ADD THIS HERE ###
                                          .dataTables_wrapper .dataTables_paginate .paginate_button{box-sizing:border-box;display:inline-block;min-width:1.5em;padding:0.5em 1em;margin-left:2px;text-align:center;text-decoration:none !important;cursor:pointer;*cursor:hand;color:#ffffff !important;border:1px solid transparent;border-radius:2px}

                                          ###To change text and background color of the `Select` box ###
                                          .dataTables_length select {
                                          color: #0E334A;
                                          background-color: #0E334A
                                          }

                                          ###To change text and background color of the `Search` box ###
                                          .dataTables_filter input {
                                          color: #0E334A;
                                          background-color: #0E334A
                                          }

                                          thead {
                                          color: #ffffff;
                                          }

                                          tbody {
                                          color: #000000;
                                          }

                                          "

                    )
  ),

                          h4("Tableau de resultats"),
                          dataTableOutput("tab_res"),

                          hr(),

                          h4("Meilleur modele"),
                          dataTableOutput("best_mod")

                        )

                      )
             ),

             tabPanel("Code & Donnees", fluid = TRUE, icon = icon("database"),
                      sidebarLayout(
                        sidebarPanel(

                          h3("Affichage des donnees"),

                          radioButtons(inputId = "Display1",
                                       label = "",
                                       choices = c("preview", "str","summary"),
                                       selected = "preview"),

                          hr(),

                          h3("Affichage du code"),

                          checkboxGroupInput(inputId = "CodeR",
                                             label = "",
                                             choices = c("Afficher le code R" = "R1"))

                        ),

                        mainPanel()
                      )
             ),

             tabPanel("Graphiques", fluid = TRUE, icon = icon("chart-line"),
                      sidebarLayout(
                        sidebarPanel(

                          h3("Choix du modele"),

                          radioButtons(inputId = "Display2",
                                       label = "",
                                       choices = c("Modele 1", "Modele 2","Modele 3","Modele 4"),
                                       selected = "Modele 1"),

                          hr(),

                          h3("Sauvegarder le graphique"),

                          selectInput(inputId = "ExportGraph",
                                      label = "Choisir le format",
                                      choices = c("PNG", "JPEG","BMP"),
                                      selected = "PNG"),

                          downloadButton("downloadData2", "Download")

                        ),

                        mainPanel()
                      )
             ),

             navbarMenu("Plus d'informations", icon = icon("info-circle"),
                        tabPanel("ÃƒÂ‰tude", fluid = TRUE,
                                 fluidRow(
                                   column(6,
                                          h4(p("RÃƒÂ©sumÃƒÂ©")),
                                          h5(p("Cette ÃƒÂ©tude a ÃƒÂ©tÃƒÂ© rÃƒÂ©alisÃƒÂ©e au cours d'un stage de fin d'ÃƒÂ©tudes en deuxiÃƒÂ¨me annÃƒÂ©e de Master DSMS (Data Science et ModÃƒÂ©lisation Statistique) ÃƒÂ  l'UniversitÃƒÂ© de Bretagne Sud. Le stage s'est dÃƒÂ©roulÃƒÂ© au sein du LMBA (Laboratoire de MathÃƒÂ©matiques de Bretagne Atlantique) sur une pÃƒÂ©riode de six mois."),
                                             p("Le sujet du stage ÃƒÂ©tait le suivant : Ã‚Â« Automatisation d'une procÃƒÂ©dure de sÃƒÂ©lection de modÃƒÂ¨les dans le cadre du Couplage ModÃƒÂ¨le-DonnÃƒÂ©es Ã‚Â»."),
                                             p("Au cours d'un projet prÃƒÂ©cÃƒÂ©dent, un outil avait ÃƒÂ©tÃƒÂ© contruit afin d'ajuster un modÃƒÂ¨le (de type Couplage ModÃƒÂ¨le-DonnÃƒÂ©es) sur des donnÃƒÂ©es et de collecter certaines informations associÃƒÂ©es ÃƒÂ  celui-ci. L'objectif de notre stage ÃƒÂ©tait donc d'ÃƒÂ©prouver l'outil dÃƒÂ©jÃƒÂ  existant, d'augmenter sa robustesse et son niveau de gÃƒÂ©nÃƒÂ©ricitÃƒÂ© et enfin d'automatiser la procÃƒÂ©dure complÃƒÂ¨te de sÃƒÂ©lection de modÃƒÂ¨les."),
                                             p("Cette interface Shiny est en quelque sorte la mise en forme de nos travaux."),
                                             p("Les dÃƒÂ©tails qui sont propres ÃƒÂ  notre programme sont rÃƒÂ©fÃƒÂ©rencÃƒÂ©s dans l'onglet intitulÃƒÂ© Ã‚Â« DÃƒÂ©tails Ã‚Â».")
                                          )
                                   ),
                                   column(6,
                                          h4(p("Le Couplage ModÃƒÂ¨le-DonnÃƒÂ©es")),
                                          h5(p("Si l'on se rÃƒÂ©fÃƒÂ¨re aux travaux effectuÃƒÂ©s par FLOURENT (2019) dans le domaine du Smart Farming (l'agriculture de prÃƒÂ©cision), on peut dire que le Couplage ModÃƒÂ¨le-DonnÃƒÂ©es est une approche qui se situe ÃƒÂ  mi-chemin entre les approches dÃƒÂ®tes Ã‚Â« Black Box Ã‚Â» et Ã‚Â« White Box Ã‚Â»."),
                                             p("Le type de modÃƒÂ¨le appelÃƒÂ© Ã‚Â« Black Box Ã‚Â» fait en grande partie rÃƒÂ©fÃƒÂ©rence aux modÃƒÂ¨les classiques du Machine Learning (rÃƒÂ©seaux de neurones .). D'aprÃƒÂ¨s GORCZYCA et al (2018), VALLETTA et al. (2017), MA et al. (2014) et IP et al. (2018), la popularitÃƒÂ© de ces modÃƒÂ¨les peut s'expliquer par leur facilitÃƒÂ© d'utilisation, ainsi que par la diversitÃƒÂ© des problÃƒÂ¨mes pouvant ÃƒÂªtre rÃƒÂ©solus grÃƒÂ¢ce ÃƒÂ  de tels algorithmes. NÃƒÂ©anmoins ces modÃƒÂ¨les contiennent peu de connaissances a priori. Par consÃƒÂ©quent, les outils basÃƒÂ©s sur ce type de modÃƒÂ¨les sont peu informatifs d'un point de vue biologique (TAN et GILBERT (2003), SHAVLIK et al. (1995), HUBBARD et REINHARDT (1998)). Il faut ÃƒÂ©galement noter qu'il est nÃƒÂ©cessaire d'apprendre les paramÃƒÂ¨tres de ces modÃƒÂ¨les ÃƒÂ  partir de beaucoup de donnÃƒÂ©es et ceci dans le but de pallier l'absence d'expertise biologique (DUMPALA et al. (2017))"),
                                             p("ÃƒÂ€ l'inverse, les modÃƒÂ¨les Ã‚Â« White Box Ã‚Â» correspondent ÃƒÂ  des modÃƒÂ¨les mÃƒÂ©canistes rÃƒÂ©alistes (VAZQUEZ-CRUZ et al. (2014)). Si l'on se penche sur les travaux de BASTIANELLI et SAUVANT (1997) et MARTIN et SAUVANT (2010), la construction de modÃƒÂ¨les mÃƒÂ©canistes rÃƒÂ©alistes est une tÃƒÂ¢che complexe menant gÃƒÂ©nÃƒÂ©ralement ÃƒÂ  un modÃƒÂ¨le contenant un grand nombre d'ÃƒÂ©quations et de paramÃƒÂ¨tres ÃƒÂ  dÃƒÂ©terminer. Ce type de modÃƒÂ¨le nÃƒÂ©cessite d'avoir beaucoup de connaissances concernant le systÃƒÂ¨me ÃƒÂ©tudiÃƒÂ©."),
                                             p("On cite une nouvelle fois les travaux de FLOURENT : Ã‚Â« Le Couplage ModÃƒÂ¨le-DonnÃƒÂ©es consiste ÃƒÂ  intÃƒÂ©grer des connaissances concernant la dynamique du systÃƒÂ¨me ÃƒÂ©tudiÃƒÂ© via la construction d'un modÃƒÂ¨le mathÃƒÂ©matique et ÃƒÂ  utiliser ensuite des donnÃƒÂ©es pour ajuster les paramÃƒÂ¨tres du modÃƒÂ¨le construit Ã‚Â». On peut aussi reprendre les travaux de FRENOD (2017), ROUSSEAU et NODET (2013), SACKS et al. (2007) et WANG et al. (2010), et dire que le Couplage ModÃƒÂ¨les-DonnÃƒÂ©es consiste ÃƒÂ  construire un modÃƒÂ¨le mathÃƒÂ©matique parcimonieux, correspondant ÃƒÂ  une synthÃƒÂ¨se mathÃƒÂ©matique du systÃƒÂ¨me ÃƒÂ©tudiÃƒÂ©.")
                                          )
                                   ))

                        ),

                        tabPanel("DÃƒÂ©tails", fluid = TRUE,
                                 fluidRow(
                                   column(6,
                                          #br(),
                                          h4(p("ModÃƒÂ¨les")),
                                          h5(p("Notre programme comporte trois types de modÃƒÂ¨les et quatre modÃƒÂ¨les diffÃƒÂ©rents. Deux modÃƒÂ¨les de type Couplage ModÃƒÂ¨le-DonnÃƒÂ©es (les modÃƒÂ¨les 1 et 2), un modÃƒÂ¨le de type rÃƒÂ©seau de neurones (le modÃƒÂ¨le 3) et un modÃƒÂ¨le de type linÃƒÂ©aire (le modÃƒÂ¨le 4).")),
                                          br(),
                                          h4(p("ParamÃƒÂ¨tres")),
                                          h5(p("Le premier modÃƒÂ¨le de type Couplage ModÃƒÂ¨le-DonnÃƒÂ©es est composÃƒÂ© de trois paramÃƒÂ¨tres ajustÃƒÂ©s. Le second modÃƒÂ¨le de type Couplage ModÃƒÂ¨le-DonnÃƒÂ©es est composÃƒÂ© de deux paramÃƒÂ¨tres ajustÃƒÂ©s et d'un paramÃƒÂ¨tre fixe. Le modÃƒÂ¨le de type rÃƒÂ©seau de neurones est composÃƒÂ© de trois couches cachÃƒÂ©es (la premiÃƒÂ¨re et la troisiÃƒÂ¨me couches comportent trois neurones, la deuxiÃƒÂ¨me couche compte six neurones).")),
                                          br(),
                                          h4(p("Informations")),
                                          h5(p("Notre outil permet de collecter un certain nombre d'informations sur chacun des modÃƒÂ¨les comme l'erreur d'apprentissage, l'erreur test ou encore le temps de calcul. Certaines de ces informations nous sont utiles pour calculer notre indicateur de comparaison."))

                                          #hr(),

                                   ),
                                   column(6,
                                          #br(),
                                          h4(p("Indicateur")),
                                          h5(p("Notre indicateur de comparaison se base sur cinq informations diffÃƒÂ©rentes, ÃƒÂ  savoir : l'erreur test, l'erreur d'apprentissage, le temps de calcul, la complexitÃƒÂ© du modÃƒÂ¨le et la ratio.")),
                                          br(),
                                          h4(p("Programme")),
                                          h5(p("Le programme, sur la base de l'indicateur, renvoie le Ã‚Â« meilleur Ã‚Â» modÃƒÂ¨le ainsi qu'un tableau de rÃƒÂ©sultats avec un certain nombre d'infomations. L'utilisateur a la possibilitÃƒÂ© de sÃƒÂ©lectionner les modÃƒÂ¨les qu'il souhaite comparer, de choisir diffÃƒÂ©rents ratios (taille des donnÃƒÂ©es d'apprentissage et de test) ainsi que les poids associÃƒÂ©s (alphas) aux paramÃƒÂ¨tres de l'indicateur.")),
                                          br(),
                                          h4(p("Poids associÃƒÂ©s")),
                                          h5(p("alpha 1 : poids associÃƒÂ© au ratio")),
                                          h5(p("alpha 2 : poids associÃƒÂ© ÃƒÂ  l'erreur d'apprentissage")),
                                          h5(p("alpha 3 : poids associÃƒÂ© ÃƒÂ  l'erreur test")),
                                          h5(p("alpha 4 : poids associÃƒÂ© au temps de calcul")),
                                          h5(p("alpha 5 : poids associÃƒÂ© ÃƒÂ  la complexitÃƒÂ© du modÃƒÂ¨le"))

                                   )
                                 ),
                                 br(),
                                 hr(),
                                 h6(
                                   p(
                                     a("UniversitÃƒÂ© de Bretagne Sud",
                                       href = "https://www.univ-ubs.fr/fr/index.html"),
                                     br(),
                                     br(),
                                     a("Laboratoire de MathÃƒÂ©matiques de Bretagne Atlantique",
                                       href = "http://www.lmba-math.fr/"))),

                                 h6("ConÃƒÂ§u avec",
                                    img(src = "https://www.rstudio.com/wp-content/uploads/2014/04/shiny.png", height = "30px"),
                                    "par",
                                    img(src = "https://www.rstudio.com/wp-content/uploads/2014/07/RStudio-Logo-Blue-Gray.png", height = "30px"),
                                    ".")
                        )
             )
  )
)

work_dir_3 <- "C:\\Users\\François\\Desktop\\SHINY"
setwd(work_dir_3)
getwd()

source("procedure_finale_shiny.R", local = TRUE)

#res1 = as.data.frame(procedure_finale_shiny(0.3,0.3,0.1,0.1,0.2,c(30,50,60,70,80),c(1,2,3,4))[[1]])
#res2 = as.data.frame(procedure_finale_shiny(0.3,0.3,0.1,0.1,0.2,c(30,50,60,70,80),c(1,2,3,4))[[2]])

server <- function(input, output) {

  result1 <- eventReactive(input$calculate, {

    as.data.frame(procedure_finale_shiny(input$SliderAlpha1,input$SliderAlpha2,input$SliderAlpha3,input$SliderAlpha4,input$SliderAlpha5,c(input$SliderRatio1,input$SliderRatio2,input$SliderRatio3,input$SliderRatio4,input$SliderRatio5,c(input$ModeleFinder)))[[1]])

  })

  result2 <- eventReactive(input$calculate, {

    as.data.frame(procedure_finale_shiny(input$SliderAlpha1,input$SliderAlpha2,input$SliderAlpha3,input$SliderAlpha4,input$SliderAlpha5,c(input$SliderRatio1,input$SliderRatio2,input$SliderRatio3,input$SliderRatio4,input$SliderRatio5,c(input$ModeleFinder)))[[2]])

  })

  output$best_mod <- renderDataTable({

    result2()

  })

  output$tab_res <- renderDataTable({

    result1()

  })

}

# Run the application
shinyApp(ui = ui, server = server)

</code>```

Thank you in advance!

答:
You are on the right start, but there is no need to calculate it twice (and perhaps many reasons to not do that). Try this:

server <- function(input, output, session) {
  results <- eventReactive(input$calculate, {
    procedure_finale_shiny(
      input$SliderAlpha1, input$SliderAlpha2, input$SliderAlpha3, input$SliderAlpha4, input$SliderAlpha5,
      c(input$SliderRatio1, input$SliderRatio2,input$SliderRatio3, input$SliderRatio4, input$SliderRatio5),
      as.numeric(input$ModeleFinder))
  })

  output$best_mod <- renderTable({ results()[[1]] })
  output$tab_res <- renderTable({ results()[[2]] })
}
```

I'm not familiar with the function (and it does not matter), but if you need as.data.frame, that might be more appropriate within renderDataTable than within eventReactive.

(Edited several times to account for problems with the procedure_finale_shiny function. Namely, (1) the ratio arguments should be in a vector, and the OP function call was missing a close-paren to group them; and (2) the function's last argument (choix_modeles) requires a numeric or integer argument, not the string that shiny is prone to returning from inputs.)

Body:
I'm trying to use a R function in my shiny app but in vain...
This function is called "procedure_finale_shiny" and takes many arguments :

procedure_finale_shiny(0.3,0.3,0.1,0.1,0.2,c(30,50,60,70,80),c(1,2,3,4))

and it returns a list of two elements.

And for information :

str(formals(procedure_finale_shiny))

returns

Dotted pair list of 7
 $ alpha_1      : symbol
 $ alpha_2      : symbol
 $ alpha_3      : symbol
 $ alpha_4      : symbol
 $ alpha_5      : symbol
 $ choix_ratios : symbol
 $ choix_modeles: symbol

I would like that the shiny app calculate and returns those 2 elements. The arguments (parameters) would be chosen by the user (but not the database for now just the parameters called "Choix des paramètres" in the UI).

I'm for the moment just working on the first tabPanel (1st page of the app).

Here is my user interface :  https://milesfrancois.shinyapps.io/shiny/

And here is my code (shiny app) :

library(dplyr)
library(ggplot2)
library(shiny)
library(DT)
library(ggrepel)
library(tidyr)
library(shinycssloaders)
library(shinythemes)
library(SwimmeR)
library(rsconnect)

button_color_css <- "
#DivCompClear, #FinderClear, #EnterTimes{
/* Change the background color of the update button
to blue. */
background: DodgerBlue;

/* Change the text size to 15 pixels. */
font-size: 15px;
}"

# Define UI
ui <- fluidPage(

  #Navbar structure for UI
  navbarPage("Selection de modeles", theme = shinytheme("slate"),
             tabPanel("Programme", fluid = TRUE, icon = icon("spinner"),
                      tags$style(button_color_css),
                      # Sidebar layout with a input and output definitions
                      sidebarLayout(
                        sidebarPanel(

                          h3("Chargement des donnees"),

                          fileInput("file", "Charger un jeu de donnees :"),

                          checkboxGroupInput(inputId = "DataExemple",
                                             label = "Utiliser les donnees de base :",
                                             choices = c("Donnees de base" = "D1")),

                          hr(),

                          actionButton(inputId = "DeleteData", label = "Supprimer les donnees", icon = icon("trash-alt")),

                          hr(),

                          h3("Implementation de la procedure de selection"),
                          #shinythemes::themeSelector(),

                          # Select modele
                          checkboxGroupInput(inputId = "ModeleFinder",
                                             label = "Choix des modele(s):",
                                             choices = c("Modele 1" = c(1), "Modele 2 " = c(2),"Modele 3 " = c(3),"Modele 4 " = c(4)),
                                             selected = "M1"),

                          hr(),

                          # Select ratio 1
                          sliderInput(inputId = "SliderRatio1",
                                      label = "Choix ratio 1",
                                      min = 0, max = 100, 30
                          ),

                          # Select ratio 2
                          sliderInput(inputId = "SliderRatio2",
                                      label = "Choix ratio 2",
                                      min = 0, max = 100, 30
                          ),

                          # Select ratio 3
                          sliderInput(inputId = "SliderRatio3",
                                      label = "Choix ratio 3",
                                      min = 0, max = 100, 30
                          ),

                          # Select ratio 4
                          sliderInput(inputId = "SliderRatio4",
                                      label = "Choix ratio 4",
                                      min = 0, max = 100, 30
                          ),

                          # Select ratio 5
                          sliderInput(inputId = "SliderRatio5",
                                      label = "Choix ratio 5",
                                      min = 0, max = 100, 30
                          ),

                          hr(),
                          hr(),

                          # Select alpha 1
                          sliderInput(inputId = "SliderAlpha1",
                                      label = "Importance du ratio",
                                      min = 0, max = 1, 0.3
                          ),

                          # Select alpha 2
                          sliderInput(inputId = "SliderAlpha2",
                                      label = "Importance de l'erreur d'apprentissage",
                                      min = 0, max = 1, 0.3
                          ),

                          # Select alpha 3
                          sliderInput(inputId = "SliderAlpha3",
                                      label = "Importance de l'erreur test",
                                      min = 0, max = 1, 0.3
                          ),

                          # Select alpha 4
                          sliderInput(inputId = "SliderAlpha4",
                                      label = "Importance du temps de calcul",
                                      min = 0, max = 1, 0.3
                          ),

                          # Select alpha 5
                          sliderInput(inputId = "SliderAlpha5",
                                      label = "Importance de la complexite du modele",
                                      min = 0, max = 1, 0.3
                          ),

                          hr(),
                          actionButton(inputId = "calculate", label = "Calculer", icon = icon("check")),
                          hr(),

                          h3("Sauvegarder les resultats"),

                          selectInput(inputId = "Export1",
                                      label = "Choisir le format",
                                      choices = c("csv", "texte","PDF","xlsx","SPSS","SAS","Stata"),
                                      selected = "csv"),

                          downloadButton("downloadData1", "Download")

                        ),

                        mainPanel(

                          ### add your style inline css values here

                          ### added a line of code here too `.dataTables_wrapper .dataTables_paginate .paginate_button.current:hover `###
                          tags$style(HTML("
                                          .dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_processing, .dataTables_wrapper .dataTables_paginate, .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover {
                                          color: #ffffff;
                                          }
                                          ### ADD THIS HERE ###
                                          .dataTables_wrapper .dataTables_paginate .paginate_button{box-sizing:border-box;display:inline-block;min-width:1.5em;padding:0.5em 1em;margin-left:2px;text-align:center;text-decoration:none !important;cursor:pointer;*cursor:hand;color:#ffffff !important;border:1px solid transparent;border-radius:2px}

                                          ###To change text and background color of the `Select` box ###
                                          .dataTables_length select {
                                          color: #0E334A;
                                          background-color: #0E334A
                                          }

                                          ###To change text and background color of the `Search` box ###
                                          .dataTables_filter input {
                                          color: #0E334A;
                                          background-color: #0E334A
                                          }

                                          thead {
                                          color: #ffffff;
                                          }

                                          tbody {
                                          color: #000000;
                                          }

                                          "

                    )
  ),

                          h4("Tableau de resultats"),
                          dataTableOutput("tab_res"),

                          hr(),

                          h4("Meilleur modele"),
                          dataTableOutput("best_mod")

                        )

                      )
             ),

             tabPanel("Code & Donnees", fluid = TRUE, icon = icon("database"),
                      sidebarLayout(
                        sidebarPanel(

                          h3("Affichage des donnees"),

                          radioButtons(inputId = "Display1",
                                       label = "",
                                       choices = c("preview", "str","summary"),
                                       selected = "preview"),

                          hr(),

                          h3("Affichage du code"),

                          checkboxGroupInput(inputId = "CodeR",
                                             label = "",
                                             choices = c("Afficher le code R" = "R1"))

                        ),

                        mainPanel()
                      )
             ),

             tabPanel("Graphiques", fluid = TRUE, icon = icon("chart-line"),
                      sidebarLayout(
                        sidebarPanel(

                          h3("Choix du modele"),

                          radioButtons(inputId = "Display2",
                                       label = "",
                                       choices = c("Modele 1", "Modele 2","Modele 3","Modele 4"),
                                       selected = "Modele 1"),

                          hr(),

                          h3("Sauvegarder le graphique"),

                          selectInput(inputId = "ExportGraph",
                                      label = "Choisir le format",
                                      choices = c("PNG", "JPEG","BMP"),
                                      selected = "PNG"),

                          downloadButton("downloadData2", "Download")

                        ),

                        mainPanel()
                      )
             ),

             navbarMenu("Plus d'informations", icon = icon("info-circle"),
                        tabPanel("ÃƒÂ‰tude", fluid = TRUE,
                                 fluidRow(
                                   column(6,
                                          h4(p("RÃƒÂ©sumÃƒÂ©")),
                                          h5(p("Cette ÃƒÂ©tude a ÃƒÂ©tÃƒÂ© rÃƒÂ©alisÃƒÂ©e au cours d'un stage de fin d'ÃƒÂ©tudes en deuxiÃƒÂ¨me annÃƒÂ©e de Master DSMS (Data Science et ModÃƒÂ©lisation Statistique) ÃƒÂ  l'UniversitÃƒÂ© de Bretagne Sud. Le stage s'est dÃƒÂ©roulÃƒÂ© au sein du LMBA (Laboratoire de MathÃƒÂ©matiques de Bretagne Atlantique) sur une pÃƒÂ©riode de six mois."),
                                             p("Le sujet du stage ÃƒÂ©tait le suivant : Ã‚Â« Automatisation d'une procÃƒÂ©dure de sÃƒÂ©lection de modÃƒÂ¨les dans le cadre du Couplage ModÃƒÂ¨le-DonnÃƒÂ©es Ã‚Â»."),
                                             p("Au cours d'un projet prÃƒÂ©cÃƒÂ©dent, un outil avait ÃƒÂ©tÃƒÂ© contruit afin d'ajuster un modÃƒÂ¨le (de type Couplage ModÃƒÂ¨le-DonnÃƒÂ©es) sur des donnÃƒÂ©es et de collecter certaines informations associÃƒÂ©es ÃƒÂ  celui-ci. L'objectif de notre stage ÃƒÂ©tait donc d'ÃƒÂ©prouver l'outil dÃƒÂ©jÃƒÂ  existant, d'augmenter sa robustesse et son niveau de gÃƒÂ©nÃƒÂ©ricitÃƒÂ© et enfin d'automatiser la procÃƒÂ©dure complÃƒÂ¨te de sÃƒÂ©lection de modÃƒÂ¨les."),
                                             p("Cette interface Shiny est en quelque sorte la mise en forme de nos travaux."),
                                             p("Les dÃƒÂ©tails qui sont propres ÃƒÂ  notre programme sont rÃƒÂ©fÃƒÂ©rencÃƒÂ©s dans l'onglet intitulÃƒÂ© Ã‚Â« DÃƒÂ©tails Ã‚Â».")
                                          )
                                   ),
                                   column(6,
                                          h4(p("Le Couplage ModÃƒÂ¨le-DonnÃƒÂ©es")),
                                          h5(p("Si l'on se rÃƒÂ©fÃƒÂ¨re aux travaux effectuÃƒÂ©s par FLOURENT (2019) dans le domaine du Smart Farming (l'agriculture de prÃƒÂ©cision), on peut dire que le Couplage ModÃƒÂ¨le-DonnÃƒÂ©es est une approche qui se situe ÃƒÂ  mi-chemin entre les approches dÃƒÂ®tes Ã‚Â« Black Box Ã‚Â» et Ã‚Â« White Box Ã‚Â»."),
                                             p("Le type de modÃƒÂ¨le appelÃƒÂ© Ã‚Â« Black Box Ã‚Â» fait en grande partie rÃƒÂ©fÃƒÂ©rence aux modÃƒÂ¨les classiques du Machine Learning (rÃƒÂ©seaux de neurones .). D'aprÃƒÂ¨s GORCZYCA et al (2018), VALLETTA et al. (2017), MA et al. (2014) et IP et al. (2018), la popularitÃƒÂ© de ces modÃƒÂ¨les peut s'expliquer par leur facilitÃƒÂ© d'utilisation, ainsi que par la diversitÃƒÂ© des problÃƒÂ¨mes pouvant ÃƒÂªtre rÃƒÂ©solus grÃƒÂ¢ce ÃƒÂ  de tels algorithmes. NÃƒÂ©anmoins ces modÃƒÂ¨les contiennent peu de connaissances a priori. Par consÃƒÂ©quent, les outils basÃƒÂ©s sur ce type de modÃƒÂ¨les sont peu informatifs d'un point de vue biologique (TAN et GILBERT (2003), SHAVLIK et al. (1995), HUBBARD et REINHARDT (1998)). Il faut ÃƒÂ©galement noter qu'il est nÃƒÂ©cessaire d'apprendre les paramÃƒÂ¨tres de ces modÃƒÂ¨les ÃƒÂ  partir de beaucoup de donnÃƒÂ©es et ceci dans le but de pallier l'absence d'expertise biologique (DUMPALA et al. (2017))"),
                                             p("ÃƒÂ€ l'inverse, les modÃƒÂ¨les Ã‚Â« White Box Ã‚Â» correspondent ÃƒÂ  des modÃƒÂ¨les mÃƒÂ©canistes rÃƒÂ©alistes (VAZQUEZ-CRUZ et al. (2014)). Si l'on se penche sur les travaux de BASTIANELLI et SAUVANT (1997) et MARTIN et SAUVANT (2010), la construction de modÃƒÂ¨les mÃƒÂ©canistes rÃƒÂ©alistes est une tÃƒÂ¢che complexe menant gÃƒÂ©nÃƒÂ©ralement ÃƒÂ  un modÃƒÂ¨le contenant un grand nombre d'ÃƒÂ©quations et de paramÃƒÂ¨tres ÃƒÂ  dÃƒÂ©terminer. Ce type de modÃƒÂ¨le nÃƒÂ©cessite d'avoir beaucoup de connaissances concernant le systÃƒÂ¨me ÃƒÂ©tudiÃƒÂ©."),
                                             p("On cite une nouvelle fois les travaux de FLOURENT : Ã‚Â« Le Couplage ModÃƒÂ¨le-DonnÃƒÂ©es consiste ÃƒÂ  intÃƒÂ©grer des connaissances concernant la dynamique du systÃƒÂ¨me ÃƒÂ©tudiÃƒÂ© via la construction d'un modÃƒÂ¨le mathÃƒÂ©matique et ÃƒÂ  utiliser ensuite des donnÃƒÂ©es pour ajuster les paramÃƒÂ¨tres du modÃƒÂ¨le construit Ã‚Â». On peut aussi reprendre les travaux de FRENOD (2017), ROUSSEAU et NODET (2013), SACKS et al. (2007) et WANG et al. (2010), et dire que le Couplage ModÃƒÂ¨les-DonnÃƒÂ©es consiste ÃƒÂ  construire un modÃƒÂ¨le mathÃƒÂ©matique parcimonieux, correspondant ÃƒÂ  une synthÃƒÂ¨se mathÃƒÂ©matique du systÃƒÂ¨me ÃƒÂ©tudiÃƒÂ©.")
                                          )
                                   ))

                        ),

                        tabPanel("DÃƒÂ©tails", fluid = TRUE,
                                 fluidRow(
                                   column(6,
                                          #br(),
                                          h4(p("ModÃƒÂ¨les")),
                                          h5(p("Notre programme comporte trois types de modÃƒÂ¨les et quatre modÃƒÂ¨les diffÃƒÂ©rents. Deux modÃƒÂ¨les de type Couplage ModÃƒÂ¨le-DonnÃƒÂ©es (les modÃƒÂ¨les 1 et 2), un modÃƒÂ¨le de type rÃƒÂ©seau de neurones (le modÃƒÂ¨le 3) et un modÃƒÂ¨le de type linÃƒÂ©aire (le modÃƒÂ¨le 4).")),
                                          br(),
                                          h4(p("ParamÃƒÂ¨tres")),
                                          h5(p("Le premier modÃƒÂ¨le de type Couplage ModÃƒÂ¨le-DonnÃƒÂ©es est composÃƒÂ© de trois paramÃƒÂ¨tres ajustÃƒÂ©s. Le second modÃƒÂ¨le de type Couplage ModÃƒÂ¨le-DonnÃƒÂ©es est composÃƒÂ© de deux paramÃƒÂ¨tres ajustÃƒÂ©s et d'un paramÃƒÂ¨tre fixe. Le modÃƒÂ¨le de type rÃƒÂ©seau de neurones est composÃƒÂ© de trois couches cachÃƒÂ©es (la premiÃƒÂ¨re et la troisiÃƒÂ¨me couches comportent trois neurones, la deuxiÃƒÂ¨me couche compte six neurones).")),
                                          br(),
                                          h4(p("Informations")),
                                          h5(p("Notre outil permet de collecter un certain nombre d'informations sur chacun des modÃƒÂ¨les comme l'erreur d'apprentissage, l'erreur test ou encore le temps de calcul. Certaines de ces informations nous sont utiles pour calculer notre indicateur de comparaison."))

                                          #hr(),

                                   ),
                                   column(6,
                                          #br(),
                                          h4(p("Indicateur")),
                                          h5(p("Notre indicateur de comparaison se base sur cinq informations diffÃƒÂ©rentes, ÃƒÂ  savoir : l'erreur test, l'erreur d'apprentissage, le temps de calcul, la complexitÃƒÂ© du modÃƒÂ¨le et la ratio.")),
                                          br(),
                                          h4(p("Programme")),
                                          h5(p("Le programme, sur la base de l'indicateur, renvoie le Ã‚Â« meilleur Ã‚Â» modÃƒÂ¨le ainsi qu'un tableau de rÃƒÂ©sultats avec un certain nombre d'infomations. L'utilisateur a la possibilitÃƒÂ© de sÃƒÂ©lectionner les modÃƒÂ¨les qu'il souhaite comparer, de choisir diffÃƒÂ©rents ratios (taille des donnÃƒÂ©es d'apprentissage et de test) ainsi que les poids associÃƒÂ©s (alphas) aux paramÃƒÂ¨tres de l'indicateur.")),
                                          br(),
                                          h4(p("Poids associÃƒÂ©s")),
                                          h5(p("alpha 1 : poids associÃƒÂ© au ratio")),
                                          h5(p("alpha 2 : poids associÃƒÂ© ÃƒÂ  l'erreur d'apprentissage")),
                                          h5(p("alpha 3 : poids associÃƒÂ© ÃƒÂ  l'erreur test")),
                                          h5(p("alpha 4 : poids associÃƒÂ© au temps de calcul")),
                                          h5(p("alpha 5 : poids associÃƒÂ© ÃƒÂ  la complexitÃƒÂ© du modÃƒÂ¨le"))

                                   )
                                 ),
                                 br(),
                                 hr(),
                                 h6(
                                   p(
                                     a("UniversitÃƒÂ© de Bretagne Sud",
                                       href = "https://www.univ-ubs.fr/fr/index.html"),
                                     br(),
                                     br(),
                                     a("Laboratoire de MathÃƒÂ©matiques de Bretagne Atlantique",
                                       href = "http://www.lmba-math.fr/"))),

                                 h6("ConÃƒÂ§u avec",
                                    img(src = "https://www.rstudio.com/wp-content/uploads/2014/04/shiny.png", height = "30px"),
                                    "par",
                                    img(src = "https://www.rstudio.com/wp-content/uploads/2014/07/RStudio-Logo-Blue-Gray.png", height = "30px"),
                                    ".")
                        )
             )
  )
)

work_dir_3 <- "C:\\Users\\François\\Desktop\\SHINY"
setwd(work_dir_3)
getwd()

source("procedure_finale_shiny.R", local = TRUE)

#res1 = as.data.frame(procedure_finale_shiny(0.3,0.3,0.1,0.1,0.2,c(30,50,60,70,80),c(1,2,3,4))[[1]])
#res2 = as.data.frame(procedure_finale_shiny(0.3,0.3,0.1,0.1,0.2,c(30,50,60,70,80),c(1,2,3,4))[[2]])

server <- function(input, output) {

  result1 <- eventReactive(input$calculate, {

    as.data.frame(procedure_finale_shiny(input$SliderAlpha1,input$SliderAlpha2,input$SliderAlpha3,input$SliderAlpha4,input$SliderAlpha5,c(input$SliderRatio1,input$SliderRatio2,input$SliderRatio3,input$SliderRatio4,input$SliderRatio5,c(input$ModeleFinder)))[[1]])

  })

  result2 <- eventReactive(input$calculate, {

    as.data.frame(procedure_finale_shiny(input$SliderAlpha1,input$SliderAlpha2,input$SliderAlpha3,input$SliderAlpha4,input$SliderAlpha5,c(input$SliderRatio1,input$SliderRatio2,input$SliderRatio3,input$SliderRatio4,input$SliderRatio5,c(input$ModeleFinder)))[[2]])

  })

  output$best_mod <- renderDataTable({

    result2()

  })

  output$tab_res <- renderDataTable({

    result1()

  })

}

# Run the application
shinyApp(ui = ui, server = server)

Thank you in advance!

Body:
You are on the right start, but there is no need to calculate it twice (and perhaps many reasons to not do that). Try this:

server <- function(input, output, session) {
  results <- eventReactive(input$calculate, {
    procedure_finale_shiny(
      input$SliderAlpha1, input$SliderAlpha2, input$SliderAlpha3, input$SliderAlpha4, input$SliderAlpha5,
      c(input$SliderRatio1, input$SliderRatio2,input$SliderRatio3, input$SliderRatio4, input$SliderRatio5),
      as.numeric(input$ModeleFinder))
  })

  output$best_mod <- renderTable({ results()[[1]] })
  output$tab_res <- renderTable({ results()[[2]] })
}

I'm not familiar with the function (and it does not matter), but if you need as.data.frame, that might be more appropriate within renderDataTable than within eventReactive.

(Edited several times to account for problems with the procedure_finale_shiny function. Namely, (1) the ratio arguments should be in a vector, and the OP function call was missing a close-paren to group them; and (2) the function's last argument (choix_modeles) requires a numeric or integer argument, not the string that shiny is prone to returning from inputs.)


来源: stackexchange

问:
Tomcat Java Servlet - Initialize Class on Application Startup
I have a class that takes a bit of time to start up (makes some JNI calls and what not), so it is not feasable to initialize this class everytime a page loads. Is it possible to initialize this class on application startup, then access its methods as pages are being served up?

For Example:

I have MyClass. When the application (tomcat) starts up I would like it to initialze my calss as follows:

```<code>MyClass myClassInstance = new MyClass("arg1", "arg2");
</code>```

Then when a page is called, say /testpage, I would like to make calls to myClassInstance:

```<code>import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import MyClass;

public class TestPage extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        String myResult = myClassInstance.getResult("whatever");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Test</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>" +myResult +"</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}
</code>```

Is this possible?

答:
You have two choices:

Initialize your class in servlet's init() method. You may add <load-on-startup> attribute to make sure your servlet is created at application startup and not on first access.

Add ServletContextListener and use contextInitialized() callback method. Use ServletContext#setAttribute to store created object for future use.

ContentLicense: CC BY-SA 3.0

Body:
I have a class that takes a bit of time to start up (makes some JNI calls and what not), so it is not feasable to initialize this class everytime a page loads. Is it possible to initialize this class on application startup, then access its methods as pages are being served up?

For Example:

I have MyClass. When the application (tomcat) starts up I would like it to initialze my calss as follows:

MyClass myClassInstance = new MyClass("arg1", "arg2");

Then when a page is called, say /testpage, I would like to make calls to myClassInstance:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import MyClass;

public class TestPage extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        String myResult = myClassInstance.getResult("whatever");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("");
        out.println("");
        out.println("<title>Test</title>");
        out.println("");
        out.println("");
        out.println("
" +myResult +"
");
        out.println("");
        out.println("");
    }
}

Is this possible?


问:
Can't start any React Native Projects in Expo any more
I'm flummoxed after 2 hours of trying to figure this out. Long story short, when I download a Native React Project like the Native Base KitchenSink and run it, I get errors. Not just this project but on others.

All I did was:

Download the zip file and explode it

"yarn" and then "yarn start"

Then I get this error

I get similar regex errors on totally different out-of-the-box projects as well. So I'm fairly certain it is something on my machine and not this 3rd party code.

Here is the error from a different project

I have attempted to uninstall and reinstall Node and expo-cli (via npm and yarn)

But I get the same error.

Can anyone point me in the right direction? I don't know what to uninstall at this point.
I get lots of warning messages when installing but no errors.

What do I reinstall at this point?

答:
this occurs on old projects that use old versions of packages that aren't supported by new versions of node.js. this issue was fixed in this pull request and backported but perhaps not to a version old enough to be supported by the projects you are trying to run. you can revert back to an older version of node.js if you must run them - node.js v10.x would be a good choice.

if you're not too opinionated about the library choice, you may want to try a more actively maintained ui library like react-native-paper instead.

ContentLicense: CC BY-SA 4.0


问:
How can I map items together in a json structure with jq?
I have a json structure that looks like this:

```<code>{
        "lorry1": {
                "box1": [
                        {"item": "shoes", "state": "new"},
                        {"item": "snacks", "state": "new"}
                ],
                "box2": [
                        {"item": "beer", "state": "cold"},
                        {"item": "potatoes"}
                ]
        },
        "lorry2": {
                "box1": [
                        {"item": "shoes", "state": "new"},
                        {"item": "snacks", "state": "new"}
                ],
                "box2": [
                        {"item": "beer", "state": "lukewarm"}
                ]
        }
}
</code>```

Now I want to know where I can find shoes:
I could come up with this jq query:

```<code>to_entries | select(.[].value | .[][].item=="shoes") | map({"lorry": "\(.key)"  })
</code>```

But that only gives me the lorries. Useful, but not quite there yet. I'd like to know the box they're in as well.

I came up with this, but it obviously is not correct:

```<code>to_entries | select(.[].value | .[][].item=="shoes") | keys as $box |map({"lorry": "\(.key)", "box": $box })
</code>```

The answer I'd like to get is lorry1, box1 and lorry2, box1.

Even better yet: I'd like to find all items and provide the information, like this:

```<code>"shoes": [ {"lorry1", "box1"}, {"lorry2", "box1" } ],
"snacks": [ {"lorry1", "box1"}, {"lorry2", "box1"} ],
"beer": [ {"lorry1", "box2"}, {"lorry2", "box2"} ],
"potatoes": [ {"lorry1", "box2"} ]
</code>```

but that may be asking a bit too much :)

答:
Here's a generic solution that does not assume the "items" are in arrays, or even that the values associated with the "item" keys are always strings:

```<code>jq -c '. as $in
  | [paths as $p | select($p[-1] == "item") | $p]
  | group_by(. as $p | $in|getpath($p))
  | .[]
  | (.[0] as $p | $in | getpath($p)) as $v
  | {($v|tostring):  ( map(.[:-1] | if .[-1] | type == "number" then .[:-1] else . end)) }
'
</code>```

Output

With your input:

```<code>{"beer":[["lorry1","box2"],["lorry2","box2"]]}
{"potatoes":[["lorry1","box2"]]}
{"shoes":[["lorry1","box1"],["lorry2","box1"]]}
{"snacks":[["lorry1","box1"],["lorry2","box1"]]}
</code>```

If you want the output as a single JSON object, then collect the above into an array and use add.

Body:
I have a json structure that looks like this:

{
        "lorry1": {
                "box1": [
                        {"item": "shoes", "state": "new"},
                        {"item": "snacks", "state": "new"}
                ],
                "box2": [
                        {"item": "beer", "state": "cold"},
                        {"item": "potatoes"}
                ]
        },
        "lorry2": {
                "box1": [
                        {"item": "shoes", "state": "new"},
                        {"item": "snacks", "state": "new"}
                ],
                "box2": [
                        {"item": "beer", "state": "lukewarm"}
                ]
        }
}

Now I want to know where I can find shoes:
I could come up with this jq query:

to_entries | select(.[].value | .[][].item=="shoes") | map({"lorry": "\(.key)"  })

But that only gives me the lorries. Useful, but not quite there yet. I'd like to know the box they're in as well.

I came up with this, but it obviously is not correct:

to_entries | select(.[].value | .[][].item=="shoes") | keys as $box |map({"lorry": "\(.key)", "box": $box })

The answer I'd like to get is lorry1, box1 and lorry2, box1.

Even better yet: I'd like to find all items and provide the information, like this:

"shoes": [ {"lorry1", "box1"}, {"lorry2", "box1" } ],
"snacks": [ {"lorry1", "box1"}, {"lorry2", "box1"} ],
"beer": [ {"lorry1", "box2"}, {"lorry2", "box2"} ],
"potatoes": [ {"lorry1", "box2"} ]

but that may be asking a bit too much :)

Body:
Here's a generic solution that does not assume the "items" are in arrays, or even that the values associated with the "item" keys are always strings:

jq -c '. as $in
  | [paths as $p | select($p[-1] == "item") | $p]
  | group_by(. as $p | $in|getpath($p))
  | .[]
  | (.[0] as $p | $in | getpath($p)) as $v
  | {($v|tostring):  ( map(.[:-1] | if .[-1] | type == "number" then .[:-1] else . end)) }
'

Output

With your input:

{"beer":[["lorry1","box2"],["lorry2","box2"]]}
{"potatoes":[["lorry1","box2"]]}
{"shoes":[["lorry1","box1"],["lorry2","box1"]]}
{"snacks":[["lorry1","box1"],["lorry2","box1"]]}

If you want the output as a single JSON object, then collect the above into an array and use add.


问:
How to make a loop in a loop (Python)?
I would like to execute a loop in a loop, but when I try to do that I catch a wrong calculation comparing to a singular loop.

My code with a singular loop that works:

```<code>betresult = []

#main parameters
budget = 1500
numofbets = 100
win = 7.5
loss = -15

for i in range(numofbets):
    #random list: 1 - win, 0 - loss
    test = np.random.choice(np.arange(0, 2), p=[0.333, 0.667])
    betresult.append(test)

    #number of win and loss
    winbets = np.sum(betresult)
    lossbets = numofbets - winbets

    #sum of win and loss
    winsum = winbets * win
    losssum = lossbets * loss

    #final sum
    result = budget - (winsum + losssum)

print(result)
</code>```

And I would like to put that code in a new loop, but if I make something obviously with while or for, I catch a wrong calculation.

With a singular loop I usually get one number between 1100 and 1800.

Code with a wrong calculation:

```<code>betresult = []

#main parameters
budget = 1500
numofbets = 100
win = 7.5
loss = -15

for i in range(10):
    for j in range(numofbets):
        #random list: 1 - win, 0 - loss
        test = np.random.choice(np.arange(0, 2), p=[0.333, 0.667])
        betresult.append(test)

        #number of win and loss
        winbets = np.sum(betresult)
        lossbets = numofbets - winbets

        #sum of win and loss
        winsum = winbets * win
        losssum = lossbets * loss

        #final sum
        result = budget - (winsum + losssum)

     print(result)
</code>```

With a double loop I usually get a number under 0. And the bigger a loop range, the bigger a number under 0.

An example of wrong execution (calculation):

```<code>1470.0
7.5
-1590.0
-3007.5
-4447.5
-5910.0
-7440.0
-8835.0
-10410.0
-11985.0
</code>```

答:
```<code>import numpy as np
betresult = []

#main parameters
budget = 1500
numofbets = 100
win = 7.5
loss = -15
summary = 0
for i in range(80):
    for i in range(numofbets):
        test = np.random.choice(np.arange(0, 2), p=[0.333, 0.667])
        betresult.append(test)

        winbets = np.sum(betresult)
        lossbets = numofbets - winbets

        winsum = winbets * win
        losssum = lossbets * loss

        result = budget - (winsum + losssum)
     #betresult.clear() should be outside the second loop
     betresult.clear()

print(result)
</code>```

I think you need to clear your betresult each time you run this loop.
Maybe you need some extra Code to calculate, depends on what you want.

Title: How to make a loop in a loop (Python)?

Body:
I would like to execute a loop in a loop, but when I try to do that I catch a wrong calculation comparing to a singular loop.

My code with a singular loop that works:

betresult = []

#main parameters
budget = 1500
numofbets = 100
win = 7.5
loss = -15

for i in range(numofbets):
    #random list: 1 - win, 0 - loss
    test = np.random.choice(np.arange(0, 2), p=[0.333, 0.667])
    betresult.append(test)

    #number of win and loss
    winbets = np.sum(betresult)
    lossbets = numofbets - winbets

    #sum of win and loss
    winsum = winbets * win
    losssum = lossbets * loss

    #final sum
    result = budget - (winsum + losssum)

print(result)

And I would like to put that code in a new loop, but if I make something obviously with while or for, I catch a wrong calculation.

With a singular loop I usually get one number between 1100 and 1800.

Code with a wrong calculation:

betresult = []

#main parameters
budget = 1500
numofbets = 100
win = 7.5
loss = -15

for i in range(10):
    for j in range(numofbets):
        #random list: 1 - win, 0 - loss
        test = np.random.choice(np.arange(0, 2), p=[0.333, 0.667])
        betresult.append(test)

        #number of win and loss
        winbets = np.sum(betresult)
        lossbets = numofbets - winbets

        #sum of win and loss
        winsum = winbets * win
        losssum = lossbets * loss

        #final sum
        result = budget - (winsum + losssum)

     print(result)

With a double loop I usually get a number under 0. And the bigger a loop range, the bigger a number under 0.

An example of wrong execution (calculation):

1470.0
7.5
-1590.0
-3007.5
-4447.5
-5910.0
-7440.0
-8835.0
-10410.0
-11985.0

Body:
import numpy as np
betresult = []

#main parameters
budget = 1500
numofbets = 100
win = 7.5
loss = -15
summary = 0
for i in range(80):
    for i in range(numofbets):
        test = np.random.choice(np.arange(0, 2), p=[0.333, 0.667])
        betresult.append(test)

        winbets = np.sum(betresult)
        lossbets = numofbets - winbets

        winsum = winbets * win
        losssum = lossbets * loss

        result = budget - (winsum + losssum)
     #betresult.clear() should be outside the second loop
     betresult.clear()

print(result)

I think you need to clear your betresult each time you run this loop.
Maybe you need some extra Code to calculate, depends on what you want.


问:
How to call this.close in buildResult method when using Search Delegate (Flutter)?
I have a very simple SearchApp that has an AppBar with a search Icon and a text widget. When the search Icon is tapped, showSearch is called and the CustomSearchDelegate is called. How do I make it so that in the buildResults method, this.close is immediately called without returning a widget and the query is passed to the SearchApp stateless widget to be displayed on the Text widget.

Here is the code:

```<code>class SearchApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          IconButton(
            tooltip: 'Search',
            icon: const Icon(Icons.search),
            //Don't block the main thread
            onPressed: () {
              showSearch(context: context, delegate: CustomSearchDelegate());
            },
          ),
        ],
      ),
      body: Text(query), // The query data should be displayed here
    );
  }
}

class CustomSearchDelegate extends SearchDelegate {
  @override
  List<Widget> buildActions(BuildContext context) {
    return <Widget>[Icon(Icons.close)];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return Icon(Icons.arrow_back_ios);
  }

  @override
  Widget buildResults(BuildContext context) {
    // GO back to SearchApp page immediately with the query result
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return Column();
  }
}
</code>```

答: I realized I could edit the source code of the search class, so I copied and pasted the source code and under the Textfield, I simply deleted the showResult method and replaced it with close, so no results page would be shown. As for passing the query to the original page, all I had to do was store the value in an asynchronous variable. </p>

Body:
I have a very simple SearchApp that has an AppBar with a search Icon and a text widget. When the search Icon is tapped, showSearch is called and the CustomSearchDelegate is called. How do I make it so that in the buildResults method, this.close is immediately called without returning a widget and the query is passed to the SearchApp stateless widget to be displayed on the Text widget.

Here is the code:

class SearchApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          IconButton(
            tooltip: 'Search',
            icon: const Icon(Icons.search),
            //Don't block the main thread
            onPressed: () {
              showSearch(context: context, delegate: CustomSearchDelegate());
            },
          ),
        ],
      ),
      body: Text(query), // The query data should be displayed here
    );
  }
}

class CustomSearchDelegate extends SearchDelegate {
  @override
  List<Widget> buildActions(BuildContext context) {
    return <Widget>[Icon(Icons.close)];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return Icon(Icons.arrow_back_ios);
  }

  @override
  Widget buildResults(BuildContext context) {
    // GO back to SearchApp page immediately with the query result
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return Column();
  }
}


问:
copying c++ abstract classes
Ok heres some code.

```<code>#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
};
void Main()
{
    deque<A *> aclasses = deque<A*>(0);
    deque<A *> aclasses2 = deque<A*>(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(new A(*aclasses[0]));
    aclasses2.push_back(new A(*aclasses[1]));
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.

}
</code>```

Now you might say, why don't you just put the pointers from the first deque into the second deque? While I could but I need the data to be independent. Basically I want to be able to clone items from the first deque while preserving there identity and giving them there own data.

Now the current modified version

```<code>#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
    virtual ~A() {}             // don't forget the virtual destructor
    virtual A* clone() const {
       return new A(*this);
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
    virtual B* clone() {     // return type is co-variant
       return new B( *this );
    }
};
void MainRUNNER()
{
    deque<A *> aclasses = deque<A*>(0);
    deque<A *> aclasses2 = deque<A*>(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(aclasses[0]->clone());
    aclasses2.push_back(aclasses[1]->clone());
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.
}
</code>```

答:
You have new A(...) way down there. What gets called is A's copy constructor (created implicitly by the compiler.

What you want is a clone method. See here. It recaps the appropriate item from the excellent C++ Coding Standards book. Below is a shameless copy of the final solution, which also shows a nice use of the NVI idiom to avoid the slicing problem.

```<code>class A {// …
public:
  A* Clone() const {                        // nonvirtual
    A* p = DoClone();
    assert( typeid(*p) == typeid(*this) && "DoClone incorrectly overridden" );
    return p;                                // check DoClone's returned type
  }

protected:
 A( const A& );
 virtual A* DoClone() const = 0;
};

class B : public A { // …
public:
  virtual B* Clone() const {return new B(*this); }

protected:
  B( const B& rhs ) : A( rhs ) {/* … */}
};
</code>```

update
A bit of an explanation. The basic idea of the clone is the same as the other excellent answers here.

Now, with cloning you have the danger of slicing objects. For example, if some object which derives from A forgets to implement its own clone method, then a call to A* a = d->clone() will not return a full D object (assuming D is a descendant of A)

The NVI idiom says to separate a public interface from a virtual interface. Thus, in this example, clone is public, but not virtual. It call a protected virtual method, doClone, which does the actual cloning, and which derived objects also implement. Because of the split, the clone method can verify that the type of the cloned object matches the type of the original object.

Title: copying c++ abstract classes

Body:
Ok heres some code.

#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
};
void Main()
{
    deque aclasses = deque(0);
    deque aclasses2 = deque(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(new A(*aclasses[0]));
    aclasses2.push_back(new A(*aclasses[1]));
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.

}

Now you might say, why don't you just put the pointers from the first deque into the second deque? While I could but I need the data to be independent. Basically I want to be able to clone items from the first deque while preserving there identity and giving them there own data.

Now the current modified version

#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
    virtual ~A() {}             // don't forget the virtual destructor
    virtual A* clone() const {
       return new A(*this);
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
    virtual B* clone() {     // return type is co-variant
       return new B( *this );
    }
};
void MainRUNNER()
{
    deque aclasses = deque(0);
    deque aclasses2 = deque(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(aclasses[0]->clone());
    aclasses2.push_back(aclasses[1]->clone());
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.
}

Body:
You have new A(...) way down there. What gets called is A's copy constructor (created implicitly by the compiler.

What you want is a clone method. See here. It recaps the appropriate item from the excellent C++ Coding Standards book. Below is a shameless copy of the final solution, which also shows a nice use of the NVI idiom to avoid the slicing problem.

class A {// …
public:
  A* Clone() const {                        // nonvirtual
    A* p = DoClone();
    assert( typeid(*p) == typeid(*this) && "DoClone incorrectly overridden" );
    return p;                                // check DoClone's returned type
  }

protected:
 A( const A& );
 virtual A* DoClone() const = 0;
};

class B : public A { // …
public:
  virtual B* Clone() const {return new B(*this); }

protected:
  B( const B& rhs ) : A( rhs ) {/* … */}
};

update
A bit of an explanation. The basic idea of the clone is the same as the other excellent answers here.

Now, with cloning you have the danger of slicing objects. For example, if some object which derives from A forgets to implement its own clone method, then a call to A* a = d->clone() will not return a full D object (assuming D is a descendant of A)

The NVI idiom says to separate a public interface from a virtual interface. Thus, in this example, clone is public, but not virtual. It call a protected virtual method, doClone, which does the actual cloning, and which derived objects also implement. Because of the split, the clone method can verify that the type of the cloned object matches the type of the original object.


问:
How to format a date value for Hubspot API using Python
I have read the docs saying that to pass the value for a Hubspot date field you should format your Date as midnight UTC. However, I've had no luck doing so in Python. I assume I am just missing the magic Python incantation that will get the right result. Here is what I have:

```<code>    from pytz import timezone, utc
    from hubspot.crm.contacts import SimplePublicObject,

    created_dt = # datetime from sqlalchemy query
    utcdt = utc.localize(
        datetime(
            year=created_dt.year,
            month=created_dt.month,
            day=created_dt.day
            )
    )
    ts = int(utcdt.timestamp())
    props = SimplePublicObjectInput({"last_booking": str(ts)})
    return client.crm.companies.basic_api.update(
        hs_id, simple_public_object_input=props
    )
</code>```

this returns this error:

```<code>{"status":"error",
 "message":"Property values were not valid: [{\"isValid\":false,\"message\":\"1570233600 is at 4:10:33.600 UTC, not midnight!\"...
 }
</code>```

答:
did you try adding hours and minutes to your datetime call </p>

```<code>datetime(
    year=created_dt.year,
    month=created_dt.month,
    day=created_dt.day,
    hour=0,
    minute=0
)
</code>```

Body:
I have read the docs saying that to pass the value for a Hubspot date field you should format your Date as midnight UTC. However, I've had no luck doing so in Python. I assume I am just missing the magic Python incantation that will get the right result. Here is what I have:

    from pytz import timezone, utc
    from hubspot.crm.contacts import SimplePublicObject,

    created_dt = # datetime from sqlalchemy query
    utcdt = utc.localize(
        datetime(
            year=created_dt.year,
            month=created_dt.month,
            day=created_dt.day
            )
    )
    ts = int(utcdt.timestamp())
    props = SimplePublicObjectInput({"last_booking": str(ts)})
    return client.crm.companies.basic_api.update(
        hs_id, simple_public_object_input=props
    )

this returns this error:

{"status":"error",
 "message":"Property values were not valid: [{\"isValid\":false,\"message\":\"1570233600 is at 4:10:33.600 UTC, not midnight!\"...
 }

Body:
did you try adding hours and minutes to your datetime call

datetime(
    year=created_dt.year,
    month=created_dt.month,
    day=created_dt.day,
    hour=0,
    minute=0
)


问:
Getting below error when i am installing robot framework-appiumlibrary
```<code>D:\Users\SBhagyad>pip install robotframework-appiumlibrary
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Collecting robotframework-appiumlibrary
  Using cached robotframework_appiumlibrary-1.5.0.6-py2.py3-none-any.whl (33 kB)
Requirement already satisfied: robotframework>=2.6.0 in c:\python27\lib\site-packages (from robotframework-appiumlibrary) (3.1.2)
Requirement already satisfied: six>=1.10.0 in c:\python27\lib\site-packages (from robotframework-appiumlibrary) (1.14.0)
Collecting Appium-Python-Client>=0.28
  Using cached Appium-Python-Client-1.0.1.tar.gz (51 kB)
    ERROR: Command errored out with exit status 1:
     command: 'c:\python27\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'d:\\users\\sbhagyad\\appdata\\local\\temp\\1\\pip-install-qb7jnj\\Appium-Python-Client\\setup.py'"'"'; __file__='"'"'d:\\users\\sbhagyad\\appdata\\local\\temp\\1\\pip-install-qb7jnj\\Appium-Python-Client\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'd:\users\sbhagyad\appdata\local\temp\1\pip-pip-egg-info-dvpaun'
         cwd: d:\users\sbhagyad\appdata\local\temp\1\pip-install-qb7jnj\Appium-Python-Client\
    Complete output (8 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "d:\users\sbhagyad\appdata\local\temp\1\pip-install-qb7jnj\Appium-Python-Client\setup.py", line 19, in <module>
        from appium.common.helper import library_version
      File "appium\common\helper.py", line 20
        def extract_const_attributes(cls: type) -> Dict[str, Any]:
                                        ^
    SyntaxError: invalid syntax
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
</code>```

Error

Getting Error when i am trying to install robot framework-appiumlibrary CMD
Please help to provide any solution for this
I am Using Python 2.7 and Robot Framework 3.1.2 (Python 2.7.16 on win32)

答:
The library you're trying to use doesn't support Python 2.7, because Python 2.7 is old, insecure, and unsupported.

Upgrade to a supported Python version.

From the look of the error message, it uses type hinting, so you will need at least Python 3.5. However, 3.5 will also be end of life in September 2020, so it's worthwhile updating to the latest release, currently 3.8.

You should also use a virtual environment for each of your projects. This will let you easily use different versions of Python and other libraries on your system.

Body:
D:\Users\SBhagyad>pip install robotframework-appiumlibrary
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Collecting robotframework-appiumlibrary
  Using cached robotframework_appiumlibrary-1.5.0.6-py2.py3-none-any.whl (33 kB)
Requirement already satisfied: robotframework>=2.6.0 in c:\python27\lib\site-packages (from robotframework-appiumlibrary) (3.1.2)
Requirement already satisfied: six>=1.10.0 in c:\python27\lib\site-packages (from robotframework-appiumlibrary) (1.14.0)
Collecting Appium-Python-Client>=0.28
  Using cached Appium-Python-Client-1.0.1.tar.gz (51 kB)
    ERROR: Command errored out with exit status 1:
     command: 'c:\python27\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'d:\\users\\sbhagyad\\appdata\\local\\temp\\1\\pip-install-qb7jnj\\Appium-Python-Client\\setup.py'"'"'; __file__='"'"'d:\\users\\sbhagyad\\appdata\\local\\temp\\1\\pip-install-qb7jnj\\Appium-Python-Client\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'd:\users\sbhagyad\appdata\local\temp\1\pip-pip-egg-info-dvpaun'
         cwd: d:\users\sbhagyad\appdata\local\temp\1\pip-install-qb7jnj\Appium-Python-Client\
    Complete output (8 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "d:\users\sbhagyad\appdata\local\temp\1\pip-install-qb7jnj\Appium-Python-Client\setup.py", line 19, in <module>
        from appium.common.helper import library_version
      File "appium\common\helper.py", line 20
        def extract_const_attributes(cls: type) -> Dict[str, Any]:
                                        ^
    SyntaxError: invalid syntax
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Error

Getting Error when i am trying to install robot framework-appiumlibrary CMD
Please help to provide any solution for this
I am Using Python 2.7 and Robot Framework 3.1.2 (Python 2.7.16 on win32)


问:
Express res.sendFile not doing anything
I'm having some problems with express, I want to launch, by doing localhost:3000/timer -> timetimer.html, but it isn't working.

server.js:

```<code>var express = require('express');
var path = require('path');
var indexRouter = require('./routes/index');
var app = express();

app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use(function(req,res,next){
    res.status(404).send('Richiesta Sconosciuta');
    next();
});

app.listen(function () {
  console.log('Server in ascolto sulla porta 3000!');
});

module.exports = app;
</code>```

index.js:

```<code>var express = require('express');
var path = require('path');
var router = express.Router();

router.get('/principale', function(req,res){
    res.sendFile('/principale.html', {root: path.join(__dirname,'../public')});
});

router.get('/timer', function(req,res,next){
    //res.sendFile('public/timetimer.html', {root: path.join(__dirname,'../public')});
    res.sendFile(__dirname + "/timetimer.html")
});

module.exports = router;
</code>```

Structure of the folder:

The launch of the code works, i.e. it says that server.js is listening on 3000, but when I write localhost:3000/timer the browser is unable to reach the site

答:
you didn't specify port in app.listen

try:

```<code>app.listen(3000, function () {
  console.log('Server in ascolto sulla porta 3000!');
});
</code>```

Title: Express res.sendFile not doing anything

Body:
I'm having some problems with express, I want to launch, by doing localhost:3000/timer -> timetimer.html, but it isn't working.

server.js:

var express = require('express');
var path = require('path');
var indexRouter = require('./routes/index');
var app = express();

app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use(function(req,res,next){
    res.status(404).send('Richiesta Sconosciuta');
    next();
});

app.listen(function () {
  console.log('Server in ascolto sulla porta 3000!');
});

module.exports = app;

index.js:

var express = require('express');
var path = require('path');
var router = express.Router();

router.get('/principale', function(req,res){
    res.sendFile('/principale.html', {root: path.join(__dirname,'../public')});
});

router.get('/timer', function(req,res,next){
    //res.sendFile('public/timetimer.html', {root: path.join(__dirname,'../public')});
    res.sendFile(__dirname + "/timetimer.html")
});

module.exports = router;

Structure of the folder:

The launch of the code works, i.e. it says that server.js is listening on 3000, but when I write localhost:3000/timer the browser is unable to reach the site

Body:
you didn't specify port in app.listen

try:

app.listen(3000, function () {
  console.log('Server in ascolto sulla porta 3000!');
});


问:
Use a specific Scrapy downloader middleware per request
I use Crawlera as a IP rotating service to crawl a specific website which is banning my IP quickly but I have this problem only with one website out of a dozen.

As it is possible to register multiple middlewares for a Scrapy project, I wanted to know if it was possible to define the downloader middleware to use PER REQUEST.

So I could use my Crawlera's quota only for the problematic website and not for all my requests.

答:
One of possible solution - usage custom_settings spider attribute (and removing CrawleraMiddleware from project settings
(assuming that you have 1 spider per 1 website and CrawleraMiddleware enabled in project settings):

```<code>class ProblemSpider(scrapy.spider):

    custom_settings = {
        'DOWNLOADER_MIDDLEWARES' : {'scrapy_crawlera.CrawleraMiddleware': 610},
        'CRAWLERA_ENABLED' : True,
        'CRAWLERA_APIKEY' : '<API key>'}

    def parse(self, response):
....
</code>```

In this case CrawleraMiddleware will be used only in spiders where it defined in their custom_settings attribute.

Body:
One of possible solution - usage custom_settings spider attribute (and removing CrawleraMiddleware from project settings
(assuming that you have 1 spider per 1 website and CrawleraMiddleware enabled in project settings):

class ProblemSpider(scrapy.spider):

    custom_settings = {
        'DOWNLOADER_MIDDLEWARES' : {'scrapy_crawlera.CrawleraMiddleware': 610},
        'CRAWLERA_ENABLED' : True,
        'CRAWLERA_APIKEY' : '<API key>'}

    def parse(self, response):
....

In this case CrawleraMiddleware will be used only in spiders where it defined in their custom_settings attribute.


答:
__dirname is the directory name of the current module.

So it is the routes folder.

timetimer.html isn't in the routes folder, so you're passing it a non-existent path.

Title: Express res.sendFile not doing anything


问:
How do I optimize a "latest sales" sql query?
This query has become my nemesis over the past few years because I've never found a way to optimize it. Now my nemesis becomes your nemesis! :)

Consider the following table:

```<code>create table Sales (
  SaleId int identity(1,1) primary key,
  SalesmanId int not null,
  Amount smallmoney not null
)
</code>```

For the sake of argument, assume that this table has 10^100 rows (business is brisk) and therefore a table scan is out of the question.

Now we want to determine the SaleId of each salesman's most recent sale. Simple enough, right? Here is the query for that:

```<code>select
  SalesmanId,
  max(SaleId) SaleId
from Sales
group by Sales.SalesmanId
</code>```

When we run this query the query optimizer does a full table scan, which is expected because it has no way of knowing where each salesman's sales fall within the table. So let's help it out by adding the following index:

```<code>create unique nonclustered index IX_Sales on Sales
(
  SalesmanId asc,
  SaleId asc
)
</code>```

Now it should be trivial (for a human, anyway) to find the most recent values because we use the values of the first column of the index to identify all possible salesmen and the last entries of the second column to locate each salesman's latest sale. Unfortunately, the query optimizer still does an index seek over the entire index (all 10^100 rows) in this case, so it takes just as long.

Interestingly, if we write the query to find the latest sale for a given salesman,

```<code>select max(SaleId)
from Sales
where SalesmanId = 1
</code>```

the query optimizer uses an index seek on IX_Sales and gets it with one row of I/O. Even without IX_Sales, it does a clustered index scan that somehow gets it in one row of I/O (maybe using the table statistics?). But if we modify this to

```<code>select max(SaleId)
from Sales
where SalesmanId = 1
group by SalesmanId
</code>```

or

```<code>select max(SaleId)
from Sales
group by SalesmanId
having SalesmanId = 1
</code>```

we're back to a high row-count index seek over lots of rows (although less than if you'd omitted the filter altogether, again probably due to statistics).

So ... any ideas on how I could defeat my nemesis?

Update

Some have suggested joining against a table of possible SalesmanId values, like so

```<code>select Latest.*
from
(
  select
    SalesmanId,
    max(SaleId) SaleId
  from Sales
  group by SalesmanId
) Latest
inner join Salesmen on
  Salesmen.SalesmanId = Latest.SalesmanId
</code>```

I tested this idea but the query optimizer still chooses to do a full table scan.

答:
Think outside the box. Whenever a sale happens, update a column in the salesman table to refer to the most recent saleid. We all fall to the normalization trap. Sometimes its better to be redundant. See CQRS for taking this to an extreme.

Hope this helps.

Body:
This query has become my nemesis over the past few years because I've never found a way to optimize it. Now my nemesis becomes your nemesis! :)

Consider the following table:

create table Sales (
  SaleId int identity(1,1) primary key,
  SalesmanId int not null,
  Amount smallmoney not null
)

For the sake of argument, assume that this table has 10^100 rows (business is brisk) and therefore a table scan is out of the question.

Now we want to determine the SaleId of each salesman's most recent sale. Simple enough, right? Here is the query for that:

select
  SalesmanId,
  max(SaleId) SaleId
from Sales
group by Sales.SalesmanId

When we run this query the query optimizer does a full table scan, which is expected because it has no way of knowing where each salesman's sales fall within the table. So let's help it out by adding the following index:

create unique nonclustered index IX_Sales on Sales
(
  SalesmanId asc,
  SaleId asc
)

Now it should be trivial (for a human, anyway) to find the most recent values because we use the values of the first column of the index to identify all possible salesmen and the last entries of the second column to locate each salesman's latest sale. Unfortunately, the query optimizer still does an index seek over the entire index (all 10^100 rows) in this case, so it takes just as long.

Interestingly, if we write the query to find the latest sale for a given salesman,

select max(SaleId)
from Sales
where SalesmanId = 1

the query optimizer uses an index seek on IX_Sales and gets it with one row of I/O. Even without IX_Sales, it does a clustered index scan that somehow gets it in one row of I/O (maybe using the table statistics?). But if we modify this to

select max(SaleId)
from Sales
where SalesmanId = 1
group by SalesmanId

or

select max(SaleId)
from Sales
group by SalesmanId
having SalesmanId = 1

we're back to a high row-count index seek over lots of rows (although less than if you'd omitted the filter altogether, again probably due to statistics).

So ... any ideas on how I could defeat my nemesis?

Update

Some have suggested joining against a table of possible SalesmanId values, like so

select Latest.*
from
(
  select
    SalesmanId,
    max(SaleId) SaleId
  from Sales
  group by SalesmanId
) Latest
inner join Salesmen on
  Salesmen.SalesmanId = Latest.SalesmanId

I tested this idea but the query optimizer still chooses to do a full table scan.


问:
Is there a way to change windows mouse cursors to a custom one using python?
I want to be able to change the windows mouse cursors into a custom one (with the .ani or .cur extention) globally using a python script. Is there any package or module that can help me accomplish this?</p>

答:
Yes (in windows), in windows:   you need to change a registry key, then tell windows to load new cursor.

This code does the trick:

```<code>import os
import ctypes

path = r"HKEY_CURRENT_USER\Control Panel\Cursors"
cur_loc = r"path\to\cursor.cur"

os.system(f"""REG ADD "{path}" /v Arrow /t REG_EXPAND_SZ /d "{cur_loc}" /f""")

ctypes.windll.user32.SystemParametersInfoA(0x57)
</code>```

Body:
Yes (in windows), in windows:   you need to change a registry key, then tell windows to load new cursor.

This code does the trick:

import os
import ctypes

path = r"HKEY_CURRENT_USER\Control Panel\Cursors"
cur_loc = r"path\to\cursor.cur"

os.system(f"""REG ADD "{path}" /v Arrow /t REG_EXPAND_SZ /d "{cur_loc}" /f""")

ctypes.windll.user32.SystemParametersInfoA(0x57)


问:
Python re.findall organize list
I have a text file with entries like this:

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Body>
      <Applications_GetResponse xmlns="http://www.country.com">
         <Applications>
            <CS_Application>
               <Name>Spain</Name>
               <Key>2345364564</Key>
               <Status>NORMAL</Status>
               <Modules>
                  <CS_Module>
                     <Name>zaragoza</Name>
                     <Key>8743249725</Key>
                     <DevelopmentEffort>0</DevelopmentEffort>
                     <LogicalDBConnections/>
                  </CS_Module>
                  <CS_Module>
                     <Name>malaga</Name>
                     <Key>8743249725</Key>
                     <DevelopmentEffort>0</DevelopmentEffort>
                     <LogicalDBConnections/>
                  </CS_Module>
               </Modules>
               <CreatedBy>7</CreatedBy>
            </CS_Application>
            <CS_Application>
               <Name>UK</Name>
               <Key>2345364564</Key>
               <Status>NORMAL</Status>
               <Modules>
                  <CS_Module>
                     <Name>london</Name>
                     <Key>8743249725</Key>
                     <DevelopmentEffort>0</DevelopmentEffort>
                     <LogicalDBConnections/>
                  </CS_Module>
                  <CS_Module>
                     <Name>liverpool</Name>
                     <Key>8743249725</Key>
                     <DevelopmentEffort>0</DevelopmentEffort>
                     <LogicalDBConnections/>
                  </CS_Module>
               </Modules>
               <CreatedBy>7</CreatedBy>
            </CS_Application>
        </Applications>
      </Applications_GetResponse>
   </soap:Body>
</soap:Envelope>```
</div>
</div>
</p>

<p>I would like to analyze it and obtain the name of the country in the sequence of the cities.</p>

<p>I tried some things with python re.finall, but I didn't get anything like it</p>

```print("HERE APPLICATIONS")
applications = re.findall('<CS_Application><Name>(.*?)</Name>', response_apply.text)
print(applications)
print("HERE MODULES")
modules = re.findall('<CS_Module><Name>(.*?)</Name>', response_apply.text)
print(modules)
```

<p>return:</p>

```host-10$ sudo python3 capture.py
HERE APPLICATIONS
['Spain', 'UK']
HERE MODULES
['zaragoza', 'malaga', 'london', 'liverpool']
```

<p>The expected result is, I would like the result to be like this:</p>

```HERE
The Country: Spain - Cities: zaragoza,malaga
The Country: UK - Cities: london,liverpool
```

答:
Regex is not good to parse xml. Better use xml parser..
If you want regex solution then hope below code help you.</p>

```<code>import re

s = """\n<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">\n   <soap:Body>\n      <Applications_GetResponse xmlns="http://www.country.com">\n         <Applications>\n            <CS_Application>\n               <Name>Spain</Name>\n               <Key>2345364564</Key>\n               <Status>NORMAL</Status>\n               <Modules>\n                  <CS_Module>\n                     <Name>zaragoza</Name>\n                     <Key>8743249725</Key>\n                     <DevelopmentEffort>0</DevelopmentEffort>\n                     <LogicalDBConnections/>\n                  </CS_Module>\n                  <CS_Module>\n                     <Name>malaga</Name>\n                     <Key>8743249725</Key>\n                     <DevelopmentEffort>0</DevelopmentEffort>\n                     <LogicalDBConnections/>\n                  </CS_Module>\n               </Modules>\n               <CreatedBy>7</CreatedBy>\n            </CS_Application>\n            <CS_Application>\n               <Name>UK</Name>\n               <Key>2345364564</Key>\n               <Status>NORMAL</Status>\n               <Modules>\n                  <CS_Module>\n                     <Name>london</Name>\n                     <Key>8743249725</Key>\n                     <DevelopmentEffort>0</DevelopmentEffort>\n                     <LogicalDBConnections/>\n                  </CS_Module>\n                  <CS_Module>\n                     <Name>liverpool</Name>\n                     <Key>8743249725</Key>\n                     <DevelopmentEffort>0</DevelopmentEffort>\n                     <LogicalDBConnections/>\n                  </CS_Module>\n               </Modules>\n               <CreatedBy>7</CreatedBy>\n            </CS_Application>\n        </Applications>\n      </Applications_GetResponse>\n   </soap:Body>\n</soap:Envelope>\n"""
pattern1 = re.compile(r'<CS_Application>([\s\S]*?)</CS_Application>')
pattern2 = re.compile(r'<Name>(.*)?</Name>')

for m in re.finditer(pattern1, s):
    ss = m.group(1)
    res = []
    for mm in re.finditer(pattern2, ss):
        res.append(mm.group(1))
    print("The Country: "+res[0]+" - Cities: "+",".join(res[1:len(res)]))
</code>```

Title: Python re.findall organize list

Body:
I have a text file with entries like this:

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <soap:Body>
      <Applications_GetResponse xmlns="http://www.country.com">
         <Applications>
            <CS_Application>
               <Name>Spain</Name>
               <Key>2345364564</Key>
               <Status>NORMAL</Status>
               <Modules>
                  <CS_Module>
                     <Name>zaragoza</Name>
                     <Key>8743249725</Key>
                     <DevelopmentEffort>0</DevelopmentEffort>
                     <LogicalDBConnections/>
                  </CS_Module>
                  <CS_Module>
                     <Name>malaga</Name>
                     <Key>8743249725</Key>
                     <DevelopmentEffort>0</DevelopmentEffort>
                     <LogicalDBConnections/>
                  </CS_Module>
               </Modules>
               <CreatedBy>7</CreatedBy>
            </CS_Application>
            <CS_Application>
               <Name>UK</Name>
               <Key>2345364564</Key>
               <Status>NORMAL</Status>
               <Modules>
                  <CS_Module>
                     <Name>london</Name>
                     <Key>8743249725</Key>
                     <DevelopmentEffort>0</DevelopmentEffort>
                     <LogicalDBConnections/>
                  </CS_Module>
                  <CS_Module>
                     <Name>liverpool</Name>
                     <Key>8743249725</Key>
                     <DevelopmentEffort>0</DevelopmentEffort>
                     <LogicalDBConnections/>
                  </CS_Module>
               </Modules>
               <CreatedBy>7</CreatedBy>
            </CS_Application>
        </Applications>
      </Applications_GetResponse>
   </soap:Body>
</soap:Envelope>

I would like to analyze it and obtain the name of the country in the sequence of the cities.

I tried some things with python re.finall, but I didn't get anything like it

print("HERE APPLICATIONS")
applications = re.findall('<CS_Application><Name>(.*?)</Name>', response_apply.text)
print(applications)
print("HERE MODULES")
modules = re.findall('<CS_Module><Name>(.*?)</Name>', response_apply.text)
print(modules)

return:

host-10$ sudo python3 capture.py
HERE APPLICATIONS
['Spain', 'UK']
HERE MODULES
['zaragoza', 'malaga', 'london', 'liverpool']

The expected result is, I would like the result to be like this:

HERE
The Country: Spain - Cities: zaragoza,malaga
The Country: UK - Cities: london,liverpool

Body:
Regex is not good to parse xml. Better use xml parser..
If you want regex solution then hope below code help you.

import re

s = """\n<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">\n   <soap:Body>\n      <Applications_GetResponse xmlns="http://www.country.com">\n         <Applications>\n            <CS_Application>\n               <Name>Spain</Name>\n               <Key>2345364564</Key>\n               <Status>NORMAL</Status>\n               <Modules>\n                  <CS_Module>\n                     <Name>zaragoza</Name>\n                     <Key>8743249725</Key>\n                     <DevelopmentEffort>0</DevelopmentEffort>\n                     <LogicalDBConnections/>\n                  </CS_Module>\n                  <CS_Module>\n                     <Name>malaga</Name>\n                     <Key>8743249725</Key>\n                     <DevelopmentEffort>0</DevelopmentEffort>\n                     <LogicalDBConnections/>\n                  </CS_Module>\n               </Modules>\n               <CreatedBy>7</CreatedBy>\n            </CS_Application>\n            <CS_Application>\n               <Name>UK</Name>\n               <Key>2345364564</Key>\n               <Status>NORMAL</Status>\n               <Modules>\n                  <CS_Module>\n                     <Name>london</Name>\n                     <Key>8743249725</Key>\n                     <DevelopmentEffort>0</DevelopmentEffort>\n                     <LogicalDBConnections/>\n                  </CS_Module>\n                  <CS_Module>\n                     <Name>liverpool</Name>\n                     <Key>8743249725</Key>\n                     <DevelopmentEffort>0</DevelopmentEffort>\n                     <LogicalDBConnections/>\n                  </CS_Module>\n               </Modules>\n               <CreatedBy>7</CreatedBy>\n            </CS_Application>\n        </Applications>\n      </Applications_GetResponse>\n   </soap:Body>\n</soap:Envelope>\n"""
pattern1 = re.compile(r'<CS_Application>([\s\S]*?)</CS_Application>')
pattern2 = re.compile(r'<Name>(.*)?</Name>')

for m in re.finditer(pattern1, s):
    ss = m.group(1)
    res = []
    for mm in re.finditer(pattern2, ss):
        res.append(mm.group(1))
    print("The Country: "+res[0]+" - Cities: "+",".join(res[1:len(res)]))