问:
arguments imply differing number of rows: 1, 0
i'm new to shinny and create random forest model to deploy at shinny. but i can't create the dataframe that consist of input variable that used to make predictions,

When i checked the length of dataframe, it's already same with train model the error is

arguments imply differing number of rows: 1, 0

a. i have already check the length variable and it's already same
b. remove the target variable at data frame because the data frame is consist of input variable to predict target variable

```<code>

# Random Forest Model
rf_model_final <-readRDS("rf_model_final.RDS")
#> Warning in gzfile(file, "rb"): cannot open compressed file 'rf_model_final.RDS',
#> probable reason 'No such file or directory'
#> Error in gzfile(file, "rb"): cannot open the connection

# Train and test dataframe

wsdm_model_train<-readRDS("wsdm_model_train.RDS")
#> Warning in gzfile(file, "rb"): cannot open compressed file
#> 'wsdm_model_train.RDS', probable reason 'No such file or directory'
#> Error in gzfile(file, "rb"): cannot open the connection
wsdm_model_test<-readRDS("wsdm_model_test.RDS")
#> Warning in gzfile(file, "rb"): cannot open compressed file
#> 'wsdm_model_test.RDS', probable reason 'No such file or directory'
#> Error in gzfile(file, "rb"): cannot open the connection

# Variable Importance Random Forest
varmp_final <- readRDS("varmp_final.RDS")
#> Warning in gzfile(file, "rb"): cannot open compressed file 'varmp_final.RDS',
#> probable reason 'No such file or directory'
#> Error in gzfile(file, "rb"): cannot open the connection
# round to 0
varmp_final$`mean decrease gini` <- round(varmp_final$`mean decrease gini`,0)
#> Error in eval(expr, envir, enclos): object 'varmp_final' not found
# Remove'_'
new_variables = c("automatic subscription","average time per day","plan list price mean",
                  "Number of Unique Track","Sum of Unique Song"," Sum of Songs at full duration",
                  "Number of Songs in full duration per day","The Period of Subscription"
                  ,"sum of number 25",
                  "sum of number 25 per day" )
varmp_final$new_variables <- new_variables
#> Error in varmp_final$new_variables <- new_variables: object 'varmp_final' not found
varmp_df <-varmp_final %>%
  select(-variable)
#> Error in select(., -variable): object 'varmp_final' not found

varmp_df<- varmp_df %>%
  mutate(tooltip = glue("Mean decrease gini: {`mean decrease gini`}"))
#> Error in mutate(., tooltip = glue("Mean decrease gini: {`mean decrease gini`}")): object 'varmp_df' not found

# Data Visualization Dataframe
# For Listening hour
forest_viz_ggplot <- readRDS("forest_viz_ggplot.RDS")
#> Warning in gzfile(file, "rb"): cannot open compressed file
#> 'forest_viz_ggplot.RDS', probable reason 'No such file or directory'
#> Error in gzfile(file, "rb"): cannot open the connection
# For Registration line plot
wsdm_for_registration <- readRDS("wsdm_for_registration.RDS")
#> Warning in gzfile(file, "rb"): cannot open compressed file
#> 'wsdm_for_registration.RDS', probable reason 'No such file or directory'
#> Error in gzfile(file, "rb"): cannot open the connection
# For auto renew and loyalty
forest_viz <- readRDS("forest_viz.RDS")
#> Warning in gzfile(file, "rb"): cannot open compressed file 'forest_viz.RDS',
#> probable reason 'No such file or directory'
#> Error in gzfile(file, "rb"): cannot open the connection
# change the name of variable into yes or no
forest_viz$is_auto_renew <-ifelse(forest_viz$is_auto_renew==1,"yes","no")
#> Error in ifelse(forest_viz$is_auto_renew == 1, "yes", "no"): object 'forest_viz' not found
# change the type of data is_auto_renew variable
forest_viz$is_auto_renew <-as.factor(forest_viz$is_auto_renew)
#> Error in is.factor(x): object 'forest_viz' not found
# Data wrangling for auto_renew plot
forest_viz_auto_renew<- forest_viz %>%
  select(is_auto_renew,is_churn) %>%
  group_by(is_auto_renew,is_churn) %>%
  count() %>%
  spread(is_churn,n) %>%
  ungroup %>%
  drop_na()
#> Error in select(., is_auto_renew, is_churn): object 'forest_viz' not found

forest_viz_coba <- forest_viz_auto_renew %>%
  pivot_longer(-is_auto_renew,names_to = "condition",names_transform = list(condition =as.factor))
#> Error in pivot_longer(., -is_auto_renew, names_to = "condition", names_transform = list(condition = as.factor)): object 'forest_viz_auto_renew' not found

forest_viz_coba<- forest_viz_coba %>%
  mutate(`has auto renew feature?` = is_auto_renew,
         `churn or not` = condition,
         `number of subscriber` = value)
#> Error in mutate(., `has auto renew feature?` = is_auto_renew, `churn or not` = condition, : object 'forest_viz_coba' not found

auto_renew_plot_df <- forest_viz_coba %>%
  select(-is_auto_renew,-condition,-value)
#> Error in select(., -is_auto_renew, -condition, -value): object 'forest_viz_coba' not found

auto_renew_plot_df$`has auto renew feature?` <-ifelse(auto_renew_plot_df$`has auto renew feature?`=="yes","has auto renew feature","doesn't have auto renew feature")
#> Error in ifelse(auto_renew_plot_df$`has auto renew feature?` == "yes", : object 'auto_renew_plot_df' not found
auto_renew_plot_df$`has auto renew feature?` <- as.factor(auto_renew_plot_df$`has auto renew feature?`)
#> Error in is.factor(x): object 'auto_renew_plot_df' not found

wsdm_model_test$unq_track <- round(wsdm_model_test$unq_track ,0)
#> Error in eval(expr, envir, enclos): object 'wsdm_model_test' not found
wsdm_model_test$num_100_perday <- round(wsdm_model_test$num_100_perday ,0)
#> Error in eval(expr, envir, enclos): object 'wsdm_model_test' not found
# Data wrangling for loyalty_range
forest_viz_loyalityplot_df <-forest_viz %>%
  select(loyality_range,is_churn) %>%
  group_by(loyality_range,is_churn) %>%
  count() %>%
  spread(is_churn,n) %>%
  ungroup %>%
  drop_na()
#> Error in select(., loyality_range, is_churn): object 'forest_viz' not found

# Data wrangling for listening hour

forest_viz_listeninghourplot_df <- forest_viz %>%
  select(listening_hour,is_churn) %>%
  group_by(listening_hour,is_churn) %>%
  count() %>%
  spread(is_churn,n) %>%
  ungroup %>%
  drop_na()
#> Error in select(., listening_hour, is_churn): object 'forest_viz' not found

listening_hour_df <- forest_viz_listeninghourplot_df %>%
  pivot_longer(-listening_hour,names_to = "churn or stay",names_transform = list(`churn or stay` =as.factor))
#> Error in pivot_longer(., -listening_hour, names_to = "churn or stay", : object 'forest_viz_listeninghourplot_df' not found

# Define UI for application that draws a histogram
ui <- dashboardPage( skin = "black",
  dashboardHeader(title = " KKBOXX Churn Prediction Dashboard" ),
  dashboardSidebar(
    sidebarMenu(
      menuItem(text = "Home",tabName = "home",icon =icon("house")),
      menuItem(text = "Data Analysis",tabName = "da",icon =icon("square-poll-vertical")),
        menuItem(text = "Prediction",tabName = "pred",icon=icon("volume-high")),
      menuItem(text = "Database",tabName = "dbs",icon=icon("database"))

    )

  ),
  dashboardBody(
    tabItems(
      tabItem(tabName ="home",
              box(
                solidHeader = TRUE, align = "center",
                width = 12,
                imageOutput("home_img",height = "600px"))

      )
    ,
      tabItem(tabName = "pred",

             fluidRow(column( width = 5,
              box(background = "light-blue",selectInput(inputId = "automaticsubscription",
                          label = "Has auto subscription feature?",
                          choices =levels(wsdm_model_test$is_auto_renew))),
              box(  sliderInput(inputId = "slidelisten",
                                label = "The Duration of listening hour",
                                min = min(wsdm_model_test$listening_hour),
                                max = max(wsdm_model_test$listening_hour),
                                value = min(wsdm_model_test$listening_hour),
                                step = 200)),
              box( selectInput(inputId = "pricerange",
                  label = "How much does the subscriber pay?",
                  choices =levels(wsdm_model_test$price_range))),

              box(sliderInput(inputId = "slideof100",
                              label = "Number of Full Duration Song ",
                              min = min(wsdm_model_test$num_100_perday),
                              max = max(wsdm_model_test$num_100_perday),
                              value = min(wsdm_model_test$num_100_perday),
                              step = 5)),
              box(
                selectInput(inputId = "loyalinput",
                            label = "How loyal are the subscriber",
                            choices =levels(wsdm_model_test$loyality_range))),
              box(sliderInput(inputId = "slideuniquetrack",
                            label = "Number of listened song each day",
                            min = min(wsdm_model_test$unq_track),
                            max = max(wsdm_model_test$unq_track),
                            value = min(wsdm_model_test$unq_track),
                            step = 5)),
                box(actionButton("go", "Predict!",icon("paper-plane"),
                               style="color: #fff; background-color: #337ab7; border-color: #2e6da4"))),
              fluidRow(
                infoBoxOutput("predchurn"))

      )

    )

  )

))
#> Error in levels(wsdm_model_test$is_auto_renew): object 'wsdm_model_test' not found

# Define server logic required to draw a histogram
server <- function(input, output) {

  forest_model_lr <-readRDS("forest_model_lr.RDS")

  rf_model_final <-readRDS("rf_model_final.RDS")

  output$predchurn <- renderInfoBox({
    go<-input$go
    churn_df <- data.frame(
      plan_list_price = max(wsdm_model_test$plan_list_price),
      actual_amount_paid = max(wsdm_model_test$actual_amount_paid),
      is_auto_renew = as.factor(input$automaticsubscription),
      year_registration = max(wsdm_model_test$year_registration),
      sum_num_25 =mean(wsdm_model_test$sum_num_25),
      sum_num_50 = mean(wsdm_model_test$sum_num_50),
      sum_num_75 = mean(wsdm_model_test$sum_num_75),
      sum_num_985 = mean(wsdm_model_test$sum_num_985),
      sum_num_100 = mean(wsdm_model_test$sum_num_100),
      num_unq_sum = mean(wsdm_model_test$num_unq_sum),
      plan_list_price_mean = mean(wsdm_model_test$plan_list_price_mean),
      actual_amount_paid_mean = mean(wsdm_model_test$actual_amount_paid),
      avg_time_perday= mean(wsdm_model_test$avg_time_perday),
      unq_track = input$slideuniquetrack,
      num_25_perday = mean(wsdm_model_test$num_25_perday),
      num_50_perday = mean(wsdm_model_test$num_50_perday),
      num_75_perday = mean(wsdm_model_test$num_75_perday),
      num_985_perday = mean(wsdm_model_test$num_985_perday),
      num_100_perday = as.numeric(input$slide100),
      loyality_range  = as.factor(input$loyalinput),
      price_day =  mean(wsdm_model_test$price_day),
      price_range = as.factor(input$pricerange),
      listening_hour = as.numeric(input$slidelisten))

  })

  # output$Contents <- renderPrint({
  #   if (input$go>0) {
  #     isolate("Calculation complete.")
  #   } else {
  #     return("Server is ready for calculation.")  }
  # })
  #
  #
  # # Prediction Output
  # output$tabledata <- renderDataTable({
  #   if (input$go>0) {
  #     isolate(datasetprediction())
  #   }
  # })

}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

Body:
i'm new to shinny and create random forest model to deploy at shinny. but i can't create the dataframe that consist of input variable that used to make predictions,

When i checked the length of dataframe, it's already same with train model the error is

arguments imply differing number of rows: 1, 0

a. i have already check the length variable and it's already same
b. remove the target variable at data frame because the data frame is consist of input variable to predict target variable

# Random Forest Model
rf_model_final <-readRDS("rf_model_final.RDS")
#> Warning in gzfile(file, "rb"): cannot open compressed file 'rf_model_final.RDS',
#> probable reason 'No such file or directory'
#> Error in gzfile(file, "rb"): cannot open the connection

# Train and test dataframe

wsdm_model_train<-readRDS("wsdm_model_train.RDS")
#> Warning in gzfile(file, "rb"): cannot open compressed file
#> 'wsdm_model_train.RDS', probable reason 'No such file or directory'
#> Error in gzfile(file, "rb"): cannot open the connection
wsdm_model_test<-readRDS("wsdm_model_test.RDS")
#> Warning in gzfile(file, "rb"): cannot open compressed file
#> 'wsdm_model_test.RDS', probable reason 'No such file or directory'
#> Error in gzfile(file, "rb"): cannot open the connection

# Variable Importance Random Forest
varmp_final <- readRDS("varmp_final.RDS")
#> Warning in gzfile(file, "rb"): cannot open compressed file 'varmp_final.RDS',
#> probable reason 'No such file or directory'
#> Error in gzfile(file, "rb"): cannot open the connection
# round to 0
varmp_final$`mean decrease gini` <- round(varmp_final$`mean decrease gini`,0)
#> Error in eval(expr, envir, enclos): object 'varmp_final' not found
# Remove'_'
new_variables = c("automatic subscription","average time per day","plan list price mean",
                  "Number of Unique Track","Sum of Unique Song"," Sum of Songs at full duration",
                  "Number of Songs in full duration per day","The Period of Subscription"
                  ,"sum of number 25",
                  "sum of number 25 per day" )
varmp_final$new_variables <- new_variables
#> Error in varmp_final$new_variables <- new_variables: object 'varmp_final' not found
varmp_df <-varmp_final %>%
  select(-variable)
#> Error in select(., -variable): object 'varmp_final' not found

varmp_df<- varmp_df %>%
  mutate(tooltip = glue("Mean decrease gini: {`mean decrease gini`}"))
#> Error in mutate(., tooltip = glue("Mean decrease gini: {`mean decrease gini`}")): object 'varmp_df' not found

# Data Visualization Dataframe
# For Listening hour
forest_viz_ggplot <- readRDS("forest_viz_ggplot.RDS")
#> Warning in gzfile(file, "rb"): cannot open compressed file
#> 'forest_viz_ggplot.RDS', probable reason 'No such file or directory'
#> Error in gzfile(file, "rb"): cannot open the connection
# For Registration line plot
wsdm_for_registration <- readRDS("wsdm_for_registration.RDS")
#> Warning in gzfile(file, "rb"): cannot open compressed file
#> 'wsdm_for_registration.RDS', probable reason 'No such file or directory'
#> Error in gzfile(file, "rb"): cannot open the connection
# For auto renew and loyalty
forest_viz <- readRDS("forest_viz.RDS")
#> Warning in gzfile(file, "rb"): cannot open compressed file 'forest_viz.RDS',
#> probable reason 'No such file or directory'
#> Error in gzfile(file, "rb"): cannot open the connection
# change the name of variable into yes or no
forest_viz$is_auto_renew <-ifelse(forest_viz$is_auto_renew==1,"yes","no")
#> Error in ifelse(forest_viz$is_auto_renew == 1, "yes", "no"): object 'forest_viz' not found
# change the type of data is_auto_renew variable
forest_viz$is_auto_renew <-as.factor(forest_viz$is_auto_renew)
#> Error in is.factor(x): object 'forest_viz' not found
# Data wrangling for auto_renew plot
forest_viz_auto_renew<- forest_viz %>%
  select(is_auto_renew,is_churn) %>%
  group_by(is_auto_renew,is_churn) %>%
  count() %>%
  spread(is_churn,n) %>%
  ungroup %>%
  drop_na()
#> Error in select(., is_auto_renew, is_churn): object 'forest_viz' not found

forest_viz_coba <- forest_viz_auto_renew %>%
  pivot_longer(-is_auto_renew,names_to = "condition",names_transform = list(condition =as.factor))
#> Error in pivot_longer(., -is_auto_renew, names_to = "condition", names_transform = list(condition = as.factor)): object 'forest_viz_auto_renew' not found

forest_viz_coba<- forest_viz_coba %>%
  mutate(`has auto renew feature?` = is_auto_renew,
         `churn or not` = condition,
         `number of subscriber` = value)
#> Error in mutate(., `has auto renew feature?` = is_auto_renew, `churn or not` = condition, : object 'forest_viz_coba' not found

auto_renew_plot_df <- forest_viz_coba %>%
  select(-is_auto_renew,-condition,-value)
#> Error in select(., -is_auto_renew, -condition, -value): object 'forest_viz_coba' not found

auto_renew_plot_df$`has auto renew feature?` <-ifelse(auto_renew_plot_df$`has auto renew feature?`=="yes","has auto renew feature","doesn't have auto renew feature")
#> Error in ifelse(auto_renew_plot_df$`has auto renew feature?` == "yes", : object 'auto_renew_plot_df' not found
auto_renew_plot_df$`has auto renew feature?` <- as.factor(auto_renew_plot_df$`has auto renew feature?`)
#> Error in is.factor(x): object 'auto_renew_plot_df' not found

wsdm_model_test$unq_track <- round(wsdm_model_test$unq_track ,0)
#> Error in eval(expr, envir, enclos): object 'wsdm_model_test' not found
wsdm_model_test$num_100_perday <- round(wsdm_model_test$num_100_perday ,0)
#> Error in eval(expr, envir, enclos): object 'wsdm_model_test' not found
# Data wrangling for loyalty_range
forest_viz_loyalityplot_df <-forest_viz %>%
  select(loyality_range,is_churn) %>%
  group_by(loyality_range,is_churn) %>%
  count() %>%
  spread(is_churn,n) %>%
  ungroup %>%
  drop_na()
#> Error in select(., loyality_range, is_churn): object 'forest_viz' not found

# Data wrangling for listening hour

forest_viz_listeninghourplot_df <- forest_viz %>%
  select(listening_hour,is_churn) %>%
  group_by(listening_hour,is_churn) %>%
  count() %>%
  spread(is_churn,n) %>%
  ungroup %>%
  drop_na()
#> Error in select(., listening_hour, is_churn): object 'forest_viz' not found

listening_hour_df <- forest_viz_listeninghourplot_df %>%
  pivot_longer(-listening_hour,names_to = "churn or stay",names_transform = list(`churn or stay` =as.factor))
#> Error in pivot_longer(., -listening_hour, names_to = "churn or stay", : object 'forest_viz_listeninghourplot_df' not found

# Define UI for application that draws a histogram
ui <- dashboardPage( skin = "black",
  dashboardHeader(title = " KKBOXX Churn Prediction Dashboard" ),
  dashboardSidebar(
    sidebarMenu(
      menuItem(text = "Home",tabName = "home",icon =icon("house")),
      menuItem(text = "Data Analysis",tabName = "da",icon =icon("square-poll-vertical")),
        menuItem(text = "Prediction",tabName = "pred",icon=icon("volume-high")),
      menuItem(text = "Database",tabName = "dbs",icon=icon("database"))

    )

  ),
  dashboardBody(
    tabItems(
      tabItem(tabName ="home",
              box(
                solidHeader = TRUE, align = "center",
                width = 12,
                imageOutput("home_img",height = "600px"))

      )
    ,
      tabItem(tabName = "pred",

             fluidRow(column( width = 5,
              box(background = "light-blue",selectInput(inputId = "automaticsubscription",
                          label = "Has auto subscription feature?",
                          choices =levels(wsdm_model_test$is_auto_renew))),
              box(  sliderInput(inputId = "slidelisten",
                                label = "The Duration of listening hour",
                                min = min(wsdm_model_test$listening_hour),
                                max = max(wsdm_model_test$listening_hour),
                                value = min(wsdm_model_test$listening_hour),
                                step = 200)),
              box( selectInput(inputId = "pricerange",
                  label = "How much does the subscriber pay?",
                  choices =levels(wsdm_model_test$price_range))),

              box(sliderInput(inputId = "slideof100",
                              label = "Number of Full Duration Song ",
                              min = min(wsdm_model_test$num_100_perday),
                              max = max(wsdm_model_test$num_100_perday),
                              value = min(wsdm_model_test$num_100_perday),
                              step = 5)),
              box(
                selectInput(inputId = "loyalinput",
                            label = "How loyal are the subscriber",
                            choices =levels(wsdm_model_test$loyality_range))),
              box(sliderInput(inputId = "slideuniquetrack",
                            label = "Number of listened song each day",
                            min = min(wsdm_model_test$unq_track),
                            max = max(wsdm_model_test$unq_track),
                            value = min(wsdm_model_test$unq_track),
                            step = 5)),
                box(actionButton("go", "Predict!",icon("paper-plane"),
                               style="color: #fff; background-color: #337ab7; border-color: #2e6da4"))),
              fluidRow(
                infoBoxOutput("predchurn"))

      )

    )

  )

))
#> Error in levels(wsdm_model_test$is_auto_renew): object 'wsdm_model_test' not found

# Define server logic required to draw a histogram
server <- function(input, output) {

  forest_model_lr <-readRDS("forest_model_lr.RDS")

  rf_model_final <-readRDS("rf_model_final.RDS")

  output$predchurn <- renderInfoBox({
    go<-input$go
    churn_df <- data.frame(
      plan_list_price = max(wsdm_model_test$plan_list_price),
      actual_amount_paid = max(wsdm_model_test$actual_amount_paid),
      is_auto_renew = as.factor(input$automaticsubscription),
      year_registration = max(wsdm_model_test$year_registration),
      sum_num_25 =mean(wsdm_model_test$sum_num_25),
      sum_num_50 = mean(wsdm_model_test$sum_num_50),
      sum_num_75 = mean(wsdm_model_test$sum_num_75),
      sum_num_985 = mean(wsdm_model_test$sum_num_985),
      sum_num_100 = mean(wsdm_model_test$sum_num_100),
      num_unq_sum = mean(wsdm_model_test$num_unq_sum),
      plan_list_price_mean = mean(wsdm_model_test$plan_list_price_mean),
      actual_amount_paid_mean = mean(wsdm_model_test$actual_amount_paid),
      avg_time_perday= mean(wsdm_model_test$avg_time_perday),
      unq_track = input$slideuniquetrack,
      num_25_perday = mean(wsdm_model_test$num_25_perday),
      num_50_perday = mean(wsdm_model_test$num_50_perday),
      num_75_perday = mean(wsdm_model_test$num_75_perday),
      num_985_perday = mean(wsdm_model_test$num_985_perday),
      num_100_perday = as.numeric(input$slide100),
      loyality_range  = as.factor(input$loyalinput),
      price_day =  mean(wsdm_model_test$price_day),
      price_range = as.factor(input$pricerange),
      listening_hour = as.numeric(input$slidelisten))

  })

  # output$Contents <- renderPrint({
  #   if (input$go>0) {
  #     isolate("Calculation complete.")
  #   } else {
  #     return("Server is ready for calculation.")  }
  # })
  #
  #
  # # Prediction Output
  # output$tabledata <- renderDataTable({
  #   if (input$go>0) {
  #     isolate(datasetprediction())
  #   }
  # })

}

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


来源: stackexchange

问:
`chrome.scripting.getRegisteredContentScripts` always returns an empty array
I have a Chrome extension with an action that I'm using to test getRegisteredContentScripts. The action boils down to:

const result = await chrome.scripting.executeScript({
    target: { tabId },
    injectImmediately: true,
    files: [
        "js/contentScript.bundle.js"
    ]
})
console.log(result);
const scripts = await browser.scripting.getRegisteredContentScripts();
console.log(scripts);
```
<p>This logs:</p>
```[{"documentId":"79E2F787C5E2EFB02BAD520D660A6606","frameId":0,"result":null}]
[]
```

