问:
I can't filter results of a Yajara Datatable in front end of a date range (client side)
I'm tryng to filter a date field between two dates, but this dont work, for some reason the ajax run, but dont change de recordsFiltered, my  code is bellow:

AJAX

```<code>$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {var min = $("#b_datac_inicio").val();var max =  $("#b_datac_fim").val();var date = data[6]; // A coluna "date" é a sétima coluna (índice 6)
</code>```
```<code>  // Verifica se a data está dentro do intervalo de data especificado pelo usuário
  if (min == "" && max == "") {
     return true;
  }
  if (min == "" && date <= max) {
     return true;
  }
  if (max == "" && date >= min) {
     return true;
  }
  if (date <= max && date >= min) {
     return true;
  }
  return false;
</code>```
```<code>});
</code>```
```<code>$('#b_datac_inicio, #b_datac_fim').change( function() {
</code>```
```<code>         table.draw();
 });`
</code>```

PHP / HTML

```<code>                            <input type="date" id="b_datac_inicio" class="form-control form-control-sm filter-input" placeholder="Digite o periodo" data-column="0" />

                            <input type="date" id="b_datac_fim" class="form-control form-control-sm filter-input" placeholder="Digite o periodo" data-column="0" />
</code>```

RESULT OF AJAX (Lan tab of developer options on brownser)

```<code>{draw: 7, recordsTotal: 102, recordsFiltered: 102, data: [,…], input: {draw: "7",…}} data :  [,…] 0 :  {id: 148, user_cad_id: 1, grupo_cad_id: 2, grupo_cad_nome: "Coodenação de Int",…} 1 :  {id: 147, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 2 :  {id: 146, user_cad_id: 1, grupo_cad_id: 2, grupo_cad_nome: "Coodenação de Int",…} 3 :  {id: 145, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 4 :  {id: 144, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 5 :  {id: 143, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 6 :  {id: 142, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 7 :  {id: 141, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 8 :  {id: 140, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 9 :  {id: 139, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} draw :  7 input :  {draw: "7",…} recordsFiltered :  102 recordsTotal :  102
</code>```

I expect that after the "processing" the listed itens of my index change, also the number of total records and showing itens X to XX.

Body:
I'm tryng to filter a date field between two dates, but this dont work, for some reason the ajax run, but dont change de recordsFiltered, my  code is bellow:

AJAX

$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {var min = $("#b_datac_inicio").val();var max =  $("#b_datac_fim").val();var date = data[6]; // A coluna "date" é a sétima coluna (índice 6)

  // Verifica se a data está dentro do intervalo de data especificado pelo usuário
  if (min == "" && max == "") {
     return true;
  }
  if (min == "" && date <= max) {
     return true;
  }
  if (max == "" && date >= min) {
     return true;
  }
  if (date <= max && date >= min) {
     return true;
  }
  return false;

});

$('#b_datac_inicio, #b_datac_fim').change( function() {

         table.draw();
 });`

PHP / HTML

                            <input type="date" id="b_datac_inicio" class="form-control form-control-sm filter-input" placeholder="Digite o periodo" data-column="0" />

                            <input type="date" id="b_datac_fim" class="form-control form-control-sm filter-input" placeholder="Digite o periodo" data-column="0" />

RESULT OF AJAX (Lan tab of developer options on brownser)

{draw: 7, recordsTotal: 102, recordsFiltered: 102, data: [,…], input: {draw: "7",…}} data :  [,…] 0 :  {id: 148, user_cad_id: 1, grupo_cad_id: 2, grupo_cad_nome: "Coodenação de Int",…} 1 :  {id: 147, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 2 :  {id: 146, user_cad_id: 1, grupo_cad_id: 2, grupo_cad_nome: "Coodenação de Int",…} 3 :  {id: 145, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 4 :  {id: 144, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 5 :  {id: 143, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 6 :  {id: 142, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 7 :  {id: 141, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 8 :  {id: 140, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 9 :  {id: 139, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} draw :  7 input :  {draw: "7",…} recordsFiltered :  102 recordsTotal :  102

I expect that after the "processing" the listed itens of my index change, also the number of total records and showing itens X to XX.


来源: stackexchange

问:
VisNetwork: Use VisConfigure argument container to move parameters to dropdownBlock (shinydashboardPlus)
I am having a hard time understanding how the container argument from function VisNetwork::VisConfigure  works. It seems as though one can move the configuration list in another HTML container but my understanding is too limited (and I found no examples online).

My goal would be to place the configuration list in a shinydashboardPlus::dropdownBlock (i.e., in the dashboardHeader leftUI argument), see reproducible example below:

```<code>library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(visNetwork)

# Define the function to retrieve the parameters from VisConfigure
# See: https://github.com/datastorm-open/visNetwork/issues/333
visShinyGetOptionsFromConfigurator <- function (graph, input = paste0(graph$id, "_configurator")) {
  if (!any(class(graph) %in% "visNetwork_Proxy")) {
    stop("Can't use visGetPositions with visNetwork object. Only within shiny & using visNetworkProxy")
  }
  data <- list(id = graph$id, input = input)
  graph$session$sendCustomMessage("visShinyGetOptionsFromConfigurator", data)
  graph
}

ui <- dashboardPage(
  dashboardHeader(title = "Test visConfigure container argument",
                  leftUi = tagList(
                    shinydashboardPlus::dropdownBlock(
                      id = "graphparams",
                      title = "Graph parameters",
                      icon = shiny::icon("gears"),
                      shinyWidgets::prettyRadioButtons(
                        inputId = "physics",
                        label = "Parameters should appear here",
                        choices = c("Yes","No"))))),
  dashboardSidebar(width = 220),
  dashboardBody(
  fluidRow(box(id = "network",
               title = "Network",
               status = "primary",
               width = 12,
               solidHeader = TRUE,
               collapsible = TRUE,
               visNetworkOutput('network'))),
  fluidRow(actionButton("ops", "Options"))))

server <- function(input, output, session) {
  getDiagramPlot <- function(nodes, edges){
    v <- visNetwork(
      nodes,
      edges) %>%
      visIgraphLayout(layout = "layout_on_sphere", physics = TRUE, randomSeed = 1234) %>%
      visPhysics(solver = "hierarchicalRepulsion",
                             hierarchicalRepulsion = list(springLength = 850, nodeDistance = 90),
                             stabilization = "onlyDynamicEdges") %>%
      visOptions(highlightNearest = list(enabled = T, degree = 1, hover = F), autoResize = TRUE, collapse = FALSE) %>%
      visEdges(color = list(highlight = "red")) %>%
      visEdges(arrows = edges$arrows) %>%
      visConfigure(enabled = TRUE, filter = "physics", container = NULL) %>%
      visInteraction(multiselect = F)
    return(v)
  }

  nodes <- data.frame(id = 0:20, label = LETTERS[1:21])
  edges <- data.frame(from = 0, to = 1:20, value = seq(0.35, 0.5, length.out = 20))

  output$network <- renderVisNetwork(
    getDiagramPlot(nodes, edges)
  )

  # Send to console the settings from VisConfigure
  # See: https://github.com/datastorm-open/visNetwork/issues/333
  observeEvent(input$ops, { visNetworkProxy("network") %>% visShinyGetOptionsFromConfigurator() })
  observe({ if(!is.null(input$network_configurator)) print(input$network_configurator)
  })

  session$onSessionEnded(stopApp)
}

shinyApp(ui, server)

</code>```

Any idea?

Best,

C.

I tried to set container = input$graphparams but it didn't work.

ContentLicense: CC BY-SA 4.0

Body:
I am having a hard time understanding how the container argument from function VisNetwork::VisConfigure  works. It seems as though one can move the configuration list in another HTML container but my understanding is too limited (and I found no examples online).

My goal would be to place the configuration list in a shinydashboardPlus::dropdownBlock (i.e., in the dashboardHeader leftUI argument), see reproducible example below:

library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(visNetwork)

# Define the function to retrieve the parameters from VisConfigure
# See: https://github.com/datastorm-open/visNetwork/issues/333
visShinyGetOptionsFromConfigurator <- function (graph, input = paste0(graph$id, "_configurator")) {
  if (!any(class(graph) %in% "visNetwork_Proxy")) {
    stop("Can't use visGetPositions with visNetwork object. Only within shiny & using visNetworkProxy")
  }
  data <- list(id = graph$id, input = input)
  graph$session$sendCustomMessage("visShinyGetOptionsFromConfigurator", data)
  graph
}

ui <- dashboardPage(
  dashboardHeader(title = "Test visConfigure container argument",
                  leftUi = tagList(
                    shinydashboardPlus::dropdownBlock(
                      id = "graphparams",
                      title = "Graph parameters",
                      icon = shiny::icon("gears"),
                      shinyWidgets::prettyRadioButtons(
                        inputId = "physics",
                        label = "Parameters should appear here",
                        choices = c("Yes","No"))))),
  dashboardSidebar(width = 220),
  dashboardBody(
  fluidRow(box(id = "network",
               title = "Network",
               status = "primary",
               width = 12,
               solidHeader = TRUE,
               collapsible = TRUE,
               visNetworkOutput('network'))),
  fluidRow(actionButton("ops", "Options"))))

server <- function(input, output, session) {
  getDiagramPlot <- function(nodes, edges){
    v <- visNetwork(
      nodes,
      edges) %>%
      visIgraphLayout(layout = "layout_on_sphere", physics = TRUE, randomSeed = 1234) %>%
      visPhysics(solver = "hierarchicalRepulsion",
                             hierarchicalRepulsion = list(springLength = 850, nodeDistance = 90),
                             stabilization = "onlyDynamicEdges") %>%
      visOptions(highlightNearest = list(enabled = T, degree = 1, hover = F), autoResize = TRUE, collapse = FALSE) %>%
      visEdges(color = list(highlight = "red")) %>%
      visEdges(arrows = edges$arrows) %>%
      visConfigure(enabled = TRUE, filter = "physics", container = NULL) %>%
      visInteraction(multiselect = F)
    return(v)
  }

  nodes <- data.frame(id = 0:20, label = LETTERS[1:21])
  edges <- data.frame(from = 0, to = 1:20, value = seq(0.35, 0.5, length.out = 20))

  output$network <- renderVisNetwork(
    getDiagramPlot(nodes, edges)
  )

  # Send to console the settings from VisConfigure
  # See: https://github.com/datastorm-open/visNetwork/issues/333
  observeEvent(input$ops, { visNetworkProxy("network") %>% visShinyGetOptionsFromConfigurator() })
  observe({ if(!is.null(input$network_configurator)) print(input$network_configurator)
  })

  session$onSessionEnded(stopApp)
}

shinyApp(ui, server)

Any idea?

Best,

C.

I tried to set container = input$graphparams but it didn't work.


问:
Gitlab Package Registry not deleted object
Deleting a package from the UI, the package is deleted from the UI, but does not remove an object from uploaded files in the path /var/opt/gitlab/gitlab-rails/shared/packages

Does this run with a cron job or are they not deleted at all?


问:
Having issues? Our Microsoft Customer Care Helpline team has your back
Update the Gmail app to the most recent version before you start:
On your phone or tablet, launch the Google Play Store application.
In the search box, enter “Gmail,” and then click Update.

Follow the steps for your account type:

Outlook.com users: skip this step
Exchange or other accounts: you may have to ask your IT admin or email provider for server settings and set up your account manually
Microsoft 365 work or school: you may see a Redirect request screen. Tap OK
On the Incoming server settings screen, change your server to outlook.office365.com
4. Follow any prompts you may get for security or device permissions, sync settings, and more.

If you have a Microsoft 365 work or school account, you may also be asked to confirm Remote security administration and approve additional security measures. In this case, choose OK or Activate.

Go to the inbox you just set up. If you see an email that says “Action Required to Sync Email,” open it and tap Use another Mail app instead. If you don’t see this message and emails are syncing, skip this step.

Swipe down from the top of your screen to pull down the Android notification bar. tap the notification if you get one that says “Unable to sync calendar and contacts.” Next, select Allow to grant access and you are done.


问:
Redshift - Relation does not exist on materialized view with AutoRefresh On
one of our users is getting an error (only occasionally) on a view that has autorefresh on. the name of the table is vwdeviceplatform. Is it because the view is being autofreshed at the time they are running the query? Any way to avoid that? We don't want to schedule manual refreshes.

```<code>Invalid operation. Relation "mv_tbl_vwdeviceplatform_0" does not exist.
</code>```

User is using dbeaver

Body:
one of our users is getting an error (only occasionally) on a view that has autorefresh on. the name of the table is vwdeviceplatform. Is it because the view is being autofreshed at the time they are running the query? Any way to avoid that? We don't want to schedule manual refreshes.

Invalid operation. Relation "mv_tbl_vwdeviceplatform_0" does not exist.

User is using dbeaver


问:
Is it possible don't create a lot of variables of a struct for read and update the value inside?
I have a simple code for update an user in a viewModel but I want to Know if is it possible that I can use other way for show one or much properties of a struct and make changes without create new variables

This is my code...

```<code>struct UpdateEmployee: View {

    @ObservedObject var employeesViewModel : EmployeesViewModel
    @Binding var employee: User
    @State var name = ""
    @State var correo = ""
    @State var genero = ""
    var body: some View {
        VStack{
            VStack{
                Text("Nombre")
                    .foregroundColor(Color.black)
                 TextField("Nombre", text: $name)
                    .frame(maxHeight: 45)
                    .border(Color.gray, width: 0.5)
                    .padding([.horizontal, .bottom, .top], 30)
            }
            VStack{
                Text("Correo")
                    .foregroundColor(Color.black)
                TextField("Correo", text: $correo)
                    .frame(maxHeight: 45)
                    .border(Color.gray, width: 0.5)
                    .padding([.horizontal, .bottom, .top], 30)
            }
            VStack{
                Text("Genero")
                    .foregroundColor(Color.black)

                TextField("Genero", text: $genero)
                    .frame(maxHeight: 45)
                    .border(Color.gray, width: 0.5)
                    .padding([.horizontal, .bottom, .top], 30)
            }

            Button {
                print(employee.id)
                employee.name = name
                employee.email = correo
                employee.sex = genero
                employeesViewModel.updateEmployee(employee: employee)
            } label: {
                Text("Actualizar")
            }
            Spacer()
        }
        .onAppear{
            self.name = employee.name ?? ""
            self.correo = employee.email ?? ""
            self.genero = employee.sex ?? ""

        }

    }

}
</code>```

In this code I create variables name, email and sex, those are inside of struct User (employee), I like to know if it possible don't create the variables.

Body:
I have a simple code for update an user in a viewModel but I want to Know if is it possible that I can use other way for show one or much properties of a struct and make changes without create new variables

This is my code...

struct UpdateEmployee: View {

    @ObservedObject var employeesViewModel : EmployeesViewModel
    @Binding var employee: User
    @State var name = ""
    @State var correo = ""
    @State var genero = ""
    var body: some View {
        VStack{
            VStack{
                Text("Nombre")
                    .foregroundColor(Color.black)
                 TextField("Nombre", text: $name)
                    .frame(maxHeight: 45)
                    .border(Color.gray, width: 0.5)
                    .padding([.horizontal, .bottom, .top], 30)
            }
            VStack{
                Text("Correo")
                    .foregroundColor(Color.black)
                TextField("Correo", text: $correo)
                    .frame(maxHeight: 45)
                    .border(Color.gray, width: 0.5)
                    .padding([.horizontal, .bottom, .top], 30)
            }
            VStack{
                Text("Genero")
                    .foregroundColor(Color.black)

                TextField("Genero", text: $genero)
                    .frame(maxHeight: 45)
                    .border(Color.gray, width: 0.5)
                    .padding([.horizontal, .bottom, .top], 30)
            }

            Button {
                print(employee.id)
                employee.name = name
                employee.email = correo
                employee.sex = genero
                employeesViewModel.updateEmployee(employee: employee)
            } label: {
                Text("Actualizar")
            }
            Spacer()
        }
        .onAppear{
            self.name = employee.name ?? ""
            self.correo = employee.email ?? ""
            self.genero = employee.sex ?? ""

        }

    }

}

In this code I create variables name, email and sex, those are inside of struct User (employee), I like to know if it possible don't create the variables.


问:
Android: EditText SNN form validation
I have such a piece of code

```<code>private fun snnFormatValidation() {
    binding.snnText.addTextChangedListener(object : TextWatcher {
        private var spaceDeleted = false
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            //in-progress
        }

        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
            val charDeleted = s.subSequence(start, start + count)
            spaceDeleted = " " == charDeleted.toString()
        }

        override fun afterTextChanged(editable: Editable) {
            binding.snnText.removeTextChangedListener(this)
            val cursorPosition: Int = binding.snnText.selectionStart
            val withSpaces = formatText(editable)
            binding.snnText.setText(withSpaces)
            binding.snnText.setSelection(cursorPosition + (withSpaces.length - editable.length))
            if (spaceDeleted) {
                binding.snnText.setSelection(binding.snnText.selectionStart - 1)
                spaceDeleted = false
            }
            binding.snnText.addTextChangedListener(this)
        }

        private fun formatText(text: CharSequence): String {
            val formatted = StringBuilder()
            var count = 0
            for (i in text.indices) {
                if (Character.isDigit(text[i])) {
                    if (count % 4 == 0 && count > 0) formatted.append("-")
                    formatted.append(text[i])
                    ++count
                }
            }
            return formatted.toString()
        }
    })
}
</code>```

But when I enter 5 characters, I catch the following error

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.siolla.app, PID: 28136
java.lang.IndexOutOfBoundsException: setSpan (7 ... 7) ends beyond length 6
at android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1326)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:685)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:677)
at androidx.emoji2.text.SpannableBuilder.setSpan(SpannableBuilder.java:140)
at android.text.Selection.setSelection(Selection.java:94)
at android.text.Selection.setSelection(Selection.java:78)
at android.text.Selection.setSelection(Selection.java:153)
at android.widget.EditText.setSelection(EditText.java:136)
at com.siolla.application.ui.snn.SnnFragment$snnFormatValidation$1.afterTextChanged(SnnFragment.kt:76)

Can anyone explain or show me what I'm doing wrong?

Title: Android: EditText SNN form validation

Body:
I have such a piece of code

private fun snnFormatValidation() {
    binding.snnText.addTextChangedListener(object : TextWatcher {
        private var spaceDeleted = false
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            //in-progress
        }

        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
            val charDeleted = s.subSequence(start, start + count)
            spaceDeleted = " " == charDeleted.toString()
        }

        override fun afterTextChanged(editable: Editable) {
            binding.snnText.removeTextChangedListener(this)
            val cursorPosition: Int = binding.snnText.selectionStart
            val withSpaces = formatText(editable)
            binding.snnText.setText(withSpaces)
            binding.snnText.setSelection(cursorPosition + (withSpaces.length - editable.length))
            if (spaceDeleted) {
                binding.snnText.setSelection(binding.snnText.selectionStart - 1)
                spaceDeleted = false
            }
            binding.snnText.addTextChangedListener(this)
        }

        private fun formatText(text: CharSequence): String {
            val formatted = StringBuilder()
            var count = 0
            for (i in text.indices) {
                if (Character.isDigit(text[i])) {
                    if (count % 4 == 0 && count > 0) formatted.append("-")
                    formatted.append(text[i])
                    ++count
                }
            }
            return formatted.toString()
        }
    })
}

But when I enter 5 characters, I catch the following error

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.siolla.app, PID: 28136
java.lang.IndexOutOfBoundsException: setSpan (7 ... 7) ends beyond length 6
at android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1326)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:685)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:677)
at androidx.emoji2.text.SpannableBuilder.setSpan(SpannableBuilder.java:140)
at android.text.Selection.setSelection(Selection.java:94)
at android.text.Selection.setSelection(Selection.java:78)
at android.text.Selection.setSelection(Selection.java:153)
at android.widget.EditText.setSelection(EditText.java:136)
at com.siolla.application.ui.snn.SnnFragment$snnFormatValidation$1.afterTextChanged(SnnFragment.kt:76)

Can anyone explain or show me what I'm doing wrong?


问:
Execute Postgresql procedure in databricks pyspark
how are you?

I'm trying to run a postgresql stored procedure inside Databricks using the following (obviously with my credentials and my function) but wont work

```<code>jdbcDF = spark.read.format("jdbc").option("url","jdbc:postgresql://host:5432/db").option("driver", "org.postgresql.Driver").option("query", "SELECT * from  function()").option("user", "user").option("password", "password").load()
</code>```

this procedure deletes some rows under some conditions, it executes successfully inside databricks, but when I go to look at the table in postgresql, there was no change, as if it had not been executed. Within postgresql the function works normally. Any other options I can try?

ps. I can't connect to the database using psycopg, so I need to go with something like this

Body:
how are you?

I'm trying to run a postgresql stored procedure inside Databricks using the following (obviously with my credentials and my function) but wont work

jdbcDF = spark.read.format("jdbc").option("url","jdbc:postgresql://host:5432/db").option("driver", "org.postgresql.Driver").option("query", "SELECT * from  function()").option("user", "user").option("password", "password").load()

this procedure deletes some rows under some conditions, it executes successfully inside databricks, but when I go to look at the table in postgresql, there was no change, as if it had not been executed. Within postgresql the function works normally. Any other options I can try?

ps. I can't connect to the database using psycopg, so I need to go with something like this


问:
How to emulate devices with jest and puppeteer
Since puppeteer.devices() got removed, there are no blog posts or other helping sources on how to emulate a certain device with a jest and puppeteer setup.

I'm not a JS or node expert, I'm new to jest and puppeteer, but I need to test my frontend.

So I got the following jest test:

/**
 * @jest-environment puppeteer
 */

const { toMatchImageSnapshot } = require('jest-image-snapshot');
expect.extend({ toMatchImageSnapshot });

const puppet = require('puppeteer');
const iPhone = puppet.KnownDevices['iPhone X'];
const Tablet = puppet.KnownDevices['iPad portrait'];
// past three lines do just nothing and i don't know how to fix that

describe('Visual Regression Testing', () => {

    test('Home Page Tablet', async function(){
        await page.emulate( Tablet );
        await page.goto('http://example.com', {
            waitUntil: 'networkidle0',
        });

        const screenshot = await page.screenshot();
        expect(screenshot).toMatchImageSnapshot({
            failureThreshold: '0.10',
            failureThresholdType: 'percent',
        });
    });

});
```
<p>these node packages are relevant, I guess:</p>
<pre class="lang-json prettyprint-override"><code>        "jest": "^29.3.1",
        "jest-image-snapshot": "^6.1.0",
        "jest-puppeteer": "^6.2.0",
        "puppeteer": "^19.5.0",
</code>```

Does anyone have an idea how the code from the puppeteer docs

import {KnownDevices} from 'puppeteer';
const iPhone = KnownDevices['iPhone 6'];
```

will transform to work with jest?

Body:
Since puppeteer.devices() got removed, there are no blog posts or other helping sources on how to emulate a certain device with a jest and puppeteer setup.

I'm not a JS or node expert, I'm new to jest and puppeteer, but I need to test my frontend.

So I got the following jest test:

/**
 * @jest-environment puppeteer
 */

const { toMatchImageSnapshot } = require('jest-image-snapshot');
expect.extend({ toMatchImageSnapshot });

const puppet = require('puppeteer');
const iPhone = puppet.KnownDevices['iPhone X'];
const Tablet = puppet.KnownDevices['iPad portrait'];
// past three lines do just nothing and i don't know how to fix that

describe('Visual Regression Testing', () => {

    test('Home Page Tablet', async function(){
        await page.emulate( Tablet );
        await page.goto('http://example.com', {
            waitUntil: 'networkidle0',
        });

        const screenshot = await page.screenshot();
        expect(screenshot).toMatchImageSnapshot({
            failureThreshold: '0.10',
            failureThresholdType: 'percent',
        });
    });

});

these node packages are relevant, I guess:

        "jest": "^29.3.1",
        "jest-image-snapshot": "^6.1.0",
        "jest-puppeteer": "^6.2.0",
        "puppeteer": "^19.5.0",

Does anyone have an idea how the code from the puppeteer docs

import {KnownDevices} from 'puppeteer';
const iPhone = KnownDevices['iPhone 6'];

will transform to work with jest?


问:
How to insert charater in next of text-cursor in text widget in tkinter in Python?
I started Python recently, and I want to put the auto-completing in my custom file editor. But, I cannot make auto-completing quotes, brackets, etc like in other famous file editors. (like Visual Studio)

I tried to code auto-completing like this:

```<code>def keyevent(key):
    k = key.keysym
    print(k)
    if key == "apostrophe":
        ent.insert("end", "\'")
    elif key == "quotedbl":
        ent.insert("end", "\"")
    elif key == "bracketleft":
        ent.insert("end", "]")
    elif key == "parenleft":
        ent.insert("end", ")")
    elif key == "braceleft":
        ent.insert("end", "}")

app.bind("<Key>", keyevent)
</code>```

I thought it will act like what I want.
and when I run this code, nothing happens on the text widget.
How can I insert charater in next of text-cursor?

Body:
I started Python recently, and I want to put the auto-completing in my custom file editor. But, I cannot make auto-completing quotes, brackets, etc like in other famous file editors. (like Visual Studio)

I tried to code auto-completing like this:

def keyevent(key):
    k = key.keysym
    print(k)
    if key == "apostrophe":
        ent.insert("end", "\'")
    elif key == "quotedbl":
        ent.insert("end", "\"")
    elif key == "bracketleft":
        ent.insert("end", "]")
    elif key == "parenleft":
        ent.insert("end", ")")
    elif key == "braceleft":
        ent.insert("end", "}")

app.bind("<Key>", keyevent)

I thought it will act like what I want.
and when I run this code, nothing happens on the text widget.
How can I insert charater in next of text-cursor?


问:
Cross checking table data to calculate a sum
I have a fixtures table that is as follows:

FixtureID | HomeTeam | AwayTeam | isResult

And then a results table:

ResultID | FixtureID | TeamID | Conduct

Each team will enter a record with scores and conduct (out of 5), however, I need to calculate the conduct of the teams and that's turning out to be a bit tricky.

I have the following:

SELECT IF(TeamID = f.HomeTeam,f.AwayTeam,f.HomeTeam) RatedTeamID, SUM(Conduct) / COUNT(*) AS Conduct FROM Fixtures f INNER JOIN Results r ON r.FixtureID = f.FixtureID WHERE f.IsResult = 1 GROUP BY RatedTeamID

However I need to count the conduct scores for the team that is not the team that has left the conduct rating and I'm utterly confused as to how I can get it as the Conduct column is currently returning the Conduct they have left for other teams, rather than calculating the conduct rating left for them.


问:
Updating post count via Javascript Fetch not showing
I want to show the like count when a user clicks on the like button (e.g 1 Like, 2 Likes) using Fetch but the count is not showing.

I am using the Django to create the Like and Unlike Scenario. Here is my code:

VIEWS.PY

```<code>def update_like(request):
    username = request.user
    post_id = request.GET.get('post_id')
    post = NewTweet.objects.get(id = post_id)

    like_filter = LikesPost.objects.filter(post_id=post_id, username=username).first()

    if like_filter == None:
        new_like = LikesPost.objects.create(post_id=post_id, username=username)
        new_like.save()
        post.save()
        return HttpResponseRedirect(reverse("index"))
    else:
        like_filter.delete()
        post.save()
        return HttpResponseRedirect(reverse("index"))
</code>```

MAIN.JS

```<code>document.addEventListener('DOMContentLoaded', function () {
    const likeIcon = document.querySelector("#likeBtn")
    likeIcon.addEventListener("click", handleLike)

    function handleLike(event) {
        //save the parent element in id
        let id = parseInt(event.target.parentElement.dataset.id)
        let likes = parseInt(event.target.previousElementSibling.innerText)

        fetch(`/updatelike/${id}`, {
            method: "POST",
        })
            .then(response => response.json())
            .then((data) => {
                if (data.likes <= 1) {
                    document.querySelector('#likeCount').innerHTML = `${likes + 1} like`
                }
                else {
                    document.querySelector('#likeCount').innerHTML = `${likes + 1} likes`
                }

            })
    }
})
</code>```

INDEX.HTML

```<code>{% extends "network/layout.html" %}

{% block body %}
                <div class="middle-sidebar">
                    <div class="main-page-header mt-3 sticky-top">Home</div>
                    <div class="main-page-input">
                        <!-- <form class="d-flex flex-column"> -->
                            <div class="row">
                                <div class="col-2 main-page-header-profile-picture">
                                    <img src="https://i.pinimg.com/originals/a6/58/32/a65832155622ac173337874f02b218fb.png" class="main-page-header-profile-picture" alt="profile-picture"/>
                                </div>
                                <div class="col-10">
                                    <div class="main-page-input-box">
                                        <form method="POST" action="new_post">
                                        {% csrf_token %}
                                            {{ form.as_p }}
                                            <div>
                                                <textarea name="caption" id="tweet-box" class="form-control main-page-tweet-box text-wrap" cols="30" rows="10" placeholder="What's happening">
                                                </textarea>
                                                    <!-- <input type="text" class="form-control main-page-tweet-box text-wrap" id="exampleFormControlInput1" placeholder="What's happening"> -->
                                            </div>
                                                <div class="main-page-input-privacy pb-2 mt-3">
                                                    <i class="fas fa-globe-americas main-page-input-privacy-icon"></i>
                                                    <span class="ain-page-input-privacy-text ml-2">Everyone can reply</span>
                                                </div>
                                            </div>
                                            <div class="main-page-input-icons mt-3">
                                                <ul class="main-page-input-icons-ul">
                                                    <li><i class="fa-solid fa-image"></i></li>
                                                    <li><i class="fa-solid fa-square-poll-horizontal"></i></li>
                                                    <li><i class="fa-solid fa-face-grin"></i></li>
                                                    <li><i class="fa-regular fa-calendar"></i></li>
                                                    <li><i class="fa-solid fa-location-dot"></i></li>
                                                </ul>
                                                <button type="submit" class="btn btn-primary rounded-pill px-4 main-page-tweet-button"><strong>Tweet</strong></button>
                                            </div>
                                        </form>

                                </div>
                            </div>
                    <!-- </form> -->
                    </div>
                    <div class="tweet-feed">
                        {% for post in all_post %}
                            <div class="tweet">
                                <img src="http://placeimg.com/140/140/people" alt="author profile picture" class="tweet-author-image"/>
                                <div class="tweet-feed-content">
                                    <div class="tweet-header">
                                        <a href="#" class="tweet-author-username">{{post.user}}</a>
                                        <div class="tweet-author-handle">@ {{post.user}</div>
                                        <div class="tweet-dot">.</div>
                                        <div class="tweeted-time">{{post.created_at}}</div>
                                    </div>
                                    <div class="tweet-content">
                                        <div class="tweet-created-content">{{post.caption}}</div>
                                    </div>
                                    <span id="likeCount"></span>
                                    <div class="engagement-icons">
                                        <ul class="engagement-icons-ul mt-1">
                                            <li><i class="fa-regular fa-comment"></i></li>
                                            <li><i class="fa-solid fa-retweet"></i></li>
                                            <li><a href="/update_like?post_id={{post.id}}"><i id="LikeBtn" class="fa-regular fa-heart"></i></a></li>
                                            <li><i class="fa-solid fa-arrow-up-from-bracket"></i></li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        {% endfor %}
                        </div>
                    </div>
                </div>
{% endblock %}
</code>```

LAYOUT.HTML

```<code>{% load static %}

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>{% block title %}Social Network{% endblock %}</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
        <!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> -->
        <link href="{% static 'network/styles.css' %}" rel="stylesheet">
        <script src="https://kit.fontawesome.com/984d0a3d8c.js" crossorigin="anonymous"></script>
    </head>
    <body>

        <div class="col-5">
            {% block body %}
            {% endblock %}
        </div>
        <script src='{% static 'network/js/main.js' %}'></script>
    </body>
</html>
</code>```

MODELS.PY

```<code>class NewTweet(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    caption = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.user} posted {self.caption}"

class LikesPost(models.Model):
    post_id = models.CharField(max_length=100)
    username = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.username
</code>```

I've tried to adjust this but the likeCount is still not showing

Body:
I want to show the like count when a user clicks on the like button (e.g 1 Like, 2 Likes) using Fetch but the count is not showing.

I am using the Django to create the Like and Unlike Scenario. Here is my code:

VIEWS.PY

def update_like(request):
    username = request.user
    post_id = request.GET.get('post_id')
    post = NewTweet.objects.get(id = post_id)

    like_filter = LikesPost.objects.filter(post_id=post_id, username=username).first()

    if like_filter == None:
        new_like = LikesPost.objects.create(post_id=post_id, username=username)
        new_like.save()
        post.save()
        return HttpResponseRedirect(reverse("index"))
    else:
        like_filter.delete()
        post.save()
        return HttpResponseRedirect(reverse("index"))

MAIN.JS

document.addEventListener('DOMContentLoaded', function () {
    const likeIcon = document.querySelector("#likeBtn")
    likeIcon.addEventListener("click", handleLike)

    function handleLike(event) {
        //save the parent element in id
        let id = parseInt(event.target.parentElement.dataset.id)
        let likes = parseInt(event.target.previousElementSibling.innerText)

        fetch(`/updatelike/${id}`, {
            method: "POST",
        })
            .then(response => response.json())
            .then((data) => {
                if (data.likes <= 1) {
                    document.querySelector('#likeCount').innerHTML = `${likes + 1} like`
                }
                else {
                    document.querySelector('#likeCount').innerHTML = `${likes + 1} likes`
                }

            })
    }
})

INDEX.HTML

{% extends "network/layout.html" %}

{% block body %}

Home

                                        <form method="POST" action="new_post">
                                        {% csrf_token %}
                                            {{ form.as_p }}

                                                <textarea name="caption" id="tweet-box" class="form-control main-page-tweet-box text-wrap" cols="30" rows="10" placeholder="What's happening">
                                                </textarea>

                                                    Everyone can reply

                                                <button type="submit" class="btn btn-primary rounded-pill px-4 main-page-tweet-button">Tweet</button>

                                        </form>

                        {% for post in all_post %}

                                        {{post.user}}

@ {{post.user}

.

{{post.created_at}}

{{post.caption}}

                        {% endfor %}

{% endblock %}

LAYOUT.HTML

{% load static %}

<!DOCTYPE html>

        <title>{% block title %}Social Network{% endblock %}</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">

        <link href="{% static 'network/styles.css' %}" rel="stylesheet">

            {% block body %}
            {% endblock %}

MODELS.PY

class NewTweet(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    caption = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.user} posted {self.caption}"

class LikesPost(models.Model):
    post_id = models.CharField(max_length=100)
    username = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.username

I've tried to adjust this but the likeCount is still not showing


问:
R - finding local maxima in time-series-type data
I was looking at the labor participation rate in the US with the help of the FRED datasets PAYEMS and POPTOTUSA647NWDB. As you may expect, labor participation goes up and down through recessions and booms. In the figure, I'd like to indicate the local maxima.

My first approach is to visually select date cut-offs between the maxima and determine the maximum value between them

```<code>date_breaks <-
    ymd(c(
        19680101,
        19750101,
        19810101,
        19920101,
        20020101,
        20100101,
        20210101,
        20300101
    ))

maxes <-
    jobspop %>%
    mutate(periods = cut(date, breaks = date_breaks)) %>%
    group_by(periods) %>%
    slice_max(workingpop, n = 1) %>%
    ungroup() %>%
    drop_na()
</code>```

Although this approach works, it depends on me to select the correct cut-off dates. Are there better ways to detect local maxima automatically?

--edit--
This question was flagged because it seemed similar to others. My data is significantly more noisy than the example data in the proposed similar questions.

Reference - example dataframe

```<code>> jobspop
# A tibble: 756 x 4
   date         PAYEMS POPTOTUSA647NWDB workingpop
   <date>        <dbl>            <dbl>      <dbl>
 1 1960-01-01 54274000        180671000      0.300
 2 1960-02-01 54513000        180671000      0.302
 3 1960-03-01 54454000        180671000      0.301
 4 1960-04-01 54813000        180671000      0.303
 5 1960-05-01 54475000        180671000      0.302
 6 1960-06-01 54348000        180671000      0.301
 7 1960-07-01 54306000        180671000      0.301
</code>```

Complete code: https://github.com/robhanssen/econ-analysis/blob/main/scripts/jobs_report.r

Body:
I was looking at the labor participation rate in the US with the help of the FRED datasets PAYEMS and POPTOTUSA647NWDB. As you may expect, labor participation goes up and down through recessions and booms. In the figure, I'd like to indicate the local maxima.

My first approach is to visually select date cut-offs between the maxima and determine the maximum value between them

date_breaks <-
    ymd(c(
        19680101,
        19750101,
        19810101,
        19920101,
        20020101,
        20100101,
        20210101,
        20300101
    ))

maxes <-
    jobspop %>%
    mutate(periods = cut(date, breaks = date_breaks)) %>%
    group_by(periods) %>%
    slice_max(workingpop, n = 1) %>%
    ungroup() %>%
    drop_na()

Although this approach works, it depends on me to select the correct cut-off dates. Are there better ways to detect local maxima automatically?

--edit--
This question was flagged because it seemed similar to others. My data is significantly more noisy than the example data in the proposed similar questions.

Reference - example dataframe

> jobspop
# A tibble: 756 x 4
   date         PAYEMS POPTOTUSA647NWDB workingpop
   <date>        <dbl>            <dbl>      <dbl>
 1 1960-01-01 54274000        180671000      0.300
 2 1960-02-01 54513000        180671000      0.302
 3 1960-03-01 54454000        180671000      0.301
 4 1960-04-01 54813000        180671000      0.303
 5 1960-05-01 54475000        180671000      0.302
 6 1960-06-01 54348000        180671000      0.301
 7 1960-07-01 54306000        180671000      0.301

Complete code: https://github.com/robhanssen/econ-analysis/blob/main/scripts/jobs_report.r


问:
Join two models when only 1 model has a foreign key
```<code>ModelA
------
id
atr_a
atr_b
atr_c
is_active
</code>```
```<code>ModelB
------
id
atr_d
atr_e
modelA_id
</code>```

Without modifying either model, I need to include ModelB data in my ModelA ViewSet.  I am not sure how this should be done given my constraints.

```<code>class ModelAViewSet(...):
    endpoint_permissions = [...]

    queryset = (
        ModelA.objects.filter(is_active=True)
    )
    serializer_class = ModelASerializer
    filterset_class = ModelAFilter
</code>```

If I had the foreign key included in ModelA, it would be trivial, simplying including the ModelB serializer in my modelA serializer for the foreign key column, but without that, I am not sure on the approach. (Adding ModelB as a foreign key modelA is not an option)

```<code>class ModelASerializer(serializers.ModelSerializer):
    atr_a = serializers.CharField()
    atr_b = serializers.CharField()
    atr_c = serializers.CharField()
    class Meta:
        ref_name = "ModelA"
        model = ModelA
        fields = (
            "id",
            "atr_a",
            "atr_b",
            "atr_c"
        )
</code>```
```<code>class ModelBSerializer(serializers.ModelSerializer):
    atr_d = serializers.CharField()
    atr_e = serializers.CharField()
    class Meta:
        ref_name = "ModelB"
        model = ModelB
        fields = (
            "id",
            "atr_d",
            "atr_e"
        )
</code>```

Wanted output

```<code>{
id : 1,
atr_a : "a",
atr_b : "b",
atr_c : "c",
atr_d : "d",
atr_e : "e"
}
</code>```

Body:
ModelA
------
id
atr_a
atr_b
atr_c
is_active

ModelB
------
id
atr_d
atr_e
modelA_id

Without modifying either model, I need to include ModelB data in my ModelA ViewSet.  I am not sure how this should be done given my constraints.

class ModelAViewSet(...):
    endpoint_permissions = [...]

    queryset = (
        ModelA.objects.filter(is_active=True)
    )
    serializer_class = ModelASerializer
    filterset_class = ModelAFilter

If I had the foreign key included in ModelA, it would be trivial, simplying including the ModelB serializer in my modelA serializer for the foreign key column, but without that, I am not sure on the approach. (Adding ModelB as a foreign key modelA is not an option)

class ModelASerializer(serializers.ModelSerializer):
    atr_a = serializers.CharField()
    atr_b = serializers.CharField()
    atr_c = serializers.CharField()
    class Meta:
        ref_name = "ModelA"
        model = ModelA
        fields = (
            "id",
            "atr_a",
            "atr_b",
            "atr_c"
        )

class ModelBSerializer(serializers.ModelSerializer):
    atr_d = serializers.CharField()
    atr_e = serializers.CharField()
    class Meta:
        ref_name = "ModelB"
        model = ModelB
        fields = (
            "id",
            "atr_d",
            "atr_e"
        )

Wanted output

{
id : 1,
atr_a : "a",
atr_b : "b",
atr_c : "c",
atr_d : "d",
atr_e : "e"
}


问:
Row and column that matches with 2 table in excel
Having a table as below:

Need to fill the value based on row and column

output expected


问:
auto scale docker swarm in GCP
Any help on auto scale docker swarm in GCP. Was trying for a reference link or coe sample for the same.

Can't fin a simplest link to use docker API

Title: auto scale docker swarm in GCP


问:
Is there a way to calculate overlap percentage/score from a perspective of smaller chemical structure?
I'm trying to identify individual components of a hetero-molecule. For example, for A = B + C + D, taking A as the reference, I want to find B from B_list = [B1,B2,B3,...,Bn]. Identifying B works using A.HasSubstructMatch(B1/B2..Bn) from rdkit, however it is true only if there is 100% match. Can I identify B from B_list which has a match of say 99% with A.

I can't seem to find a way to calculate scores for items in B_list against A. The fingerprint (FP) scores are not helping because I want to get scores purely from perspective of B. The FP metrics work both ways!!

I tried using FP metric i.e., DataStructs.FingerprintSimilarity(A,B) but this doesn't seem to work as I expected. I generated FP for each B in B_list against A and used a cut-off to filter the list. However, my B (see below) with best FP metric doesn't seem to be a sub-structure of A. It is something else.

For your ref:
A='COC1=CC(C2=CN(C)C(=O)C3=CN=CC=C23)=CC(OC)=C1CN1CCN(CCOCCOCC(=O)NCC2=CC=C(S(=O)(=O)NC3=CC=CC4=C3\[NH\]C=C4Cl)C=C2)CC1'

```<code>B_with_best_FP = 'CCOC1=CC(C(C)(C)C)=CC=C1C1=N\[C@@\](C)(C2=CC=C(Cl)C=C2)\[C@@\](C)(C2=CC=C(Cl)C=C2)N1C(=O)N1CCN(CCCS(C)(=O)=O)CC1'
</code>```

My_ideal_B = B from B_list which has maximum sub-structure match with A with a score. B_with_best_FP isn't the one.

B_list = https://drive.google.com/file/d/1BjcY8BLJOE98-OQT_zRSoRr7tWcO72Nt/view?usp=sharing

Body:
I'm trying to identify individual components of a hetero-molecule. For example, for A = B + C + D, taking A as the reference, I want to find B from B_list = [B1,B2,B3,...,Bn]. Identifying B works using A.HasSubstructMatch(B1/B2..Bn) from rdkit, however it is true only if there is 100% match. Can I identify B from B_list which has a match of say 99% with A.

I can't seem to find a way to calculate scores for items in B_list against A. The fingerprint (FP) scores are not helping because I want to get scores purely from perspective of B. The FP metrics work both ways!!

I tried using FP metric i.e., DataStructs.FingerprintSimilarity(A,B) but this doesn't seem to work as I expected. I generated FP for each B in B_list against A and used a cut-off to filter the list. However, my B (see below) with best FP metric doesn't seem to be a sub-structure of A. It is something else.

For your ref:
A='COC1=CC(C2=CN(C)C(=O)C3=CN=CC=C23)=CC(OC)=C1CN1CCN(CCOCCOCC(=O)NCC2=CC=C(S(=O)(=O)NC3=CC=CC4=C3\[NH\]C=C4Cl)C=C2)CC1'

B_with_best_FP = 'CCOC1=CC(C(C)(C)C)=CC=C1C1=N\[C@@\](C)(C2=CC=C(Cl)C=C2)\[C@@\](C)(C2=CC=C(Cl)C=C2)N1C(=O)N1CCN(CCCS(C)(=O)=O)CC1'

My_ideal_B = B from B_list which has maximum sub-structure match with A with a score. B_with_best_FP isn't the one.

B_list = https://drive.google.com/file/d/1BjcY8BLJOE98-OQT_zRSoRr7tWcO72Nt/view?usp=sharing


问:
VSCode PowerShell terminal UnauthorizedAccessException when reading config file
I am getting the following error when launching a PowerShell terminal from VSCode:

```<code>Unhandled exception. System.Management.Automation.PSInvalidOperationException: PowerShell has stopped working because of a security issue: Cannot read the configuration file: C:\Users\user\OneDrive\Documents\PowerShell\powershell.config.json ---> System.UnauthorizedAccessException: Access to the path 'C:\Users\user\OneDrive\Documents\PowerShell\powershell.config.json' is denied.
</code>```

I am in a corporate environment with no admin rights but that does not seem to be the issue as I can open that config file with non-elevated processes. Also, I can launch the Powershell terminal outside VS Code fine.

I believe Powershell can't access files in Onedrive, I read somewhere that by disabling Files On-Demand this issue can be solved but I am still getting that error.

Is there a way to change the config file location outside Onedrive? I checked VSCode settings but didn't find any option.

UPDATE: This seems to be actually a permission issue as it is happening when running Powershell outside VSCode too.

Body:
I am getting the following error when launching a PowerShell terminal from VSCode:

Unhandled exception. System.Management.Automation.PSInvalidOperationException: PowerShell has stopped working because of a security issue: Cannot read the configuration file: C:\Users\user\OneDrive\Documents\PowerShell\powershell.config.json ---> System.UnauthorizedAccessException: Access to the path 'C:\Users\user\OneDrive\Documents\PowerShell\powershell.config.json' is denied.

I am in a corporate environment with no admin rights but that does not seem to be the issue as I can open that config file with non-elevated processes. Also, I can launch the Powershell terminal outside VS Code fine.

I believe Powershell can't access files in Onedrive, I read somewhere that by disabling Files On-Demand this issue can be solved but I am still getting that error.

Is there a way to change the config file location outside Onedrive? I checked VSCode settings but didn't find any option.

UPDATE: This seems to be actually a permission issue as it is happening when running Powershell outside VSCode too.


问:
Install Flet on debian 10 fail
pip install flet on debian 10 works. But cannot run program after that.It fails with
'`GLIBCXX_3.4.26' not found ' error.

I debian 10 supported or is there a workaround?.

Title: Install Flet on debian 10 fail


问:
Must I set the dimensions of each grid items by selecting them individually or doing that in the container div using grid properties?
Which method is right when setting the width and height properties of a grid item inside the container?

Using grid-template-rows and grid-template-columns or

Applying the width and height properties of each grid items

Secondly, I have been struggling with placing my grid contents **[direct children of my grid container] ** at the center of the body of my page. If apply place-items: center on my container to center it horizontally and vertically, it does not work. Please I need you advise.

```<code>*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#container {
  display: grid;
  place-items: center;
}

.grid-item {
  background-color: navy;
  color: white;
  /*margin: 3px;*/
  /*width: 100px;*/
  /*height: 100px;*/
}
</code>```

Body:
Which method is right when setting the width and height properties of a grid item inside the container?

Using grid-template-rows and grid-template-columns or

Applying the width and height properties of each grid items

Secondly, I have been struggling with placing my grid contents **[direct children of my grid container] ** at the center of the body of my page. If apply place-items: center on my container to center it horizontally and vertically, it does not work. Please I need you advise.

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#container {
  display: grid;
  place-items: center;
}

.grid-item {
  background-color: navy;
  color: white;
  /*margin: 3px;*/
  /*width: 100px;*/
  /*height: 100px;*/
}


问:
how to read secrets in docker file
Below is the github action

name: Build image
  uses: docker/build-push-action@v3.2.0
  with:
    build-args:
    secrets: |
        "github_token=${{ inputs.token }}"
        "uname=${{ github.actor }}"
        "Mysecret=SecretValue"
```
<p>in the Docker file</p>
<pre class="lang-bash prettyprint-override"><code>RUN --mount=type=secret,id=github_token \
    cat /run/secrets/github_token

RUN --mount=type=secret,id=github_actor \
    cat /run/secrets/github_actor

RUN --mount=type=secret,id=github_actor \
    varu=$(cat /run/secrets/github_actor)

RUN --mount=type=secret,id=github_token \
    var=$(cat /run/secrets/github_token)

RUN echo $var
</code>```

I'm not able to consume the secrets, those are printing but not able to assing the secret to a variables for use in next statement.

If I want to get Mysecret value to a variable in docker file how do I get it?

Title: how to read secrets in docker file

Body:
Below is the github action

name: Build image
  uses: docker/build-push-action@v3.2.0
  with:
    build-args:
    secrets: |
        "github_token=${{ inputs.token }}"
        "uname=${{ github.actor }}"
        "Mysecret=SecretValue"

in the Docker file

RUN --mount=type=secret,id=github_token \
    cat /run/secrets/github_token

RUN --mount=type=secret,id=github_actor \
    cat /run/secrets/github_actor

RUN --mount=type=secret,id=github_actor \
    varu=$(cat /run/secrets/github_actor)

RUN --mount=type=secret,id=github_token \
    var=$(cat /run/secrets/github_token)

RUN echo $var

I'm not able to consume the secrets, those are printing but not able to assing the secret to a variables for use in next statement.

If I want to get Mysecret value to a variable in docker file how do I get it?


问:
In Azure Application Gateway, is it possible to do math operations when rewriting URLs/Query Strings?
I am designing a service that needs to route requests based on the remainder from the division of a path or query string parameter by a constant value. For example, let's say the incoming address looks like abc.com/1234 and that the constant's value is 5.

Here is a list of sample incoming requests paths, underlying expression, and desired routes:

```<code>| Incoming | Expression | Route |
|:---------|:----------:| -----:|
| abc.com/10 | 10 % 5 = 0 | xyz-0.com |
| abc.com/11 | 11 % 5 = 1 | xyz-1.com |
| abc.com/12 | 12 % 5 = 2 | xyz-2.com |
| abc.com/17 | 17 % 5 = 2 | xyz-2.com |
</code>```

This question mentions the same kind of rewrite/redirect, but regex replace seems to not be supported.

Would it be possible to achieve this with Azure Application Gateway rewrites (or Azure Front Door; looks to have the same capabilities as AG as far as rewrites go)?

Body:
I am designing a service that needs to route requests based on the remainder from the division of a path or query string parameter by a constant value. For example, let's say the incoming address looks like abc.com/1234 and that the constant's value is 5.

Here is a list of sample incoming requests paths, underlying expression, and desired routes:

| Incoming | Expression | Route |
|:---------|:----------:| -----:|
| abc.com/10 | 10 % 5 = 0 | xyz-0.com |
| abc.com/11 | 11 % 5 = 1 | xyz-1.com |
| abc.com/12 | 12 % 5 = 2 | xyz-2.com |
| abc.com/17 | 17 % 5 = 2 | xyz-2.com |

This question mentions the same kind of rewrite/redirect, but regex replace seems to not be supported.

Would it be possible to achieve this with Azure Application Gateway rewrites (or Azure Front Door; looks to have the same capabilities as AG as far as rewrites go)?


问:
Is there a way to configure an iPhone is an iBeacon in Xcode?
I am making a small project that can configure an iOS device as an iBeacon to broadcast Bluetooth signals.

Problem:
The Bluetooth code for configuring the device as an iBeacon to broadcast BLE signals is throwing 2 errors that I can't seem to fix, the error messages are below. These errors are what's stopping the iOS device from being configured into an iBeacon.

Message 1:
"[CoreBluetooth] API MISUSE: <CBPeripheralManager: 0x28206c0c0> can only accept this command while in the powered on state"

Message 2:
"[CoreBluetooth] XPC connection invalid"

If someone could assist me in getting my app to work that would be greatly appreciated.

I tried to use a CBPeripheralManager object to configure the device as an iBeacon. Both of the error messages are stemming from this object.


问:
How to delete file in input type="file"
Here is my input code, I need to add a cross so that the input is cleared when clicked.

But without using the form only input and label

```<code>
       let inputs = document.querySelectorAll('.input__file');
        Array.prototype.forEach.call(inputs, function (input) {
          let label = input.nextElementSibling,
            labelVal = label.querySelector('.input__file-button-text').innerText;
          input.addEventListener('change', function (e) {
            let countFiles = '';
            if (this.files && this.files.length >= 1)
              countFiles = this.files.length;
            if (countFiles)
              label.querySelector('.input__file-button-text').innerText = 'Выбрано файлов: ' + countFiles;

            else
              label.querySelector('.input__file-button-text').innerText = labelVal;

          });

        });
</code>```

Title: How to delete file in input type="file"

Body:
Here is my input code, I need to add a cross so that the input is cleared when clicked.

But without using the form only input and label

       let inputs = document.querySelectorAll('.input__file');
        Array.prototype.forEach.call(inputs, function (input) {
          let label = input.nextElementSibling,
            labelVal = label.querySelector('.input__file-button-text').innerText;
          input.addEventListener('change', function (e) {
            let countFiles = '';
            if (this.files && this.files.length >= 1)
              countFiles = this.files.length;
            if (countFiles)
              label.querySelector('.input__file-button-text').innerText = 'Выбрано файлов: ' + countFiles;

            else
              label.querySelector('.input__file-button-text').innerText = labelVal;

          });

        });


问:
Python folium fetching csv data to the jinja macro template
I have the jinja macro template provided to my code, which executes the Leaflet circle creation.

I would like to include the .csv data in this template when possible

```<code>df = pd.read_csv("survey.csv")

class Circle(folium.ClickForMarker):
_template = Template(u"""
        {% macro script(this, kwargs) %}
            var circle_job = L.circle();
            function newMarker(e){
                circle_job.setLatLng(e.latlng).addTo({{this._parent.get_name()}});
                circle_job.setRadius({{rad}});
                circle_job.getPopup({{role}})
                      if {{role}} = "Contractor" {
                      color="red"
                      }else{
                      color="black"
                      }
                circle_job.bringToFront()
                parent.document.getElementById("latitude").value = lat;
                parent.document.getElementById("longitude").value =lng;
                };
            {{this._parent.get_name()}}.on('click', newMarker);
         {% endmacro %}
          """)  # noqa

  def __init__(self, popup=None):
    super(Circle, self).__init__(popup)
    self._name = 'Circle'

job_range = Circle()

for i,row in df.iterrows():
    lat =df.at[i, 'lat']
    lng = df.at[i, 'lng']
    sp = df.at[i, 'sp']
    phone = df.at[i, 'phone']
    role = df.at[i, 'role']
    rad = int(df.at[i, 'radius'])
</code>```

is it possible something like this?

A similar approach was here:

How add circle markers to a rendered folium map embedded in a QWebEngineView?

UPDATE I:

I tried recently something like this:

```<code>class Circle(MacroElement):
 _template = Template(u"""
        {% macro script(this, kwargs) %}
            var {{this.get_name()}} = L.circle();
            function newCircle(e){
{{this.get_name()}}.setLatLng(e.latlng)
.addTo({{this._parent.get_name()}});
                {{this.get_name()}}.setRadius({{rad}});
                {{this.get_name()}}.setStyle({
                color: 'black',
                fillcolor: 'black'
                });
                };
            {{this._parent.get_name()}}.on('click', newCircle);
        {% endmacro %}
        """)  # noqa

def __init__(self,
             popup=None
             ):
    super(Circle, self).__init__()
    self._name = 'Circle'

for i,row in df.iterrows():
  lat =df.at[i, 'lat']
  lng = df.at[i, 'lng']
  sp = df.at[i, 'sp']
  phone = df.at[i, 'phone']
  role = df.at[i, 'role']
  rad = int(df.at[i, 'radius'])

popup = '<b>Phone: </b>' + str(df.at[i,'phone'])
work_range = os.path.join('survey_range.geojson')
job_range = Circle()
</code>```

Now I lost some features, whereas the Js console says nothing. Is it possible to fetch data from df.iterrows directly to the Macroelement?

UPDATE II

I tried to fiddle with def__init__ section and now my code looks as follows:

class Circle(MacroElement):

```<code>  def __init__(self,
             popup=None,
             draggable=False,
             edit_options=None,
             radius=rad
             #lat,
             #lng
             ):
    super(Circle, self).__init__()
    self._name = 'Circle',
    self.radius = radius,

    self._template = Template(u"""
        {% macro script(this, kwargs) %}
            var circle_job = L.circle();
            function newCircle(e){

 circle_job.setLatLng(e.latlng).addTo({{this._parent.get_name()}});
                circle_job.setRadius(50000);
                circle_job.setStyle({
                color: 'black',
                fillcolor: 'black'
                });
                };
            {{this._parent.get_name()}}.on('click', newCircle);
        {% endmacro %}
        """)  # noqa

for i,row in df.iterrows():
lat =df.at[i, 'lat']
lng = df.at[i, 'lng']
sp = df.at[i, 'sp']
phone = df.at[i, 'phone']
role = df.at[i, 'role']
rad = int(df.at[i, 'radius'])
</code>```

and the error thrown is:   The rad is not defined

Is there any way of including the stuff from inside of df.iterrows() in the jinja2 template via defining the def___init?

Body:
I have the jinja macro template provided to my code, which executes the Leaflet circle creation.

I would like to include the .csv data in this template when possible

df = pd.read_csv("survey.csv")

class Circle(folium.ClickForMarker):
_template = Template(u"""
        {% macro script(this, kwargs) %}
            var circle_job = L.circle();
            function newMarker(e){
                circle_job.setLatLng(e.latlng).addTo({{this._parent.get_name()}});
                circle_job.setRadius({{rad}});
                circle_job.getPopup({{role}})
                      if {{role}} = "Contractor" {
                      color="red"
                      }else{
                      color="black"
                      }
                circle_job.bringToFront()
                parent.document.getElementById("latitude").value = lat;
                parent.document.getElementById("longitude").value =lng;
                };
            {{this._parent.get_name()}}.on('click', newMarker);
         {% endmacro %}
          """)  # noqa

  def __init__(self, popup=None):
    super(Circle, self).__init__(popup)
    self._name = 'Circle'

job_range = Circle()

for i,row in df.iterrows():
    lat =df.at[i, 'lat']
    lng = df.at[i, 'lng']
    sp = df.at[i, 'sp']
    phone = df.at[i, 'phone']
    role = df.at[i, 'role']
    rad = int(df.at[i, 'radius'])

is it possible something like this?

A similar approach was here:

How add circle markers to a rendered folium map embedded in a QWebEngineView?

UPDATE I:

I tried recently something like this:

class Circle(MacroElement):
 _template = Template(u"""
        {% macro script(this, kwargs) %}
            var {{this.get_name()}} = L.circle();
            function newCircle(e){
{{this.get_name()}}.setLatLng(e.latlng)
.addTo({{this._parent.get_name()}});
                {{this.get_name()}}.setRadius({{rad}});
                {{this.get_name()}}.setStyle({
                color: 'black',
                fillcolor: 'black'
                });
                };
            {{this._parent.get_name()}}.on('click', newCircle);
        {% endmacro %}
        """)  # noqa

def __init__(self,
             popup=None
             ):
    super(Circle, self).__init__()
    self._name = 'Circle'

for i,row in df.iterrows():
  lat =df.at[i, 'lat']
  lng = df.at[i, 'lng']
  sp = df.at[i, 'sp']
  phone = df.at[i, 'phone']
  role = df.at[i, 'role']
  rad = int(df.at[i, 'radius'])

popup = 'Phone: ' + str(df.at[i,'phone'])
work_range = os.path.join('survey_range.geojson')
job_range = Circle()

Now I lost some features, whereas the Js console says nothing. Is it possible to fetch data from df.iterrows directly to the Macroelement?

UPDATE II

I tried to fiddle with def__init__ section and now my code looks as follows:

class Circle(MacroElement):

  def __init__(self,
             popup=None,
             draggable=False,
             edit_options=None,
             radius=rad
             #lat,
             #lng
             ):
    super(Circle, self).__init__()
    self._name = 'Circle',
    self.radius = radius,

    self._template = Template(u"""
        {% macro script(this, kwargs) %}
            var circle_job = L.circle();
            function newCircle(e){

 circle_job.setLatLng(e.latlng).addTo({{this._parent.get_name()}});
                circle_job.setRadius(50000);
                circle_job.setStyle({
                color: 'black',
                fillcolor: 'black'
                });
                };
            {{this._parent.get_name()}}.on('click', newCircle);
        {% endmacro %}
        """)  # noqa

for i,row in df.iterrows():
lat =df.at[i, 'lat']
lng = df.at[i, 'lng']
sp = df.at[i, 'sp']
phone = df.at[i, 'phone']
role = df.at[i, 'role']
rad = int(df.at[i, 'radius'])

and the error thrown is:   The rad is not defined

Is there any way of including the stuff from inside of df.iterrows() in the jinja2 template via defining the def___init?


问:
Form is not saved because it has errors, but errors are not displayed
I have a SignUp form for user, also I have a validation for fields, I'll provide all of that. So, when user insert for example on field username > s but that field need to have more then 3 characters, program should show error and not save that data into table. What's happening? Application process the error, I mean form is not submitted when I made a error on purpose, but error is not showing on HTML, not on stack trace. Page is just returned but error message are not showing, good thing is just that form is not saved if there is error so that work, problem is just message not appearing.

I have a SignUp form, and for example I have this validation on username and firstName:

```<code>@NotEmpty
@Size(min = 3, max = 20, message = "Username not valid")
private String username;

@NotEmpty(message = "Please, insert a first name")
private String firstName;
</code>```

This is how I display form, its login and register on same page, that is why I have two model attributes:

```<code>@GetMapping("/loginAndRegisterForm")
public String showLoginForm(Model model) {
    // create model object to store form data
    LoginRequest loginRequest = new LoginRequest();
    SignupRequest signupRequest = new SignupRequest();
    model.addAttribute("login", loginRequest);
    model.addAttribute("user", signupRequest);
    return "login_and_registration";
}
</code>```

This is SignUp controller, with result.hasErrors() inside it:

```<code>@PostMapping("/signup")
@Transactional
public String signup(@ModelAttribute("signup") @Valid SignupRequest signupRequest, BindingResult result, Model model) throws Exception {

    boolean thereAreErrors = result.hasErrors();
    if (thereAreErrors) {
        LoginRequest loginRequest = new LoginRequest();
        model.addAttribute("user", signupRequest);
        model.addAttribute("signup", signupRequest);

        model.addAttribute("login", loginRequest);
        return "login_and_registration";
    }

    User user = new User(signupRequest.getUsername(), signupRequest.getFirstName(), signupRequest.getLastName(), signupRequest.getEmail(), encoder.encode(signupRequest.getPassword()));

    model.addAttribute("signup", signupRequest);
    userRepository.save(user);

    return "redirect:/api/auth/loginAndRegisterForm";
}
</code>```

And this is Thymeleaf:

```<code>    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

<head>
    <title>Spring Security Tutorial</title>
    <link rel="stylesheet" type="text/css" th:href="@{/css/loginAndRegistration.css}"/>
</head>

<body>
<div class="main">
    <input type="checkbox" id="chk" aria-hidden="true">

    <div class="signup">
        <form
                method="post"
                role="form"
                th:action="@{/api/auth/signup}"
                th:object="${user}">

            <label for="chk" aria-hidden="true">Sign up</label>
            <input
                    class="form-control"
                    id="usernameSignUp"
                    name="username"
                    placeholder="Enter username"
                    th:field="*{username}"
                    type="text"/>

            <p th:errors="*{username}" class="text-danger"
               th:if="${#fields.hasErrors('username')}"></p>

            <input
                    class="form-control"
                    id="firstName"
                    name="firstName"
                    placeholder="Enter first name"
                    th:field="*{firstName}"
                    type="text"/>

            <p th:errors="*{firstName}" class="text-danger"
               th:if="${#fields.hasErrors('firstName')}"></p>

            <input
                    class="form-control"
                    id="lastName"
                    name="lastName"
                    placeholder="Enter lastName"
                    th:field="*{lastName}"
                    type="text"/>

            <p th:errors="*{firstName}" class="text-danger"
               th:if="${#fields.hasErrors('firstName')}"></p>

            <input
                    class="form-control"
                    id="email"
                    name="email"
                    placeholder="Enter email"
                    th:field="*{email}"
                    type="email"/>

            <p th:errors="*{email}" class="text-danger"
               th:if="${#fields.hasErrors('email')}"></p>

            <input
                    class="form-control"
                    id="passwordSignUp"
                    name="password"
                    placeholder="Enter password"
                    th:field="*{password}"
                    type="password"/>

            <p th:errors="*{password}" class="text-danger"
               th:if="${#fields.hasErrors('password')}"></p>

            <button>Sign up</button>
        </form>
    </div>

    <div class="login">
        <form
                method="post"
                role="form"
                th:action="@{/api/auth/login}"
                th:object="${login}">

            <label for="chk" aria-hidden="true">Login</label>

            <input
                    class="form-control"
                    id="usernameLogin"
                    name="username"
                    placeholder="Enter username"
                    th:field="*{username}"
                    type="text"/>

            <p th:errors="*{username}" class="text-danger"
               th:if="${#fields.hasErrors('username')}"></p>

            <input
                    class="form-control"
                    id="passwordLogin"
                    name="password"
                    placeholder="Enter password"
                    th:field="*{password}"
                    type="password"/>

            <p th:errors="*{password}" class="text-danger"
               th:if="${#fields.hasErrors('password')}"></p>

            <button>Login</button>
        </form>
    </div>
</div>
</body>
</html>
</code>```

Body:
I have a SignUp form for user, also I have a validation for fields, I'll provide all of that. So, when user insert for example on field username > s but that field need to have more then 3 characters, program should show error and not save that data into table. What's happening? Application process the error, I mean form is not submitted when I made a error on purpose, but error is not showing on HTML, not on stack trace. Page is just returned but error message are not showing, good thing is just that form is not saved if there is error so that work, problem is just message not appearing.

I have a SignUp form, and for example I have this validation on username and firstName:

@NotEmpty
@Size(min = 3, max = 20, message = "Username not valid")
private String username;

@NotEmpty(message = "Please, insert a first name")
private String firstName;

This is how I display form, its login and register on same page, that is why I have two model attributes:

@GetMapping("/loginAndRegisterForm")
public String showLoginForm(Model model) {
    // create model object to store form data
    LoginRequest loginRequest = new LoginRequest();
    SignupRequest signupRequest = new SignupRequest();
    model.addAttribute("login", loginRequest);
    model.addAttribute("user", signupRequest);
    return "login_and_registration";
}

This is SignUp controller, with result.hasErrors() inside it:

@PostMapping("/signup")
@Transactional
public String signup(@ModelAttribute("signup") @Valid SignupRequest signupRequest, BindingResult result, Model model) throws Exception {

    boolean thereAreErrors = result.hasErrors();
    if (thereAreErrors) {
        LoginRequest loginRequest = new LoginRequest();
        model.addAttribute("user", signupRequest);
        model.addAttribute("signup", signupRequest);

        model.addAttribute("login", loginRequest);
        return "login_and_registration";
    }

    User user = new User(signupRequest.getUsername(), signupRequest.getFirstName(), signupRequest.getLastName(), signupRequest.getEmail(), encoder.encode(signupRequest.getPassword()));

    model.addAttribute("signup", signupRequest);
    userRepository.save(user);

    return "redirect:/api/auth/loginAndRegisterForm";
}

And this is Thymeleaf:

    <!DOCTYPE html>

    <title>Spring Security Tutorial</title>
    <link rel="stylesheet" type="text/css" th:href="@{/css/loginAndRegistration.css}"/>

    <input type="checkbox" id="chk" aria-hidden="true">

        <form
                method="post"
                role="form"
                th:action="@{/api/auth/signup}"
                th:object="${user}">

            Sign up
            <input
                    class="form-control"
                    id="usernameSignUp"
                    name="username"
                    placeholder="Enter username"
                    th:field="*{username}"
                    type="text"/>

            <input
                    class="form-control"
                    id="firstName"
                    name="firstName"
                    placeholder="Enter first name"
                    th:field="*{firstName}"
                    type="text"/>

            <input
                    class="form-control"
                    id="lastName"
                    name="lastName"
                    placeholder="Enter lastName"
                    th:field="*{lastName}"
                    type="text"/>

            <input
                    class="form-control"
                    id="email"
                    name="email"
                    placeholder="Enter email"
                    th:field="*{email}"
                    type="email"/>

            <input
                    class="form-control"
                    id="passwordSignUp"
                    name="password"
                    placeholder="Enter password"
                    th:field="*{password}"
                    type="password"/>

            <button>Sign up</button>
        </form>

        <form
                method="post"
                role="form"
                th:action="@{/api/auth/login}"
                th:object="${login}">

            Login

            <input
                    class="form-control"
                    id="usernameLogin"
                    name="username"
                    placeholder="Enter username"
                    th:field="*{username}"
                    type="text"/>

            <input
                    class="form-control"
                    id="passwordLogin"
                    name="password"
                    placeholder="Enter password"
                    th:field="*{password}"
                    type="password"/>

            <button>Login</button>
        </form>


问:
Displaying web page on iOS 14
For one functionality of my application, I need to display a Web page.
I use WKWebView as a UIViewRepresentable and it works fine for iOS 15 and 16. But I have an issue on iOS 14. The page remains white and after a few seconds, I receive an error message:

Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service.

Here is my code:

```<code>struct WebViewOgone: UIViewRepresentable {
    static private(set) var browserColorDepth: String = ""
    static private(set) var browserJavaEnabled: String = ""
    static private(set) var browserLanguage: String = ""
    static private(set) var browserScreenHeight: String = ""
    static private(set) var browserScreenWidth: String = ""
    static private(set) var browserTimezone: String = ""
    static private(set) var browserUserAgent: String = ""

    @Binding var url: URL?

    private let webView = WKWebView()

    @State var urlChangedObservation: NSKeyValueObservation?
    private let willChange = PassthroughSubject<URL?, Never>()

    func makeUIView(context: Context) -> WKWebView {
        webView.navigationDelegate = context.coordinator
        return webView
    }

    func makeCoordinator() -> WebViewCoordinator {
        WebViewCoordinator(self)
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        let javascript: String = "(function() { " +
        "" +
        "return ('BROWSERCOLORDEPTH:'+screen.colorDepth+'#BROWSERJAVAENABLED:'+navigator.javaEnabled()+'#BROWSERLANGUAGE:'+navigator.language+'#BROWSERSCREENHEIGHT:'+screen.height+'#BROWSERSCREENWIDTH:'+screen.width+'#BROWSERTIMEZONE:'+new Date().getTimezoneOffset()+'#BROWSERUSERAGENT:'+navigator.userAgent);})();"

        self.webView.evaluateJavaScript(javascript) { result, error in
            guard error == nil else {
                print("An error occured while evaluating JS")
                return
            }

            guard let resultString = result as? String else {
                return
            }

            let splitedData = resultString.components(separatedBy: "#")
            splitedData.forEach { data in
                let info = data.components(separatedBy: ":")
                if  info.count == 2 {
                    let key = info.first
                    let value = info.last
                    switch key {
                    case "BROWSERCOLORDEPTH" :
                        WebViewOgone.browserColorDepth = value ?? ""
                        return
                    case "BROWSERJAVAENABLED" :
                        WebViewOgone.browserJavaEnabled = value ?? ""
                        return
                    case "BROWSERLANGUAGE" :
                        WebViewOgone.browserLanguage = value ?? ""
                        return
                    case "BROWSERSCREENHEIGHT" :
                        WebViewOgone.browserScreenHeight = value ?? ""
                        return
                    case "BROWSERSCREENWIDTH" :
                        WebViewOgone.browserScreenWidth = value ?? ""
                        return
                    case "BROWSERTIMEZONE" :
                        WebViewOgone.browserTimezone = value ?? ""
                        return
                    case "BROWSERUSERAGENT" :
                        WebViewOgone.browserUserAgent = value ?? ""
                        return
                    default:
                        return
                    }
                }
            }
        }
    }

    public func display(_ html: String) -> WebViewOgone {
        self.webView.loadHTMLString(html, baseURL: nil)
        return self
    }

    public func load(_ url: String) -> WebViewOgone {
        let link = URL(string: url)!
        let request = URLRequest(url: link)
        self.webView.load(request)
        return self
    }

    class WebViewCoordinator: NSObject, WKNavigationDelegate {
        var parent: WebViewOgone

        init(_ parent: WebViewOgone) {
            self.parent = parent
        }

        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            if let urlStr = navigationAction.request.url?.absoluteString {
                parent.url = URL(string: urlStr)
            }
            decisionHandler(.allow)
        }

        func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
            print("didcommit")
        }

        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            print("didfinished")
        }
    }
}
</code>```

I already try to add the view inside the array of subviews in the makeView method but it didn't work

Title: Displaying web page on iOS 14

Body:
For one functionality of my application, I need to display a Web page.
I use WKWebView as a UIViewRepresentable and it works fine for iOS 15 and 16. But I have an issue on iOS 14. The page remains white and after a few seconds, I receive an error message:

Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service.

Here is my code:

struct WebViewOgone: UIViewRepresentable {
    static private(set) var browserColorDepth: String = ""
    static private(set) var browserJavaEnabled: String = ""
    static private(set) var browserLanguage: String = ""
    static private(set) var browserScreenHeight: String = ""
    static private(set) var browserScreenWidth: String = ""
    static private(set) var browserTimezone: String = ""
    static private(set) var browserUserAgent: String = ""

    @Binding var url: URL?

    private let webView = WKWebView()

    @State var urlChangedObservation: NSKeyValueObservation?
    private let willChange = PassthroughSubject<URL?, Never>()

    func makeUIView(context: Context) -> WKWebView {
        webView.navigationDelegate = context.coordinator
        return webView
    }

    func makeCoordinator() -> WebViewCoordinator {
        WebViewCoordinator(self)
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        let javascript: String = "(function() { " +
        "" +
        "return ('BROWSERCOLORDEPTH:'+screen.colorDepth+'#BROWSERJAVAENABLED:'+navigator.javaEnabled()+'#BROWSERLANGUAGE:'+navigator.language+'#BROWSERSCREENHEIGHT:'+screen.height+'#BROWSERSCREENWIDTH:'+screen.width+'#BROWSERTIMEZONE:'+new Date().getTimezoneOffset()+'#BROWSERUSERAGENT:'+navigator.userAgent);})();"

        self.webView.evaluateJavaScript(javascript) { result, error in
            guard error == nil else {
                print("An error occured while evaluating JS")
                return
            }

            guard let resultString = result as? String else {
                return
            }

            let splitedData = resultString.components(separatedBy: "#")
            splitedData.forEach { data in
                let info = data.components(separatedBy: ":")
                if  info.count == 2 {
                    let key = info.first
                    let value = info.last
                    switch key {
                    case "BROWSERCOLORDEPTH" :
                        WebViewOgone.browserColorDepth = value ?? ""
                        return
                    case "BROWSERJAVAENABLED" :
                        WebViewOgone.browserJavaEnabled = value ?? ""
                        return
                    case "BROWSERLANGUAGE" :
                        WebViewOgone.browserLanguage = value ?? ""
                        return
                    case "BROWSERSCREENHEIGHT" :
                        WebViewOgone.browserScreenHeight = value ?? ""
                        return
                    case "BROWSERSCREENWIDTH" :
                        WebViewOgone.browserScreenWidth = value ?? ""
                        return
                    case "BROWSERTIMEZONE" :
                        WebViewOgone.browserTimezone = value ?? ""
                        return
                    case "BROWSERUSERAGENT" :
                        WebViewOgone.browserUserAgent = value ?? ""
                        return
                    default:
                        return
                    }
                }
            }
        }
    }

    public func display(_ html: String) -> WebViewOgone {
        self.webView.loadHTMLString(html, baseURL: nil)
        return self
    }

    public func load(_ url: String) -> WebViewOgone {
        let link = URL(string: url)!
        let request = URLRequest(url: link)
        self.webView.load(request)
        return self
    }

    class WebViewCoordinator: NSObject, WKNavigationDelegate {
        var parent: WebViewOgone

        init(_ parent: WebViewOgone) {
            self.parent = parent
        }

        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            if let urlStr = navigationAction.request.url?.absoluteString {
                parent.url = URL(string: urlStr)
            }
            decisionHandler(.allow)
        }

        func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
            print("didcommit")
        }

        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            print("didfinished")
        }
    }
}

I already try to add the view inside the array of subviews in the makeView method but it didn't work


问:
Unable to load libraries
I recently updated R and Rstudio and since then have not been able to load any libraries, including ggplot2, tidyverse.

Just for clarity, let me share the messages I get when I install tidyverse and try to load the library:

install.packages("tidyverse")
WARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding:

**https://cran.rstudio.com/bin/windows/Rtools/
Installing package into ‘C:/Users/Computer User 1/AppData/Local/R/win-library/4.2’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.2/tidyverse_1.3.2.zip'
Content type 'application/zip' length 428970 bytes (418 KB)
downloaded 418 KB

package ‘tidyverse’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
C:\Users\Computer User 1\AppData\Local\Temp\RtmpQZdI11\downloaded_packages**

**> library(tidyverse)
Error: package or namespace load failed for ‘tidyverse’ in inDL(x, as.logical(local), as.logical(now), ...):
unable to load shared object 'C:/Program Files/R/R-4.2.2/library/stats/libs/x64/stats.dll':
LoadLibrary failure:  The specified module could not be found.
**

Also, to be clear, I did install the latest version of Rtools.

Now I tried reading through several messages on google regarding the same error but failed to understand the solution. The main thing I do not understand is why the packages are installed here: C:\Users\Computer User 1\AppData\Local\Temp\RtmpQZdI11\downloaded_packages, and then are loaded from here: C:/Program Files/R/R-4.2.2/library/stats/libs/x64/stats.dll.

I have tried specifying the library path but have not been successful at solving the problem. I don't know why R is unable to load the libraries. Also, on running .libpaths(), I get two libraries:
[1] "C:/Users/Computer User 1/AppData/Local/R/win-library/4.2"
[2] "C:/Program Files/R/R-4.2.2/library"
And when I try to install tidyverse here: C:/Program Files/R/R-4.2.2/library, I get this error: the folder is unwritable.

I don't know how to solve this issue. Please help.

Title: Unable to load libraries


问:
Why isn't my path working with gsap's motion path?
Background:
I am animating a circle down my web page to follow a certain path using GSAP's motion path plugin. I have scaled the path to ensure it follows the same proportions on all devices using this code:

```<code>let w = window.innerWidth;
let h = document.querySelector("main").offsetHeight;

const pathSpec = "M305.91,0c8.54,101.44,17.07,203.69,5.27,304.8s-45.5,202.26-112.37,279c-36,41.37-80.92,74.88-113.34,119.16-66.32,90.59-70.8,210.86-72.71,323.13C9.69,1206.79,9.48,1387.9,1.71,1568c-8,186.11,25.77,370.42,48.07,554.43q4.36,36,8.07,72.07c14.18,140.22,9.95,281.38,8.06,422-1.87,139.1,26.43,260.75,66.38,393.67l82.47,274.39,8.25,27.44,29.87,129c40.8,176.3,87,363.23,64.51,545.49-11,89.33-3.5,182.44-2.28,272.84l3.83,286.1c3.63,188.78,5.07,377.63,7.6,566.44l3.83,286.08c1.27,94.55-4,191.79,3.84,286,14.37,172.9-10,353.08-14.33,527.78q-7,283.21,1.14,566.55,8.14,281.61,31.34,562.53c7.43,90,21.31,180.76,26.7,270.47,5.6,93.24-4,190-6,283.47l-3.45,164.33";

const yScale = h / 8059.08;
const xScale = w / 380.28;

let newPath = "";

  const pathBits = Array.from(pathSpec.matchAll(/([MmLlHhVvCcSsQqTtAa])([\d\.,\se-]*)/g));
  console.log(pathBits);

  pathBits.forEach((bit) => {
    const command = bit[1];
    const coordinates = bit[2];

    newPath += command;

    const coordArray = coordinates.split(/[,\s]/g);
    // console.log("coordArray", coordArray);

    newPath += coordArray.map((coord, index) => {

      if (index % 2 == 0) {
        return parseFloat(coord) * yScale;
      }
      else {
        return parseFloat(coord) * xScale;
      }

    }).join(',');

  });
</code>```

So, essentially, I've created coordArray to split the array into the x and y coordinates and added it to newPath which is the scaled version. Then, I've added newPath to motionPath using:

```<code>const tlCircle = gsap.timeline();

tlCircle.to(".circle-animation", {
  scrollTrigger: {
    scroller: "main",
    trigger: ".circle-animation",
    start: "top 10%",
    end: "max",
    scrub: 1,
  },
  ease: "true",
  motionPath: {
    path: newPath,
    autoRotate: true
  }
});
</code>```

When I put the pathSpec var in the path parameter, my circle animates but not when I put the newPath in, even though the web console shows it is in the same format as pathSpec but just scaled.

I've tried to debug this console logs to see what the input and outputs are which are what I want -- newPath is a. svg path in a string but scaled to fit my window but it doesn't work when I use it in motionPath.

Body:
Background:
I am animating a circle down my web page to follow a certain path using GSAP's motion path plugin. I have scaled the path to ensure it follows the same proportions on all devices using this code:

let w = window.innerWidth;
let h = document.querySelector("main").offsetHeight;

const pathSpec = "M305.91,0c8.54,101.44,17.07,203.69,5.27,304.8s-45.5,202.26-112.37,279c-36,41.37-80.92,74.88-113.34,119.16-66.32,90.59-70.8,210.86-72.71,323.13C9.69,1206.79,9.48,1387.9,1.71,1568c-8,186.11,25.77,370.42,48.07,554.43q4.36,36,8.07,72.07c14.18,140.22,9.95,281.38,8.06,422-1.87,139.1,26.43,260.75,66.38,393.67l82.47,274.39,8.25,27.44,29.87,129c40.8,176.3,87,363.23,64.51,545.49-11,89.33-3.5,182.44-2.28,272.84l3.83,286.1c3.63,188.78,5.07,377.63,7.6,566.44l3.83,286.08c1.27,94.55-4,191.79,3.84,286,14.37,172.9-10,353.08-14.33,527.78q-7,283.21,1.14,566.55,8.14,281.61,31.34,562.53c7.43,90,21.31,180.76,26.7,270.47,5.6,93.24-4,190-6,283.47l-3.45,164.33";

const yScale = h / 8059.08;
const xScale = w / 380.28;

let newPath = "";

  const pathBits = Array.from(pathSpec.matchAll(/([MmLlHhVvCcSsQqTtAa])([\d\.,\se-]*)/g));
  console.log(pathBits);

  pathBits.forEach((bit) => {
    const command = bit[1];
    const coordinates = bit[2];

    newPath += command;

    const coordArray = coordinates.split(/[,\s]/g);
    // console.log("coordArray", coordArray);

    newPath += coordArray.map((coord, index) => {

      if (index % 2 == 0) {
        return parseFloat(coord) * yScale;
      }
      else {
        return parseFloat(coord) * xScale;
      }

    }).join(',');

  });

So, essentially, I've created coordArray to split the array into the x and y coordinates and added it to newPath which is the scaled version. Then, I've added newPath to motionPath using:

const tlCircle = gsap.timeline();

tlCircle.to(".circle-animation", {
  scrollTrigger: {
    scroller: "main",
    trigger: ".circle-animation",
    start: "top 10%",
    end: "max",
    scrub: 1,
  },
  ease: "true",
  motionPath: {
    path: newPath,
    autoRotate: true
  }
});

When I put the pathSpec var in the path parameter, my circle animates but not when I put the newPath in, even though the web console shows it is in the same format as pathSpec but just scaled.

I've tried to debug this console logs to see what the input and outputs are which are what I want -- newPath is a. svg path in a string but scaled to fit my window but it doesn't work when I use it in motionPath.