问:
R shiny dynamic filtering
New R shiny user here..
I have 6 filters for a datatable and want to be able to have dynamic filters working in any direction. For instance: I have filters A, B, C, D, E, F. If I filter at A or B or C etc, I want all the other filters dynamically update to show unique() of filtered datatable and so on if I move through the filters in any direction.

I tried a bunch of different techniques and they all didn't seem to work well. Eventually I bit the bullet and wrote the most verbose code to account for all possible combinations of filter directions. So for example:

First in ui.R I set up selectInput for filters A, B, C, D, E, F

Then in server.R I easily filter the table

```<code>tt <- reactive({
    dt <- mytable
    dt <- dt[,input$ColumnsToShow2,drop=FALSE]
if (input$A != "All") {
  dt <- dt[dt$A == input$A,]
}

if (input$B != "All") {
  dt <- dt[dt$B == input$B,]
}
if (input$C != "All") {
  dt <- dt[dt$C == input$C,]
}
if (input$D != "All") {
  dt <- dT[dt$D == input$D,]
}
if (input$E != "All") {
  dt <- dt[dt$E == input$E,]
}
if (input$F != "All") {
  dt <- dt[dt$F == input$F,]
}
    dt
})
</code>```

and then I go -

```<code>observe({
#One filter is used:

If A!="All" && B && C && D && E && F are all =="All", then UpdateSelectInput filters B,C,D,E,F

If B!="All" and A && C && D && E && F are all == "All", then
UpdateSelectInput filters A,C,D,E,F

If C and so on, you get the logic

#Two filters are used:
If A!="All" && B!="All" && C && D && E && F are all == "All", then
UpdateSelectInput filters C, D, E, F

if A!="All" && C!="All" && B && D && E && F are all == "All", then
UpdateSelectInput filters B, D, E, F

#etc all the way through

if E!="All" && F!="All" && A && B && C && D are all == "All", then
UpdateSelectInput filters A, B, C, D.

#three filters are used...all the way through 5 filters are used

)}
</code>```

You get the point now. I'm pretty sure you can set up a similar example to work with.

NB: When I tried to only use just 6 if != "All" without the additional "&&" conditions for the boolean (like I did to filter the datatable itself), it did not work.

I have the filters working perfectly this way like I want them, but my gut feeling is that I'm working too hard at this.

Thanks for reading all this and for your help!!

Addendum - here's an example that I was expecting to work but doesn't:

```<code>data <- structure(list(Country.Name = structure(c(1L, 1L, 1L, 1L, 1L,
                                                     1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L
), .Label = c("High income", "Low income", "Mid income"), class =
"factor"),
Country.Code = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
                       2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L,
3L), .Label = c("HIC",

"LIC", "MIC"), class = "factor"), Indicator.Name = structure(c(10L,

9L, 11L, 8L, 6L, 4L, 7L, 5L, 3L, 2L, 18L, 19L, 1L, 17L, 16L,

12L, 20L, 13L, 14L, 15L, 3L), .Label = c("2005 PPP conversion factor,
GDP (LCU per international $)",

"2005 PPP conversion factor, private consumption (LCU per international
$)",

"Adequacy of social protection and labor programs (% of total welfare
of beneficiary households)",

"Adequacy of unemployment benefits and ALMP (% of total welfare of
beneficiary households)",

"Benefit incidence of social protection and labor programs to poorest
quintile (% of total SPL benefits)",

"Benefit incidence of unemployment benefits and ALMP to poorest
quintile (% of total U/ALMP benefits)",

"Coverage of social protection and labor programs (% of population)",

"Coverage of unemployment benefits and ALMP (% of population)",

"Coverage of unemployment benefits and ALMP in 2nd quintile (% of
population)",

"Coverage of unemployment benefits and ALMP in 3rd quintile (% of
population)",

"Coverage of unemployment benefits and ALMP in poorest quintile (% of
population)",

"DEC alternative conversion factor (LCU per US$)", "Net secondary
income (Net current transfers from abroad) (constant LCU)",

"Net secondary income (Net current transfers from abroad) (current
LCU)",

"Net secondary income (Net current transfers from abroad) (current
US$)",

"Official exchange rate (LCU per US$, period average)", "PPP conversion
factor, GDP (LCU per international $)",

"PPP conversion factor, private consumption (LCU per international $)",

"Price level ratio of PPP conversion factor (GDP) to market exchange
rate",

"Terms of trade adjustment (constant LCU)"), class = "factor"),
Indicator.Code = structure(c(21L, 20L, 19L, 18L, 17L, 16L,
                         15L, 14L, 13L, 12L, 11L, 10L, 9L, 8L, 7L, 6L,
5L, 4L, 3L,
                         2L, 1L), .Label = c("NY.GSR.NFCY.CN",
"NY.GSR.NFCY.KN", "NY.TAX.NIND.CD",
                                             "NY.TAX.NIND.CN",
"NY.TAX.NIND.KN", "NY.TRF.NCTR.CD", "NY.TRF.NCTR.CN",
                                             "NY.TRF.NCTR.KN",
"NY.TTF.GNFS.KN", "PA.NUS.ATLS", "PA.NUS.FCRF",
                                             "PA.NUS.PPP",
"PA.NUS.PPP.05", "PA.NUS.PPPC.RF", "per_allsp.cov_pop_tot",

"per_lm_alllm.adq_pop_tot", "per_lm_alllm.ben_q1_tot",
"per_lm_alllm.cov_pop_tot",
                                             "per_lm_alllm.cov_q1_tot",
"per_lm_alllm.cov_q2_tot", "per_lm_alllm.cov_q3_tot"
                         ), class = "factor"), Source.no =
structure(c(3L, 3L, 3L,

3L, 3L, 3L, 3L, 3L, 3L, 8L, 1L, 7L, 8L, 1L, 5L, 4L, 9L, 6L,

2L, 10L, 11L), .Label = c(" for Economic Co-operation and Development
(OECD).",

" nonresidents. Data are in current local currency.", "es include both
direct and indirect beneficiaries.",

"expressed in local currency units per U.S. dollar.", "local currency
units relative to the U.S. dollar).",

"nonresidents. Data are in constant local currency.", "onversion
factors are based on the 2011 ICP round.",

"rapolated estimates based on the latest ICP round.", "stant prices.
Data are in constant local currency.",

"to nonresidents. Data are in current U.S. dollars.", "to producers.
Data are in constant local currency."

), class = "factor"), Source.organization = structure(c(4L,

4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 2L, 5L,

3L, 3L, 3L, 3L, 3L), .Label = c("d Bank, International Comparison
Program database.",

"Monetary Fund, International Financial Statistics.", "ounts data, and
OECD National Accounts data files.",

"sehold surveys. (datatopics.worldbank.org/aspire/)", "stics,
supplemented by World Bank staff estimates."

), class = "factor")), .Names = c("Country.Name", "Country.Code",

"Indicator.Name", "Indicator.Code", "Source.no", "Source.organization"

), class = "data.frame", row.names = c(NA, -21L))

shinyApp(
  ui = fluidPage(

    fluidRow(
      column(2,
             selectInput("CN",
                         "Country name:",
                         c("All",
                           unique(as.character(data$Country.Name))))
      ),
      column(2,
             selectInput("CC",
                         "Country code:",
                         c("All",
                           unique(as.character(data$Country.Code))))
      ),
      column(2,
             selectInput("IN",
                         "Indicator name:",
                         c("All",
                           unique(as.character(data$Indicator.Name))))
      ),
      column(2,
             selectInput("IC",
                         "Indicator Code:",
                         c("All",
                           unique(as.character(data$Indicator.Code))))
      ),
      column(2,
             selectInput("SN",
                         "Source no:",
                         c("All",
                           unique(as.character(data$Source.no))))
      ),
      column(2,
             selectInput("SO",
                         "Source org:",
                         c("All",
                           unique(as.character(data$Source.organization))))
      )

    ),

    fluidRow(
      div(DT::dataTableOutput("table1"),style="font-size: 100%",tags$head(tags$style(type="text/css", "#table table td {line-height:50%;}")) )
    )
  ),
  server = function(input, output,session) {

    table_one <- reactive({
      if (input$CN != "All") {
        data <- data[data$Country.Name == input$CN,]
      }
      if (input$CC != "All") {
        data <- data[data$Country.Code == input$CC,]
      }
      if (input$IN != "All") {
        data <- data[data$Indicator.Name == input$IN,]
      }
      if (input$IC != "All") {
        data <- data[data$Indicator.Code == input$IC,]
      }
      if (input$SN != "All") {
        data <- data[data$Source.no == input$SN,]
      }
      if (input$SO != "All") {
        data <- data[data$Source.organization == input$SO,]
      }
      data
    })

    output$table1 <- DT::renderDataTable(DT::datatable({
      table_one()
    },rownames = FALSE,
    options = list(scrollX=TRUE,
                   autoWidth = TRUE,
                   columnDefs = list(list(width = '150px', targets = "_all")))

    ))

    #filter code begin
    #if all filters are "all"
    observe({
      if (input$CN=="All"&&input$CC=="All"&&input$IN=="All"&&input$IC=="All"&&input$SN=="All"&&input$SO=="All"){
        updateSelectInput(session,"CN",choices = c("All",unique(as.character(data$Country.Name))))
        updateSelectInput(session,"CC",choices = c("All",unique(as.character(data$Country.Code))))
        updateSelectInput(session,"IN",choices = c("All",unique(as.character(data$Indicator.Name))))
        updateSelectInput(session,"IC",choices = c("All",unique(as.character(data$Indicator.Code))))
        updateSelectInput(session,"SN",choices = c("All",unique(as.character(data$Source.no))))
        updateSelectInput(session,"SO",choices = c("All",unique(as.character(data$Source.organization))))
      }

      #otherwise
      if (input$CN!="All"){
        #updateSelectInput(session,"CN",choices = c("All",unique(as.character(table_one()$Country.Name))))
        updateSelectInput(session,"CC",choices = c("All",unique(as.character(table_one()$Country.Code))))
        updateSelectInput(session,"IN",choices = c("All",unique(as.character(table_one()$Indicator.Name))))
        updateSelectInput(session,"IC",choices = c("All",unique(as.character(table_one()$Indicator.Code))))
        updateSelectInput(session,"SN",choices = c("All",unique(as.character(table_one()$Source.no))))
        updateSelectInput(session,"SO",choices = c("All",unique(as.character(table_one()$Source.organization))))
      }
      if (input$CC!="All"){
        updateSelectInput(session,"CN",choices = c("All",unique(as.character(table_one()$Country.Name))))
        #updateSelectInput(session,"CC",choices = c("All",unique(as.character(table_one()$Country.Code))))
        updateSelectInput(session,"IN",choices = c("All",unique(as.character(table_one()$Indicator.Name))))
        updateSelectInput(session,"IC",choices = c("All",unique(as.character(table_one()$Indicator.Code))))
        updateSelectInput(session,"SN",choices = c("All",unique(as.character(table_one()$Source.no))))
        updateSelectInput(session,"SO",choices = c("All",unique(as.character(table_one()$Source.organization))))
      }
      if (input$IN!="All"){
        updateSelectInput(session,"CN",choices = c("All",unique(as.character(table_one()$Country.Name))))
        updateSelectInput(session,"CC",choices = c("All",unique(as.character(table_one()$Country.Code))))
        #updateSelectInput(session,"IN",choices = c("All",unique(as.character(table_one()$Indicator.Name))))
        updateSelectInput(session,"IC",choices = c("All",unique(as.character(table_one()$Indicator.Code))))
        updateSelectInput(session,"SN",choices = c("All",unique(as.character(table_one()$Source.no))))
        updateSelectInput(session,"SO",choices = c("All",unique(as.character(table_one()$Source.organization))))
      }
      if (input$IC!="All"){
        updateSelectInput(session,"CN",choices = c("All",unique(as.character(table_one()$Country.Name))))
        updateSelectInput(session,"CC",choices = c("All",unique(as.character(table_one()$Country.Code))))
        updateSelectInput(session,"IN",choices = c("All",unique(as.character(table_one()$Indicator.Name))))
        #updateSelectInput(session,"IC",choices = c("All",unique(as.character(table_one()$Indicator.Code))))
        updateSelectInput(session,"SN",choices = c("All",unique(as.character(table_one()$Source.no))))
        updateSelectInput(session,"SO",choices = c("All",unique(as.character(table_one()$Source.organization))))
      }
      if (input$SN!="All"){
        updateSelectInput(session,"CN",choices = c("All",unique(as.character(table_one()$Country.Name))))
        updateSelectInput(session,"CC",choices = c("All",unique(as.character(table_one()$Country.Code))))
        updateSelectInput(session,"IN",choices = c("All",unique(as.character(table_one()$Indicator.Name))))
        updateSelectInput(session,"IC",choices = c("All",unique(as.character(table_one()$Indicator.Code))))
        #updateSelectInput(session,"SN",choices = c("All",unique(as.character(table_one()$Source.no))))
        updateSelectInput(session,"SO",choices = c("All",unique(as.character(table_one()$Source.organization))))
      }
      if (input$SO!="All"){
        updateSelectInput(session,"CN",choices = c("All",unique(as.character(table_one()$Country.Name))))
        updateSelectInput(session,"CC",choices = c("All",unique(as.character(table_one()$Country.Code))))
        updateSelectInput(session,"IN",choices = c("All",unique(as.character(table_one()$Indicator.Name))))
        updateSelectInput(session,"IC",choices = c("All",unique(as.character(table_one()$Indicator.Code))))
        updateSelectInput(session,"SN",choices = c("All",unique(as.character(table_one()$Source.no))))
        #updateSelectInput(session,"SO",choices = c("All",unique(as.character(table_one()$Source.organization))))
      }

    })

  }
)
</code>```