So in other words it seems to be injecting the script, and indeed I can see the content script running in my browser, but getRegisteredContentScripts() always returns an empty array.

Why is this, and how can I fix it?

ContentLicense: CC BY-SA 4.0

Body:
I have a Chrome extension with an action that I'm using to test getRegisteredContentScripts. The action boils down to:

const result = await chrome.scripting.executeScript({
    target: { tabId },
    injectImmediately: true,
    files: [
        "js/contentScript.bundle.js"
    ]
})
console.log(result);
const scripts = await browser.scripting.getRegisteredContentScripts();
console.log(scripts);

This logs:

[{"documentId":"79E2F787C5E2EFB02BAD520D660A6606","frameId":0,"result":null}]
[]

So in other words it seems to be injecting the script, and indeed I can see the content script running in my browser, but getRegisteredContentScripts() always returns an empty array.

Why is this, and how can I fix it?


问:
Stop downloading sound from server after rerender in react
this is my first request ever so please be understanding. I have no idea how to deal with the problem that occurred after trying to add a hook to use sound in react. during rerender the sound is re-downloaded due to the use of new Audio(). I tried to use useMemo but I can't return the sound with it. Can someone explain to me how to go about it so that I can save the sound somehow, preferably when the page loads, and then use it freely? I don't need code, although it would help, but it's just an idea of how to get it. If you have any questions, I'll try to answer them all. Thank you for your help! i'm new in react. I think about give audio elements static in html file and next get it in react for play, but i don't know it is gut idea :(

useSound hook:

import { useEffect, useState, useRef } from "react";

const useSound = (url, isLoop) => {
  const audio = useRef(new Audio(url));
  const [status, setStatus] = useState(false);

  const toggle = () => {
    setStatus(!status);
  };

  useEffect(() => {
    if (isLoop && audio.current) {
      status ? audio.current.play() : audio.current.pause();
      audio.current.volume = 0.2;
      audio.current.loop = true;
    } else {
      const audio_simple = new Audio(url);
      audio_simple.play();
    }
  }, [status]);

  useEffect(() => {
    if (!isLoop) {
      audio.current.addEventListener("ended", () => setStatus(false));
      return () => {
        audio.current.removeEventListener("ended", () => setStatus(false));
      };
    }
  }, []);

  return [status, toggle];
};

export default useSound;
```
<p>usage:</p>
<pre class="lang-js prettyprint-override"><code>import bell from "../../media/bell.wav";
import { Sound } from "./Sound";

const [status2, toggle2] = useSound(bell, false);

onClick={() => toggle2()}

</code>```

Body:
this is my first request ever so please be understanding. I have no idea how to deal with the problem that occurred after trying to add a hook to use sound in react. during rerender the sound is re-downloaded due to the use of new Audio(). I tried to use useMemo but I can't return the sound with it. Can someone explain to me how to go about it so that I can save the sound somehow, preferably when the page loads, and then use it freely? I don't need code, although it would help, but it's just an idea of how to get it. If you have any questions, I'll try to answer them all. Thank you for your help! i'm new in react. I think about give audio elements static in html file and next get it in react for play, but i don't know it is gut idea :(

useSound hook:

import { useEffect, useState, useRef } from "react";

const useSound = (url, isLoop) => {
  const audio = useRef(new Audio(url));
  const [status, setStatus] = useState(false);

  const toggle = () => {
    setStatus(!status);
  };

  useEffect(() => {
    if (isLoop && audio.current) {
      status ? audio.current.play() : audio.current.pause();
      audio.current.volume = 0.2;
      audio.current.loop = true;
    } else {
      const audio_simple = new Audio(url);
      audio_simple.play();
    }
  }, [status]);

  useEffect(() => {
    if (!isLoop) {
      audio.current.addEventListener("ended", () => setStatus(false));
      return () => {
        audio.current.removeEventListener("ended", () => setStatus(false));
      };
    }
  }, []);

  return [status, toggle];
};

export default useSound;

usage:

import bell from "../../media/bell.wav";
import { Sound } from "./Sound";

const [status2, toggle2] = useSound(bell, false);

onClick={() => toggle2()}


问:
WooCommerce: Stop scroll to top and scroll to specific section when error occurs
When users enter an invalid card and payment gets decline, WooCommerce scrolls to the top of the page. As such, users may miss the error message.

Based on these two articles:
stop scroll to top after add to cart
https://github.com/woocommerce/woocommerce/issues/20930

I am trying to insert a code that will scroll to a specific div element when the error message is encountered.

```<code><div id="anchor1" class="elementor-menu-anchor"></div>
</code>```

Here is my code. Unfortunately, it does not appear to work.

```<code>jQuery( function($){
$.scroll_to_notices = function() {
$("#anchor1").scrollIntoView();
};
});
</code>```

How can I fix this? Thanks

Body:
When users enter an invalid card and payment gets decline, WooCommerce scrolls to the top of the page. As such, users may miss the error message.

Based on these two articles:
stop scroll to top after add to cart
https://github.com/woocommerce/woocommerce/issues/20930

I am trying to insert a code that will scroll to a specific div element when the error message is encountered.

Here is my code. Unfortunately, it does not appear to work.

jQuery( function($){
$.scroll_to_notices = function() {
$("#anchor1").scrollIntoView();
};
});

How can I fix this? Thanks


问:
OpenCV - Detect whether the given image is a credit card or not
I have a program that prints out the credit card information, but I also want to be able to tell whether the image being presented is of a credit card or not.

It functions flawlessly after being tested on several credit card photos. The output list contained 0 values because I had provided incorrect images as well. As a workaround, I printed out the text Not a Credit Card image, however it is not the best approach to take.

What will be the most effective approach for this issue, if somebody could help advise me? Thanks.

USAGE

```<code>python ocr_template_match.py --image images/credit_card_01.png --reference ocr_a_reference.png
</code>```

Code

```<code># import the necessary packages
from imutils import contours
import numpy as np
import argparse
import imutils
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
                help="path to input image")
ap.add_argument("-r", "--reference", required=True,
                help="path to reference OCR-A image")
args = vars(ap.parse_args())

# define a dictionary that maps the first digit of a credit card
# number to the credit card type
FIRST_NUMBER = {
    "3": "American Express",
    "4": "Visa",
    "5": "MasterCard",
    "6": "Discover Card"
}

# load the reference OCR-A image from disk, convert it to grayscale,
# and threshold it, such that the digits appear as *white* on a
# *black* background
# and invert it, such that the digits appear as *white* on a *black*
ref = cv2.imread(args["reference"])
ref = cv2.cvtColor(ref, cv2.COLOR_BGR2GRAY)
ref = cv2.threshold(ref, 10, 255, cv2.THRESH_BINARY_INV)[1]

# find contours in the OCR-A image (i.e,. the outlines of the digits)
# sort them from left to right, and initialize a dictionary to map
# digit name to the ROI
refCnts = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL,
                           cv2.CHAIN_APPROX_SIMPLE)
refCnts = imutils.grab_contours(refCnts)
refCnts = contours.sort_contours(refCnts, method="left-to-right")[0]
digits = {}

# loop over the OCR-A reference contours
for (i, c) in enumerate(refCnts):
    # compute the bounding box for the digit, extract it, and resize
    # it to a fixed size
    (x, y, w, h) = cv2.boundingRect(c)
    roi = ref[y:y + h, x:x + w]
    roi = cv2.resize(roi, (57, 88))

    # update the digits dictionary, mapping the digit name to the ROI
    digits[i] = roi

# initialize a rectangular (wider than it is tall) and square
# structuring kernel
rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3))
sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))

# load the input image, resize it, and convert it to grayscale
image = cv2.imread(args["image"])
image = imutils.resize(image, width=300)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# apply a tophat (whitehat) morphological operator to find light
# regions against a dark background (i.e., the credit card numbers)
tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, rectKernel)

# compute the Scharr gradient of the tophat image, then scale
# the rest back into the range [0, 255]
gradX = cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0,
                  ksize=-1)
gradX = np.absolute(gradX)
(minVal, maxVal) = (np.min(gradX), np.max(gradX))
gradX = (255 * ((gradX - minVal) / (maxVal - minVal)))
gradX = gradX.astype("uint8")

# apply a closing operation using the rectangular kernel to help
# cloes gaps in between credit card number digits, then apply
# Otsu's thresholding method to binarize the image
gradX = cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel)
thresh = cv2.threshold(gradX, 0, 255,
                       cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

# apply a second closing operation to the binary image, again
# to help close gaps between credit card number regions
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel)

# find contours in the thresholded image, then initialize the
# list of digit locations
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
                        cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
locs = []

# loop over the contours
for (i, c) in enumerate(cnts):
    # compute the bounding box of the contour, then use the
    # bounding box coordinates to derive the aspect ratio
    (x, y, w, h) = cv2.boundingRect(c)
    ar = w / float(h)

    # since credit cards used a fixed size fonts with 4 groups
    # of 4 digits, we can prune potential contours based on the
    # aspect ratio
    if ar > 2.5 and ar < 4.0:
        # contours can further be pruned on minimum/maximum width
        # and height
        if (w > 40 and w < 55) and (h > 10 and h < 20):
            # append the bounding box region of the digits group
            # to our locations list
            locs.append((x, y, w, h))

# sort the digit locations from left-to-right, then initialize the
# list of classified digits
locs = sorted(locs, key=lambda x: x[0])
output = []

# loop over the 4 groupings of 4 digits
for (i, (gX, gY, gW, gH)) in enumerate(locs):
    # initialize the list of group digits
    groupOutput = []

    # extract the group ROI of 4 digits from the grayscale image,
    # then apply thresholding to segment the digits from the
    # background of the credit card
    group = gray[gY - 5:gY + gH + 5, gX - 5:gX + gW + 5]
    group = cv2.threshold(group, 0, 255,
                          cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

    # detect the contours of each individual digit in the group,
    # then sort the digit contours from left to right
    digitCnts = cv2.findContours(group.copy(), cv2.RETR_EXTERNAL,
                                 cv2.CHAIN_APPROX_SIMPLE)
    digitCnts = imutils.grab_contours(digitCnts)
    digitCnts = contours.sort_contours(digitCnts,
                                       method="left-to-right")[0]

    # loop over the digit contours
    for c in digitCnts:
        # compute the bounding box of the individual digit, extract
        # the digit, and resize it to have the same fixed size as
        # the reference OCR-A images
        (x, y, w, h) = cv2.boundingRect(c)
        roi = group[y:y + h, x:x + w]
        roi = cv2.resize(roi, (57, 88))

        # initialize a list of template matching scores
        scores = []

        # loop over the reference digit name and digit ROI
        for (digit, digitROI) in digits.items():
            # apply correlation-based template matching, take the
            # score, and update the scores list
            result = cv2.matchTemplate(roi, digitROI,
                                       cv2.TM_CCOEFF)
            (_, score, _, _) = cv2.minMaxLoc(result)
            scores.append(score)

        # the classification for the digit ROI will be the reference
        # digit name with the *largest* template matching score
        groupOutput.append(str(np.argmax(scores)))

    # draw the digit classifications around the group
    cv2.rectangle(image, (gX - 5, gY - 5),
                  (gX + gW + 5, gY + gH + 5), (0, 0, 255), 2)
    cv2.putText(image, "".join(groupOutput), (gX, gY - 15),
                cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 0, 255), 2)

    # update the output digits list
    output.extend(groupOutput)

if(len(output) == 0):
    print("Not a Credit Card image")
else:
    # display the output credit card information to the screen
    print("Credit Card Type: {}".format(FIRST_NUMBER[output[0]]))
    print("Credit Card #: {}".format("".join(output)))
    cv2.imshow("Image", image)
    cv2.waitKey(0)
</code>```

Body:
I have a program that prints out the credit card information, but I also want to be able to tell whether the image being presented is of a credit card or not.

It functions flawlessly after being tested on several credit card photos. The output list contained 0 values because I had provided incorrect images as well. As a workaround, I printed out the text Not a Credit Card image, however it is not the best approach to take.

What will be the most effective approach for this issue, if somebody could help advise me? Thanks.

USAGE

python ocr_template_match.py --image images/credit_card_01.png --reference ocr_a_reference.png

Code

# import the necessary packages
from imutils import contours
import numpy as np
import argparse
import imutils
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
                help="path to input image")
ap.add_argument("-r", "--reference", required=True,
                help="path to reference OCR-A image")
args = vars(ap.parse_args())

# define a dictionary that maps the first digit of a credit card
# number to the credit card type
FIRST_NUMBER = {
    "3": "American Express",
    "4": "Visa",
    "5": "MasterCard",
    "6": "Discover Card"
}

# load the reference OCR-A image from disk, convert it to grayscale,
# and threshold it, such that the digits appear as *white* on a
# *black* background
# and invert it, such that the digits appear as *white* on a *black*
ref = cv2.imread(args["reference"])
ref = cv2.cvtColor(ref, cv2.COLOR_BGR2GRAY)
ref = cv2.threshold(ref, 10, 255, cv2.THRESH_BINARY_INV)[1]

# find contours in the OCR-A image (i.e,. the outlines of the digits)
# sort them from left to right, and initialize a dictionary to map
# digit name to the ROI
refCnts = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL,
                           cv2.CHAIN_APPROX_SIMPLE)
refCnts = imutils.grab_contours(refCnts)
refCnts = contours.sort_contours(refCnts, method="left-to-right")[0]
digits = {}

# loop over the OCR-A reference contours
for (i, c) in enumerate(refCnts):
    # compute the bounding box for the digit, extract it, and resize
    # it to a fixed size
    (x, y, w, h) = cv2.boundingRect(c)
    roi = ref[y:y + h, x:x + w]
    roi = cv2.resize(roi, (57, 88))

    # update the digits dictionary, mapping the digit name to the ROI
    digits[i] = roi

# initialize a rectangular (wider than it is tall) and square
# structuring kernel
rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3))
sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))

# load the input image, resize it, and convert it to grayscale
image = cv2.imread(args["image"])
image = imutils.resize(image, width=300)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# apply a tophat (whitehat) morphological operator to find light
# regions against a dark background (i.e., the credit card numbers)
tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, rectKernel)

# compute the Scharr gradient of the tophat image, then scale
# the rest back into the range [0, 255]
gradX = cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0,
                  ksize=-1)
gradX = np.absolute(gradX)
(minVal, maxVal) = (np.min(gradX), np.max(gradX))
gradX = (255 * ((gradX - minVal) / (maxVal - minVal)))
gradX = gradX.astype("uint8")