答:
Using the filter() function and piping from dplyr might be the answer. I used it inside of a renderPlot({}) server function, and it worked for me (I didn't try it in an observe function).

```<code>data = data %>% filter(if(input$CN == 'ALL'){Country.Name %in% c("countryname_1", "countryname_2",...,"countryname_n")} else {Country.Name == input$CN}) %>%
  filter(if(input$CC == 'ALL'){Country.Code %in% c("countrycode_1",..,"countrycode_n")} else {Country.Code == input$CC}) %>%
</code>```

and so on for each filter

There is probably a better way to get the unfiltered version in case you have a lot of countries than this part inside the if statement:  Country.Code %in% c("countrycode_1",..,"countrycode_n") , but the if/else nested inside the filter, and filter statements for each attribute connected with %>% piping worked for me (and saved a LOT of space).

These links might help too:
filtering values

using filter with if/else statement

*edit update: I ended up put this filter function configuration in the observe function and it works great, seems more organized too

Title: R shiny dynamic filtering

Body:
New R shiny user here..
I have 6 filters for a datatable and want to be able to have dynamic filters working in any direction. For instance: I have filters A, B, C, D, E, F. If I filter at A or B or C etc, I want all the other filters dynamically update to show unique() of filtered datatable and so on if I move through the filters in any direction.

I tried a bunch of different techniques and they all didn't seem to work well. Eventually I bit the bullet and wrote the most verbose code to account for all possible combinations of filter directions. So for example:

First in ui.R I set up selectInput for filters A, B, C, D, E, F

Then in server.R I easily filter the table

tt <- reactive({
    dt <- mytable
    dt <- dt[,input$ColumnsToShow2,drop=FALSE]
if (input$A != "All") {
  dt <- dt[dt$A == input$A,]
}

if (input$B != "All") {
  dt <- dt[dt$B == input$B,]
}
if (input$C != "All") {
  dt <- dt[dt$C == input$C,]
}
if (input$D != "All") {
  dt <- dT[dt$D == input$D,]
}
if (input$E != "All") {
  dt <- dt[dt$E == input$E,]
}
if (input$F != "All") {
  dt <- dt[dt$F == input$F,]
}
    dt
})

and then I go -

observe({
#One filter is used:

If A!="All" && B && C && D && E && F are all =="All", then UpdateSelectInput filters B,C,D,E,F

If B!="All" and A && C && D && E && F are all == "All", then
UpdateSelectInput filters A,C,D,E,F

If C and so on, you get the logic

#Two filters are used:
If A!="All" && B!="All" && C && D && E && F are all == "All", then
UpdateSelectInput filters C, D, E, F

if A!="All" && C!="All" && B && D && E && F are all == "All", then
UpdateSelectInput filters B, D, E, F

#etc all the way through

if E!="All" && F!="All" && A && B && C && D are all == "All", then
UpdateSelectInput filters A, B, C, D.

#three filters are used...all the way through 5 filters are used

)}

You get the point now. I'm pretty sure you can set up a similar example to work with.

NB: When I tried to only use just 6 if != "All" without the additional "&&" conditions for the boolean (like I did to filter the datatable itself), it did not work.

I have the filters working perfectly this way like I want them, but my gut feeling is that I'm working too hard at this.

Thanks for reading all this and for your help!!

Addendum - here's an example that I was expecting to work but doesn't:

data <- structure(list(Country.Name = structure(c(1L, 1L, 1L, 1L, 1L,
                                                     1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L
), .Label = c("High income", "Low income", "Mid income"), class =
"factor"),
Country.Code = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
                       2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L,
3L), .Label = c("HIC",

"LIC", "MIC"), class = "factor"), Indicator.Name = structure(c(10L,

9L, 11L, 8L, 6L, 4L, 7L, 5L, 3L, 2L, 18L, 19L, 1L, 17L, 16L,

12L, 20L, 13L, 14L, 15L, 3L), .Label = c("2005 PPP conversion factor,
GDP (LCU per international $)",

"2005 PPP conversion factor, private consumption (LCU per international
$)",

"Adequacy of social protection and labor programs (% of total welfare
of beneficiary households)",

"Adequacy of unemployment benefits and ALMP (% of total welfare of
beneficiary households)",

"Benefit incidence of social protection and labor programs to poorest
quintile (% of total SPL benefits)",

"Benefit incidence of unemployment benefits and ALMP to poorest
quintile (% of total U/ALMP benefits)",

"Coverage of social protection and labor programs (% of population)",

"Coverage of unemployment benefits and ALMP (% of population)",

"Coverage of unemployment benefits and ALMP in 2nd quintile (% of
population)",

"Coverage of unemployment benefits and ALMP in 3rd quintile (% of
population)",

"Coverage of unemployment benefits and ALMP in poorest quintile (% of
population)",

"DEC alternative conversion factor (LCU per US$)", "Net secondary
income (Net current transfers from abroad) (constant LCU)",

"Net secondary income (Net current transfers from abroad) (current
LCU)",

"Net secondary income (Net current transfers from abroad) (current
US$)",

"Official exchange rate (LCU per US$, period average)", "PPP conversion
factor, GDP (LCU per international $)",

"PPP conversion factor, private consumption (LCU per international $)",

"Price level ratio of PPP conversion factor (GDP) to market exchange
rate",

"Terms of trade adjustment (constant LCU)"), class = "factor"),
Indicator.Code = structure(c(21L, 20L, 19L, 18L, 17L, 16L,
                         15L, 14L, 13L, 12L, 11L, 10L, 9L, 8L, 7L, 6L,
5L, 4L, 3L,
                         2L, 1L), .Label = c("NY.GSR.NFCY.CN",
"NY.GSR.NFCY.KN", "NY.TAX.NIND.CD",
                                             "NY.TAX.NIND.CN",
"NY.TAX.NIND.KN", "NY.TRF.NCTR.CD", "NY.TRF.NCTR.CN",
                                             "NY.TRF.NCTR.KN",
"NY.TTF.GNFS.KN", "PA.NUS.ATLS", "PA.NUS.FCRF",
                                             "PA.NUS.PPP",
"PA.NUS.PPP.05", "PA.NUS.PPPC.RF", "per_allsp.cov_pop_tot",

"per_lm_alllm.adq_pop_tot", "per_lm_alllm.ben_q1_tot",
"per_lm_alllm.cov_pop_tot",
                                             "per_lm_alllm.cov_q1_tot",
"per_lm_alllm.cov_q2_tot", "per_lm_alllm.cov_q3_tot"
                         ), class = "factor"), Source.no =
structure(c(3L, 3L, 3L,

3L, 3L, 3L, 3L, 3L, 3L, 8L, 1L, 7L, 8L, 1L, 5L, 4L, 9L, 6L,

2L, 10L, 11L), .Label = c(" for Economic Co-operation and Development
(OECD).",

" nonresidents. Data are in current local currency.", "es include both
direct and indirect beneficiaries.",

"expressed in local currency units per U.S. dollar.", "local currency
units relative to the U.S. dollar).",

"nonresidents. Data are in constant local currency.", "onversion
factors are based on the 2011 ICP round.",

"rapolated estimates based on the latest ICP round.", "stant prices.
Data are in constant local currency.",

"to nonresidents. Data are in current U.S. dollars.", "to producers.
Data are in constant local currency."

), class = "factor"), Source.organization = structure(c(4L,

4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 2L, 5L,

3L, 3L, 3L, 3L, 3L), .Label = c("d Bank, International Comparison
Program database.",

"Monetary Fund, International Financial Statistics.", "ounts data, and
OECD National Accounts data files.",

"sehold surveys. (datatopics.worldbank.org/aspire/)", "stics,
supplemented by World Bank staff estimates."

), class = "factor")), .Names = c("Country.Name", "Country.Code",

"Indicator.Name", "Indicator.Code", "Source.no", "Source.organization"

), class = "data.frame", row.names = c(NA, -21L))

shinyApp(
  ui = fluidPage(

    fluidRow(
      column(2,
             selectInput("CN",
                         "Country name:",
                         c("All",
                           unique(as.character(data$Country.Name))))
      ),
      column(2,
             selectInput("CC",
                         "Country code:",
                         c("All",
                           unique(as.character(data$Country.Code))))
      ),
      column(2,
             selectInput("IN",
                         "Indicator name:",
                         c("All",
                           unique(as.character(data$Indicator.Name))))
      ),
      column(2,
             selectInput("IC",
                         "Indicator Code:",
                         c("All",
                           unique(as.character(data$Indicator.Code))))
      ),
      column(2,
             selectInput("SN",
                         "Source no:",
                         c("All",
                           unique(as.character(data$Source.no))))
      ),
      column(2,
             selectInput("SO",
                         "Source org:",
                         c("All",
                           unique(as.character(data$Source.organization))))
      )

    ),

    fluidRow(
      div(DT::dataTableOutput("table1"),style="font-size: 100%",tags$head(tags$style(type="text/css", "#table table td {line-height:50%;}")) )
    )
  ),
  server = function(input, output,session) {

    table_one <- reactive({
      if (input$CN != "All") {
        data <- data[data$Country.Name == input$CN,]
      }
      if (input$CC != "All") {
        data <- data[data$Country.Code == input$CC,]
      }
      if (input$IN != "All") {
        data <- data[data$Indicator.Name == input$IN,]
      }
      if (input$IC != "All") {
        data <- data[data$Indicator.Code == input$IC,]
      }
      if (input$SN != "All") {
        data <- data[data$Source.no == input$SN,]
      }
      if (input$SO != "All") {
        data <- data[data$Source.organization == input$SO,]
      }
      data
    })

    output$table1 <- DT::renderDataTable(DT::datatable({
      table_one()
    },rownames = FALSE,
    options = list(scrollX=TRUE,
                   autoWidth = TRUE,
                   columnDefs = list(list(width = '150px', targets = "_all")))

    ))

    #filter code begin
    #if all filters are "all"
    observe({
      if (input$CN=="All"&&input$CC=="All"&&input$IN=="All"&&input$IC=="All"&&input$SN=="All"&&input$SO=="All"){
        updateSelectInput(session,"CN",choices = c("All",unique(as.character(data$Country.Name))))
        updateSelectInput(session,"CC",choices = c("All",unique(as.character(data$Country.Code))))
        updateSelectInput(session,"IN",choices = c("All",unique(as.character(data$Indicator.Name))))
        updateSelectInput(session,"IC",choices = c("All",unique(as.character(data$Indicator.Code))))
        updateSelectInput(session,"SN",choices = c("All",unique(as.character(data$Source.no))))
        updateSelectInput(session,"SO",choices = c("All",unique(as.character(data$Source.organization))))
      }

      #otherwise
      if (input$CN!="All"){
        #updateSelectInput(session,"CN",choices = c("All",unique(as.character(table_one()$Country.Name))))
        updateSelectInput(session,"CC",choices = c("All",unique(as.character(table_one()$Country.Code))))
        updateSelectInput(session,"IN",choices = c("All",unique(as.character(table_one()$Indicator.Name))))
        updateSelectInput(session,"IC",choices = c("All",unique(as.character(table_one()$Indicator.Code))))
        updateSelectInput(session,"SN",choices = c("All",unique(as.character(table_one()$Source.no))))
        updateSelectInput(session,"SO",choices = c("All",unique(as.character(table_one()$Source.organization))))
      }
      if (input$CC!="All"){
        updateSelectInput(session,"CN",choices = c("All",unique(as.character(table_one()$Country.Name))))
        #updateSelectInput(session,"CC",choices = c("All",unique(as.character(table_one()$Country.Code))))
        updateSelectInput(session,"IN",choices = c("All",unique(as.character(table_one()$Indicator.Name))))
        updateSelectInput(session,"IC",choices = c("All",unique(as.character(table_one()$Indicator.Code))))
        updateSelectInput(session,"SN",choices = c("All",unique(as.character(table_one()$Source.no))))
        updateSelectInput(session,"SO",choices = c("All",unique(as.character(table_one()$Source.organization))))
      }
      if (input$IN!="All"){
        updateSelectInput(session,"CN",choices = c("All",unique(as.character(table_one()$Country.Name))))
        updateSelectInput(session,"CC",choices = c("All",unique(as.character(table_one()$Country.Code))))
        #updateSelectInput(session,"IN",choices = c("All",unique(as.character(table_one()$Indicator.Name))))
        updateSelectInput(session,"IC",choices = c("All",unique(as.character(table_one()$Indicator.Code))))
        updateSelectInput(session,"SN",choices = c("All",unique(as.character(table_one()$Source.no))))
        updateSelectInput(session,"SO",choices = c("All",unique(as.character(table_one()$Source.organization))))
      }
      if (input$IC!="All"){
        updateSelectInput(session,"CN",choices = c("All",unique(as.character(table_one()$Country.Name))))
        updateSelectInput(session,"CC",choices = c("All",unique(as.character(table_one()$Country.Code))))
        updateSelectInput(session,"IN",choices = c("All",unique(as.character(table_one()$Indicator.Name))))
        #updateSelectInput(session,"IC",choices = c("All",unique(as.character(table_one()$Indicator.Code))))
        updateSelectInput(session,"SN",choices = c("All",unique(as.character(table_one()$Source.no))))
        updateSelectInput(session,"SO",choices = c("All",unique(as.character(table_one()$Source.organization))))
      }
      if (input$SN!="All"){
        updateSelectInput(session,"CN",choices = c("All",unique(as.character(table_one()$Country.Name))))
        updateSelectInput(session,"CC",choices = c("All",unique(as.character(table_one()$Country.Code))))
        updateSelectInput(session,"IN",choices = c("All",unique(as.character(table_one()$Indicator.Name))))
        updateSelectInput(session,"IC",choices = c("All",unique(as.character(table_one()$Indicator.Code))))
        #updateSelectInput(session,"SN",choices = c("All",unique(as.character(table_one()$Source.no))))
        updateSelectInput(session,"SO",choices = c("All",unique(as.character(table_one()$Source.organization))))
      }
      if (input$SO!="All"){
        updateSelectInput(session,"CN",choices = c("All",unique(as.character(table_one()$Country.Name))))
        updateSelectInput(session,"CC",choices = c("All",unique(as.character(table_one()$Country.Code))))
        updateSelectInput(session,"IN",choices = c("All",unique(as.character(table_one()$Indicator.Name))))
        updateSelectInput(session,"IC",choices = c("All",unique(as.character(table_one()$Indicator.Code))))
        updateSelectInput(session,"SN",choices = c("All",unique(as.character(table_one()$Source.no))))
        #updateSelectInput(session,"SO",choices = c("All",unique(as.character(table_one()$Source.organization))))
      }

    })

  }
)

Body:
Using the filter() function and piping from dplyr might be the answer. I used it inside of a renderPlot({}) server function, and it worked for me (I didn't try it in an observe function).

data = data %>% filter(if(input$CN == 'ALL'){Country.Name %in% c("countryname_1", "countryname_2",...,"countryname_n")} else {Country.Name == input$CN}) %>%
  filter(if(input$CC == 'ALL'){Country.Code %in% c("countrycode_1",..,"countrycode_n")} else {Country.Code == input$CC}) %>%

and so on for each filter

There is probably a better way to get the unfiltered version in case you have a lot of countries than this part inside the if statement:  Country.Code %in% c("countrycode_1",..,"countrycode_n") , but the if/else nested inside the filter, and filter statements for each attribute connected with %>% piping worked for me (and saved a LOT of space).

These links might help too:
filtering values

using filter with if/else statement

*edit update: I ended up put this filter function configuration in the observe function and it works great, seems more organized too


来源: stackexchange

问:
how to use $this->request->param of Kohana to get request variables
I have written  a sample controller in kohana

```<code>    <?php

defined('SYSPATH') OR die('No direct access allowed.');

class Controller_Album extends Controller {

  public function action_index() {
    $content=$this->request->param('id','value is null');
    $this->response->body($content);
  }

}
</code>```

But when I am trying to hit url http://localhost/k/album?id=4
I am getting NULL value.
how can I access request variable in kohana using request->param and without using $_GET and $_POST method ?

答:
In Kohana v3.1+ Request class has query() and post() methods. They work both as getter and setter:

```<code>// get $_POST data
$data = $this->request->post();
// returns $_GET['foo'] or NULL if not exists
$foo = $this->request->query('foo');

// set $_POST['foo'] value for the executing request
$request->post('foo', 'bar');
// or put array of vars. All existing data will be deleted!
$request->query(array('foo' => 'bar'));
</code>```

But remember that setting GET/POST data will not overload current $_GET/$_POST values. They will be sent after request executing ($request->execute() call).

ContentLicense: CC BY-SA 3.0

Body:
I have written  a sample controller in kohana

    <?php

defined('SYSPATH') OR die('No direct access allowed.');

class Controller_Album extends Controller {

  public function action_index() {
    $content=$this->request->param('id','value is null');
    $this->response->body($content);
  }

}

But when I am trying to hit url http://localhost/k/album?id=4
I am getting NULL value.
how can I access request variable in kohana using request->param and without using $_GET and $_POST method ?

Body:
In Kohana v3.1+ Request class has query() and post() methods. They work both as getter and setter:

// get $_POST data
$data = $this->request->post();
// returns $_GET['foo'] or NULL if not exists
$foo = $this->request->query('foo');

// set $_POST['foo'] value for the executing request
$request->post('foo', 'bar');
// or put array of vars. All existing data will be deleted!
$request->query(array('foo' => 'bar'));

But remember that setting GET/POST data will not overload current $_GET/$_POST values. They will be sent after request executing ($request->execute() call).


问:
Parameterized Table Population
I am trying to populate a table(whose name is parameterized). The program runs fine, up until the point where the command gets executed.
Here is the code:

```<code>table_name = input("Enter table name: ")
value_name = input("Enter name: ")
sql = "INSERT INTO %s (name) VALUES (%s)" % db.escape_string(table_name), (value_name)
cursor.execute(sql)
</code>```

I get the following error:
TypeError: not enough arguments for format string

Thanks to anyone who takes the time to help. Have a great rest of the day :)

答:
as an alternative you good go with the new formatting format

```<code>sql = f"INSERT INTO {tab} (name) VALUES ({val})".format(tab=db.escape_string(table_name),
                                                        val=value_name)
</code>```

or

```<code>sql = f"INSERT INTO {db.escape_string(table_name)} (name) VALUES ({value_name})"
</code>```

ContentLicense: CC BY-SA 4.0

Title: Parameterized Table Population

Body:
I am trying to populate a table(whose name is parameterized). The program runs fine, up until the point where the command gets executed.
Here is the code:

table_name = input("Enter table name: ")
value_name = input("Enter name: ")
sql = "INSERT INTO %s (name) VALUES (%s)" % db.escape_string(table_name), (value_name)
cursor.execute(sql)

I get the following error:
TypeError: not enough arguments for format string

Thanks to anyone who takes the time to help. Have a great rest of the day :)

Body:
as an alternative you good go with the new formatting format

sql = f"INSERT INTO {tab} (name) VALUES ({val})".format(tab=db.escape_string(table_name),
                                                        val=value_name)

or

sql = f"INSERT INTO {db.escape_string(table_name)} (name) VALUES ({value_name})"


问:
C++ Factories -> Java Factories?
When I was first learning C++, I came across this article about factories,
Pluggable C++ Factory, and ever since I've used that pattern for my factories in C++.  Now, I've been doing Java recently and on more than one occasion I've wanted to use a factory, but I can't seem to figure out a way to extend the factory at compile time.

Any implementation of a factory I can think of in Java involves telling the actual factory class about all of the underlying classes, which is rather suboptimal.

So, how can I get all subclasses of a class to register themselves in a static dictionary at compile time/program instantiation?

EDIT
It seems that my question was too vague.  Let me elaborate,

In Java if I were to try to replicate this pattern like so:
Factory.java

```<code>abstract class Factory {
private static Dictionary<int, Factory> dict;
public Factory(int index) {
  dict[int] = self;
}
public Foo getFoo(int index) {return dict[index].createFoo();}
protected abstract Foo makeFoo();
}
</code>```

Derived.java

```<code>class Derived extends Factory {
public Derived() {super(DERIVED_INDEX);}
private static Derived tmp = new Derived();
public Foo makeFoo() {return new FooImplementation();}
}
</code>```

The factory won't update with the reference to Derived (and thus won't create Derived instances) unless I manually register it myself, which defeats the purpose of having the static tmp member.

答:
You might find the Reflections library useful.

Using Reflections you can query your metadata such as:

```<code>* get all subtypes of some type
* get all types/methods/fields annotated with some annotation, w/o annotation parameters matching
* get all resources matching matching a regular expression
</code>```

Using this library you can define an interface and a factory which can create any implementation of that interface (by searching for those implementations)

Title: C++ Factories -> Java Factories?

Body:
When I was first learning C++, I came across this article about factories,
Pluggable C++ Factory, and ever since I've used that pattern for my factories in C++.  Now, I've been doing Java recently and on more than one occasion I've wanted to use a factory, but I can't seem to figure out a way to extend the factory at compile time.

Any implementation of a factory I can think of in Java involves telling the actual factory class about all of the underlying classes, which is rather suboptimal.

So, how can I get all subclasses of a class to register themselves in a static dictionary at compile time/program instantiation?

EDIT
It seems that my question was too vague.  Let me elaborate,

In Java if I were to try to replicate this pattern like so:
Factory.java

abstract class Factory {
private static Dictionary<int, Factory> dict;
public Factory(int index) {
  dict[int] = self;
}
public Foo getFoo(int index) {return dict[index].createFoo();}
protected abstract Foo makeFoo();
}

Derived.java

class Derived extends Factory {
public Derived() {super(DERIVED_INDEX);}
private static Derived tmp = new Derived();
public Foo makeFoo() {return new FooImplementation();}
}

The factory won't update with the reference to Derived (and thus won't create Derived instances) unless I manually register it myself, which defeats the purpose of having the static tmp member.

Body:
You might find the Reflections library useful.

Using Reflections you can query your metadata such as:

* get all subtypes of some type
* get all types/methods/fields annotated with some annotation, w/o annotation parameters matching
* get all resources matching matching a regular expression

Using this library you can define an interface and a factory which can create any implementation of that interface (by searching for those implementations)


问:
How to have multiple versions of the same object, each with different properties
I'm making a text based version of Skyrim and I'm unable to find a way to make enchantments/smithing bonuses work. I have a class for weapons and a class for armor. I have an object for each weapon and piece of armor included in my game. My properties for weapons are name, basedamage, smithingbonus, enchantment, and value. For armor the properties are name, slot, basedefense, smithingbonus, enchantment, and value.

You are able to have multiple of the same item in your inventory which creates the problem of being unable to have different versions of the same item. For example, let's say you have 2 iron swords and you want to enchant one. If you do this using ironsword.enchantment = [firedamage, 20], now both iron swords and every iron sword you find from now on will have a 20 fire damage enchantment. The same issue occurs with smithing where if you enhance one iron sword, all iron swords will become enhanced.

Does anyone know a solution to this? One I can think of would be to have like 1000 versions of each object and that each time you get a new one you would get the next object. For example: the first iron sword you got would be the object ironsword1. The next time you get an ironsword it would be ironsword2 and this would continue until you got 1000 iron swords. This would obviously be very time consuming to implement and I feel like there is definitely a better way.

答:
I think you may be misunderstanding how classes work, or more specifically the difference between classes and instances.

It makes sense to have a class for Weapon, but you don't want IronSword to be an instance of that class, you'll want it to be a subclass. In your inventory you'd then have two instances of the class IronSword with specific enchantments. Alternatively, you might not do an explicit subclass for iron swords but simply instantiate multiple weapons with parameters that identify them as iron swords. But either way, one object should correspond to one object, i.e. each inventory option should be a separate object.

Here is a very good series of YouTube videos that give an introduction to OOP in Python:
https://www.youtube.com/watch?v=ZDa-Z5JzLYM


问:
Swift UITableViewCell - Cell Image changes if I scroll down too fast, but only on the first attempt
I am parsing a JSON within my viewDidLoad method. One of the keys within this JSON is the image URL, which goes into a a string array called "allCImages"

This is just a string. Therefore to populate the image into the cell, in my cellForRowAt method, I have the following:

```<code>cell.vcCellImage.downloadImage(from: allCImages[indexPath.section])
</code>```

Note: vcCellImage is the IBOutlet of my cell image view.

The "downloadImage" method is part of the following extension:

```<code>extension UIImageView {
    func downloadImage(from imgURL: String!) {
        let theUrl = URLRequest(url: URL(string: imgURL)!)

        // set initial image to nil so it doesn't use the image from a reused cell
        image = nil

        // check if the image is already in the cache
        if let imageToCache = vc1ImageCache.object(forKey: imgURL! as NSString) {
            self.image = imageToCache
            print("Image is in Cache")
            return
        }

        // download the image asynchronously
        let task = URLSession.shared.dataTask(with: theUrl) { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async {
                // create UIImage
                let imageToCache = UIImage(data: data!)
                // add image to cache
                vc1ImageCache.setObject(imageToCache!, forKey: imgURL! as NSString)
                self.image = imageToCache
            }
        }

        task.resume()
    }
</code>```

This is working almost perfectly. For example:

1) If I scroll down my tableview slowly, all the cells contain the correct image

2) If I scroll up my tableview, slowly or quickly, all the cells contain the correct image. This is proven by the fact that my console is printing the following:

Image is in Cache

Image is in Cache

Image is in Cache

I.e, the tableview is getting my image from the cache (since to scroll up, I must have scrolled down before)

3) The issue is if I scroll down my tableview really quickly, on the first attempt. Since the image has not cached yet, the cell will display the wrong image, before changing to the correct image. Classic problem

Therefore I am missing this small piece of logic. How to resolve this?

EDIT: I tried this but the issue remains:

class VCTableViewCell: UITableViewCell {

override func prepareForReuse() {
    super.prepareForReuse()
    vcCellImage.image = nil
}

答:
first off all if you are appending your api or any data like this just remove this

```<code>var arr = [string]()

viewDidLoad()
{
arr.append("s","sd","sd)
}
</code>```

accept this

```<code>var arr = [string]()

viewWillAppear()
{
arr.removeAll()
//call api
//append Data
arr.append("s","sd","sd)
}
</code>```

I have similar problem then I solve it like this, may be it helpful for you also.

Body:
I am parsing a JSON within my viewDidLoad method. One of the keys within this JSON is the image URL, which goes into a a string array called "allCImages"

This is just a string. Therefore to populate the image into the cell, in my cellForRowAt method, I have the following:

cell.vcCellImage.downloadImage(from: allCImages[indexPath.section])

Note: vcCellImage is the IBOutlet of my cell image view.

The "downloadImage" method is part of the following extension:

extension UIImageView {
    func downloadImage(from imgURL: String!) {
        let theUrl = URLRequest(url: URL(string: imgURL)!)

        // set initial image to nil so it doesn't use the image from a reused cell
        image = nil

        // check if the image is already in the cache
        if let imageToCache = vc1ImageCache.object(forKey: imgURL! as NSString) {
            self.image = imageToCache
            print("Image is in Cache")
            return
        }

        // download the image asynchronously
        let task = URLSession.shared.dataTask(with: theUrl) { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async {
                // create UIImage
                let imageToCache = UIImage(data: data!)
                // add image to cache
                vc1ImageCache.setObject(imageToCache!, forKey: imgURL! as NSString)
                self.image = imageToCache
            }
        }

        task.resume()
    }

This is working almost perfectly. For example:

1) If I scroll down my tableview slowly, all the cells contain the correct image

2) If I scroll up my tableview, slowly or quickly, all the cells contain the correct image. This is proven by the fact that my console is printing the following:

Image is in Cache

Image is in Cache

Image is in Cache

I.e, the tableview is getting my image from the cache (since to scroll up, I must have scrolled down before)

3) The issue is if I scroll down my tableview really quickly, on the first attempt. Since the image has not cached yet, the cell will display the wrong image, before changing to the correct image. Classic problem

Therefore I am missing this small piece of logic. How to resolve this?

EDIT: I tried this but the issue remains:

class VCTableViewCell: UITableViewCell {

override func prepareForReuse() {
    super.prepareForReuse()
    vcCellImage.image = nil
}

Body:
first off all if you are appending your api or any data like this just remove this

var arr = [string]()

viewDidLoad()
{
arr.append("s","sd","sd)
}

accept this

var arr = [string]()

viewWillAppear()
{
arr.removeAll()
//call api
//append Data
arr.append("s","sd","sd)
}

I have similar problem then I solve it like this, may be it helpful for you also.


问:
Replace comma and dot in Pandas
I have a Column with data like 3.4500,00 EUR.
Now I want to compare this with another column having float numbers like 4000.00.
How do I take this string, remove the EUR and replace comma with decimal and then convert into float to compare?</p>

答:
Here is my solution:

mock data:

```<code>         amount     amount2
0   3.4500,00EUR    4000
1   3.600,00EUR     500
</code>```

use apply() then convert the data type to float

```<code>data['amount'] = data['amount'].apply(lambda x: x.replace('EUR', '')).apply(lambda x: x.replace('.', '')).apply(lambda x: x.replace(',', '.')).astype('float')
</code>```

result:

```<code>    amount    amount2
0   34500.0     4000
1   3600.0      500
</code>```

Title: Replace comma and dot in Pandas

Body:
Here is my solution:

mock data:

         amount     amount2
0   3.4500,00EUR    4000
1   3.600,00EUR     500

use apply() then convert the data type to float

data['amount'] = data['amount'].apply(lambda x: x.replace('EUR', '')).apply(lambda x: x.replace('.', '')).apply(lambda x: x.replace(',', '.')).astype('float')

result:

    amount    amount2
0   34500.0     4000
1   3600.0      500


答:
You can use regular expressions to make your conditions general that would work in all cases:

```<code># Make example dataframe for showing answer
df = pd.DataFrame({'Value':['3.4500,00 EUR', '88.782,21 DOLLAR']})

              Value
0     3.4500,00 EUR
1  88.782,21 DOLLAR
</code>```

Use str.replace with regular expression:

```<code>df['Value'].str.replace('[A-Za-z]', '').str.replace(',', '.').astype(float)

0    34500.00
1    88782.21
Name: Value, dtype: float64
</code>```

Explanation:

str.replace('[A-Za-z\.]', '') removes all alphabetic characters and dots.

str.replace(',', '.') replaces the comma for a dot

astype(float) converts it from object (string) type to float

Title: Replace comma and dot in Pandas

Body:
I have a Column with data like 3.4500,00 EUR.
Now I want to compare this with another column having float numbers like 4000.00.
How do I take this string, remove the EUR and replace comma with decimal and then convert into float to compare?

Body:
You can use regular expressions to make your conditions general that would work in all cases:

# Make example dataframe for showing answer
df = pd.DataFrame({'Value':['3.4500,00 EUR', '88.782,21 DOLLAR']})

              Value
0     3.4500,00 EUR
1  88.782,21 DOLLAR

Use str.replace with regular expression:

df['Value'].str.replace('[A-Za-z]', '').str.replace(',', '.').astype(float)

0    34500.00
1    88782.21
Name: Value, dtype: float64

Explanation:

str.replace('[A-Za-z\.]', '') removes all alphabetic characters and dots.

str.replace(',', '.') replaces the comma for a dot

astype(float) converts it from object (string) type to float


问:
ASP.NET Core - Any reason not to use a parameter object with dependency injection?
I like the DI feature of ASP.NET Core, but am finding that some of my classes end up with huge constructor parameter signatures...

```<code>public class Foo {
  private IBar1 _bar1;
  private IBar2 _bar2;
  // lots more here...

  public Foo(IBar1 bar1, IBar2 bar2, lots more here...) {
    _Bar1 = bar1;
    _Bar2 = bar2;
    // ...
  }

  public DoSomething() {
    // Use _bar1
  }
}
</code>```

In case this looks like a code smell, it's worth pointing out that any controller is going to use AutoMapper, an email service and 2 or 3 managers related to ASP.NET Identity, so I have 4 or 5 dependencies before I start injecting a single repository. Even if I only use 2 repositories, I can end up with 6 or 7 dependencies without actually violating any SOLID principles.

I was wondering about using a parameter object instead. I could create a class that has a public property for every injected dependency in my application, takes a constructor parameter for each one, and then just inject this into each class instead of all the individual Bars...

```<code>public class Foo {
  private IAllBars _allBars;

  public Foo(IAllBars allBars) {
    _allBars = allBars;
  }

  public DoSomething() {
    // Use _allBars.Bar1
  }
}
</code>```

The only disadvantage I can see is that it would mean that every class would have every dependency injected into it via the parameter object. In theory, this sounds like a bad idea, but I can't find any evidence that it would cause any problems.

Anyone any comments? Am I letting myself into potential trouble by trying to make my constructor code neater?

答:
What you're describing sounds like the service locator pattern, and while it seems tempting to simplify your code by eliminating all those constructor parameters, it usually ends up hurting maintainability in the long run. Check out Mark Seemann's post Service Locator violates encapsulation for more details about why it should be avoided.

Generally, when you find yourself with a class with dozens of constructor parameters, it means that class might have too many responsibilities. Can it be decomposed into a number of smaller classes with narrower goals? Rather than introducing a "catch-all" class that knows about everything, maybe there's a complex part of your application that you can abstract behind a facade.

Sometimes, you do end up with large coordinator classes that have many dependencies and that's okay in certain circumstances. However, if you have many of these it's usually a design smell.

Body:
I like the DI feature of ASP.NET Core, but am finding that some of my classes end up with huge constructor parameter signatures...

public class Foo {
  private IBar1 _bar1;
  private IBar2 _bar2;
  // lots more here...

  public Foo(IBar1 bar1, IBar2 bar2, lots more here...) {
    _Bar1 = bar1;
    _Bar2 = bar2;
    // ...
  }

  public DoSomething() {
    // Use _bar1
  }
}

In case this looks like a code smell, it's worth pointing out that any controller is going to use AutoMapper, an email service and 2 or 3 managers related to ASP.NET Identity, so I have 4 or 5 dependencies before I start injecting a single repository. Even if I only use 2 repositories, I can end up with 6 or 7 dependencies without actually violating any SOLID principles.

I was wondering about using a parameter object instead. I could create a class that has a public property for every injected dependency in my application, takes a constructor parameter for each one, and then just inject this into each class instead of all the individual Bars...

public class Foo {
  private IAllBars _allBars;

  public Foo(IAllBars allBars) {
    _allBars = allBars;
  }

  public DoSomething() {
    // Use _allBars.Bar1
  }
}

The only disadvantage I can see is that it would mean that every class would have every dependency injected into it via the parameter object. In theory, this sounds like a bad idea, but I can't find any evidence that it would cause any problems.

Anyone any comments? Am I letting myself into potential trouble by trying to make my constructor code neater?


问:
One-to-Many custom schema mapping in Corda Persistence
In Corda persistence, how to write a schema to map array of nested objects as children inside a parent?

I am looking at this document https://docs.corda.net/api-persistence.html and managed to create simple, non-nested properties of the state object mapped to the columns in the database. However, it is still not working for list objects as children.

The current code reads below and it is throwing error. What are output_index and transaction_id columns?

org.hibernate.MappingException: Foreign key (child_table [parent]) must have same
  number of columns as the referenced primary key (parent_table
  [output_index,transaction_id])

```<code>package com.template

import net.corda.core.identity.AbstractParty
import net.corda.core.schemas.MappedSchema
import net.corda.core.schemas.PersistentState
import net.corda.core.serialization.CordaSerializable
import javax.persistence.*

object TestSchema

@CordaSerializable
object ChildSchemaV1 : MappedSchema(schemaFamily = TestSchema.javaClass, version = 1, mappedTypes = listOf(PersistentChild::class.java)) {
    @Entity
    @Table(name = "child_table",
            indexes = arrayOf(Index(name = "id_child_idx", columnList = "child_id")))
    class PersistentChild(
            @Column(name = "child_id")
            var childId: Int,

            @ManyToOne
            var parent: ParentSchemaV1.PersistentParent

    ) : PersistentState() {
        constructor() : this(0, ParentSchemaV1.PersistentParent())
    }
}

@CordaSerializable
object ParentSchemaV1 : MappedSchema(schemaFamily = TestSchema.javaClass, version = 1, mappedTypes = listOf(PersistentParent::class.java)) {
    @Entity
    @Table(name = "parent_table",
            indexes = arrayOf(Index(name = "id_idx", columnList = "id")))
    class PersistentParent(

            @Column(name = "id", length = 100)
            var id: String,

            @OneToMany(mappedBy="parent")
            var children: List<ChildSchemaV1.PersistentChild>

    ) : PersistentState() {
        constructor() : this("", ArrayList<ChildSchemaV1.PersistentChild>())
    }
}
</code>```

generateMappedObject function in the Corda state is not included here because it is quite straightforward and I don't think that part is causing issue.

Please note the code above is simplified version of the actual code and hasn't been tested.

答:
Your Code Snippet suggests that you have two schemas  ChildSchemaV1 and ParentSchemaV1 for the same single Corda State(Curious to know how you mapped these schemas in you state). A suggestion would be to use single schema for a particular state .

Also in the Relational mapping of child to parent

```<code>        @ManyToOne
        var parent: ParentSchemaV1.PersistentParent
</code>```

Instead Use the below Code Snippet where it maps to the State as your joining columns must be output_index,transaction_id as these are primary keys for Persisted State

```<code>        @ManyToOne
        var cordaStateVar: CordaSate
</code>```

Check the complete Code below from the official Corda Site .

```<code>@CordaSerializable
object SchemaV1 : MappedSchema(schemaFamily = Schema::class.java, version = 1,
mappedTypes = listOf(PersistentParentToken::class.java,
PersistentChildToken::class.java)) {

@Entity
@Table(name = "parent_data")
class PersistentParentToken(
        @Column(name = "owner")
        var owner: String,

        @Column(name = "issuer")
        var issuer: String,

        @Column(name = "amount")
        var currency: Int,

        @Column(name = "linear_id")
        var linear_id: UUID,

         @JoinColumns(JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"), JoinColumn(name = "output_index", referencedColumnName = "output_index"))

        var listOfPersistentChildTokens: MutableList<PersistentChildToken>
) : PersistentState()

@Entity
@CordaSerializable
@Table(name = "child_data")
class PersistentChildToken(
        @Id
        var Id: UUID = UUID.randomUUID(),

        @Column(name = "owner")
        var owner: String,

        @Column(name = "issuer")
        var issuer: String,

        @Column(name = "amount")
        var currency: Int,

        @Column(name = "linear_id")
        var linear_id: UUID,

        @ManyToOne(targetEntity = PersistentParentToken::class)
        var persistentParentToken: TokenState

) : PersistentState()
</code>```

Body:
In Corda persistence, how to write a schema to map array of nested objects as children inside a parent?

I am looking at this document https://docs.corda.net/api-persistence.html and managed to create simple, non-nested properties of the state object mapped to the columns in the database. However, it is still not working for list objects as children.

The current code reads below and it is throwing error. What are output_index and transaction_id columns?

org.hibernate.MappingException: Foreign key (child_table [parent]) must have same
  number of columns as the referenced primary key (parent_table
  [output_index,transaction_id])

package com.template

import net.corda.core.identity.AbstractParty
import net.corda.core.schemas.MappedSchema
import net.corda.core.schemas.PersistentState
import net.corda.core.serialization.CordaSerializable
import javax.persistence.*

object TestSchema

@CordaSerializable
object ChildSchemaV1 : MappedSchema(schemaFamily = TestSchema.javaClass, version = 1, mappedTypes = listOf(PersistentChild::class.java)) {
    @Entity
    @Table(name = "child_table",
            indexes = arrayOf(Index(name = "id_child_idx", columnList = "child_id")))
    class PersistentChild(
            @Column(name = "child_id")
            var childId: Int,

            @ManyToOne
            var parent: ParentSchemaV1.PersistentParent

    ) : PersistentState() {
        constructor() : this(0, ParentSchemaV1.PersistentParent())
    }
}

@CordaSerializable
object ParentSchemaV1 : MappedSchema(schemaFamily = TestSchema.javaClass, version = 1, mappedTypes = listOf(PersistentParent::class.java)) {
    @Entity
    @Table(name = "parent_table",
            indexes = arrayOf(Index(name = "id_idx", columnList = "id")))
    class PersistentParent(

            @Column(name = "id", length = 100)
            var id: String,

            @OneToMany(mappedBy="parent")
            var children: List<ChildSchemaV1.PersistentChild>

    ) : PersistentState() {
        constructor() : this("", ArrayList<ChildSchemaV1.PersistentChild>())
    }
}

generateMappedObject function in the Corda state is not included here because it is quite straightforward and I don't think that part is causing issue.

Please note the code above is simplified version of the actual code and hasn't been tested.

Body:
Your Code Snippet suggests that you have two schemas  ChildSchemaV1 and ParentSchemaV1 for the same single Corda State(Curious to know how you mapped these schemas in you state). A suggestion would be to use single schema for a particular state .

Also in the Relational mapping of child to parent

        @ManyToOne
        var parent: ParentSchemaV1.PersistentParent

Instead Use the below Code Snippet where it maps to the State as your joining columns must be output_index,transaction_id as these are primary keys for Persisted State

        @ManyToOne
        var cordaStateVar: CordaSate

Check the complete Code below from the official Corda Site .

@CordaSerializable
object SchemaV1 : MappedSchema(schemaFamily = Schema::class.java, version = 1,
mappedTypes = listOf(PersistentParentToken::class.java,
PersistentChildToken::class.java)) {

@Entity
@Table(name = "parent_data")
class PersistentParentToken(
        @Column(name = "owner")
        var owner: String,

        @Column(name = "issuer")
        var issuer: String,

        @Column(name = "amount")
        var currency: Int,

        @Column(name = "linear_id")
        var linear_id: UUID,

         @JoinColumns(JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"), JoinColumn(name = "output_index", referencedColumnName = "output_index"))

        var listOfPersistentChildTokens: MutableList<PersistentChildToken>
) : PersistentState()

@Entity
@CordaSerializable
@Table(name = "child_data")
class PersistentChildToken(
        @Id
        var Id: UUID = UUID.randomUUID(),

        @Column(name = "owner")
        var owner: String,

        @Column(name = "issuer")
        var issuer: String,

        @Column(name = "amount")
        var currency: Int,

        @Column(name = "linear_id")
        var linear_id: UUID,

        @ManyToOne(targetEntity = PersistentParentToken::class)
        var persistentParentToken: TokenState

) : PersistentState()


问:
How To Forward-Fill empty values in a table
I have a Big Query table that looks like this:
![Table[(https://ibb.co/1ZXMH71)
As you can see most values are empty.
I'd like to forward-fill those empty values, meaning using the last known value ordered by time.

Apparently, there is a function for that called FILL
https://cloud.google.com/dataprep/docs/html/FILL-Function_57344752
But I have no idea how to use it.

This is the Query I've tried posting on the web UI:

```<code>SELECT sns_6,Time
FROM TABLE_PATH
FILL sns_6,-1,0 order: Time
</code>```

the error I get is:
Syntax error: Unexpected identifier "sns_6" at [3:6]
What I want is to get a new table where the column sns_6 is filled with the last known value.

As a bonus: I'd like this to happen for all columns but because fill only supports a single column, for now, I'll have to iterate over all the columns. If anyone has an idea of how to do the iteration This would be a great bonus.

答:
Below is for BigQuery Standard SQL

I'd like to forward-fill those empty values, meaning using the last known value ordered by time

```<code>#standardSQL
SELECT time
  LAST_VALUE(sns_1 IGNORE NULLS) OVER(ORDER BY time) sns_1,
  LAST_VALUE(sns_2 IGNORE NULLS) OVER(ORDER BY time) sns_2
FROM `project.dataset.table`
</code>```

I'd like this to happen for all columns

You can add as many below lines as many columns you need to fill (obviously you need to replace sns_N with the real column's name

```<code>  LAST_VALUE(sns_N IGNORE NULLS) OVER(ORDER BY time) sns_N
</code>```

Body:
I have a Big Query table that looks like this:
![Table[(https://ibb.co/1ZXMH71)
As you can see most values are empty.
I'd like to forward-fill those empty values, meaning using the last known value ordered by time.

Apparently, there is a function for that called FILL
https://cloud.google.com/dataprep/docs/html/FILL-Function_57344752
But I have no idea how to use it.

This is the Query I've tried posting on the web UI:

SELECT sns_6,Time
FROM TABLE_PATH
FILL sns_6,-1,0 order: Time

the error I get is:
Syntax error: Unexpected identifier "sns_6" at [3:6]
What I want is to get a new table where the column sns_6 is filled with the last known value.

As a bonus: I'd like this to happen for all columns but because fill only supports a single column, for now, I'll have to iterate over all the columns. If anyone has an idea of how to do the iteration This would be a great bonus.

Body:
Below is for BigQuery Standard SQL

I'd like to forward-fill those empty values, meaning using the last known value ordered by time

#standardSQL
SELECT time
  LAST_VALUE(sns_1 IGNORE NULLS) OVER(ORDER BY time) sns_1,
  LAST_VALUE(sns_2 IGNORE NULLS) OVER(ORDER BY time) sns_2
FROM `project.dataset.table`

I'd like this to happen for all columns

You can add as many below lines as many columns you need to fill (obviously you need to replace sns_N with the real column's name

  LAST_VALUE(sns_N IGNORE NULLS) OVER(ORDER BY time) sns_N


问:
Segemented Control for iPhone not working
I have a segmented control with the following code in its action method:

```<code>-(IBAction)toggleControls:(id)sender{
    if([sender selectedSegmentIndex] == kSwitchesSegmentIndex){
        leftSwitch.hidden = NO;
        rightSwitch.hidden = NO;
        doSomethingButton.hidden = YES;
    }

    else{
        leftSwitch.hidden = YES;
        rightSwitch.hidden = YES;
        doSomethingButton.hidden = NO;
    }
}
</code>```

However, when I run the program I'm getting an error with kSwitchesSegmentIndex. It's saying that kSwitchesSegmentIndex is an undeclared identifier. Can anyone help me with what's wrong here?

答:
You have to show us where kSwitchesSegmentIndex is being defined.  The convention is to define variables like that like:

```<code>#define kSwitchesSegmentIndex 1
</code>```

Or, you could define it as an int:

```<code>int kSwitchesSegmentIndex = 1;
</code>```

Since it shouldn't need to change value the first choice might be best.

Example:

```<code>#include <AVFoundation/AVFoundation.h>

#define kMyConstant1 0
#define kMyConstant2 1

@implementation MyClass
</code>```

Body:
I have a segmented control with the following code in its action method:

-(IBAction)toggleControls:(id)sender{
    if([sender selectedSegmentIndex] == kSwitchesSegmentIndex){
        leftSwitch.hidden = NO;
        rightSwitch.hidden = NO;
        doSomethingButton.hidden = YES;
    }

    else{
        leftSwitch.hidden = YES;
        rightSwitch.hidden = YES;
        doSomethingButton.hidden = NO;
    }
}

However, when I run the program I'm getting an error with kSwitchesSegmentIndex. It's saying that kSwitchesSegmentIndex is an undeclared identifier. Can anyone help me with what's wrong here?

Body:
You have to show us where kSwitchesSegmentIndex is being defined.  The convention is to define variables like that like:

#define kSwitchesSegmentIndex 1

Or, you could define it as an int:

int kSwitchesSegmentIndex = 1;

Since it shouldn't need to change value the first choice might be best.

Example:

#include <AVFoundation/AVFoundation.h>

#define kMyConstant1 0
#define kMyConstant2 1

@implementation MyClass


问:
Mat-Table isn't showing anything even though the data is being logged(console.log)
I want to use mat-table to display a list of users called from my database using a Spring RestAPI but even after following a number of tutorials the table is only showing the header (the column names) and when I check my console it shows the list of users.

Here's my html component:

```<code><div class="container-scroller">
  <app-navbar></app-navbar>
  <div class="container-fluid page-body-wrapper">
    <app-sidebar></app-sidebar>
    <div class="main-panel">
      <div class="content-wrapper">
        <div class="row">
          <div class="col-lg-12 grid-margin stretch-card">
            <div class="card">
              <div class="card-body">
                <h4 class="card-title" style="font-weight: 600">Users List</h4>
                <div class="table-responsive">
                  <table mat-table [dataSource]="dataSource">
                    <ng-container matColumnDef="id">
                      <th mat-header-cell *matHeaderCellDef> ID </th>
                      <td mat-cell *matCellDef="let element"> {{element.id}} </td>
                    </ng-container>

                    <ng-container matColumnDef="userName">
                      <th mat-header-cell *matHeaderCellDef> Username </th>
                      <td mat-cell *matCellDef="let element"> {{element.username}} </td>
                    </ng-container>

                    <ng-container matColumnDef="firstName">
                      <th mat-header-cell *matHeaderCellDef> firstName </th>
                      <td mat-cell *matCellDef="let element"> {{element.firstName}} </td>
                    </ng-container>

                    <ng-container matColumnDef="lastName">
                      <th mat-header-cell *matHeaderCellDef> Last Name </th>
                      <td mat-cell *matCellDef="let element"> {{element.LastName}} </td>
                    </ng-container>

                    <ng-container matColumnDef="email">
                      <th mat-header-cell *matHeaderCellDef> Email </th>
                      <td mat-cell *matCellDef="let element"> {{element.email}} </td>
                    </ng-container>

                    <ng-container matColumnDef="registeredDate">
                      <th mat-header-cell *matHeaderCellDef> Registered Date </th>
                      <td mat-cell *matCellDef="let element"> {{element.registeredDate | date: shortDate}} </td>
                    </ng-container>

                    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
                    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

the .ts file:

```<code>import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { UserService } from '../user.service';
import { MatTableDataSource } from '@angular/material';
import { User } from '../user';

@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['../app.component.scss', './dashboard.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
  loginuser: any = {};
  user: User[] = [];
  displayedColumns: string[] = ['id', 'userName', 'firstName', 'lastName', 'email', 'registeredDate'];
  public datasource = new MatTableDataSource<User>();
  constructor(private service: UserService) {}

  ngOnInit() {
      this.loginuser = JSON.parse(localStorage.getItem('currentUser'));
      this.getALLUSERS(this.loginuser.token);
  }

  public getALLUSERS(token: any) {
      this.service.getAllUsers(token).subscribe(u => {
      this.datasource.filteredData = u as User[];
      console.log('datasource: ', this.datasource.filteredData);
  });
  }

  onClick(selectedItem) {
      console.log('selected item: ', selectedItem);
  }
}
</code>```

the User interface:

```<code>export interface User {
   id: number;
   username: string;
   firstname: string;
   lastname: string;
   email: string;
   registereddate: Date;
}
</code>```

答:
You should update data instead of filteredData of DataSource.

```<code>this.datasource.data = u;
</code>```

Body:
I want to use mat-table to display a list of users called from my database using a Spring RestAPI but even after following a number of tutorials the table is only showing the header (the column names) and when I check my console it shows the list of users.

Here's my html component:

  <app-navbar></app-navbar>

    <app-sidebar></app-sidebar>

Users List

                    <ng-container matColumnDef="id">
                       ID
                       {{element.id}}
                    </ng-container>

                    <ng-container matColumnDef="userName">
                       Username
                       {{element.username}}
                    </ng-container>

                    <ng-container matColumnDef="firstName">
                       firstName
                       {{element.firstName}}
                    </ng-container>

                    <ng-container matColumnDef="lastName">
                       Last Name
                       {{element.LastName}}
                    </ng-container>

                    <ng-container matColumnDef="email">
                       Email
                       {{element.email}}
                    </ng-container>

                    <ng-container matColumnDef="registeredDate">
                       Registered Date
                       {{element.registeredDate | date: shortDate}}
                    </ng-container>

the .ts file:

import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { UserService } from '../user.service';
import { MatTableDataSource } from '@angular/material';
import { User } from '../user';

@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['../app.component.scss', './dashboard.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
  loginuser: any = {};
  user: User[] = [];
  displayedColumns: string[] = ['id', 'userName', 'firstName', 'lastName', 'email', 'registeredDate'];
  public datasource = new MatTableDataSource<User>();
  constructor(private service: UserService) {}

  ngOnInit() {
      this.loginuser = JSON.parse(localStorage.getItem('currentUser'));
      this.getALLUSERS(this.loginuser.token);
  }

  public getALLUSERS(token: any) {
      this.service.getAllUsers(token).subscribe(u => {
      this.datasource.filteredData = u as User[];
      console.log('datasource: ', this.datasource.filteredData);
  });
  }

  onClick(selectedItem) {
      console.log('selected item: ', selectedItem);
  }
}

the User interface:

export interface User {
   id: number;
   username: string;
   firstname: string;
   lastname: string;
   email: string;
   registereddate: Date;
}

Body:
You should update data instead of filteredData of DataSource.

this.datasource.data = u;


问:
Visual Studio Code: Unable to locate phpcs
I am facing this issue in Visual Studio Code.  I have already tried reinstalling the phpcs extension but still facing this issue.

Unable to locate phpcs

Please add phpcs to your global path or use the composer dependency manager to install it in your project locally in Visual studio Code

答:
Install PHP Sniffer
instead of phpcs

PHP Sniffer worked on the fly without any extra configuration

phpcs could not recognize my commands, despite a configured PATH, Composer & PHPCS installed.

The commands were recognized in the terminal, but not by the plugin
(under windows 10)


答:
When you crate two instance or an object they are not the same thing. Let's sat I have a generic class Triangle with attributes a, b, c. I can have two different triangle with different side length at the same time. You have to modify the attribute of only 1 instance of armor/weapon at a time. Can you post an example of your class weapon/object implementation so we can get a better idea of what you're trying to do?

Edit:

Let's try to explain class and subclass with your environment. We want do define a generic object called weapon, that has some attribute for damage and range.

```<code>class Weapon:
    def __init__(self, dmg):
        self.dmg = dmg
        self.range = 1
        self.ench = None
        self.upg = None
    def enchant(self, value):
        self.ench = value
    def upgrade(self, value):
        self.upg = value
    def __str__(self):
        return "Generic weapon, {} dmg and {} range".format(self.dmg, self.range)
</code>```

Now we want to create a subclass named Sword, that inherit everything from the generic class, but can implement more specific attribute and function.

```<code>class Sword(Weapon):
    def __init__(self, dmg):
        Weapon(self, dmg)
        self.range = 5
    def __str__(self):
        "Sword, {} dmg, {} range, {} enchant, {} upgrade"
           .format(self.dmg, self.range, self.ench, self.upg)
</code>```

You can now use both type of weapon in the same style, subclass ING the generic parent class.

```<code>a = Weapon(2)
b = Sword(5)
c = Sword(5)
c.enchant(2)
d = Sword(5)
d.upgrade(1)
print("{}\n{}\n{}\n{}".format(a,b,c,d))

=> Generic weapon, 2 dmg and 1 range
   Sword, 5 dmg, 5 range, None enchant, None upgrade
   Sword, 5 dmg, 5 range, 2 enchant, None upgrade
   Sword, 5 dmg, 5 range, None enchant, 1 upgrade
</code>```

I hope you get some of this concept, I suggest you look more into this from some tutorial online, you can just search for OOP.

Title: How to have multiple versions of the same object, each with different properties

Body:
I'm making a text based version of Skyrim and I'm unable to find a way to make enchantments/smithing bonuses work. I have a class for weapons and a class for armor. I have an object for each weapon and piece of armor included in my game. My properties for weapons are name, basedamage, smithingbonus, enchantment, and value. For armor the properties are name, slot, basedefense, smithingbonus, enchantment, and value.

You are able to have multiple of the same item in your inventory which creates the problem of being unable to have different versions of the same item. For example, let's say you have 2 iron swords and you want to enchant one. If you do this using ironsword.enchantment = [firedamage, 20], now both iron swords and every iron sword you find from now on will have a 20 fire damage enchantment. The same issue occurs with smithing where if you enhance one iron sword, all iron swords will become enhanced.

Does anyone know a solution to this? One I can think of would be to have like 1000 versions of each object and that each time you get a new one you would get the next object. For example: the first iron sword you got would be the object ironsword1. The next time you get an ironsword it would be ironsword2 and this would continue until you got 1000 iron swords. This would obviously be very time consuming to implement and I feel like there is definitely a better way.

Body:
When you crate two instance or an object they are not the same thing. Let's sat I have a generic class Triangle with attributes a, b, c. I can have two different triangle with different side length at the same time. You have to modify the attribute of only 1 instance of armor/weapon at a time. Can you post an example of your class weapon/object implementation so we can get a better idea of what you're trying to do?

Edit:

Let's try to explain class and subclass with your environment. We want do define a generic object called weapon, that has some attribute for damage and range.

class Weapon:
    def __init__(self, dmg):
        self.dmg = dmg
        self.range = 1
        self.ench = None
        self.upg = None
    def enchant(self, value):
        self.ench = value
    def upgrade(self, value):
        self.upg = value
    def __str__(self):
        return "Generic weapon, {} dmg and {} range".format(self.dmg, self.range)

Now we want to create a subclass named Sword, that inherit everything from the generic class, but can implement more specific attribute and function.

class Sword(Weapon):
    def __init__(self, dmg):
        Weapon(self, dmg)
        self.range = 5
    def __str__(self):
        "Sword, {} dmg, {} range, {} enchant, {} upgrade"
           .format(self.dmg, self.range, self.ench, self.upg)

You can now use both type of weapon in the same style, subclass ING the generic parent class.

a = Weapon(2)
b = Sword(5)
c = Sword(5)
c.enchant(2)
d = Sword(5)
d.upgrade(1)
print("{}\n{}\n{}\n{}".format(a,b,c,d))

=> Generic weapon, 2 dmg and 1 range
   Sword, 5 dmg, 5 range, None enchant, None upgrade
   Sword, 5 dmg, 5 range, 2 enchant, None upgrade
   Sword, 5 dmg, 5 range, None enchant, 1 upgrade

I hope you get some of this concept, I suggest you look more into this from some tutorial online, you can just search for OOP.


问:
How to format a chrono::time_point as a string
I need to get current date and time in c++. I can use chrono to get the system time but I also need to save this in json file as string. Moreover the chrono time which I have tried gives below format:

```<code>auto time = std::chrono::system_clock::now();
</code>```

output:

```<code>Thu Oct 11 19:10:24 2012
</code>```

But I need date time format in below format:

```<code>2016-12-07T00:52:07
</code>```

Also I need this date time in string so that I can save it in Json file. Can anyone please suggest a good way to achieve this. Thanks.

答:
The easiest way is to use Howard Hinnant's free, open-source, header-only date.h:

```<code>#include "date/date.h"
#include <iostream>
#include <string>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto time = system_clock::now();
    std::string s = format("%FT%T", floor<seconds>(time));
    std::cout << s << '\n';
}
</code>```

This library is the prototype for the new C++20, chrono extensions.  Though in C++20, the details of the formatting may change slightly to bring it in line with the expected C++20 fmt library.

Body:
I need to get current date and time in c++. I can use chrono to get the system time but I also need to save this in json file as string. Moreover the chrono time which I have tried gives below format:

auto time = std::chrono::system_clock::now();

output:

Thu Oct 11 19:10:24 2012

But I need date time format in below format:

2016-12-07T00:52:07

Also I need this date time in string so that I can save it in Json file. Can anyone please suggest a good way to achieve this. Thanks.

Body:
The easiest way is to use Howard Hinnant's free, open-source, header-only date.h:

#include "date/date.h"
#include <iostream>
#include <string>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto time = system_clock::now();
    std::string s = format("%FT%T", floor<seconds>(time));
    std::cout << s << '\n';
}

This library is the prototype for the new C++20, chrono extensions.  Though in C++20, the details of the formatting may change slightly to bring it in line with the expected C++20 fmt library.


问:
Reducer: Updating an array inside an array
I'm new to Redux, how would I reference the state of a nested array in my reducer?

Here is my state:

```<code>const initState = {
  tabs: [
    { arr: [] },
    { arr: [] }
  ]
};
</code>```

I tried doing something like:

```<code>tabs[0].arr: //do stuff
</code>```

inside my reducer, but I get a parsing error. What is the correct way to reference the array in the first tab?

Edit:
I am adding more code for clarity

```<code>function reducer(state = initState, action) {
  if (action.type == 'ADD_ARR') {
      return {
          state.tabs[0].arr: [...state.tabs[0].arr, action.arr]
      }
 }
}
//I get this message: 'Parsing error: Unexpected token, expected ","' at the period between 'state' and 'tabs[0]'
</code>```

The rest of my code

```<code>const arrAction = { type: "ADD_ARR", arr: "hello" };
store.dispatch(arrAction);
</code>```

答:
Try to avoid state mutation, by not updating the array directly. You also need to pass an index of the array you want to modify.

```<code>const arrAction = { type: "ADD_ARR", arr: "hello", index: 0 };
store.dispatch(arrAction);

function reducer(state = initState, action) {
  if (action.type == 'ADD_ARR') {

    const index = action.index;
    const arr = [...state.tabs[index].arr, action.arr];

    return {
      ...state,
      tabs: [...state.tabs.slice(0, index),
        Object.assign({}, state.tabs[index], { arr: [...arr] }),
        ...state.tabs.slice(index + 1)
      ]
    };
  }
}
</code>```

    ```

Body:
I'm new to Redux, how would I reference the state of a nested array in my reducer?

Here is my state:

const initState = {
  tabs: [
    { arr: [] },
    { arr: [] }
  ]
};

I tried doing something like:

tabs[0].arr: //do stuff

inside my reducer, but I get a parsing error. What is the correct way to reference the array in the first tab?

Edit:
I am adding more code for clarity

function reducer(state = initState, action) {
  if (action.type == 'ADD_ARR') {
      return {
          state.tabs[0].arr: [...state.tabs[0].arr, action.arr]
      }
 }
}
//I get this message: 'Parsing error: Unexpected token, expected ","' at the period between 'state' and 'tabs[0]'

The rest of my code

const arrAction = { type: "ADD_ARR", arr: "hello" };
store.dispatch(arrAction);

Body:
Try to avoid state mutation, by not updating the array directly. You also need to pass an index of the array you want to modify.

const arrAction = { type: "ADD_ARR", arr: "hello", index: 0 };
store.dispatch(arrAction);

function reducer(state = initState, action) {
  if (action.type == 'ADD_ARR') {

    const index = action.index;
    const arr = [...state.tabs[index].arr, action.arr];

    return {
      ...state,
      tabs: [...state.tabs.slice(0, index),
        Object.assign({}, state.tabs[index], { arr: [...arr] }),
        ...state.tabs.slice(index + 1)
      ]
    };
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.0.3/react-redux.min.js"></script>
<script src="http://wzrd.in/standalone/uuid%2Fv1@latest"></script>

<div id="root"></div>

    <script type="text/babel">
      const { Provider, connect } = ReactRedux;
      const { applyMiddleware, createStore, combineReducers } = Redux;

      function addArr(payload) {
        return { type: 'ADD_ARR', payload}
      }

      const initialState = {
        tabs: [{ arr: [] }, { arr: [] }]
      };

      function rootReducer(state = initialState, action) {

        if (action.type == 'ADD_ARR') {
          const index = action.payload.index;
          const arr = [...state.tabs[index].arr, action.payload.title];

          return {
            ...state,
            tabs: [
              ...state.tabs.slice(0, index),
              Object.assign({}, state.tabs[index], { arr: [...arr] }),
              ...state.tabs.slice(index + 1)
            ]
          };
        }
        return state;
      }

      const store = createStore(rootReducer);

      const mapStateToProps = state => {
        return { tabs: state.tabs };
      };

      function mapDispatchToProps(dispatch) {
        return {
          addExpense: expense => dispatch(addExpense(expense)),
          addArr: e => dispatch(addArr(e))
        };
      }

      const ConnectedList = ({ tabs, addExpense }) => {

        const tab1 = tabs[0].arr;
        const tab2 = tabs[1].arr;

        return (
          <div>
            {tab1.length > 0 && <p>tabs [0] arr values</p>}
            <ul className="list-group list-group-flush">
              {tab1.map((el, index) => (
                <li className="list-group-item" key={index}>
                  {el}
                </li>
              ))}
            </ul>

            {tab2.length > 0 && <p>tabs [1] arr values</p>}
            <ul className="list-group list-group-flush">
              {tab2.map((el, index) => (
                <li className="list-group-item" key={index}>
                  {el}
                </li>
              ))}
            </ul>
          </div>
        );
      };

      const List = connect(mapStateToProps)(ConnectedList);

      class StuffForm extends React.Component {
        state = {
          title: '',
        };

        handleSubmit = (index) => {

          if (!this.state.title) {
            return;
          }

          const { title} = this.state;

          this.props.addArr({
            title,
            index
          });

          this.setState({
            title: '',
          });
        };

        handleInput = e => {
          this.setState({
            [e.target.name]: e.target.value
          });
        };

        render() {
          return (
            <div>
              <input
                name="title"
                placeholder="title"
                onChange={this.handleInput}
                value={this.state.title}
              />
            <button onClick={() => this.handleSubmit(0)}>Add to arr[0]</button>
            <button onClick={() => this.handleSubmit(1)}>Add to arr[1]</button>
              </div>
          );
        }
      }

      const Form = connect(
        null,
        mapDispatchToProps
      )(StuffForm);

      class App extends React.Component {
        render() {
          return (
            <div>
              <List />
              <Form />
            </div>
          );
        }
      }
      ReactDOM.render(
        <Provider store={store}>
          <App />
        </Provider>,
        document.getElementById('root')
      );
    </script>


问:
How do I install opencv using pip?
I need to install cv2 for a script that has been written for me. I tried  pip install cv2 and pip install open_cv and got the same problem - a warning message from dist.py and complains about zlib being not found. No cv2 installed. I also tried pyopenvc and pip install opencv-python.

So, I went to the opencv site and downloaded the relevant exe. Ran it - generated a heap of subdirectories and a make file and stuff.

What do I do now?

答:
run the following command by creating a virtual enviroment using python 3 and run

```<code>pip3 install opencv-python
</code>```

to check it has installed correctly run

```<code>python3 -c "import cv2"
</code>```

Title: How do I install opencv using pip?

Body:
run the following command by creating a virtual enviroment using python 3 and run

pip3 install opencv-python

to check it has installed correctly run

python3 -c "import cv2"


问:
Component isn't re-rendering after state change in reducer
Let's say I have a link that, when clicked, adds a random number to an array in my state object called queue. The entire state.queue array is displayed on my page and gets updated as we click the link. I currently have a link that is supposed to be doing something similar but after my reducer alters the state (adds a new item to the array), my page isn't (re-?)rendering my component and so the page does not update.

What should I be doing to show the entirety of state.queue on my page, including dynamically updating as I click the link? Here's what I have:

Channel.js

```<code>class Channel extends Component {
    constructor(props) {
        super(props);
        this.state = {
            queue: [],
            // more initializations
        };
      ...
    }
    ...
    render() {
        return (
            <div>
            {/*This part is never called because this.state.queue never has anything in it! */}
             {this.state.queue &&
                this.state.queue.length > 0 &&
                    <div>
                        <ul>
                            {this.state.queue.map((queuedItem, i) =>
                                <li key={i}>{queuedItem}</li>
                            )}
                        </ul>
                    </div>}

                <div>

                    <QResults
                        allQueryResults={this.state.queryState}
                        requestHandler={queueNewRequest}
                    />
                </div>
            </div>
        );
    }
}

function mapStateToProps(state) {
    const{queue} = state
    return {queue}
}

 function mapDispatchToProps(dispatch) {
    return ({
        queueNewRequest: (newRequestData) => { dispatch({type: newRequestData}) }
    })
}

export default withRouter(connect(mapStateToProps , mapDispatchToProps )(Channel))
</code>```

QResults.js

```<code>export default class QResults extends Component {
    render() {
        const {requestHandler} = this.props

        return (
            <ul>
                {this.props.allQueryResults.items.map((trackAlbum, i) =>
                    <li key={i}>
                        <a href='#'
                        onClick={
                            () => requestHandler(trackAlbum.name)}>
                            Some link
                        </a>
                    </li>
                )}
            </ul>
        )
    }
}
</code>```

actions.js

```<code>export const QUEUE_NEW_REQUEST = 'QUEUE_NEW_REQUEST'

export function queueNewRequest(newRequestInfo) {
    return dispatch => {
        dispatch({
            type: QUEUE_NEW_REQUEST,
            payload: newRequestInfo
        })
    }
}
</code>```

reducers.js

```<code>import { combineReducers } from 'redux'

function reducer1(state = {}, action) {
    ...
}

function reducer2(state = {}, action) {
    switch (action.type) {
        case QUEUE_NEW_REQUEST:
             return {
                ...state,
                /*queue: [...state.queue,action.payload],*/ //compiler complains that 'TypeError: state.queue is not iterable'
                queue:[action.payload]
            }
        default:
            return state
    }
}
const rootReducer = combineReducers({
    reducer1,
    reducer2
})

export default rootReducer
</code>```

答:
Once you connected the state object to the props with connect you will get the returned objects in the props. See this: https://react-redux.js.org/using-react-redux/connect-mapstate#return.

So, you just need to change this.state.queue to this.props.queue in your Channel.js file.

And your component is not rendering because it's not dependent on the changed props. So, doing the above-suggested change should solve the issue.

Body:
Let's say I have a link that, when clicked, adds a random number to an array in my state object called queue. The entire state.queue array is displayed on my page and gets updated as we click the link. I currently have a link that is supposed to be doing something similar but after my reducer alters the state (adds a new item to the array), my page isn't (re-?)rendering my component and so the page does not update.

What should I be doing to show the entirety of state.queue on my page, including dynamically updating as I click the link? Here's what I have:

Channel.js

class Channel extends Component {
    constructor(props) {
        super(props);
        this.state = {
            queue: [],
            // more initializations
        };
      ...
    }
    ...
    render() {
        return (

            {/*This part is never called because this.state.queue never has anything in it! */}
             {this.state.queue &&
                this.state.queue.length > 0 &&

                            {this.state.queue.map((queuedItem, i) =>

{queuedItem}

                            )}

}

                    <QResults
                        allQueryResults={this.state.queryState}
                        requestHandler={queueNewRequest}
                    />

        );
    }
}

function mapStateToProps(state) {
    const{queue} = state
    return {queue}
}

 function mapDispatchToProps(dispatch) {
    return ({
        queueNewRequest: (newRequestData) => { dispatch({type: newRequestData}) }
    })
}

export default withRouter(connect(mapStateToProps , mapDispatchToProps )(Channel))

QResults.js

export default class QResults extends Component {
    render() {
        const {requestHandler} = this.props

        return (

                {this.props.allQueryResults.items.map((trackAlbum, i) =>

                         requestHandler(trackAlbum.name)}>
                            Some link

                )}

        )
    }
}

actions.js

export const QUEUE_NEW_REQUEST = 'QUEUE_NEW_REQUEST'

export function queueNewRequest(newRequestInfo) {
    return dispatch => {
        dispatch({
            type: QUEUE_NEW_REQUEST,
            payload: newRequestInfo
        })
    }
}

reducers.js

import { combineReducers } from 'redux'

function reducer1(state = {}, action) {
    ...
}

function reducer2(state = {}, action) {
    switch (action.type) {
        case QUEUE_NEW_REQUEST:
             return {
                ...state,
                /*queue: [...state.queue,action.payload],*/ //compiler complains that 'TypeError: state.queue is not iterable'
                queue:[action.payload]
            }
        default:
            return state
    }
}
const rootReducer = combineReducers({
    reducer1,
    reducer2
})

export default rootReducer