# apply a closing operation using the rectangular kernel to help
# cloes gaps in between credit card number digits, then apply
# Otsu's thresholding method to binarize the image
gradX = cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel)
thresh = cv2.threshold(gradX, 0, 255,
                       cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

# apply a second closing operation to the binary image, again
# to help close gaps between credit card number regions
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel)

# find contours in the thresholded image, then initialize the
# list of digit locations
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
                        cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
locs = []

# loop over the contours
for (i, c) in enumerate(cnts):
    # compute the bounding box of the contour, then use the
    # bounding box coordinates to derive the aspect ratio
    (x, y, w, h) = cv2.boundingRect(c)
    ar = w / float(h)

    # since credit cards used a fixed size fonts with 4 groups
    # of 4 digits, we can prune potential contours based on the
    # aspect ratio
    if ar > 2.5 and ar < 4.0:
        # contours can further be pruned on minimum/maximum width
        # and height
        if (w > 40 and w < 55) and (h > 10 and h < 20):
            # append the bounding box region of the digits group
            # to our locations list
            locs.append((x, y, w, h))

# sort the digit locations from left-to-right, then initialize the
# list of classified digits
locs = sorted(locs, key=lambda x: x[0])
output = []

# loop over the 4 groupings of 4 digits
for (i, (gX, gY, gW, gH)) in enumerate(locs):
    # initialize the list of group digits
    groupOutput = []

    # extract the group ROI of 4 digits from the grayscale image,
    # then apply thresholding to segment the digits from the
    # background of the credit card
    group = gray[gY - 5:gY + gH + 5, gX - 5:gX + gW + 5]
    group = cv2.threshold(group, 0, 255,
                          cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

    # detect the contours of each individual digit in the group,
    # then sort the digit contours from left to right
    digitCnts = cv2.findContours(group.copy(), cv2.RETR_EXTERNAL,
                                 cv2.CHAIN_APPROX_SIMPLE)
    digitCnts = imutils.grab_contours(digitCnts)
    digitCnts = contours.sort_contours(digitCnts,
                                       method="left-to-right")[0]

    # loop over the digit contours
    for c in digitCnts:
        # compute the bounding box of the individual digit, extract
        # the digit, and resize it to have the same fixed size as
        # the reference OCR-A images
        (x, y, w, h) = cv2.boundingRect(c)
        roi = group[y:y + h, x:x + w]
        roi = cv2.resize(roi, (57, 88))

        # initialize a list of template matching scores
        scores = []

        # loop over the reference digit name and digit ROI
        for (digit, digitROI) in digits.items():
            # apply correlation-based template matching, take the
            # score, and update the scores list
            result = cv2.matchTemplate(roi, digitROI,
                                       cv2.TM_CCOEFF)
            (_, score, _, _) = cv2.minMaxLoc(result)
            scores.append(score)

        # the classification for the digit ROI will be the reference
        # digit name with the *largest* template matching score
        groupOutput.append(str(np.argmax(scores)))

    # draw the digit classifications around the group
    cv2.rectangle(image, (gX - 5, gY - 5),
                  (gX + gW + 5, gY + gH + 5), (0, 0, 255), 2)
    cv2.putText(image, "".join(groupOutput), (gX, gY - 15),
                cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 0, 255), 2)

    # update the output digits list
    output.extend(groupOutput)

if(len(output) == 0):
    print("Not a Credit Card image")
else:
    # display the output credit card information to the screen
    print("Credit Card Type: {}".format(FIRST_NUMBER[output[0]]))
    print("Credit Card #: {}".format("".join(output)))
    cv2.imshow("Image", image)
    cv2.waitKey(0)


问:
AlarmManager.setAlarmClock not triggering
I have been coding an app on my phone, a xiaomi with MIUI 12.0.3 and android 10, and the alarm triggered normally, but recently I changed to another phone, a realme with android 12, and the alarm doesn't trigger anymore.

Instead of the application opening itself when the alarm triggers and the new activity starting, I need to open the app and then the activity starts, the alarm never opens the app by its own, which is what I am looking for since this is essentialy an alarm app.

I tried changing all the battery settings and background restrictions on the phone but still it doesn't work. Is there something that have changed on the android version that has made this stop working? Here's the code of the alarm.

```<code>    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun prepareNextAlarm() {
    alarm = getSystemService(ALARM_SERVICE) as AlarmManager
    val intent = Intent(applicationContext, Pedometer::class.java)
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)

    val pi = PendingIntent.getActivity(applicationContext, 0, intent, 0)
    val nextAlarmTime = getNextAlarmTimestamp();
    val alarmInfo = AlarmManager.AlarmClockInfo(nextAlarmTime, pi);
    saveNextAlarmTime(nextAlarmTime)
    alarm!!.setAlarmClock(alarmInfo, pi);

}
</code>```

Thank you so much for everyone in advance for the help!

Body:
I have been coding an app on my phone, a xiaomi with MIUI 12.0.3 and android 10, and the alarm triggered normally, but recently I changed to another phone, a realme with android 12, and the alarm doesn't trigger anymore.

Instead of the application opening itself when the alarm triggers and the new activity starting, I need to open the app and then the activity starts, the alarm never opens the app by its own, which is what I am looking for since this is essentialy an alarm app.

I tried changing all the battery settings and background restrictions on the phone but still it doesn't work. Is there something that have changed on the android version that has made this stop working? Here's the code of the alarm.

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun prepareNextAlarm() {
    alarm = getSystemService(ALARM_SERVICE) as AlarmManager
    val intent = Intent(applicationContext, Pedometer::class.java)
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)

    val pi = PendingIntent.getActivity(applicationContext, 0, intent, 0)
    val nextAlarmTime = getNextAlarmTimestamp();
    val alarmInfo = AlarmManager.AlarmClockInfo(nextAlarmTime, pi);
    saveNextAlarmTime(nextAlarmTime)
    alarm!!.setAlarmClock(alarmInfo, pi);

}

Thank you so much for everyone in advance for the help!


问:
Converting CSV to Parquet in spark without writing/saving it
I am trying to convert a CSV to Parquet and then use it for other purposes and I couldn't find how to do it without saving it, I've only seen this kind of structure to convert and it always writes/saves the data:

data = spark.read.load(sys.argv[1], format="csv", sep="|", inferSchema="true", header="true")

data.write.format("parquet").mode("overwrite").save(sys.argv[2])
```

Am I missing something? I am also happy with scala solutions.
Thanks!

I've tried to play with the mode option in "write" but it didn't help.

Body:
I am trying to convert a CSV to Parquet and then use it for other purposes and I couldn't find how to do it without saving it, I've only seen this kind of structure to convert and it always writes/saves the data:

data = spark.read.load(sys.argv[1], format="csv", sep="|", inferSchema="true", header="true")

data.write.format("parquet").mode("overwrite").save(sys.argv[2])

Am I missing something? I am also happy with scala solutions.
Thanks!

I've tried to play with the mode option in "write" but it didn't help.


问:
Can I create a 3D plot with geom_bar?
Let's say that I have a dataframe

```<code>df  = data.frame(x = LETTERS[1:5],
                 y = c(100,225,150,275,125))
df
</code>```

Would it be possible to make a plot as the one uploaded in the question using geon_bar ? Thanks.

Title: Can I create a 3D plot with geom_bar?

Body:
Let's say that I have a dataframe

df  = data.frame(x = LETTERS[1:5],
                 y = c(100,225,150,275,125))
df

Would it be possible to make a plot as the one uploaded in the question using geon_bar ? Thanks.


问:
How to remove the top margin for SSRS tablix while exporting to PDF?
We have a SSRS report that shows the Head, Body and Footer properly in the MS report viewer. But once we export the report to PDF then the report shows a gap between the header and the body components.
Here is the Report Viewer preview :

And once we exported the same report to PDF file :

The tablix is actually a sub report , So we checked the report properties and removed all the margins for it.
Here is the report properties :

I found some what similar questions , but it wasn't helpful.

Question 1

Question 2

So the question is how can we avoid the whitespace at the top between the header and body while exporting to PDF ?

Example 2:
If I remove the small space in the header below all the controls then it shows like this in the preview :

and once we export to PDF then we can see that the tablix went over the header.

So in this example we don't have a extra space in the header, So the MS Report Viewer preview is okay , but when we try to export then the tablix will go over the header. To overcome this issue I added a small extra space in the header

Header:


问:
Laravel route using dynamic slugs for category, sub-category and more deeper
I have created a blog application which works fine and I am using only two-level-deep routing using servants as below:

www.site.com/{parent-category}/{sub-category}/{post}

I'm running into a problem because some categories will have more sub-categories and go deeper. A method in a controller becomes large and difficult to understand.

Currently my URL structure is like this:

www.site.com/cancer/symptoms/<post-name>

```<code>Route::get('/{parent?}/{child?}/{post?}', [WebSiteController::class, 'index'])->where('child', '^[a-zA-Z0-9-_\/]+$')->name('homepage');
</code>```

I achieve this by checking each parameter to see if it has a value and if it has a defined value, I load the specific view and model

```<code>public function index($parent = null, $child = null, $post = null)
{
    // If no slug defined show homepage
    if ($parent == null && $parent == '' && $child == null && $child == '') {
        return view('website.homepage');
    }
    // Parent category is defined but child slug not. Show only root category
    else if($parent !== null && $child == null)
    {
        $category = PostCategory::where('slug', $parent)->where('post_category_id', 0)->firstOrFail();

        return view('website.category', compact('category'));
    }
    // Parent and child category is defined. Show child category
    else if ($parent !== null && $child !== null)
    {
        $category = PostCategory::where('slug', $child)->firstOrFail();

        return view('website.category', compact('category','children_toc', 'posts'));
    }
    else {
            abort('404');
    }
}
</code>```

And I should optimize it so that it can be created like this:

www.site.com/medical/diseases/cancer/symptoms/sub-category/sub-sub-category/<post-name>

I understand that I have to add for each category a parameter in the route and in the controller.

To route more subcategories, I would have to add more parameters in the controller method and do a check for each one, which caused a big and difficult to maintain.

```<code>Route::get('/{parent?}/{child?}/{child2?}/{child3/{child4?}?}/{post?}', [WebSiteController::class, 'index'])->where('child', '^[a-zA-Z0-9-_\/]+$')->name('homepage');

public function index($parent = null, $child = null, $child2 = null, $child3= null, etc..., $post = null)
{
    if($child !== null && $child2 == null)
    {
        $category = ....;

        // do somthing
    }
   else if($child2 !== null && $child3 == null)
   {
      // do somthing
   }
  // ...
}
</code>```

This can go on to infinity

if I want to add another level I have to do it manually through the code. Is there a way to do it dynamically?

Or is better way to store slug like full url in db column like:/medical/diseases/cancer/symptoms?

Here is migration

```<code>public function up()
{
    Schema::create('post_category', function (Blueprint $table) {
        $table->id();
        $table->unsignedInteger('post_category_id')->nullable();
        $table->string("name")->nullable(false);
        $table->string("slug") ;

        $table->timestamps();
    });
}
</code>```

Body:
I have created a blog application which works fine and I am using only two-level-deep routing using servants as below:

www.site.com/{parent-category}/{sub-category}/{post}

I'm running into a problem because some categories will have more sub-categories and go deeper. A method in a controller becomes large and difficult to understand.

Currently my URL structure is like this:

www.site.com/cancer/symptoms/<post-name>

Route::get('/{parent?}/{child?}/{post?}', [WebSiteController::class, 'index'])->where('child', '^[a-zA-Z0-9-_\/]+$')->name('homepage');

I achieve this by checking each parameter to see if it has a value and if it has a defined value, I load the specific view and model

public function index($parent = null, $child = null, $post = null)
{
    // If no slug defined show homepage
    if ($parent == null && $parent == '' && $child == null && $child == '') {
        return view('website.homepage');
    }
    // Parent category is defined but child slug not. Show only root category
    else if($parent !== null && $child == null)
    {
        $category = PostCategory::where('slug', $parent)->where('post_category_id', 0)->firstOrFail();

        return view('website.category', compact('category'));
    }
    // Parent and child category is defined. Show child category
    else if ($parent !== null && $child !== null)
    {
        $category = PostCategory::where('slug', $child)->firstOrFail();

        return view('website.category', compact('category','children_toc', 'posts'));
    }
    else {
            abort('404');
    }
}

And I should optimize it so that it can be created like this:

www.site.com/medical/diseases/cancer/symptoms/sub-category/sub-sub-category/<post-name>

I understand that I have to add for each category a parameter in the route and in the controller.

To route more subcategories, I would have to add more parameters in the controller method and do a check for each one, which caused a big and difficult to maintain.

Route::get('/{parent?}/{child?}/{child2?}/{child3/{child4?}?}/{post?}', [WebSiteController::class, 'index'])->where('child', '^[a-zA-Z0-9-_\/]+$')->name('homepage');

public function index($parent = null, $child = null, $child2 = null, $child3= null, etc..., $post = null)
{
    if($child !== null && $child2 == null)
    {
        $category = ....;

        // do somthing
    }
   else if($child2 !== null && $child3 == null)
   {
      // do somthing
   }
  // ...
}

This can go on to infinity

if I want to add another level I have to do it manually through the code. Is there a way to do it dynamically?

Or is better way to store slug like full url in db column like:/medical/diseases/cancer/symptoms?

Here is migration

public function up()
{
    Schema::create('post_category', function (Blueprint $table) {
        $table->id();
        $table->unsignedInteger('post_category_id')->nullable();
        $table->string("name")->nullable(false);
        $table->string("slug") ;

        $table->timestamps();
    });
}


问:
How can I create a Git workflow that listens for changes in a specific directory and displays select branches in a dropdown?
so I am new to git action workflow and got my first task which is a workflow_dispatch which listen to a code changes in some directory (source/team_a).
I want to be able to display only the relevant branches as a potential input.
After that I want to be able to deploy that branch into a environment.
I consult with chatGPT and he suggest the following, I prefer to get a real expert opinion about that.

name: Deploy to QA
on:
  workflow_dispatch:
    inputs:
      branch:
        description: "Branch to deploy"
        required: true
        type: string
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Get list of branches
        id: branches
        run: |
          # Replace REPO_OWNER and REPO_NAME with the owner and name of your repository
          curl -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
               https://api.github.com/repos/REPO_OWNER/REPO_NAME/branches | \
               jq '.[] | select(.name | startswith("source/team_a")) | .name'
      - name: Set branch list
        uses: actions/set-output@v1
        with:
          name: branches
          value: ${{ fromJson(steps.branches.outputs.stdout) | join(",") }}
      - name: Deploy to QA
        uses: actions/some-deployment-action@v1
        with:
          git_auth: ${{ secrets.GIT_AUTH }}
          repository: my-repository
          target: qa
          branch: ${{ inputs.branch }}
      - name: Run tests
        run: run-tests.sh

```


问:
Polars read_excel set option to include filtered rows
I've noticed that the Polars read_excel/Xlsx2csv doesn't include rows that are filtered in excel file(s). However, there is an option in Polars read_csv to set xlsx2csv options (xlsx2csv_options: dict[str, Any]).

I've tried to check from Xlsx2csv documentation whether there would be such an option, but couldn't find it. ChatGPT instructed to try "--skip-filtered-rows", but not sure how can I enter that to the Polars read_csv xlsx2csv option as a dictionary?

Workaround I've used is to read the excel file with pandas first and then read it with polars, but would prefer to do this with polars directly.

```<code>pl.from_pandas(pd.read_excel(file))
</code>```

xlsx2csv version 0.8.0

polars version 0.15.13

EDIT: Found the same issue in github as well: https://github.com/dilshod/xlsx2csv/issues/246

Looks like there was added a new setting to xlsx2csv "skip_hidden_rows" in the version 0.8.0. However, when I tried to use the below, I am still getting only the filtered rows from the excel files.

```<code>pl.read_excel(file, xlsx2csv_options={"skip_hidden_rows": False})
</code>```

Body:
I've noticed that the Polars read_excel/Xlsx2csv doesn't include rows that are filtered in excel file(s). However, there is an option in Polars read_csv to set xlsx2csv options (xlsx2csv_options: dict[str, Any]).

I've tried to check from Xlsx2csv documentation whether there would be such an option, but couldn't find it. ChatGPT instructed to try "--skip-filtered-rows", but not sure how can I enter that to the Polars read_csv xlsx2csv option as a dictionary?

Workaround I've used is to read the excel file with pandas first and then read it with polars, but would prefer to do this with polars directly.

pl.from_pandas(pd.read_excel(file))

xlsx2csv version 0.8.0

polars version 0.15.13

EDIT: Found the same issue in github as well: https://github.com/dilshod/xlsx2csv/issues/246

Looks like there was added a new setting to xlsx2csv "skip_hidden_rows" in the version 0.8.0. However, when I tried to use the below, I am still getting only the filtered rows from the excel files.

pl.read_excel(file, xlsx2csv_options={"skip_hidden_rows": False})


问:
How can I pass the id list in nested serialiazer and get dict output
I pass the list of tag ids in nested serializer during POST. I want to get all the fields of the object in Response, I got only the id.

My output:

```<code>{
    "id": 87,
    "tags": [
        1,
        2
    ]...
</code>```

I need it to be like this:

```<code>{

    "id": 0,
    "tags":

[

    {
        "id": 0,
        "name": "breakfast",
        "color": "#E26C2D",
        "slug": "breakfast"
    } ...
</code>```

How can I do it?

My code:

```<code>class RecipesSerializer(serializers.ModelSerializer):
    author = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault())
    image = Picture2Text(required=False, allow_null=True)
    ingredients = IngredientsSerializer(many=True, required=False)

    class Meta:
        model = Recipes
        fields = (
            'id',
            'tags',
            'author',
            'ingredients',
            'is_favorited',
            'is_in_shopping_cart',
            'name',
            'image',
            'text',
            'cooking_time',
        )

    def create(self, validated_data):

        new_recipe = Recipes.objects.create(
            author=self.context['request'].user,
            name=validated_data['name'],
            image=validated_data['image'],
            text=validated_data['text'],
            cooking_time=validated_data['cooking_time'],
        )
        new_recipe.save()

        for ingredient in validated_data['ingredients']:
            ingredient_obj = Ingredients.objects.get(id=ingredient['id'])
            RecipeIngredients.objects.create(
                recipe=new_recipe,
                ingredients=ingredient_obj,
                amount=ingredient['amount']
            )
            amount = ingredient['amount']
            ingredient_obj.amount = amount
            ingredient_obj.save()
            new_recipe.ingredients.add(ingredient_obj)

        for tag in validated_data['tags']:
            tag_obj = Tags.objects.get(id=tag.id)
            new_recipe.tags.add(tag_obj)

        new_recipe.save()

        return new_recipe
</code>```

I tried to explicit the tag serializer but it didn`t work. I did:

```<code>class RecipesSerializer(serializers.ModelSerializer):
    author = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault())
    image = Picture2Text(required=False, allow_null=True)
    tags = TagWithinRecipeSerializer(many=True, read_only=True)
</code>```

With:

```<code>class TagWithinRecipeSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField()

    class Meta:
        fields = ('id', 'name', 'color', 'slug')
        model = Tags
</code>```

But it didn't work:

```<code>  File "/home/aladinsane/.local/lib/python3.10/site-packages/rest_framework/serializers.py", line 205, in save
    self.instance = self.create(validated_data)
  File "/home/aladinsane/Development/foodgram-project-react-master-home/backend/api/serializers.py", line 194, in create
    for ingredient in data['ingredients']:
NameError: name 'data' is not defined
</code>```

How can I get what I need? Any help will be appreciated.

Body:
I pass the list of tag ids in nested serializer during POST. I want to get all the fields of the object in Response, I got only the id.

My output:

{
    "id": 87,
    "tags": [
        1,
        2
    ]...

I need it to be like this:

{

    "id": 0,
    "tags":

[

    {
        "id": 0,
        "name": "breakfast",
        "color": "#E26C2D",
        "slug": "breakfast"
    } ...

How can I do it?

My code:

class RecipesSerializer(serializers.ModelSerializer):
    author = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault())
    image = Picture2Text(required=False, allow_null=True)
    ingredients = IngredientsSerializer(many=True, required=False)

    class Meta:
        model = Recipes
        fields = (
            'id',
            'tags',
            'author',
            'ingredients',
            'is_favorited',
            'is_in_shopping_cart',
            'name',
            'image',
            'text',
            'cooking_time',
        )

    def create(self, validated_data):

        new_recipe = Recipes.objects.create(
            author=self.context['request'].user,
            name=validated_data['name'],
            image=validated_data['image'],
            text=validated_data['text'],
            cooking_time=validated_data['cooking_time'],
        )
        new_recipe.save()

        for ingredient in validated_data['ingredients']:
            ingredient_obj = Ingredients.objects.get(id=ingredient['id'])
            RecipeIngredients.objects.create(
                recipe=new_recipe,
                ingredients=ingredient_obj,
                amount=ingredient['amount']
            )
            amount = ingredient['amount']
            ingredient_obj.amount = amount
            ingredient_obj.save()
            new_recipe.ingredients.add(ingredient_obj)

        for tag in validated_data['tags']:
            tag_obj = Tags.objects.get(id=tag.id)
            new_recipe.tags.add(tag_obj)

        new_recipe.save()

        return new_recipe

I tried to explicit the tag serializer but it didn`t work. I did:

class RecipesSerializer(serializers.ModelSerializer):
    author = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault())
    image = Picture2Text(required=False, allow_null=True)
    tags = TagWithinRecipeSerializer(many=True, read_only=True)

With:

class TagWithinRecipeSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField()

    class Meta:
        fields = ('id', 'name', 'color', 'slug')
        model = Tags

But it didn't work:

  File "/home/aladinsane/.local/lib/python3.10/site-packages/rest_framework/serializers.py", line 205, in save
    self.instance = self.create(validated_data)
  File "/home/aladinsane/Development/foodgram-project-react-master-home/backend/api/serializers.py", line 194, in create
    for ingredient in data['ingredients']:
NameError: name 'data' is not defined

How can I get what I need? Any help will be appreciated.


问:
I have trouble setting up the VS Code Task Problem Matcher with tailwindcss
I have a task that starts npx tailwindcss, but does not seem to match problems.

My task:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "tailwindcss",
            "type": "shell",
            "command": "npx tailwindcss -i ${workspaceFolder}/app/static/input.css -o ${workspaceFolder}/app/static/main.css --watch",
            "isBackground": true,
            "problemMatcher": {
                "pattern": [
                    {
                        "regexp": "^CssSyntaxError: tailwindcss: (.*):(\\d+):(\\d+): (.+)$",
                        "file": 1,
                        "line": 2,
                        "column": 3,
                        "message": 4
                    }
                ],
                "background": {
                    "activeOnStart": true,
                    "beginsPattern": "^Rebuilding\\.\\.\\..*",
                    "endsPattern":"^Done in .*$"
                },
            },
        }
    ]
}
```
<h3>Successful Output</h3>
```Rebuilding...

 daisyUI components 2.46.0  https://daisyui.com
  ✔ Including:  base, components, 29 themes, utilities
  ❤ Support daisyUI:  https://opencollective.com/daisyui

Done in 199ms.
```
<p>Shows <img src="https://i.stack.imgur.com/ibtkT.png" alt="enter image description here" /></p>
<h3>Error Output</h3>
``` *  Executing task: npx tailwindcss -i C:\Users\Daniel\Documents\source\azwei/app/static/input.css -o C:\Users\Daniel\Documents\source\azwei/app/static/main.css --watch

& c:/Users/Daniel/Documents/source/azwei/.venv310/Scripts/Activate.ps1

Rebuilding...

 daisyUI components 2.46.0  https://daisyui.com
  ✔ Including:  base, components, 29 themes, utilities
  ❤ Support daisyUI:  https://opencollective.com/daisyui

CssSyntaxError: tailwindcss: C:\Users\Daniel\Documents\source\azwei/app/static/input.css:27:5: The `label-alt-text` class does not exist. If `label-alt-text` is a custom class, make sure it is defined within a `@layer` directive.
    at Input.error (C:\Users\Daniel\Documents\source\azwei\node_modules\postcss\lib\input.js:148:16)
    at AtRule.error (C:\Users\Daniel\Documents\source\azwei\node_modules\postcss\lib\node.js:60:32)
    at processApply (C:\Users\Daniel\Documents\source\azwei\node_modules\tailwindcss\lib\lib\expandApplyAtRules.js:376:29)
    at C:\Users\Daniel\Documents\source\azwei\node_modules\tailwindcss\lib\lib\expandApplyAtRules.js:524:9
    at C:\Users\Daniel\Documents\source\azwei\node_modules\tailwindcss\lib\processTailwindFeatures.js:55:50
    at Object.Once (C:\Users\Daniel\Documents\source\azwei\node_modules\tailwindcss\lib\cli\build\plugin.js:251:19)
    at LazyResult.runOnRoot (C:\Users\Daniel\Documents\source\azwei\node_modules\postcss\lib\lazy-result.js:337:23)
    at LazyResult.runAsync (C:\Users\Daniel\Documents\source\azwei\node_modules\postcss\lib\lazy-result.js:393:26)
    at async Object.watch (C:\Users\Daniel\Documents\source\azwei\node_modules\tailwindcss\lib\cli\build\plugin.js:359:13)
    at async build (C:\Users\Daniel\Documents\source\azwei\node_modules\tailwindcss\lib\cli\build\index.js:40:9) {
  reason: 'The `label-alt-text` class does not exist. If `label-alt-text` is a custom class, make sure it is defined within a `@layer` directive.',
  file: 'C:\\Users\\Daniel\\Documents\\source\\azwei/app/static/input.css',
  source: '@tailwind base;\n' +
    '@tailwind components;\n' +
    '@tailwind utilities;\n' +
    '\n' +
    '.menu .collapse-title,\n' +
    '.menu .collapse>input[type="checkbox"] {\n' +
    '    @apply min-h-min;\n' +
    '}\n' +
    '\n' +
    '.menu .collapse-content.menu {\n' +
    '    @apply p-0;\n' +
    '}\n' +
    '\n' +
    '.menu .collapse:hover .collapse-title {\n' +
    '    @apply bg-base-content bg-opacity-10;\n' +
    '}\n' +
    '\n' +
    '.menu .collapse-content.menu li a {\n' +
    '    @apply py-1;\n' +
    '}\n' +
    '\n' +
    '.pl-13 {\n' +
    '    padding-left: 3.25rem;\n' +
    '}\n' +
    '\n' +
    'label {\n' +
    '    @apply label label-alt-text;\n' +
    '}',
  line: 27,
  column: 5,
  endLine: 27,
  endColumn: 33,
  input: {
    line: 27,
    column: 5,
    endLine: 27,
    endColumn: 33,
    source: '@tailwind base;\n' +
      '@tailwind components;\n' +
      '@tailwind utilities;\n' +
      '\n' +
      '.menu .collapse-title,\n' +
      '.menu .collapse>input[type="checkbox"] {\n' +
      '    @apply min-h-min;\n' +
      '}\n' +
      '\n' +
      '.menu .collapse-content.menu {\n' +
      '    @apply p-0;\n' +
      '}\n' +
      '\n' +
      '.menu .collapse:hover .collapse-title {\n' +
      '    @apply bg-base-content bg-opacity-10;\n' +
      '}\n' +
      '\n' +
      '.menu .collapse-content.menu li a {\n' +
      '    @apply py-1;\n' +
      '}\n' +
      '\n' +
      '.pl-13 {\n' +
      '    padding-left: 3.25rem;\n' +
      '}\n' +
      '\n' +
      'label {\n' +
      '    @apply label label-alt-text;\n' +
      '}',
    url: 'file:///C:/Users/Daniel/Documents/source/azwei/app/static/input.css',
    file: 'C:\\Users\\Daniel\\Documents\\source\\azwei/app/static/input.css'
  },
  plugin: 'tailwindcss'
}

```

Keeps spinning

Any ideas?

Body:
I have a task that starts npx tailwindcss, but does not seem to match problems.

My task:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "tailwindcss",
            "type": "shell",
            "command": "npx tailwindcss -i ${workspaceFolder}/app/static/input.css -o ${workspaceFolder}/app/static/main.css --watch",
            "isBackground": true,
            "problemMatcher": {
                "pattern": [
                    {
                        "regexp": "^CssSyntaxError: tailwindcss: (.*):(\\d+):(\\d+): (.+)$",
                        "file": 1,
                        "line": 2,
                        "column": 3,
                        "message": 4
                    }
                ],
                "background": {
                    "activeOnStart": true,
                    "beginsPattern": "^Rebuilding\\.\\.\\..*",
                    "endsPattern":"^Done in .*$"
                },
            },
        }
    ]
}

Successful Output

Rebuilding...

 daisyUI components 2.46.0  https://daisyui.com
  ✔ Including:  base, components, 29 themes, utilities
  ❤ Support daisyUI:  https://opencollective.com/daisyui

Done in 199ms.

Shows

Error Output

 *  Executing task: npx tailwindcss -i C:\Users\Daniel\Documents\source\azwei/app/static/input.css -o C:\Users\Daniel\Documents\source\azwei/app/static/main.css --watch

& c:/Users/Daniel/Documents/source/azwei/.venv310/Scripts/Activate.ps1

Rebuilding...

 daisyUI components 2.46.0  https://daisyui.com
  ✔ Including:  base, components, 29 themes, utilities
  ❤ Support daisyUI:  https://opencollective.com/daisyui

CssSyntaxError: tailwindcss: C:\Users\Daniel\Documents\source\azwei/app/static/input.css:27:5: The `label-alt-text` class does not exist. If `label-alt-text` is a custom class, make sure it is defined within a `@layer` directive.
    at Input.error (C:\Users\Daniel\Documents\source\azwei\node_modules\postcss\lib\input.js:148:16)
    at AtRule.error (C:\Users\Daniel\Documents\source\azwei\node_modules\postcss\lib\node.js:60:32)
    at processApply (C:\Users\Daniel\Documents\source\azwei\node_modules\tailwindcss\lib\lib\expandApplyAtRules.js:376:29)
    at C:\Users\Daniel\Documents\source\azwei\node_modules\tailwindcss\lib\lib\expandApplyAtRules.js:524:9
    at C:\Users\Daniel\Documents\source\azwei\node_modules\tailwindcss\lib\processTailwindFeatures.js:55:50
    at Object.Once (C:\Users\Daniel\Documents\source\azwei\node_modules\tailwindcss\lib\cli\build\plugin.js:251:19)
    at LazyResult.runOnRoot (C:\Users\Daniel\Documents\source\azwei\node_modules\postcss\lib\lazy-result.js:337:23)
    at LazyResult.runAsync (C:\Users\Daniel\Documents\source\azwei\node_modules\postcss\lib\lazy-result.js:393:26)
    at async Object.watch (C:\Users\Daniel\Documents\source\azwei\node_modules\tailwindcss\lib\cli\build\plugin.js:359:13)
    at async build (C:\Users\Daniel\Documents\source\azwei\node_modules\tailwindcss\lib\cli\build\index.js:40:9) {
  reason: 'The `label-alt-text` class does not exist. If `label-alt-text` is a custom class, make sure it is defined within a `@layer` directive.',
  file: 'C:\\Users\\Daniel\\Documents\\source\\azwei/app/static/input.css',
  source: '@tailwind base;\n' +
    '@tailwind components;\n' +
    '@tailwind utilities;\n' +
    '\n' +
    '.menu .collapse-title,\n' +
    '.menu .collapse>input[type="checkbox"] {\n' +
    '    @apply min-h-min;\n' +
    '}\n' +
    '\n' +
    '.menu .collapse-content.menu {\n' +
    '    @apply p-0;\n' +
    '}\n' +
    '\n' +
    '.menu .collapse:hover .collapse-title {\n' +
    '    @apply bg-base-content bg-opacity-10;\n' +
    '}\n' +
    '\n' +
    '.menu .collapse-content.menu li a {\n' +
    '    @apply py-1;\n' +
    '}\n' +
    '\n' +
    '.pl-13 {\n' +
    '    padding-left: 3.25rem;\n' +
    '}\n' +
    '\n' +
    'label {\n' +
    '    @apply label label-alt-text;\n' +
    '}',
  line: 27,
  column: 5,
  endLine: 27,
  endColumn: 33,
  input: {
    line: 27,
    column: 5,
    endLine: 27,
    endColumn: 33,
    source: '@tailwind base;\n' +
      '@tailwind components;\n' +
      '@tailwind utilities;\n' +
      '\n' +
      '.menu .collapse-title,\n' +
      '.menu .collapse>input[type="checkbox"] {\n' +
      '    @apply min-h-min;\n' +
      '}\n' +
      '\n' +
      '.menu .collapse-content.menu {\n' +
      '    @apply p-0;\n' +
      '}\n' +
      '\n' +
      '.menu .collapse:hover .collapse-title {\n' +
      '    @apply bg-base-content bg-opacity-10;\n' +
      '}\n' +
      '\n' +
      '.menu .collapse-content.menu li a {\n' +
      '    @apply py-1;\n' +
      '}\n' +
      '\n' +
      '.pl-13 {\n' +
      '    padding-left: 3.25rem;\n' +
      '}\n' +
      '\n' +
      'label {\n' +
      '    @apply label label-alt-text;\n' +
      '}',
    url: 'file:///C:/Users/Daniel/Documents/source/azwei/app/static/input.css',
    file: 'C:\\Users\\Daniel\\Documents\\source\\azwei/app/static/input.css'
  },
  plugin: 'tailwindcss'
}

Keeps spinning

Any ideas?


问:
Django - ListView - populate table dynamically
I am trying to create a generic table (that I can reuse for other Objects as well) by passing in the views the context "table"

As part of view.py I have the following information passed on as Context:

object_list = User.objects.all()

table.columns that contains the Column Accessor (the property of the User object I want to access) and the Header Name
e.g. {'last_name': 'Last Name', 'first_name': 'First Name'}

In my template I want to loop through the objects, and find the "Column Accessor" and get the property of the object.
So far I have the following, but I am not sure how I can access the property of the object from the template. I can imagine I could create a filter tag, but any help on how to accomplish that would be appreciated.

```<code> #template.py
 {% for object in object_list %}
    {% for column in table.columns %}
        <td>{{object.????}}</td>
    {% endfor %}
{% endfor %}
</code>```

Body:
I am trying to create a generic table (that I can reuse for other Objects as well) by passing in the views the context "table"

As part of view.py I have the following information passed on as Context:

object_list = User.objects.all()

table.columns that contains the Column Accessor (the property of the User object I want to access) and the Header Name
e.g. {'last_name': 'Last Name', 'first_name': 'First Name'}

In my template I want to loop through the objects, and find the "Column Accessor" and get the property of the object.
So far I have the following, but I am not sure how I can access the property of the object from the template. I can imagine I could create a filter tag, but any help on how to accomplish that would be appreciated.

 #template.py
 {% for object in object_list %}
    {% for column in table.columns %}
        {{object.????}}
    {% endfor %}
{% endfor %}


问:
scalable inline-svg inside grid-item does not scale well
I made an inline svg with 3d.js and I want to use it in a grid layout.
Its using minmax(0,xfr) to make sure nothing gets bigger then the grid-item itself.
That works resonable but not with inline svg.
It seems to ignore the size at first, so I had to set the width and height.
But even that is ignored, when the screen becomes wide enough :(

Also it is not positioned in the middle but at the top so also the  justify-self: center;
align-self: center; options of the grid-item is totaly ignored.

I am trying for hours now with all kind of settings (like preserve aspect ratio etc) but they all seems to not work. Also transform does not seem to work in all screen resolutions.
It seems I do something completely wrong, the size is determent by the svg element while the grid should set the size and the svg should adapt.

How can I make this svg behave like a normal scalable picture/div ?
You can see the code in codepen :

```<code><div class="container">
  <div class="Picture"></div>
  <div class="Time">
    <div class="StopWatch">

    </div>
    <div class="MinutesText"></div>
  </div>
  <div class="Level">
    <div class="LevelPicture" style=" width:100%; height:100%">

         <svg  viewBox="0 0 100 100" id="circleLevel">

   </svg>
    </div>
    <div class="LevelText"></div>
  </div>
  <div class="Arrow">

  </div>
</div>

.container {  display: grid;
  grid-template-columns: minmax(0, 0.2fr) minmax(0, 1.5fr) minmax(0, 2.6fr) minmax(0, 0.6fr) minmax(0, 0.1fr);
  grid-template-rows: minmax(0, 0.2fr) minmax(0, 1.3fr) minmax(0, 1.3fr) minmax(0, 0.2fr);
  gap: 0px 0px;
  grid-auto-flow: row;
  grid-template-areas:
    ". . . . ."
    ". Picture Time . ."
    ". Picture Level Arrow ."
    ". . . . .";
}

.Picture {
  justify-self: center;
  align-self: center;
  grid-area: Picture;
}

.Time {  display: grid;
  grid-template-columns: minmax(0,0.4fr) minmax(0,1.6fr);
  grid-template-rows: minmax(0,1fr);
  gap: 0px 0px;
  grid-auto-flow: row;
  grid-template-areas:
    "StopWatch MinutesText";
  grid-area: Time;
}

.StopWatch {
  justify-self: center;
  align-self: center;
  grid-area: StopWatch;
}

.MinutesText {
  justify-self: start;
  align-self: center;
  grid-area: MinutesText;
}

.Level {  display: grid;
  grid-template-columns: minmax(0,0.4fr) minmax(0,1.6fr);
  grid-template-rows: minmax(0,1fr);
  gap: 0px 0px;
  grid-auto-flow: row;
  grid-template-areas:
    "LevelPicture LevelText";
  grid-area: Level;
}

.LevelPicture {
  justify-self: center;
  align-self: center;
  grid-area: LevelPicture;
}

.LevelText {
  justify-self: start;
  align-self: center;
  grid-area: LevelText;
}

.Arrow {
  justify-self: center;
  align-self: center;
  grid-area: Arrow;
}

html, body , .container {
  height: 100%;
  margin: 0;
}
</code>```

https://codepen.io/mistert007/pen/mdjRwqr?editors=1111

Body:
I made an inline svg with 3d.js and I want to use it in a grid layout.
Its using minmax(0,xfr) to make sure nothing gets bigger then the grid-item itself.
That works resonable but not with inline svg.
It seems to ignore the size at first, so I had to set the width and height.
But even that is ignored, when the screen becomes wide enough :(

Also it is not positioned in the middle but at the top so also the  justify-self: center;
align-self: center; options of the grid-item is totaly ignored.

I am trying for hours now with all kind of settings (like preserve aspect ratio etc) but they all seems to not work. Also transform does not seem to work in all screen resolutions.
It seems I do something completely wrong, the size is determent by the svg element while the grid should set the size and the svg should adapt.

How can I make this svg behave like a normal scalable picture/div ?
You can see the code in codepen :

         <svg  viewBox="0 0 100 100" id="circleLevel">

   </svg>

.container {  display: grid;
  grid-template-columns: minmax(0, 0.2fr) minmax(0, 1.5fr) minmax(0, 2.6fr) minmax(0, 0.6fr) minmax(0, 0.1fr);
  grid-template-rows: minmax(0, 0.2fr) minmax(0, 1.3fr) minmax(0, 1.3fr) minmax(0, 0.2fr);
  gap: 0px 0px;
  grid-auto-flow: row;
  grid-template-areas:
    ". . . . ."
    ". Picture Time . ."
    ". Picture Level Arrow ."
    ". . . . .";
}

.Picture {
  justify-self: center;
  align-self: center;
  grid-area: Picture;
}

.Time {  display: grid;
  grid-template-columns: minmax(0,0.4fr) minmax(0,1.6fr);
  grid-template-rows: minmax(0,1fr);
  gap: 0px 0px;
  grid-auto-flow: row;
  grid-template-areas:
    "StopWatch MinutesText";
  grid-area: Time;
}

.StopWatch {
  justify-self: center;
  align-self: center;
  grid-area: StopWatch;
}

.MinutesText {
  justify-self: start;
  align-self: center;
  grid-area: MinutesText;
}

.Level {  display: grid;
  grid-template-columns: minmax(0,0.4fr) minmax(0,1.6fr);
  grid-template-rows: minmax(0,1fr);
  gap: 0px 0px;
  grid-auto-flow: row;
  grid-template-areas:
    "LevelPicture LevelText";
  grid-area: Level;
}

.LevelPicture {
  justify-self: center;
  align-self: center;
  grid-area: LevelPicture;
}

.LevelText {
  justify-self: start;
  align-self: center;
  grid-area: LevelText;
}

.Arrow {
  justify-self: center;
  align-self: center;
  grid-area: Arrow;
}

html, body , .container {
  height: 100%;
  margin: 0;
}

https://codepen.io/mistert007/pen/mdjRwqr?editors=1111


问:
productId mi kettle
I tried connecting to my Xiaomi mi kettle using some python script and i got stuck with productID

i tried the common once's like 1116, 131, 275 but the didnt work.
Does anyone knows another product id's?

i tried bruteforcing but it didn't seem to work.

Title: productId mi kettle


问:
Get 403 when trying to make post request to controller endpoint
Summary: I want users who are not logged in to be able to make a post request to a certain endpoint, /users/registration/create specifically. I've tried to configure my security filter chain to permit requests to /users/registration/**. I can make a GET request to /users/registration/form, fill out the fields, and then click submit. When I submit the form (to /users/registration/create), the browser responds with a 403.

I have the following configuration:

```<code>    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((requests) -> requests
                .requestMatchers( "/users/registration/**").permitAll()
            );
        return http.build();
    }
</code>```

I can load /users/registration/form in my browser just fine, but once I submit the form, which sends the data to /users/registration/create, I get a 403 as a response.

In case it's needed...

Here's my controller:

```<code>@Controller
public class UserRegistrationsController {
    @Autowired
    private AppUserService appUserService;

    @GetMapping("/users/registration/form")
    public String newRegistration(WebRequest request, Model model) {
        AppUserDto appUserDto = new AppUserDto();
        model.addAttribute("user", appUserDto);
        return "users/registration";
    }

    @PostMapping("/users/registration/create")
    public void createRegistration(
        @ModelAttribute("user") @Valid AppUserDto appUserDto,
        HttpServletRequest request,
        Errors errors
    ) {
        try {
            AppUser registered = appUserService.registerNewUserAccount(appUserDto);
        } catch (AppUserAlreadyExistsException ex) {

        }
    }
}
</code>```

Not sure if this is the right way to do it, but I tried disabling CSRF and doing the same request again:

```<code>    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authorize) -> {
            authorize.requestMatchers("/", "/users/registration/**").permitAll();
        });
        http.csrf().disable();
        return http.build();
    }
</code>```

Body:
Summary: I want users who are not logged in to be able to make a post request to a certain endpoint, /users/registration/create specifically. I've tried to configure my security filter chain to permit requests to /users/registration/**. I can make a GET request to /users/registration/form, fill out the fields, and then click submit. When I submit the form (to /users/registration/create), the browser responds with a 403.

I have the following configuration:

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((requests) -> requests
                .requestMatchers( "/users/registration/**").permitAll()
            );
        return http.build();
    }

I can load /users/registration/form in my browser just fine, but once I submit the form, which sends the data to /users/registration/create, I get a 403 as a response.

In case it's needed...

Here's my controller:

@Controller
public class UserRegistrationsController {
    @Autowired
    private AppUserService appUserService;

    @GetMapping("/users/registration/form")
    public String newRegistration(WebRequest request, Model model) {
        AppUserDto appUserDto = new AppUserDto();
        model.addAttribute("user", appUserDto);
        return "users/registration";
    }

    @PostMapping("/users/registration/create")
    public void createRegistration(
        @ModelAttribute("user") @Valid AppUserDto appUserDto,
        HttpServletRequest request,
        Errors errors
    ) {
        try {
            AppUser registered = appUserService.registerNewUserAccount(appUserDto);
        } catch (AppUserAlreadyExistsException ex) {

        }
    }
}

Not sure if this is the right way to do it, but I tried disabling CSRF and doing the same request again:

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authorize) -> {
            authorize.requestMatchers("/", "/users/registration/**").permitAll();
        });
        http.csrf().disable();
        return http.build();
    }


问:
Creating share of one variable in Top/Bottom 10 of another variable
I have 5 variables: nacional , nacional=1 for natives , nacional=0 for non-natives, FirmsID: NPC_FIC, Establsihmenti;s ID: ESTAB_ID, Occupation codes: CCPCodes and skill ratio: sk_ratio.I am going to compute the share of immigrants in Top 10 and Bottom 10 occupations. Since each firm has more than one establishment more often makes the solution tricky. Any help are apprecited.

input float nacioanal double(NPC_FIC ESTAB_ID) float CCPCodes double sk_ratio
1 500988754       100861 1114 4.359499
1 501950749       893218 1114 4.359499
1 500988750       990861 6914 2.309491
1 501951290       125210 1114 4.359499
1 500988760       100861 1141 5.459470
1 502000740      -820100 1114 4.359499
0 500988762       880861 7514 66.359409
1 500988754       100861 1114 4.359499
1 577988759       210869 4116 6.059120
1 500988092       670869 3216 10.059785

I used 'extremes  sk_ratio CCPCodes, n(10)' to make top/bottom 10 but because of repeated valules I could not go futher.


问:
Chartjs y axes label overflow
We are using react chart js but the problem occurs when we try to show multi-line charts in small widgets with high y-axis values.

Overflow occurs in smaller widths and large y axes numbers. I already try a thousand suffixes but it doesn't work. Is it possible to keep the y-axis constant by making the x-axis smaller? Or handle it responsive.

 function randomTwoNumbers(n1, n2) {
        return Math.floor(Math.random() * (n2 - n1 + 1) + n1)
      }

      function generateData(count) {
        let data = []
        for (let index = 0; index < count; index++) {
          data.push({
            x: `2022-07-${index}T00:00:00.000Z`,
            y: randomTwoNumbers(1000000, 9999999)
          })
        }

        return data
      }
      const data = {
        datasets: [
          {
            data: generateData(100),
            label: 'Temperature',
            borderColor: '#236EF1',
            tension: 0.5,
            pointRadius: 1,
            pointHoverRadius: 5,
            pointHitRadius: 20,
            yAxisID: 'y0'
          },
          {
            data: generateData(100),
            label: 'Humidity',
            borderColor: '#CA840C',
            tension: 0.5,
            pointRadius: 1,
            pointHoverRadius: 5,
            pointHitRadius: 20,
            yAxisID: 'y1'
          }
        ]
      }

      const options = {
        responsive: true,
        resizeDelay: 300,
        scales: {
          x: {
            display: true,
            grid: {
              borderColor: '#5E646E',
              tickColor: '#5E646E',
              display: true,
              drawOnChartArea: false
            },
            ticks: {
              autoSkip: false,
              maxRotation: 0,
              font: {
                size: 10,
                family: 'Inter',
                lineHeight: '12px',
                weight: '500'
              }
            },
            time: {
              unit: 'day',
              displayFormats: {
                minute: 'p',
                hour: 'p',
                day: 'MMM, do'
              }
            },
            type: 'time',
            offset: true,
            adapters: {
              date: {
                locale: {
                  code: 'en-US',
                  formatLong: {},
                  localize: {},
                  match: {}
                }
              }
            }
          },
          y0: {
            display: true,
            grid: {
              borderColor: '#5E646E',
              tickColor: '#5E646E',
              display: true,
              drawOnChartArea: false
            },
            ticks: {
              font: {
                size: 10,
                family: 'Inter',
                lineHeight: '12px',
                weight: '500'
              }
            },
            stack: 'single',
            offset: false
          },
          y1: {
            display: true,
            grid: {
              borderColor: '#5E646E',
              tickColor: '#5E646E',
              display: true,
              drawOnChartArea: false
            },
            ticks: {
              font: {
                size: 10,
                family: 'Inter',
                lineHeight: '12px',
                weight: '500'
              }
            },
            stack: 'single',
            offset: false
          }
        },
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          },
          title: {
            display: false
          },
          tooltip: {
            displayColors: false
          }
        }
      }

      var config = {
        type: 'line',
        data,
        options
      }

      var ctx = document.getElementById('canvas').getContext('2d')
      window.myLine = new Chart(ctx, config)```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.2/chart.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-adapter-moment/1.0.1/chartjs-adapter-moment.min.js"></script>

    <div style="width: 200px">
      <canvas id="canvas"></canvas>
    </div></code>```

Title: Chartjs y axes label overflow

Body:
We are using react chart js but the problem occurs when we try to show multi-line charts in small widgets with high y-axis values.

Overflow occurs in smaller widths and large y axes numbers. I already try a thousand suffixes but it doesn't work. Is it possible to keep the y-axis constant by making the x-axis smaller? Or handle it responsive.

 function randomTwoNumbers(n1, n2) {
        return Math.floor(Math.random() * (n2 - n1 + 1) + n1)
      }

      function generateData(count) {
        let data = []
        for (let index = 0; index < count; index++) {
          data.push({
            x: `2022-07-${index}T00:00:00.000Z`,
            y: randomTwoNumbers(1000000, 9999999)
          })
        }

        return data
      }
      const data = {
        datasets: [
          {
            data: generateData(100),
            label: 'Temperature',
            borderColor: '#236EF1',
            tension: 0.5,
            pointRadius: 1,
            pointHoverRadius: 5,
            pointHitRadius: 20,
            yAxisID: 'y0'
          },
          {
            data: generateData(100),
            label: 'Humidity',
            borderColor: '#CA840C',
            tension: 0.5,
            pointRadius: 1,
            pointHoverRadius: 5,
            pointHitRadius: 20,
            yAxisID: 'y1'
          }
        ]
      }

      const options = {
        responsive: true,
        resizeDelay: 300,
        scales: {
          x: {
            display: true,
            grid: {
              borderColor: '#5E646E',
              tickColor: '#5E646E',
              display: true,
              drawOnChartArea: false
            },
            ticks: {
              autoSkip: false,
              maxRotation: 0,
              font: {
                size: 10,
                family: 'Inter',
                lineHeight: '12px',
                weight: '500'
              }
            },
            time: {
              unit: 'day',
              displayFormats: {
                minute: 'p',
                hour: 'p',
                day: 'MMM, do'
              }
            },
            type: 'time',
            offset: true,
            adapters: {
              date: {
                locale: {
                  code: 'en-US',
                  formatLong: {},
                  localize: {},
                  match: {}
                }
              }
            }
          },
          y0: {
            display: true,
            grid: {
              borderColor: '#5E646E',
              tickColor: '#5E646E',
              display: true,
              drawOnChartArea: false
            },
            ticks: {
              font: {
                size: 10,
                family: 'Inter',
                lineHeight: '12px',
                weight: '500'
              }
            },
            stack: 'single',
            offset: false
          },
          y1: {
            display: true,
            grid: {
              borderColor: '#5E646E',
              tickColor: '#5E646E',
              display: true,
              drawOnChartArea: false
            },
            ticks: {
              font: {
                size: 10,
                family: 'Inter',
                lineHeight: '12px',
                weight: '500'
              }
            },
            stack: 'single',
            offset: false
          }
        },
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          },
          title: {
            display: false
          },
          tooltip: {
            displayColors: false
          }
        }
      }

      var config = {
        type: 'line',
        data,
        options
      }

      var ctx = document.getElementById('canvas').getContext('2d')
      window.myLine = new Chart(ctx, config)

      <canvas id="canvas"></canvas>


问:
How do I set up a WKExtendedRuntimeSession for a standalone WatchOS app on XCode 14?
WatchOS noob here...

I created a standalone WatchOS app in XCode 14.2 and it has no "Extension" target, which I think is the expected behavior. But I would like to use a WKExtendedRuntimeSession and the documentation says to "enable your WatchKit extension’s Background Modes capability and select your app’s session type".

How am I supposed to do this if I don't have an extension?