问:
How to eliminate "Warning: Error in seq.default: 'from' must be a finite number" when running App?
I'm running a version of the below reduced code in an App that allows the user to stratify the elements in a large data frame as of a single point-in-time. The user can choose which measure to use for time: Period_1 or Period_2, and which time period to select within each of those 2 time categories. The full App offers the user several more stratification variables, and in the renderTable section below there remain vestiges of this broader functionality.

The example produces the intended results, but it generates in the R console: "Warning: Error in seq.default: 'from' must be a finite number". (I get this same warning in both the below example and the full App this example derives from).

Other warnings ("Warning in min..., na.rm = TRUE) : no non-missing arguments to min; returning Inf") were popping up before I added the custom_min and custom_max functions below.

I don't want to suppress the warning, I'd rather have the code work correctly. Any clues how to address?

```<code>library(shiny)
library(tidyverse)
library(shinyWidgets)

custom_min <- function(x) {if (length(x)>0) min(x, na.rm=TRUE) else Inf}
custom_max <- function(x) {if (length(x)>0) max(x, na.rm=TRUE) else Inf}

ui <-
  fluidPage(
    uiOutput("period"),
    uiOutput("strat_time"),
    tableOutput("stratData"))

server <- function(input, output, session) {

  stratData <- reactive({
    data.frame(
      ID = c(1,1,2,2,2,2,3,3,3),
      Period_1 = c("2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04", "2020-02", "2020-03", "2020-04"),
      Period_2 = c(1, 2, 1, 2, 3, 4, 1, 2, 3),
      Values = c(-5, 25, 35, 45, 55, 87, 10, 20, 30)
    )
  })

  output$period <- renderUI({
    radioButtons(
      inputId = 'period',
      label = NULL,
      choiceNames = c('By Period_1','By Period_2'),
      choiceValues = c('Period_1','Period_2'),
      selected = 'Period_1',
      inline = TRUE
    )
  })

  output$strat_time <- renderUI({
    req(input$period)
    chc <- unique(na.omit(stratData()[[input$period]]))
    selectInput(inputId = "strat_time",
                label = "Specify stratification point-in-time:",
                choices = chc,
                selected = chc[1])
  })

  output$stratData <- renderTable({
    qs <- ifelse(is.character(stratData()[[input$period]]), "'", "")
    filter_exp1 <- parse(text=paste0(input$period,  "==", qs,input$strat_time, qs))
    stratData_1 <- reactive({stratData() %>% filter(eval(filter_exp1))})
    breaks <- seq(custom_min(stratData_1()[[4]]),
                  custom_max(stratData_1()[[4]]),
                  by=10)
    if(max(breaks) < max(stratData_1()[[4]], na.rm=TRUE)){breaks <- c(breaks, max(breaks) + 10)}

    tmp <- stratData() %>%
      filter(eval(filter_exp1)) %>%
      mutate(sumvar = cut(!!sym("Values"), breaks=breaks, include.lowest=TRUE, right = TRUE, dig.lab = 5)) %>%
      group_by(sumvar) %>%
      summarise(Count = n(),Values = sum(!!sym("Values"))) %>%
      complete(sumvar, fill = list(Count = 0,Values = 0)) %>%
      ungroup %>%
      mutate(Count_pct = Count/sum(Count)*100, Values_pct = Values/sum(Values)*100) %>%
      dplyr::select(everything(), Count, Count_pct, Values, Values_pct)
    tmp
  })

}

shinyApp(ui, server)
</code>```

答:
This happen because your function custom_min(stratData_1()[[4]]) can return non-finite numbers, namely Inf, when length(x) > 0.

You can change your code to something like :

    min <- custom_min(stratData_1()[[4]])
    max <- custom_max(stratData_1()[[4]])
    breaks <- if(any(is.infinite(c(min,max)))) c(0, 10) else seq(min, max, by = 10)
```

Body:
I'm running a version of the below reduced code in an App that allows the user to stratify the elements in a large data frame as of a single point-in-time. The user can choose which measure to use for time: Period_1 or Period_2, and which time period to select within each of those 2 time categories. The full App offers the user several more stratification variables, and in the renderTable section below there remain vestiges of this broader functionality.

The example produces the intended results, but it generates in the R console: "Warning: Error in seq.default: 'from' must be a finite number". (I get this same warning in both the below example and the full App this example derives from).

Other warnings ("Warning in min..., na.rm = TRUE) : no non-missing arguments to min; returning Inf") were popping up before I added the custom_min and custom_max functions below.

I don't want to suppress the warning, I'd rather have the code work correctly. Any clues how to address?

library(shiny)
library(tidyverse)
library(shinyWidgets)

custom_min <- function(x) {if (length(x)>0) min(x, na.rm=TRUE) else Inf}
custom_max <- function(x) {if (length(x)>0) max(x, na.rm=TRUE) else Inf}

ui <-
  fluidPage(
    uiOutput("period"),
    uiOutput("strat_time"),
    tableOutput("stratData"))

server <- function(input, output, session) {

  stratData <- reactive({
    data.frame(
      ID = c(1,1,2,2,2,2,3,3,3),
      Period_1 = c("2020-03", "2020-04", "2020-01", "2020-02", "2020-03", "2020-04", "2020-02", "2020-03", "2020-04"),
      Period_2 = c(1, 2, 1, 2, 3, 4, 1, 2, 3),
      Values = c(-5, 25, 35, 45, 55, 87, 10, 20, 30)
    )
  })

  output$period <- renderUI({
    radioButtons(
      inputId = 'period',
      label = NULL,
      choiceNames = c('By Period_1','By Period_2'),
      choiceValues = c('Period_1','Period_2'),
      selected = 'Period_1',
      inline = TRUE
    )
  })

  output$strat_time <- renderUI({
    req(input$period)
    chc <- unique(na.omit(stratData()[[input$period]]))
    selectInput(inputId = "strat_time",
                label = "Specify stratification point-in-time:",
                choices = chc,
                selected = chc[1])
  })

  output$stratData <- renderTable({
    qs <- ifelse(is.character(stratData()[[input$period]]), "'", "")
    filter_exp1 <- parse(text=paste0(input$period,  "==", qs,input$strat_time, qs))
    stratData_1 <- reactive({stratData() %>% filter(eval(filter_exp1))})
    breaks <- seq(custom_min(stratData_1()[[4]]),
                  custom_max(stratData_1()[[4]]),
                  by=10)
    if(max(breaks) < max(stratData_1()[[4]], na.rm=TRUE)){breaks <- c(breaks, max(breaks) + 10)}

    tmp <- stratData() %>%
      filter(eval(filter_exp1)) %>%
      mutate(sumvar = cut(!!sym("Values"), breaks=breaks, include.lowest=TRUE, right = TRUE, dig.lab = 5)) %>%
      group_by(sumvar) %>%
      summarise(Count = n(),Values = sum(!!sym("Values"))) %>%
      complete(sumvar, fill = list(Count = 0,Values = 0)) %>%
      ungroup %>%
      mutate(Count_pct = Count/sum(Count)*100, Values_pct = Values/sum(Values)*100) %>%
      dplyr::select(everything(), Count, Count_pct, Values, Values_pct)
    tmp
  })

}

shinyApp(ui, server)


来源: stackexchange

问:
How to remove/ignore :hover css style on touch devices
I want to ignore all :hover CSS declarations if a user visits our website via touch device. Because the :hover CSS does not make sense, and it can even be disturbing if a tablet triggers it on click/tap because then it might stick until the element loses focus. To be honest, I don't know why touch devices feel the need to trigger :hover in first place - but this is reality, so this problem is reality as well.

a:hover {
  color:blue;
  border-color:green;
  /* etc. > ignore all at once for touch devices */
}
```

So, (how) can I remove/ignore all CSS :hover declarations at once (without having to know each one) for touch devices after having them declared?

答:
After going through the previous answers, this worked for me.
This hover will only work for desktops which has hover. And remove if you have any other hover codes for this class/id</p>
```<code>@media (hover: hover) {
  .toggle-label:hover {
     background-color: #69c9ff;
     color: #ffffff;
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to ignore all :hover CSS declarations if a user visits our website via touch device. Because the :hover CSS does not make sense, and it can even be disturbing if a tablet triggers it on click/tap because then it might stick until the element loses focus. To be honest, I don't know why touch devices feel the need to trigger :hover in first place - but this is reality, so this problem is reality as well.

a:hover {
  color:blue;
  border-color:green;
  /* etc. > ignore all at once for touch devices */
}

So, (how) can I remove/ignore all CSS :hover declarations at once (without having to know each one) for touch devices after having them declared?

Body:
After going through the previous answers, this worked for me.
This hover will only work for desktops which has hover. And remove if you have any other hover codes for this class/id

@media (hover: hover) {
  .toggle-label:hover {
     background-color: #69c9ff;
     color: #ffffff;
  }
}


问:
How to format a floating number to fixed width in Python
How do I format a floating number to a fixed width with the following requirements:

Leading zero if n < 1

Add trailing decimal zero(s) to fill up fixed width

Truncate decimal digits past fixed width

Align all decimal points

For example:

```<code>% formatter something like '{:06}'
numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]

for number in numbers:
    print formatter.format(number)
</code>```

The output would be like

```<code>  23.2300
   0.1233
   1.0000
   4.2230
9887.2000
</code>```

答:
I tried all the options like

pd.options.display.float_format = '{:.4f}'.format

pd.set_option('display.float_format', str)

pd.set_option('display.float_format', lambda x: f'%.{len(str(x%1))-2}f' % x)

pd.set_option('display.float_format', lambda x: '%.3f' % x)

but nothing worked for me.

so while assigning the variable/value (var1) to a variable (say num1) I used round(val,5) like

```<code>num1 = round(var1,5)
</code>```

This is a crude method as you have to use this round function in each assignment.  But this ensures you control on how it happens and get what you want.

ContentLicense: CC BY-SA 3.0

Body:
How do I format a floating number to a fixed width with the following requirements:

Leading zero if n < 1

Add trailing decimal zero(s) to fill up fixed width

Truncate decimal digits past fixed width

Align all decimal points

For example:

% formatter something like '{:06}'
numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]

for number in numbers:
    print formatter.format(number)

The output would be like

  23.2300
   0.1233
   1.0000
   4.2230
9887.2000

Body:
I tried all the options like

pd.options.display.float_format = '{:.4f}'.format

pd.set_option('display.float_format', str)

pd.set_option('display.float_format', lambda x: f'%.{len(str(x%1))-2}f' % x)

pd.set_option('display.float_format', lambda x: '%.3f' % x)

but nothing worked for me.

so while assigning the variable/value (var1) to a variable (say num1) I used round(val,5) like

num1 = round(var1,5)

This is a crude method as you have to use this round function in each assignment.  But this ensures you control on how it happens and get what you want.


问:
Is it possible for azure logic app to receive a file from incoming http request?
I wanted to know if its possible to perform a file upload request to azure logic app's HTTP listener?

I am not looking for built-in HTTP trigger which makes an HTTP call to the specified URL OR built-in HTTP action which makes an HTTP call to the specified URL

答:
One of the workarounds is through postman. Here is my logic app for your reference

postman request :-

Here is the output :-


问:
How to Split screen height in half in Jetpack Compose?
I want to split my screen in half horizontally in Jetpack Compose like this:

```<code>    @Composable
fun Splash(alpha: Float) {
    val configuration = LocalConfiguration.current
    val screenHeight = configuration.screenHeightDp.dp
    val screenWidth = configuration.screenWidthDp.dp
    val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.cat2))
    Box(
        modifier = Modifier
            .background(Blue)
            .height(screenHeight /  2)
            .padding(8.dp),
        contentAlignment = Alignment.TopCenter
    ) {
        Column() {
            Text(text = "Example", fontSize = 44.sp)
        }
    }
    Box(
        modifier = Modifier
            .background(Red)
            .height(screenHeight /  2)
            .padding(8.dp),
        contentAlignment = Alignment.BottomCenter
    ){
        Column {

            Text(text = "Example", textAlign = TextAlign.End, color = Grey, fontSize = 12.sp)
        }
    }
}
</code>```

I can get screen height with LocalConfiguration.current in dp and I set my top box and bottom box alignments as Alignment.TopCenter and Alignment.BottomCenter respectively but it didn't work. Second box(Red one) stays on top of the blue one.

答:
The best way to implement your image is this way:</p>
```<code>            Column(
                Modifier
                    .fillMaxSize()
                    .padding(8.dp)
            ) {
                Row(
                    Modifier
                        .fillMaxWidth()
                        .weight(1f)
                        .background(Blue),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Center,
                ) {
                    Text(text = "Example", fontSize = 44.sp)
                }
                Row(
                    Modifier
                        .fillMaxWidth()
                        .weight(1f)
                        .background(Red),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Center,
                ) {
                    Text(text = "Example", fontSize = 44.sp)
                }
            }
</code>```

Body:
I want to split my screen in half horizontally in Jetpack Compose like this:

    @Composable
fun Splash(alpha: Float) {
    val configuration = LocalConfiguration.current
    val screenHeight = configuration.screenHeightDp.dp
    val screenWidth = configuration.screenWidthDp.dp
    val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.cat2))
    Box(
        modifier = Modifier
            .background(Blue)
            .height(screenHeight /  2)
            .padding(8.dp),
        contentAlignment = Alignment.TopCenter
    ) {
        Column() {
            Text(text = "Example", fontSize = 44.sp)
        }
    }
    Box(
        modifier = Modifier
            .background(Red)
            .height(screenHeight /  2)
            .padding(8.dp),
        contentAlignment = Alignment.BottomCenter
    ){
        Column {

            Text(text = "Example", textAlign = TextAlign.End, color = Grey, fontSize = 12.sp)
        }
    }
}

I can get screen height with LocalConfiguration.current in dp and I set my top box and bottom box alignments as Alignment.TopCenter and Alignment.BottomCenter respectively but it didn't work. Second box(Red one) stays on top of the blue one.

Body:
The best way to implement your image is this way:

            Column(
                Modifier
                    .fillMaxSize()
                    .padding(8.dp)
            ) {
                Row(
                    Modifier
                        .fillMaxWidth()
                        .weight(1f)
                        .background(Blue),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Center,
                ) {
                    Text(text = "Example", fontSize = 44.sp)
                }
                Row(
                    Modifier
                        .fillMaxWidth()
                        .weight(1f)
                        .background(Red),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Center,
                ) {
                    Text(text = "Example", fontSize = 44.sp)
                }
            }


问:
Lightweight .Net CMS Library
I am looking for a lightweight CMS Library for a .net MVC application. I don't need any frontend management, just a library that can store and retrieve pieces of content. I plan on writing the frontend myself. The most complex thing I can see myself needing to store is a set of news posts. Aside from this I need to be able to store sets of arbitrary key value pairs for each page. Resource files probably provide the best model for this except that they are not editable and persistable during run time.

The closest thing I have found is Eucalypto which looks like it should fit the bill pretty well. I can rip out the forums and wiki easily enough as I don't need them. But it doesn't seem to have been developed for a while and I have heard nothing about it in the past and so would be worried about reliability. Any ideas of a library that might do this?

I am aware that it might be simpler to just roll my own SQL database for something this simple, but if a good library esists it could save me some time and trouble.

答: You may want to take a look at a document database. MindTouch's Dream comes to mind - it's the engine behind DekiWiki, and runs on Mono. I assume it'd also run on .NET with no (or minimal) changes.</p>

OwnerDisplayName: JayArr

ContentLicense: CC BY-SA 2.5

Title: Lightweight .Net CMS Library

OwnerDisplayName: Mark Brackett


问:
How can you add IP restrictions to your rails app?
Is there a way to add IP restrictions to the rails app. Some type of rack middleware so only the set list of IPs can access the rails app for security reasons?

Thanks

答:
You can add a before_filter in the application controller and check the request IP,and redirect it to a no-access page.

```<code>if request.remote_ip !~ /^XXX\.YYY\.ZZZ\./
  redirect_to no_access_url
  return false
end
</code>```

Body:
You can add a before_filter in the application controller and check the request IP,and redirect it to a no-access page.

if request.remote_ip !~ /^XXX\.YYY\.ZZZ\./
  redirect_to no_access_url
  return false
end


问:
Can I avoid to add in mongoDB null value for some field?
I m trying to develop a Spring boot with MongoDB and my problem is that I don't want that a user to put in the DB empty or null value for some field.

I already tried the option that I found on the web but it didn't work.

Code:

```<code>@Data
@Entity
@Document(collection = "product")
public class Product {
    @Id
    private String id;

    @NotEmpty
    private String name;

    @NotNull(message = "brand must not be null")
    private String brand;

    @NotNull(message = "barCode must not be null")
    private String barCode;

    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    private LocalDate importDate;

    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    private LocalDate expireDate;

    @NotNull(message = "price must not be null")
    private Double price;

    private Double deal;

    @NotNull(message = "the quantity must not be null")
    private Integer quantity;
}
</code>```

答:
You are using

@NotNull

Which is used for validation a model.

For omitting storing null values to DB you should use:

```<code>@Column(nullable=false)
private String brand;
</code>```

UPDATE:

Looks like your schema has been already generated.

You didn't share the DB configuration of your project.

If you are using Spring Boot, you have to set at application.properties additional properties to make it work:

```<code>spring.jpa.show-sql=true
spring.jpa.properties.hibernate.check_nullability=true
</code>```

However, it will help do not store null values.

For preventing to store empty values you should add for string fields:

```<code>@Size(min=1)
</code>```

If you want to validate Integer or Double that they have values more than 0, use @Min:

```<code>@Min(value = 1L, message = "The price must be positive")
private Double price;
</code>```

Body:
I m trying to develop a Spring boot with MongoDB and my problem is that I don't want that a user to put in the DB empty or null value for some field.

I already tried the option that I found on the web but it didn't work.

Code:

@Data
@Entity
@Document(collection = "product")
public class Product {
    @Id
    private String id;

    @NotEmpty
    private String name;

    @NotNull(message = "brand must not be null")
    private String brand;

    @NotNull(message = "barCode must not be null")
    private String barCode;

    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    private LocalDate importDate;

    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    private LocalDate expireDate;

    @NotNull(message = "price must not be null")
    private Double price;

    private Double deal;

    @NotNull(message = "the quantity must not be null")
    private Integer quantity;
}

Body:
You are using

@NotNull

Which is used for validation a model.

For omitting storing null values to DB you should use:

@Column(nullable=false)
private String brand;

UPDATE:

Looks like your schema has been already generated.

You didn't share the DB configuration of your project.

If you are using Spring Boot, you have to set at application.properties additional properties to make it work:

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.check_nullability=true

However, it will help do not store null values.

For preventing to store empty values you should add for string fields:

@Size(min=1)

If you want to validate Integer or Double that they have values more than 0, use @Min:

@Min(value = 1L, message = "The price must be positive")
private Double price;


问:
Why am getting the error `failed to open stream: No such file or directory`?
for the beolw code, am getting the warning - require_once(C:\xampp\htdocs\abcd\application\controllers/vendor/autoload.php): failed to open stream: No such file or directory. I've no idea why this error comes here, becoz the autoload.php file exists in vendor folder.And the folder is existing in the root directory.composer_autoload is true in config\autoload.php. Can someone tell me the possible causes of this issue?Anyhelp is much appreciated.

controller

```<code><?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once __DIR__ . '/vendor/autoload.php';
//require_once __DIR__ . '\vendor\autoload.php'; //also tried reversing the slashes like this

class Reports extends Layout_Controller
{

}
</code>```

composer install error

答:
I had the same issue with require_once __DIR__ . '../../vendor/autoload.php'; , edited @Mark's answer as follows

```<code>require_once implode(DIRECTORY_SEPARATOR, [__DIR__, 'vendor/composer', 'vendor/autoload.php']);
</code>```

and it worked!

Body:
for the beolw code, am getting the warning - require_once(C:\xampp\htdocs\abcd\application\controllers/vendor/autoload.php): failed to open stream: No such file or directory. I've no idea why this error comes here, becoz the autoload.php file exists in vendor folder.And the folder is existing in the root directory.composer_autoload is true in config\autoload.php. Can someone tell me the possible causes of this issue?Anyhelp is much appreciated.

controller

<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once __DIR__ . '/vendor/autoload.php';
//require_once __DIR__ . '\vendor\autoload.php'; //also tried reversing the slashes like this

class Reports extends Layout_Controller
{

}

composer install error

Body:
I had the same issue with require_once __DIR__ . '../../vendor/autoload.php'; , edited @Mark's answer as follows

require_once implode(DIRECTORY_SEPARATOR, [__DIR__, 'vendor/composer', 'vendor/autoload.php']);

and it worked!


问:
How can I trigger a build from a specific folder only in a monorepo? (buildkite)
We have a monorepo with 3 systems inside it.  I want to create a separate build for each of the systems.

How can I trigger a pipeline only when files change in a specific folder?

We are using github

steps:

  - label: 'Lint'
    command: '.buildkite/scripts/lint.sh'
    agents:
      node: true
      queue: xyz

  - label: 'Run Tests'
    command: '.buildkite/scripts/tests.sh'
    agents:
      node: true
      queue: xyz

```

答:
buildkite support emailed me this solution:

Thanks for reaching out! It sounds like you may want to take a look at using the monorepo diff plugin!

https://github.com/chronotc/monorepo-diff-buildkite-plugin

There is a good medium article here as well on setting it up: https://medium.com/geekculture/set-up-continuous-integration-for-monorepo-using-buildkite-61539bb0ed76

Let us know if you have any other questions or need more assistance!

Cheers,


问:
Getting 302 with Curl, but 200 with python requests
The site that I am trying to scrape must follow 302 observed by the browser network tools. I've copied the network request as Curl and its working fine, but when I convert it to python requests its just returning 200.

Curl:

```<code>curl -v 'https://my-site.com/CardAuthentication.aspx' \
  -H 'Connection: keep-alive' \
  -H 'Pragma: no-cache' \
  -H 'Cache-Control: no-cache' \
  -H 'Upgrade-Insecure-Requests: 1' \
  -H 'Origin: https://my-site.com' \
  -H 'Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryBN2XwBbcAwvRWZzk' \
  -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36' \
  -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' \
  -H 'Sec-GPC: 1' \
  -H 'Sec-Fetch-Site: same-origin' \
  -H 'Sec-Fetch-Mode: navigate' \
  -H 'Sec-Fetch-User: ?1' \
  -H 'Sec-Fetch-Dest: document' \
  -H 'Referer: https://my-site.com/CardAuthentication.aspx' \
  -H 'Accept-Language: en-US,en;q=0.9' \
  -H 'Cookie: ASP.NET_SessionId=...; TS0192fa71=...; ServiceProvider=UID=...; .ASPXAUTH=...' \
  --data-raw $'------WebKitFormBoundaryBN2XwBbcAwvRWZzk\r\ DATA \r\n' \
  --compressed
</code>```

this is returning:

```<code>*   Trying IP:443...
........
........
< HTTP/1.1 302 Found
< Cache-Control: no-cache
< Pragma: no-cache
< Content-Type: text/html; charset=utf-8
< Expires: -1
< Location: my-site.com/MemberDetails.aspx
< Date: Mon, 07 Feb 2022 09:54:49 GMT
< Content-Length: 61211
< Set-Cookie: TS0192fa71=...; Path=/; Domain=.my-site.com; Secure
</code>```

Python:

```<code>import requests
import logging

logging.basicConfig(level=logging.DEBUG)
cookies = {
    "ASP.NET_SessionId": ".....",
    "TS0192fa71": ".....",
    "ServiceProvider": ".....",
    ".ASPXAUTH": ".....",
}

headers = {
    ......
    "Content-Type": "multipart/form-data; boundary=----WebKitFormBoundaryBN2XwBbcAwvRWZzk",
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36",
    "Referer": "https://my-site.com/CardAuthentication.aspx",
    "Accept-Language": "en-US,en;q=0.9",
}

data = {
    "------WebKitFormBoundaryBN2XwBbcAwvRWZzk\r\nContent-Disposition: form-data; name": '"__EVENTTARGET"\r\n\r\n\r\n-- DATA
}

response = requests.post(
    "https://my-site.com/CardAuthentication.aspx",
    headers=headers,
    cookies=cookies,
    data=data,
)
</code>```

And the return code is 200, with response history empy.

Is there something wrong with requests library or in the way that request library is processing the data? How can I solve this?

答:
Is there something wrong with requests library or in the way that
request library is processing the data? How can I solve this?

This is default requests behavior, you need to set allow_redirects to False if you want to not follow in case of 3xx response code, example

```<code>import requests
r = requests.get("http://github.com", allow_redirects=False)
print(r.status_code)  # 301
</code>```

If you want to know more read request.request docs.

Body:
The site that I am trying to scrape must follow 302 observed by the browser network tools. I've copied the network request as Curl and its working fine, but when I convert it to python requests its just returning 200.

Curl:

curl -v 'https://my-site.com/CardAuthentication.aspx' \
  -H 'Connection: keep-alive' \
  -H 'Pragma: no-cache' \
  -H 'Cache-Control: no-cache' \
  -H 'Upgrade-Insecure-Requests: 1' \
  -H 'Origin: https://my-site.com' \
  -H 'Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryBN2XwBbcAwvRWZzk' \
  -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36' \
  -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' \
  -H 'Sec-GPC: 1' \
  -H 'Sec-Fetch-Site: same-origin' \
  -H 'Sec-Fetch-Mode: navigate' \
  -H 'Sec-Fetch-User: ?1' \
  -H 'Sec-Fetch-Dest: document' \
  -H 'Referer: https://my-site.com/CardAuthentication.aspx' \
  -H 'Accept-Language: en-US,en;q=0.9' \
  -H 'Cookie: ASP.NET_SessionId=...; TS0192fa71=...; ServiceProvider=UID=...; .ASPXAUTH=...' \
  --data-raw $'------WebKitFormBoundaryBN2XwBbcAwvRWZzk\r\ DATA \r\n' \
  --compressed

this is returning:

*   Trying IP:443...
........
........
< HTTP/1.1 302 Found
< Cache-Control: no-cache
< Pragma: no-cache
< Content-Type: text/html; charset=utf-8
< Expires: -1
< Location: my-site.com/MemberDetails.aspx
< Date: Mon, 07 Feb 2022 09:54:49 GMT
< Content-Length: 61211
< Set-Cookie: TS0192fa71=...; Path=/; Domain=.my-site.com; Secure

Python:

import requests
import logging

logging.basicConfig(level=logging.DEBUG)
cookies = {
    "ASP.NET_SessionId": ".....",
    "TS0192fa71": ".....",
    "ServiceProvider": ".....",
    ".ASPXAUTH": ".....",
}

headers = {
    ......
    "Content-Type": "multipart/form-data; boundary=----WebKitFormBoundaryBN2XwBbcAwvRWZzk",
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36",
    "Referer": "https://my-site.com/CardAuthentication.aspx",
    "Accept-Language": "en-US,en;q=0.9",
}

data = {
    "------WebKitFormBoundaryBN2XwBbcAwvRWZzk\r\nContent-Disposition: form-data; name": '"__EVENTTARGET"\r\n\r\n\r\n-- DATA
}

response = requests.post(
    "https://my-site.com/CardAuthentication.aspx",
    headers=headers,
    cookies=cookies,
    data=data,
)

And the return code is 200, with response history empy.

Is there something wrong with requests library or in the way that request library is processing the data? How can I solve this?

Body:
Is there something wrong with requests library or in the way that
request library is processing the data? How can I solve this?

This is default requests behavior, you need to set allow_redirects to False if you want to not follow in case of 3xx response code, example

import requests
r = requests.get("http://github.com", allow_redirects=False)
print(r.status_code)  # 301

If you want to know more read request.request docs.


问:
How to post xml data to soap service and process properly via spyne Python?
I want to get xml body:

```<code><root>
<row>
<param1>value1</param1>
<param2>value2</param2>
</row>
<row>
<param1>value3</param1>
<param2>value4</param2>
</row>
</root>
</code>```

in param input_data in xml form.
My code is:

```<code>from spyne import Application, rpc, ServiceBase, Unicode
from lxml import etree
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication

class TestService(ServiceBase):
   @rpc(Unicode, _returns=Unicode)
   def load_data(ctx, input_data):
       print(etree.tostring(ctx.in_document))
       print('\n')
       print(input_data)

app = Application([TestService], tns='PostData',
                 in_protocol=Soap11(),
                 out_protocol=Soap11(),
                 )

application = WsgiApplication(app)
if __name__ == '__main__':
   from wsgiref.simple_server import make_server
   server = make_server('0.0.0.0', 8090, application)
   server.serve_forever()
</code>```

raw XML in Postman:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tran="PostData">
<soapenv:Header/>
<soapenv:Body>
<tran:load_data>
<tran:input_data>
<root>
<row>
<param1>value1</param1>
<param2>value2</param2>
</row>
<row>
<param1>value3</param1>
<param2>value4</param2>
</row>
</root>
</tran:input_data>
</tran:load_data>
</soapenv:Body>
</soapenv:Envelope>
</code>```

With current implementation it doesn't work, param input_data is not shown (print(input_data)). Maybe need change param in @rpc?
There can be many raw bodies.
(Next step is to translate xml to json and load into table and I need data in xml format)
How can I do it? Thanks

答:
First, read the manual. Here's the relevant chapter: http://spyne.io/docs/2.10/manual/03_types.html

There are also a bunch of examples in the spyne repository: https://github.com/arskom/spyne/tree/master/examples

class Row(ComplexModel):
    param1 = Unicode
    param2 = Unicode

class Root(ComplexModel):
    row = Row

class TestService(ServiceBase):
   @rpc(Root, _returns=Unicode)
   def load_data(ctx, input_data):
       print(etree.tostring(ctx.in_document))
       print('\n')
       print(input_data)

```

Body:
I want to get xml body:

<root>
<row>
<param1>value1</param1>
<param2>value2</param2>
</row>
<row>
<param1>value3</param1>
<param2>value4</param2>
</row>
</root>

in param input_data in xml form.
My code is:

from spyne import Application, rpc, ServiceBase, Unicode
from lxml import etree
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication

class TestService(ServiceBase):
   @rpc(Unicode, _returns=Unicode)
   def load_data(ctx, input_data):
       print(etree.tostring(ctx.in_document))
       print('\n')
       print(input_data)

app = Application([TestService], tns='PostData',
                 in_protocol=Soap11(),
                 out_protocol=Soap11(),
                 )

application = WsgiApplication(app)
if __name__ == '__main__':
   from wsgiref.simple_server import make_server
   server = make_server('0.0.0.0', 8090, application)
   server.serve_forever()

raw XML in Postman:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tran="PostData">
<soapenv:Header/>
<soapenv:Body>
<tran:load_data>
<tran:input_data>
<root>
<row>
<param1>value1</param1>
<param2>value2</param2>
</row>
<row>
<param1>value3</param1>
<param2>value4</param2>
</row>
</root>
</tran:input_data>
</tran:load_data>
</soapenv:Body>
</soapenv:Envelope>

With current implementation it doesn't work, param input_data is not shown (print(input_data)). Maybe need change param in @rpc?
There can be many raw bodies.
(Next step is to translate xml to json and load into table and I need data in xml format)
How can I do it? Thanks


问:
Split elements into sections
I'd like to split a text into sections:

The source XML:

```<code><data>
  <p>hello</p>
  <p>nice</p>
  <p>BREAK</p>
  <p>world</p>
</data>
</code>```

My half successful attempt:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0" >
  <xsl:output indent="yes"/>

  <xsl:template match="data">
    <xsl:for-each-group select="p" group-starting-with=".[. = 'BREAK']">
      <chapter>
        <xsl:copy-of select="current-group()"/>
      </chapter>
    </xsl:for-each-group>
  </xsl:template>

</xsl:stylesheet>
</code>```

The result (fragment) I'd like to get:

```<code><chapter>
  <p>hello</p>
  <p>nice</p>
</chapter>
<chapter>
  <p>world</p>
</chapter>
</code>```

Instead I get

```<code><chapter>
   <p>hello</p>
   <p>nice</p>
</chapter>
<chapter>
   <p>BREAK</p>
   <p>world</p>
</chapter>
</code>```

(it still contains
BREAK
)

My question is: is there a straightforward way to get rid of the
BREAK
 element?

答: You can easily select <xsl:copy-of select="current-group()[not(. = 'BREAK')]"/>.

Title: Split elements into sections

Body:
I'd like to split a text into sections:

The source XML:

<data>

hello

nice

BREAK

world

</data>

My half successful attempt:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0" >
  <xsl:output indent="yes"/>

  <xsl:template match="data">
    <xsl:for-each-group select="p" group-starting-with=".[. = 'BREAK']">
      <chapter>
        <xsl:copy-of select="current-group()"/>
      </chapter>
    </xsl:for-each-group>
  </xsl:template>

</xsl:stylesheet>

The result (fragment) I'd like to get:

<chapter>

hello

nice

</chapter>
<chapter>

world

</chapter>

Instead I get

<chapter>

hello

nice

</chapter>
<chapter>

BREAK

world

</chapter>

(it still contains
BREAK
)

My question is: is there a straightforward way to get rid of the
BREAK
 element?


问:
SQL Server proc running 5x slower than plain query
I have the following query:

```<code>DECLARE @DaysNotUsed int = 14
DECLARE @DaysNotPhoned int = 7

--Total Unique Students
DECLARE @totalStudents TABLE (SchoolID uniqueidentifier, TotalUniqueStudents int)
INSERT INTO @totalStudents
SELECT
        SSGG.School,
        COUNT(DISTINCT S.StudentID)
    FROM Student S
        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
        INNER JOIN SessionHistory SH ON (SH.Student = S.StudentID AND SH.School = S.School AND SH.StartDateTime > GETDATE() - @DaysNotUsed)
    WHERE G.IsBuiltIn = 0
        AND S.HasStartedProduct = 1
    GROUP BY SSGG.School

--Last Used On
DECLARE @lastUsed TABLE (SchoolID uniqueidentifier, LastUsedOn datetime)
INSERT INTO @lastUsed
SELECT
        vi.SchoolID,
        MAX(sh.StartDateTime)
    FROM View_Installation as vi
        INNER JOIN SessionHistory as sh on sh.School = vi.SchoolID
    GROUP BY vi.SchoolID

SELECT
        VI.SchoolID,
        INS.DateAdded,
        INS.Removed,
        INS.DateRemoved,
        INS.DateToInclude,
        VI.SchoolName AS [School Name],
        VI.UsersLicensed AS [Licenses],
        ISNULL(TS.TotalUniqueStudents, 0) as [Total Unique Students],
        ISNULL(TS.TotalUniqueStudents, 0) * 100 / VI.UsersLicensed as [% of Students Using],
        S.State,
        LU.LastUsedOn,
        DATEDIFF(DAY, LU.LastUsedOn, GETDATE()) AS [Days Not Used],
        SI.AreaSalesManager AS [Sales Rep],
        SI.CaseNumber AS [Case #],
        SI.RenewalDate AS [Renewal Date],
        SI.AssignedTo AS [Assigned To],
        SI.Notes AS [Notes]
    FROM View_Installation VI
        INNER JOIN School S ON S.SchoolID = VI.SchoolID
        LEFT OUTER JOIN @totalStudents TS on TS.SchoolID = VI.SchoolID
        INNER JOIN @lastUsed LU on LU.SchoolID = VI.SchoolID
        LEFT OUTER JOIN InactiveReports..SchoolInfo SI ON S.SchoolID = SI.SchoolID
        LEFT OUTER JOIN InactiveReports..InactiveSchools INS ON S.SchoolID = INS.SchoolID
    WHERE VI.UsersLicensed > 0
        AND VI.LastPhoneHome > GETDATE() - @DaysNotPhoned
        AND
        (
            (
                SELECT COUNT(DISTINCT S.StudentID)
                    FROM Student S
                        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
                        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
                    WHERE G.IsBuiltIn = 0
                        AND S.School = VI.SchoolID
            ) * 100 / VI.UsersLicensed < 50
            OR
            VI.SchoolID NOT IN
            (
                SELECT DISTINCT SH1.School
                FROM SessionHistory SH1
                WHERE SH1.StartDateTime > GETDATE() - @DaysNotUsed
            )
        )
    ORDER BY [Days Not Used] DESC
</code>```

Running just plain sql like this in SSMS take about 10 seconds to run.  When I created a stored procedure with exactly the same code, the query takes 50 seconds instead.  The only difference in the actual code of the proc is a SET NOCOUNT ON that the IDE put in by default, but adding that line to the query doesn't have any impact.  Any idea what would cause such a dramatic slow down like this?

EDIT I neglected the declare statements at the beginning.  These are not in the proc, but are parameters to it.  Could this be the difference?

答:
I agree about the potential parameter sniffing issue, but I would also check these settings.

For the procedure:

```<code>SELECT uses_ansi_nulls, uses_quoted_identifier
  FROM sys.sql_modules
  WHERE [object_id] = OBJECT_ID('dbo.procedure_name');
</code>```

For the SSMS query window where the query is running fast:

```<code>SELECT [ansi_nulls], [quoted_identifier]
  FROM sys.dm_exec_sessions
  WHERE session_id = @@SPID;
</code>```

If either of these don't match, you might consider dropping the stored procedure and re-creating it with those two settings matching. For example, if the procedure has uses_quoted_identifier = 0 and the session has quoted_identifier = 1, you could try:

```<code>DROP PROCEDURE dbo.procedure_name;
GO
SET QUOTED_IDENTIFIER ON;
GO
CREATE PROCEDURE dbo.procedure_name
AS
BEGIN
    SET NOCOUNT ON;
    ...
END
GO
</code>```

Ideally all of your modules will be created with the exact same QUOTED_IDENTIFIER and ANSI_NULLS settings. It's possible the procedure was created when the settings were off (the default is on for both), or it's possible that where you are executing the query, one or both options are off (you can change this behavior in SSMS under Tools/Options/Query Execution/SQL Server/ANSI).

I'm not going to make any disclaimers about the behavior of the stored procedure with the different settings (for example you may have wanted ANSI_NULLS off so you could compare NULL = NULL), that you'll have to test, but at least you'll be comparing queries that are being run with the same options, and it will help narrow down potential parameter sniffing issues. If you're intentionally using SET ANSI_NULLS OFF, however, I caution you to find other approaches as that behavior will eventually be unsupported.

Other ways around parameter sniffing:

make sure you don't inadvertently compile the procedure with atypical parameters

use the recompile option either on the procedure or on the statement that seems to be the victim (I'm not sure if all of these are valid, because I can only tell that you are using SQL Server 2005 or greater, and some of these were introduced in 2008)

declare local variables similar to your input parameters, and pass the input parameter values to them, using the local variables later in the prodedure and ignoring the input parameters

The last option is my least favorite, but it's the quickest / easiest fix in the midst of troubleshooting and when users are complaining.

Body:
I have the following query:

DECLARE @DaysNotUsed int = 14
DECLARE @DaysNotPhoned int = 7

--Total Unique Students
DECLARE @totalStudents TABLE (SchoolID uniqueidentifier, TotalUniqueStudents int)
INSERT INTO @totalStudents
SELECT
        SSGG.School,
        COUNT(DISTINCT S.StudentID)
    FROM Student S
        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
        INNER JOIN SessionHistory SH ON (SH.Student = S.StudentID AND SH.School = S.School AND SH.StartDateTime > GETDATE() - @DaysNotUsed)
    WHERE G.IsBuiltIn = 0
        AND S.HasStartedProduct = 1
    GROUP BY SSGG.School

--Last Used On
DECLARE @lastUsed TABLE (SchoolID uniqueidentifier, LastUsedOn datetime)
INSERT INTO @lastUsed
SELECT
        vi.SchoolID,
        MAX(sh.StartDateTime)
    FROM View_Installation as vi
        INNER JOIN SessionHistory as sh on sh.School = vi.SchoolID
    GROUP BY vi.SchoolID

SELECT
        VI.SchoolID,
        INS.DateAdded,
        INS.Removed,
        INS.DateRemoved,
        INS.DateToInclude,
        VI.SchoolName AS [School Name],
        VI.UsersLicensed AS [Licenses],
        ISNULL(TS.TotalUniqueStudents, 0) as [Total Unique Students],
        ISNULL(TS.TotalUniqueStudents, 0) * 100 / VI.UsersLicensed as [% of Students Using],
        S.State,
        LU.LastUsedOn,
        DATEDIFF(DAY, LU.LastUsedOn, GETDATE()) AS [Days Not Used],
        SI.AreaSalesManager AS [Sales Rep],
        SI.CaseNumber AS [Case #],
        SI.RenewalDate AS [Renewal Date],
        SI.AssignedTo AS [Assigned To],
        SI.Notes AS [Notes]
    FROM View_Installation VI
        INNER JOIN School S ON S.SchoolID = VI.SchoolID
        LEFT OUTER JOIN @totalStudents TS on TS.SchoolID = VI.SchoolID
        INNER JOIN @lastUsed LU on LU.SchoolID = VI.SchoolID
        LEFT OUTER JOIN InactiveReports..SchoolInfo SI ON S.SchoolID = SI.SchoolID
        LEFT OUTER JOIN InactiveReports..InactiveSchools INS ON S.SchoolID = INS.SchoolID
    WHERE VI.UsersLicensed > 0
        AND VI.LastPhoneHome > GETDATE() - @DaysNotPhoned
        AND
        (
            (
                SELECT COUNT(DISTINCT S.StudentID)
                    FROM Student S
                        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
                        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
                    WHERE G.IsBuiltIn = 0
                        AND S.School = VI.SchoolID
            ) * 100 / VI.UsersLicensed < 50
            OR
            VI.SchoolID NOT IN
            (
                SELECT DISTINCT SH1.School
                FROM SessionHistory SH1
                WHERE SH1.StartDateTime > GETDATE() - @DaysNotUsed
            )
        )
    ORDER BY [Days Not Used] DESC

Running just plain sql like this in SSMS take about 10 seconds to run.  When I created a stored procedure with exactly the same code, the query takes 50 seconds instead.  The only difference in the actual code of the proc is a SET NOCOUNT ON that the IDE put in by default, but adding that line to the query doesn't have any impact.  Any idea what would cause such a dramatic slow down like this?

EDIT I neglected the declare statements at the beginning.  These are not in the proc, but are parameters to it.  Could this be the difference?

Body:
I agree about the potential parameter sniffing issue, but I would also check these settings.

For the procedure:

SELECT uses_ansi_nulls, uses_quoted_identifier
  FROM sys.sql_modules
  WHERE [object_id] = OBJECT_ID('dbo.procedure_name');

For the SSMS query window where the query is running fast:

SELECT [ansi_nulls], [quoted_identifier]
  FROM sys.dm_exec_sessions
  WHERE session_id = @@SPID;

If either of these don't match, you might consider dropping the stored procedure and re-creating it with those two settings matching. For example, if the procedure has uses_quoted_identifier = 0 and the session has quoted_identifier = 1, you could try:

DROP PROCEDURE dbo.procedure_name;
GO
SET QUOTED_IDENTIFIER ON;
GO
CREATE PROCEDURE dbo.procedure_name
AS
BEGIN
    SET NOCOUNT ON;
    ...
END
GO

Ideally all of your modules will be created with the exact same QUOTED_IDENTIFIER and ANSI_NULLS settings. It's possible the procedure was created when the settings were off (the default is on for both), or it's possible that where you are executing the query, one or both options are off (you can change this behavior in SSMS under Tools/Options/Query Execution/SQL Server/ANSI).

I'm not going to make any disclaimers about the behavior of the stored procedure with the different settings (for example you may have wanted ANSI_NULLS off so you could compare NULL = NULL), that you'll have to test, but at least you'll be comparing queries that are being run with the same options, and it will help narrow down potential parameter sniffing issues. If you're intentionally using SET ANSI_NULLS OFF, however, I caution you to find other approaches as that behavior will eventually be unsupported.

Other ways around parameter sniffing:

make sure you don't inadvertently compile the procedure with atypical parameters

use the recompile option either on the procedure or on the statement that seems to be the victim (I'm not sure if all of these are valid, because I can only tell that you are using SQL Server 2005 or greater, and some of these were introduced in 2008)

declare local variables similar to your input parameters, and pass the input parameter values to them, using the local variables later in the prodedure and ignoring the input parameters

The last option is my least favorite, but it's the quickest / easiest fix in the midst of troubleshooting and when users are complaining.


问:
Local authentication problem in release apk flutter
I have faced this issue recently. The local authentication would work flawlessly on flutter run and  --release, --profile . But when I make the APK and then install it, the local auth does not work, the app crashes. There is no error in the app when i run the same app but when the cable is connected to my computer.

Here, the function call begins,

```<code>onPressed: () {
                              bool enable = preferences.getBool('bioAuth');
                              if (enable == null || enable == false) {
                                showSnack('Biometric Auth not Enabled...');
                              } else {
                                biometricLogin(
                                    context: context, mainCol: mainCol);
                              }

                            },
</code>```

Here is the biometricLogin Function.

```<code>void biometricLogin({context, mainCol}) async {
bool authenticated =
    await checkBiometric(context: context, mainCol: mainCol);

if (authenticated == null || authenticated == false) {
  showSnack('BioAuth not valid...');
} else {
  bool isGoogle = preferences.getBool('googleSignIn');
  bool isApple = preferences.getBool('appleSignin');
  if (isGoogle) {
    showSnack('Logging in...');
    User user = await _auth.signInWIthGoogleCreds();
    print(user);
    if (user == null) {
      showSnack('Try logging in through Google again...');
    }
  } else if (isApple) {
    showSnack('Logging in...');
    User user = await _auth.signInWIthAppleCreds();
    print(user);
    if (user == null) {
      showSnack('Try logging in through Apple again...');
    }
  } else {
    User user;
    showSnack('Logging in...');
    var email = preferences.getString('email');
    var password = preferences.getString('pass');
    user = await _auth.signIn(email, password);
    if (user != null) {
      await preferences.setBool('loggedIn', true);
    } else {
      showSnack('Something went wrong');
    }
  }
}
</code>```

}

And here is checkBiometrics function .

```<code>Future<bool> checkBiometric({context, mainCol}) async {
if (bioAuth == null || bioAuth == false) {
  showSnack('Biometrics not Enabled');
  return false;
} else {
  try {
    canCheckBiometrics = await auth.canCheckBiometrics;
    if (!mounted) return false;
    List<BiometricType> availableBiometrics;
    availableBiometrics = await auth.getAvailableBiometrics();
    bool authenticated = false;
    if (Platform.isIOS) {
      const iosStrings = const IOSAuthMessages(
          cancelButton: 'cancel',
          goToSettingsButton: 'settings',
          goToSettingsDescription: 'Please set up your Touch ID.',
          lockOut: 'Please re-enable your Touch ID');
      if (availableBiometrics.contains(BiometricType.face) ||
          availableBiometrics.contains(BiometricType.fingerprint)) {
        authenticated = await auth.authenticateWithBiometrics(
          localizedReason: "Please authenticate to login",
          useErrorDialogs: true,
          iOSAuthStrings: iosStrings,
          stickyAuth: true,
        );
      } else
        authenticated = false;
    } else {
      authenticated = await auth.authenticateWithBiometrics(
        localizedReason: 'Touch your finger on the sensor to login',
        useErrorDialogs: true,
        stickyAuth: true,
      );
    }
    return authenticated;
  } catch (e) {
    showSnack("error using biometric auth: $e");
  }
  setState(() {
    authenticated = authenticated ? true : false;
  });
  return authenticated;
}
</code>```

}

As far as I understand. The app doesnot goes ahead of checkBiometrics, because it crashes just by pressing the button.

Body:
I have faced this issue recently. The local authentication would work flawlessly on flutter run and  --release, --profile . But when I make the APK and then install it, the local auth does not work, the app crashes. There is no error in the app when i run the same app but when the cable is connected to my computer.

Here, the function call begins,

onPressed: () {
                              bool enable = preferences.getBool('bioAuth');
                              if (enable == null || enable == false) {
                                showSnack('Biometric Auth not Enabled...');
                              } else {
                                biometricLogin(
                                    context: context, mainCol: mainCol);
                              }

                            },

Here is the biometricLogin Function.

void biometricLogin({context, mainCol}) async {
bool authenticated =
    await checkBiometric(context: context, mainCol: mainCol);

if (authenticated == null || authenticated == false) {
  showSnack('BioAuth not valid...');
} else {
  bool isGoogle = preferences.getBool('googleSignIn');
  bool isApple = preferences.getBool('appleSignin');
  if (isGoogle) {
    showSnack('Logging in...');
    User user = await _auth.signInWIthGoogleCreds();
    print(user);
    if (user == null) {
      showSnack('Try logging in through Google again...');
    }
  } else if (isApple) {
    showSnack('Logging in...');
    User user = await _auth.signInWIthAppleCreds();
    print(user);
    if (user == null) {
      showSnack('Try logging in through Apple again...');
    }
  } else {
    User user;
    showSnack('Logging in...');
    var email = preferences.getString('email');
    var password = preferences.getString('pass');
    user = await _auth.signIn(email, password);
    if (user != null) {
      await preferences.setBool('loggedIn', true);
    } else {
      showSnack('Something went wrong');
    }
  }
}

}

And here is checkBiometrics function .

Future<bool> checkBiometric({context, mainCol}) async {
if (bioAuth == null || bioAuth == false) {
  showSnack('Biometrics not Enabled');
  return false;
} else {
  try {
    canCheckBiometrics = await auth.canCheckBiometrics;
    if (!mounted) return false;
    List<BiometricType> availableBiometrics;
    availableBiometrics = await auth.getAvailableBiometrics();
    bool authenticated = false;
    if (Platform.isIOS) {
      const iosStrings = const IOSAuthMessages(
          cancelButton: 'cancel',
          goToSettingsButton: 'settings',
          goToSettingsDescription: 'Please set up your Touch ID.',
          lockOut: 'Please re-enable your Touch ID');
      if (availableBiometrics.contains(BiometricType.face) ||
          availableBiometrics.contains(BiometricType.fingerprint)) {
        authenticated = await auth.authenticateWithBiometrics(
          localizedReason: "Please authenticate to login",
          useErrorDialogs: true,
          iOSAuthStrings: iosStrings,
          stickyAuth: true,
        );
      } else
        authenticated = false;
    } else {
      authenticated = await auth.authenticateWithBiometrics(
        localizedReason: 'Touch your finger on the sensor to login',
        useErrorDialogs: true,
        stickyAuth: true,
      );
    }
    return authenticated;
  } catch (e) {
    showSnack("error using biometric auth: $e");
  }
  setState(() {
    authenticated = authenticated ? true : false;
  });
  return authenticated;
}

}

As far as I understand. The app doesnot goes ahead of checkBiometrics, because it crashes just by pressing the button.

Body:
If you receive this error: Exception has occurred. PlatformException (PlatformException(error, You need to use a Theme.AppCompat theme (or descendant) with this activity., null))

Then you need to do this:

Go to android>app>src>main>res>values>style.xml

Change the
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar"> to <style name="LaunchTheme" parent="Theme.AppCompat.Light.NoActionBar">


问:
What is the correct way to install Android Studio Bumblebee 2021.1.1 Patch 1
I am sorry but I am really confused and leery now, so I am resorting to SO to get some clarity.

I am running Android Studio Bumblebee and saw a notification about a major new release wit the following text:

```<code>Android Studio Bumblebee | 2021.1.1 Patch 1 is a major new release and includes performance improvements, bug fixes and new features.
Intellij 2021.1.1 Platform Update
New Device Manager
ADB over Wi-Fi
Run Instrumented Tests in Android Studio using Gradle
Android Gradle Plugin Upgrade Assistant now updates API usage
Non-Transitive R classes on for new projects
Apple Silicon Support Update
Jank detection track in Profilers
Profileable app profiling support in Studio Profilers
Network Inspection and ability to capture Layout Inspector snapshots
Support for Compose semantics in the Layout Inspector
Interactive Preview
Animated Vector Drawables Preview
Updated Device picker for Design Tools
Important After updating, you need to restart Android Studio to apply any memory settings you migrate from an earlier version of the IDE.
</code>```

When I click "Release Notes", I see "This minor update includes the following bug fixes:...". However, when I click "Download", a download page is opened. I am really puzzled by this because I thought a minor update would not require installing the entire thing. The notes for Android Studio - Bumblebee | 2021.1.1 Patch 1 indicates downloading the entire package is not needed:

If you already have an Android Studio build on the Stable channel, you
can get the update by clicking Help > Check for Update (Android Studio

Check for Updates on macOS). Otherwise, you can download it here.

I did a search and found people are having poor experiences with this update. Could anyone shed some light on this before I plunge into a potential disaster?

I am eager to update Bumblebee because it keeps crashing.

答:
This issue was fixed by Google (10 February 2022).

You can now update Android Studio normally.

Body:
I am sorry but I am really confused and leery now, so I am resorting to SO to get some clarity.

I am running Android Studio Bumblebee and saw a notification about a major new release wit the following text:

Android Studio Bumblebee | 2021.1.1 Patch 1 is a major new release and includes performance improvements, bug fixes and new features.
Intellij 2021.1.1 Platform Update
New Device Manager
ADB over Wi-Fi
Run Instrumented Tests in Android Studio using Gradle
Android Gradle Plugin Upgrade Assistant now updates API usage
Non-Transitive R classes on for new projects
Apple Silicon Support Update
Jank detection track in Profilers
Profileable app profiling support in Studio Profilers
Network Inspection and ability to capture Layout Inspector snapshots
Support for Compose semantics in the Layout Inspector
Interactive Preview
Animated Vector Drawables Preview
Updated Device picker for Design Tools
Important After updating, you need to restart Android Studio to apply any memory settings you migrate from an earlier version of the IDE.

When I click "Release Notes", I see "This minor update includes the following bug fixes:...". However, when I click "Download", a download page is opened. I am really puzzled by this because I thought a minor update would not require installing the entire thing. The notes for Android Studio - Bumblebee | 2021.1.1 Patch 1 indicates downloading the entire package is not needed:

If you already have an Android Studio build on the Stable channel, you
can get the update by clicking Help > Check for Update (Android Studio

Check for Updates on macOS). Otherwise, you can download it here.

I did a search and found people are having poor experiences with this update. Could anyone shed some light on this before I plunge into a potential disaster?

I am eager to update Bumblebee because it keeps crashing.


问:
Copy files in depended project reference
I have a solution with 2 projects, Project1 and Project2
project1 is referencing Project2
Project2 contains a folder called Content that contains xml files
I want that when I build Project1, the content of Project2 will be copy to the Output directory of Project1, (Without the Content folder)
I tried to achieved it using .targets file but it seems like the tasks in there are not executing.

I know I can add the files manually but I want anyone that referenced Project2 will receive the same behavior.

Will appreciate any help

答:
Try to add the two Project1’s xml files as a link in the Project2.
When you build the solution, the files will be copied automatically.

In Visual Studio:

click on Project2’s target folder,

then right-click on it and add an existing element,

then browse the XML files in Project1,

click on the arrow next to Add button on the bottom right corner,

choose « Add as a link », and voilà !

Read: https://andrewlock.net/including-linked-files-from-outside-the-project-directory-in-asp-net-core/

You can also achieve this by adding XCOPY command lines in the post-build event dialog box :

Read: https://learn.microsoft.com/en-us/visualstudio/ide/how-to-specify-build-events-csharp?view=vs-2022


问:
Show Two Languages at once
Fisrt of all i am following this guide for localization which is the official guideline of flutter but at

```<code>AppLocalizations.of(context)!.helloWorld
</code>```

It gives error as null

I think this is maybe because I recently updated flutter to 2.10 please confirm if that is the case

I want to achieve this kind of results like English on right and Urdu Language of Left which i don't know how to do that because in samples and guides they just show how to change overall app language not just for some strings

Also for time being, I have used easy_localization: 3.0.0 but still the problem is how i support multiple language at once with this package

答:
Don't use localization for this part - drawer widget - text items

wrap drawer widget with Directionality widget to prevent it from mirroring and make text in the same place.

pop the drawer after using switch widget.

Example:

```<code>import 'package:flutter/material.dart' as ltr;

drawer: Directionality(
    textDirection: ltr.TextDirection.ltr,
    child: Container(
      color: Colors.lightGreen,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('English'),
              Text('عربي'),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('English'),
              Text('عربي'),
            ],
          ),
        ],
      ),
    ),
  ),
</code>```

Title: Show Two Languages at once

Body:
Fisrt of all i am following this guide for localization which is the official guideline of flutter but at

AppLocalizations.of(context)!.helloWorld

It gives error as null

I think this is maybe because I recently updated flutter to 2.10 please confirm if that is the case

I want to achieve this kind of results like English on right and Urdu Language of Left which i don't know how to do that because in samples and guides they just show how to change overall app language not just for some strings

Also for time being, I have used easy_localization: 3.0.0 but still the problem is how i support multiple language at once with this package

Body:
Don't use localization for this part - drawer widget - text items

wrap drawer widget with Directionality widget to prevent it from mirroring and make text in the same place.

pop the drawer after using switch widget.

Example:

import 'package:flutter/material.dart' as ltr;

drawer: Directionality(
    textDirection: ltr.TextDirection.ltr,
    child: Container(
      color: Colors.lightGreen,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('English'),
              Text('عربي'),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('English'),
              Text('عربي'),
            ],
          ),
        ],
      ),
    ),
  ),


问:
Unable to Access a website using FirefoxDriver and HtmlUnitDriver
I'm trying to access the website using FirefoxDriver but I'm getting a not a valid url exception

I also tried with HtmlUnitDriver there the website title come back as null

I tied the old and new website on the below

```<code>
System.setProperty("webdriver.gecko.driver","C:\\Users\\Family\\path to firefox driver\\geckodriver.exe");

//WebDriver driver = HtmlUnitDriver();

WebDriver driver = new FirefoxDriver();

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//this is an old website
//driver.get("https://www.hollywoodbets.net");

//this is a new website
driver.get("https://new.hollywoodbets.net");

System.out.println("WEBSITE TITTLE " + driver.getTitle());

</code>```

答:
The URL you are trying to open blocks access to it for Chrome too.

I tried to open it with regular Chrome browser on my PC even without Selenium.

It presents the following message:

Error 1020 Ray ID: 6d9bdf8b1b729131 • 2022-02-07 10:18:16 UTC

Access denied

What happened?

This website is using a security service to protect itself from online attacks.

Cloudflare Ray ID: 6d9bdf8b1b729131 • Your IP: 77.137.69.164 • Performance & security by Cloudflare

Occurs both for https://new.hollywoodbets.net and for https://www.hollywoodbets.net.  The former link is actually redirecting to the first one.

Body:
I'm trying to access the website using FirefoxDriver but I'm getting a not a valid url exception

I also tried with HtmlUnitDriver there the website title come back as null

I tied the old and new website on the below

System.setProperty("webdriver.gecko.driver","C:\\Users\\Family\\path to firefox driver\\geckodriver.exe");

//WebDriver driver = HtmlUnitDriver();

WebDriver driver = new FirefoxDriver();

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

//this is an old website
//driver.get("https://www.hollywoodbets.net");

//this is a new website
driver.get("https://new.hollywoodbets.net");

System.out.println("WEBSITE TITTLE " + driver.getTitle());


问:
warning: Kotlin runtime JAR files in the classpath should have the same version
I get the following warning, but I'm not sure where v1.0.6 resides.

Is it possible this error comes from a Kotlin library somehow including an old Kotlin version?

Any ideas how to fix it or at least how can I follow the suggestion to make kotlin-reflect explicit (1.1) ?

答:
When this happens for the Lint task, one can list the dependencies with:

```<code>./gradlew -q dependencies app:dependencies --configuration lintClassPath
</code>```

Which shows that eg. kotlin-stdlib-jdk8:1.4.32 is being used:

```<code> +--- org.jetbrains.kotlin:kotlin-reflect:1.4.32 (*)
 \--- org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.4.32 (*)
</code>```

I've wrote a Gradle script, which equalizes all the Kotlin library versions:

```<code>// Runtime JAR files in the classpath should have the same version.
configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def kotlinVersion = "1.6.0"
        def requested = details.requested
        if (requested.group == 'org.jetbrains.kotlin') {
            List<String> list = ['kotlin-stdlib', 'kotlin-stdlib-jdk7', 'kotlin-stdlib-jdk8', 'kotlin-stdlib-common']
            if (list.contains(requested.name)) { details.useVersion kotlinVersion }
        }
    }
}
</code>```

There is no other way, because some older versions are being pulled in by build tools.

One likely could also add kotlin-reflect into the List<String> list (not tested).

Body:
When this happens for the Lint task, one can list the dependencies with:

./gradlew -q dependencies app:dependencies --configuration lintClassPath

Which shows that eg. kotlin-stdlib-jdk8:1.4.32 is being used:

 +--- org.jetbrains.kotlin:kotlin-reflect:1.4.32 (*)
 \--- org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.4.32 (*)

I've wrote a Gradle script, which equalizes all the Kotlin library versions:

// Runtime JAR files in the classpath should have the same version.
configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def kotlinVersion = "1.6.0"
        def requested = details.requested
        if (requested.group == 'org.jetbrains.kotlin') {
            List<String> list = ['kotlin-stdlib', 'kotlin-stdlib-jdk7', 'kotlin-stdlib-jdk8', 'kotlin-stdlib-common']
            if (list.contains(requested.name)) { details.useVersion kotlinVersion }
        }
    }
}

There is no other way, because some older versions are being pulled in by build tools.

One likely could also add kotlin-reflect into the List<String> list (not tested).


问:
MySQL stored procedure If exists
I'm creating a stored procedure in MySQL, and having trouble using IF EXISTS

My SQL is;

```<code>CREATE DEFINER=`##`@`%` PROCEDURE `myTestProceedure`(IN _id INT)
BEGIN
    IF EXISTS (SELECT * FROM cms.variables WHERE tmplvarid = 5 and id = _id) THEN
    BEGIN
    UPDATE cms.variables SET value = now() WHERE id = _id and tmplvarid = 5;
    END;
    ELSE
    BEGIN
    INSERT INTO cms.variables (`tmplvarid`, `contentid`, `value`) VALUES (5, _id, now());
    END;
    END IF;
END
</code>```

Basically, what I'm trying to do in this procedure is IF the row already exists in the DB, update it, otherwise insert it.

However despite whatever result SELECT * FROM cms.variables WHERE tmplvarid = 5 and id = _id gives, it just inserts into the database.

Any help would be greatly appreciated.

答:
The accepted answer didn't work for me running MariaDB 15.1.
It just kept evaluating the IF condition as true and trying to insert the record even if it already existed.

This is what I ended up using:

```<code>CREATE DEFINER=`ghost`@`localhost` PROCEDURE `proc_updateTable`(IN `_id` mediumint,IN `_arg2` varchar(100))
BEGIN
    #Routine body goes here...
    DECLARE exist DECIMAL DEFAULT 0;
    SELECT COUNT(*) INTO exist FROM `database`.`tbl_example` WHERE (`tbl_example`.`ID` = _id AND `tbl_example`.`arg2` = _arg2);
    IF exist < 1 THEN
        BEGIN
            INSERT INTO `database`.`tbl_example` VALUES (_id,_arg2);
        END;
    END IF;
END
</code>```

Hope this helps someone else with this problem

Title: MySQL stored procedure If exists

Body:
I'm creating a stored procedure in MySQL, and having trouble using IF EXISTS

My SQL is;

CREATE DEFINER=`##`@`%` PROCEDURE `myTestProceedure`(IN _id INT)
BEGIN
    IF EXISTS (SELECT * FROM cms.variables WHERE tmplvarid = 5 and id = _id) THEN
    BEGIN
    UPDATE cms.variables SET value = now() WHERE id = _id and tmplvarid = 5;
    END;
    ELSE
    BEGIN
    INSERT INTO cms.variables (`tmplvarid`, `contentid`, `value`) VALUES (5, _id, now());
    END;
    END IF;
END

Basically, what I'm trying to do in this procedure is IF the row already exists in the DB, update it, otherwise insert it.

However despite whatever result SELECT * FROM cms.variables WHERE tmplvarid = 5 and id = _id gives, it just inserts into the database.

Any help would be greatly appreciated.

Body:
The accepted answer didn't work for me running MariaDB 15.1.
It just kept evaluating the IF condition as true and trying to insert the record even if it already existed.

This is what I ended up using:

CREATE DEFINER=`ghost`@`localhost` PROCEDURE `proc_updateTable`(IN `_id` mediumint,IN `_arg2` varchar(100))
BEGIN
    #Routine body goes here...
    DECLARE exist DECIMAL DEFAULT 0;
    SELECT COUNT(*) INTO exist FROM `database`.`tbl_example` WHERE (`tbl_example`.`ID` = _id AND `tbl_example`.`arg2` = _arg2);
    IF exist < 1 THEN
        BEGIN
            INSERT INTO `database`.`tbl_example` VALUES (_id,_arg2);
        END;
    END IF;
END

Hope this helps someone else with this problem


问:
When does std::format throw an exception?
I am using OutputDebugStringA() to output diagnostic info from my program that I can read with DbgView.

Today I am using std::stringstream to format messages:

```<code>int value = 5;
std::stringstream ss;
ss << "value=" << value;
OutputDebugStringA(ss.str().c_str());
</code>```

This is rather verbose and I am looking into using std::format() instead:

```<code>int value = 5;
OutputDebugStringA(std::format("value={0}",value).c_str());
</code>```

which seems nice.
My only worry is that std::format may throw an exception.
But under which circumstances?

It would be really bad if some diagnostic or error checking code I write itself throws an exception that messes up the execution of my program.

EDIT:
example that throws an exception:

```<code>std::string s = std::format("value={},{}", value);
</code>```

答:
My only worry is that std::format may throw an exception. But under
which circumstances?

From [format.err.report]:

Formatting functions throw format_error if an argument fmt is passed
that is not a format string for args. They propagate exceptions thrown
by operations of formatter specializations and iterators. Failure to
allocate storage is reported by throwing an exception as described in
[res.on.exception.handling].

In short, format_error will be thrown when your format string is not valid for format arguments.

Body:
I am using OutputDebugStringA() to output diagnostic info from my program that I can read with DbgView.

Today I am using std::stringstream to format messages:

int value = 5;
std::stringstream ss;
ss << "value=" << value;
OutputDebugStringA(ss.str().c_str());

This is rather verbose and I am looking into using std::format() instead:

int value = 5;
OutputDebugStringA(std::format("value={0}",value).c_str());

which seems nice.
My only worry is that std::format may throw an exception.
But under which circumstances?

It would be really bad if some diagnostic or error checking code I write itself throws an exception that messes up the execution of my program.

EDIT:
example that throws an exception:

std::string s = std::format("value={},{}", value);


问:
Getting AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1 with no other stack trace
When using Retrofit and Coroutines to fetch data from an API I sometimes get an app crash with no stacktrace in Logcat except this: AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1

答: I have encountered this type of error many times and what worked for me was to uninstall the app from the emulator and then installing it again.</p>


问:
which parts to import in bootstrap 4 customisation
I'm currently using bootstrap in my application, where I only want to overwrite the primary colour as shown in the scss file below:

```<code>// Custom.scss

$theme-colors: (
    "primary": #243B55
);

// Option A: Include all of Bootstrap

@import "../node_modules/bootstrap/scss/bootstrap";
</code>```

Aside from this, I just want to use the regular customisations provided by bootstrap. However, since I have included all of bootstrap in the last line, the resulting css file I produce will contain all of the bootstrap code, which will make my application slower. I am thinking of importing just the necessary things to ensure the primary colour is overwritten, and include the rest of the bootstrap library using a CDN (<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">). However, I have not been able to find out which specific things I need to import in my scss file (https://getbootstrap.com/docs/4.0/getting-started/theming/ gives a list but I'm not sure which ones are necessary). If this is a valid strategy to make the application faster, what would I need to import in the scss file at the bottom to ensure that only the primary colour is overwritten?

答:
the variable you need to override is $primary. You can place all your variables overrides before importing bootstrap code.

$theme-colors will get the overridden value and will generate the code with the default variable value : $primary.

So you can replace your code with:

```<code>$primary: #243B55;
</code>```

Body:
I'm currently using bootstrap in my application, where I only want to overwrite the primary colour as shown in the scss file below:

// Custom.scss

$theme-colors: (
    "primary": #243B55
);

// Option A: Include all of Bootstrap

@import "../node_modules/bootstrap/scss/bootstrap";

Aside from this, I just want to use the regular customisations provided by bootstrap. However, since I have included all of bootstrap in the last line, the resulting css file I produce will contain all of the bootstrap code, which will make my application slower. I am thinking of importing just the necessary things to ensure the primary colour is overwritten, and include the rest of the bootstrap library using a CDN (<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">). However, I have not been able to find out which specific things I need to import in my scss file (https://getbootstrap.com/docs/4.0/getting-started/theming/ gives a list but I'm not sure which ones are necessary). If this is a valid strategy to make the application faster, what would I need to import in the scss file at the bottom to ensure that only the primary colour is overwritten?

Body:
the variable you need to override is $primary. You can place all your variables overrides before importing bootstrap code.

$theme-colors will get the overridden value and will generate the code with the default variable value : $primary.

So you can replace your code with:

$primary: #243B55;


问:
Fake in app purchases
I am using consumable in app purchase in my app. I saw today some users doing fake purchases. My code:

```<code>OnIabPurchaseFinishedListener mPurchaseFinishedListener = new OnIabPurchaseFinishedListener() {

    @Override
    public void onIabPurchaseFinished(IabResult result, final Purchase purchase) {
        if (mHelper == null) return;
        if (result.isFailure()) {
            return;
        }
        if (purchase.getSku().equals("premium")) {
            purchase
            Ion.with(mainContext, "http://domain.com/mobileapp/buyPremium/")
                    .setBodyParameter("username", purchase.getDeveloperPayload())
                    .setBodyParameter("orderId", purchase.getOrderId())
                    .setBodyParameter("orderToken", purchase.getToken())
                    .setBodyParameter("orderTime", "" + purchase.getPurchaseTime())
                    .asJsonObject()
                    .setCallback(new FutureCallback<JsonObject>() {
                        @Override
                        public void onCompleted(Exception e, JsonObject result) {
                            if (e == null) {
                                if (result.get("status").getAsInt() == 1) {
                                    mHelper.consumeAsync(purchase, mConsumeFinishedListener);
                                    if (premiumFragmentObj != null) {
                                        premiumFragmentObj.purchased();
                                    }
                                }else{
                                }
                            }
                        }
                    });

        }

    }

};
</code>```

As you can see, i am doing a http request after user completes the purchase and I am saving orderId,orderToken etc. to my database for logs.

Why i am sure for some users doing fake purchases?

I am comparing my logs with https://payments.google.com/merchant datas. And couldn't see some user's logs on merchant center.

For example my database logs (All of them fake):

How can I fix this security issue?

答:
Visit How to verify purchase for android app in server side (google play in app billing v3)

When a user makes an in-app purchase, cache the details (token, order id, and product id) locally on the client (i.e the app) then send it to your API.

Your API should then send the purchaseToken to the Google Play Developer API for validation.

https://github.com/aporat/store-receipt-validator php sample

Title: Fake in app purchases

Body:
I am using consumable in app purchase in my app. I saw today some users doing fake purchases. My code:

OnIabPurchaseFinishedListener mPurchaseFinishedListener = new OnIabPurchaseFinishedListener() {

    @Override
    public void onIabPurchaseFinished(IabResult result, final Purchase purchase) {
        if (mHelper == null) return;
        if (result.isFailure()) {
            return;
        }
        if (purchase.getSku().equals("premium")) {
            purchase
            Ion.with(mainContext, "http://domain.com/mobileapp/buyPremium/")
                    .setBodyParameter("username", purchase.getDeveloperPayload())
                    .setBodyParameter("orderId", purchase.getOrderId())
                    .setBodyParameter("orderToken", purchase.getToken())
                    .setBodyParameter("orderTime", "" + purchase.getPurchaseTime())
                    .asJsonObject()
                    .setCallback(new FutureCallback<JsonObject>() {
                        @Override
                        public void onCompleted(Exception e, JsonObject result) {
                            if (e == null) {
                                if (result.get("status").getAsInt() == 1) {
                                    mHelper.consumeAsync(purchase, mConsumeFinishedListener);
                                    if (premiumFragmentObj != null) {
                                        premiumFragmentObj.purchased();
                                    }
                                }else{
                                }
                            }
                        }
                    });

        }

    }

};

As you can see, i am doing a http request after user completes the purchase and I am saving orderId,orderToken etc. to my database for logs.

Why i am sure for some users doing fake purchases?

I am comparing my logs with https://payments.google.com/merchant datas. And couldn't see some user's logs on merchant center.

For example my database logs (All of them fake):

How can I fix this security issue?


问:
You cannot render a <Router> inside another <Router>
I have upgraded react-router-dom to v6 from v5. Previously(v5) it used to work well.
Here is the code.</p>
```<code><HashRouter>
    <Provider appStore={appStore}>
        <MemoryRouter>
            <Routes>
                <Route/>
            </Routes>
        </MemoryRouter>
    </Provider>
</HashRouter>
</code>```

答:
you actually do have a Router inside a Router remove either the memory router or hash Router and it should work fine

```<code><Provider appStore={appStore}>
    <MemoryRouter>
        <Routes>
            <Route/>
        </Routes>
    </MemoryRouter>
</Provider>
</code>```

it should work like this or remove memory router if you want I searched online and got same answers Hope i was able to help

Body:
I have upgraded react-router-dom to v6 from v5. Previously(v5) it used to work well.
Here is the code.

<HashRouter>
    <Provider appStore={appStore}>
        <MemoryRouter>
            <Routes>
                <Route/>
            </Routes>
        </MemoryRouter>
    </Provider>
</HashRouter>

Body:
you actually do have a Router inside a Router remove either the memory router or hash Router and it should work fine

<Provider appStore={appStore}>
    <MemoryRouter>
        <Routes>
            <Route/>
        </Routes>
    </MemoryRouter>
</Provider>

it should work like this or remove memory router if you want I searched online and got same answers Hope i was able to help


问:
Does the datetime.datetime.ctime() function return a fixed width string?
If I were to run the following code:

```<code>import datetime
dt = datetime.datetime.now()
date_str = dt.ctime()
</code>```

Will the result of len(date_str) always be the same, regardless of when I happen to run the code?  I think it will be, but I'm not certain. I looked at the datetime module reference but the relevant section says:

Return a string representing the date:

```<code>>>> from datetime import date
>>> date(2002, 12, 4).ctime()
'Wed Dec  4 00:00:00 2002'
</code>```

d.ctime() is equivalent to:

```<code>time.ctime(time.mktime(d.timetuple()))
</code>```

on platforms where the native C ctime() function (which time.ctime() invokes, but which date.ctime() does not invoke) conforms to the C standard.

But looking at the article on cppreference.com, the answer is less than clear to me. I did find a reference here which suggests that it will be a 24-character wide string, but I was hoping for a more official source or reference if possible. It's possible that I didn't delve far enough into the C-standard to divine the answer.

Also, based on that quote, does that mean the behavior might be platform-dependent?  Or is it likely to be generally uniform outside of niche operating systems?

(yes I know that I can manually format to fixed-width, but I want to know whether the built-in one already is that way)

答:
I've looked up datetime in the source code of cpython on github. It is implemented as this:

    def ctime(self):
        "Return ctime() style string."
        weekday = self.toordinal() % 7 or 7
        return "%s %s %2d 00:00:00 %04d" % (
            _DAYNAMES[weekday],
            _MONTHNAMES[self._month],
            self._day, self._year)
```
<p>with <code>_DAYNAMES</code> and <code>_MONTHNAMES</code> being:</p>
<pre class="lang-py prettyprint-override"><code>_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
</code>```

So I would think the length will always be the same. The only exception that I can think of is when weekday and self._month are set at 0, making them return None. Rather than a 3-string word, it returns a 4-string word in those cases. But since you always will use datetime.now(), this shouldn't be of any concern.

Body:
If I were to run the following code:

import datetime
dt = datetime.datetime.now()
date_str = dt.ctime()

Will the result of len(date_str) always be the same, regardless of when I happen to run the code?  I think it will be, but I'm not certain. I looked at the datetime module reference but the relevant section says:

Return a string representing the date:

>>> from datetime import date
>>> date(2002, 12, 4).ctime()
'Wed Dec  4 00:00:00 2002'

d.ctime() is equivalent to:

time.ctime(time.mktime(d.timetuple()))

on platforms where the native C ctime() function (which time.ctime() invokes, but which date.ctime() does not invoke) conforms to the C standard.

But looking at the article on cppreference.com, the answer is less than clear to me. I did find a reference here which suggests that it will be a 24-character wide string, but I was hoping for a more official source or reference if possible. It's possible that I didn't delve far enough into the C-standard to divine the answer.

Also, based on that quote, does that mean the behavior might be platform-dependent?  Or is it likely to be generally uniform outside of niche operating systems?

(yes I know that I can manually format to fixed-width, but I want to know whether the built-in one already is that way)

Body:
I've looked up datetime in the source code of cpython on github. It is implemented as this:

    def ctime(self):
        "Return ctime() style string."
        weekday = self.toordinal() % 7 or 7
        return "%s %s %2d 00:00:00 %04d" % (
            _DAYNAMES[weekday],
            _MONTHNAMES[self._month],
            self._day, self._year)

with _DAYNAMES and _MONTHNAMES being:

_MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
_DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

So I would think the length will always be the same. The only exception that I can think of is when weekday and self._month are set at 0, making them return None. Rather than a 3-string word, it returns a 4-string word in those cases. But since you always will use datetime.now(), this shouldn't be of any concern.


问:
How can I autoscale the font size to fit the contents of a div?
I have a div with some text:

```<code><div style="white-space:nowrap;overflow:none;width:50px;">
  With some text in it
</div>
</code>```

How can I scale the font size of the text so all of the text is visible?

答: Contrary-wise. You could wrap the text in an interior DIV, measure its width with JavaScript. Test if that width is wider than the parent DIV. Get the current font size, and incrementally move it down 1px at a time until inner DIV's width is less than or equal to the outer DIV's width.</p>

Body:
I have a div with some text:

  With some text in it

How can I scale the font size of the text so all of the text is visible?


问:
Helm upgrade doesn't pull new container
I Build a simple NodeJS API, pushed the Docker Image to a repo and deployed it to my k8s with Helm install (works perfectly fine).

The pullPolicy is Always.

Now I want to update the source code and deploy the updated version of my app. I bumped the version in all files, built and pushed the new Docker image und tried helm upgrade but it seems like nothing happened.
With helm list I can see that  revision was deployed but the changes to source code were not deployed.
watch kubectl get pods also shows that no new pods were created the way you expect it with kubectl --apply...

What did I do wrong?

答:
Possible workaround:

```<code> spec:
  template:
    metadata:
      labels:
        date: "{{ now | unixEpoch }}"
</code>```

Add it to your Deployment or StatefulSet yaml

Title: Helm upgrade doesn't pull new container

Body:
Possible workaround:

 spec:
  template:
    metadata:
      labels:
        date: "{{ now | unixEpoch }}"

Add it to your Deployment or StatefulSet yaml


问:
Issue with Spring Cloud Dataflow and Mysql 5.6
I have the following problem when trying to start a SCDF server connected to Mysql 5.6.

Using the following command to start a SCDF server connected to a mysql database (version 5.6):

java -jar spring-cloud-dataflow-server-2.9.0-RC1.jar --spring.datasource.url=jdbc:mysql://localhost:3306/database --spring.datasource.username=username --spring.datasource.password=password --spring.datasource.driver-class-name=org.mariadb.jdbc.Driver

I get this error trying to start the server:

Caused by: org.flywaydb.core.internal.license.FlywayEditionUpgradeRequiredException: Flyway Teams Edition or MySQL upgrade required: MySQL 5.6 is no longer supported by Flyway Community Edition

Looking for solutions online I tried to use this command:

java -jar spring-cloud-dataflow-server-2.9.0-RC1.jar --spring.datasource.url=jdbc:mysql://localhost:3306/jacad31_database --spring.datasource.username= --spring.datasource.password= --spring.datasource.driver-class-name=org.mariadb.jdbc.Driver --spring.flyway.enabled=false --spring.datasource.initialization-mode=always

After that the server starts but then this error happens when I try to open the SCDF dashboard:

Caused by: org.mariadb.jdbc.internal.util.exceptions.MariaDbSqlException: Table 'database.app_registration' doesn't exist

I tried to add this startup command but the error continues:

--spring.datasource.schema=classpath*:/org/springframework/cloud/dataflow/server/db/migration/mysql/V1__INITIAL_SETUP.sql

I think this happens because flyway is responsible for creating server configuration files on startup but since I'm not using flyway the config tables are not created. My question is: how can I create this tables on my database without flyway?

答: Docs are pointing to schema files in GitHub Repo. You can create tables either manually or bootstrap those via server without flyway.</p>


问:
Site Hosting Issue
I'm a programmer, but in designing, I'm new and I created my first site by using HTML, CSS and Javascript and host on hostinger but after hosted, I realize that my site background color does not look good that's why I changes inside my .css file but the changes is not reflected on my site. Please tell me a solution, so that I can fix the problem.</p>

答:
It is possible that your browser cashed old css for your site. Try this:

Ctrl+F5 - refresh window with clearing cache

Use Incognito Window

Clear your browsing data

Title: Site Hosting Issue


问:
How to import a sheet from another Google Spreadsheet using Google Apps Scipt?
I want to import a sheet from another Google Spreadsheet in place of values only using Google Apps Script, and check if the existing sheet is there or not. Any help is highly appreciated.</p>
```<code>  function CopyDataToNewFile() {
  var sss = SpreadsheetApp.openById('0AjN7uZG....'); // sss = source spreadsheet
  var ss = sss.getSheetByName('Monthly'); // ss = source sheet
  //Get full range of data
  var SRange = ss.getDataRange();
  //get A1 notation identifying the range
  var A1Range = SRange.getA1Notation();
  //get the data values in range
  var SData = SRange.getValues();

  var tss = SpreadsheetApp.openById('8AjN7u....'); // tss = target spreadsheet
  var ts = tss.getSheetByName('RAWData'); // ts = target sheet
  //set the target range to the values of the source data
  ts.getRange(A1Range).setValues(SData);
};
</code>```

答:
Try this</p>
```<code>/* Global configuration */
const CONFIG = {
  URL: {
    /* Enter the source sheet url between '' */
    SOUCE_SHEET_URL: '',
  },
  SHEET_TO_COPY: {
    /* Enter the source sheet name between '' */
    SHEET_NAME: '',
  },
  SPREADSHEET: {
    ACTIVE_SPREADSHEET: SpreadsheetApp.getActiveSpreadsheet(),
  },
  TOAST: {
    T1: 'Sheet found, deleting the current version.',
    T2: 'Sheet not found, copying the new sheet.',
    T3: 'Sheet copied successfully.',
    T4: 'Enter the correct url and sheet name.',
  }
};

const importSheet = () => {
  try {
    const sourceSheet = SpreadsheetApp.openByUrl(CONFIG.URL.SOUCE_SHEET_URL).getSheetByName(CONFIG.SHEET_TO_COPY.SHEET_NAME);
    /* Before copying the sheet, delete the exiting copy (if any) */
    const existingSheet = CONFIG.SPREADSHEET.ACTIVE_SPREADSHEET.getSheetByName(CONFIG.SHEET_TO_COPY.SHEET_NAME);
    if (existingSheet) {
      SpreadsheetApp.getActiveSpreadsheet().toast(CONFIG.TOAST.T1, 'Status', 3);
      Utilities.sleep(2000);
      CONFIG.SPREADSHEET.ACTIVE_SPREADSHEET.deleteSheet(existingSheet);
    } else {
      SpreadsheetApp.getActiveSpreadsheet().toast(CONFIG.TOAST.T2, 'Status', 3);
      Utilities.sleep(2000);
    }
    SpreadsheetApp.flush();
    const destinationSheet = sourceSheet.copyTo(CONFIG.SPREADSHEET.ACTIVE_SPREADSHEET);
    destinationSheet.setName(CONFIG.SHEET_TO_COPY.SHEET_NAME);
    CONFIG.SPREADSHEET.ACTIVE_SPREADSHEET.setActiveSheet(destinationSheet);
    SpreadsheetApp.getActiveSpreadsheet().toast(CONFIG.TOAST.T3, 'Success ', 3);
  }
  catch (err) {
    SpreadsheetApp.getActiveSpreadsheet().toast(CONFIG.TOAST.T4, 'Failed ', 3);
  }
};
</code>```

Body:
I want to import a sheet from another Google Spreadsheet in place of values only using Google Apps Script, and check if the existing sheet is there or not. Any help is highly appreciated.

  function CopyDataToNewFile() {
  var sss = SpreadsheetApp.openById('0AjN7uZG....'); // sss = source spreadsheet
  var ss = sss.getSheetByName('Monthly'); // ss = source sheet
  //Get full range of data
  var SRange = ss.getDataRange();
  //get A1 notation identifying the range
  var A1Range = SRange.getA1Notation();
  //get the data values in range
  var SData = SRange.getValues();

  var tss = SpreadsheetApp.openById('8AjN7u....'); // tss = target spreadsheet
  var ts = tss.getSheetByName('RAWData'); // ts = target sheet
  //set the target range to the values of the source data
  ts.getRange(A1Range).setValues(SData);
};

Body:
Try this

/* Global configuration */
const CONFIG = {
  URL: {
    /* Enter the source sheet url between '' */
    SOUCE_SHEET_URL: '',
  },
  SHEET_TO_COPY: {
    /* Enter the source sheet name between '' */
    SHEET_NAME: '',
  },
  SPREADSHEET: {
    ACTIVE_SPREADSHEET: SpreadsheetApp.getActiveSpreadsheet(),
  },
  TOAST: {
    T1: 'Sheet found, deleting the current version.',
    T2: 'Sheet not found, copying the new sheet.',
    T3: 'Sheet copied successfully.',
    T4: 'Enter the correct url and sheet name.',
  }
};

const importSheet = () => {
  try {
    const sourceSheet = SpreadsheetApp.openByUrl(CONFIG.URL.SOUCE_SHEET_URL).getSheetByName(CONFIG.SHEET_TO_COPY.SHEET_NAME);
    /* Before copying the sheet, delete the exiting copy (if any) */
    const existingSheet = CONFIG.SPREADSHEET.ACTIVE_SPREADSHEET.getSheetByName(CONFIG.SHEET_TO_COPY.SHEET_NAME);
    if (existingSheet) {
      SpreadsheetApp.getActiveSpreadsheet().toast(CONFIG.TOAST.T1, 'Status', 3);
      Utilities.sleep(2000);
      CONFIG.SPREADSHEET.ACTIVE_SPREADSHEET.deleteSheet(existingSheet);
    } else {
      SpreadsheetApp.getActiveSpreadsheet().toast(CONFIG.TOAST.T2, 'Status', 3);
      Utilities.sleep(2000);
    }
    SpreadsheetApp.flush();
    const destinationSheet = sourceSheet.copyTo(CONFIG.SPREADSHEET.ACTIVE_SPREADSHEET);
    destinationSheet.setName(CONFIG.SHEET_TO_COPY.SHEET_NAME);
    CONFIG.SPREADSHEET.ACTIVE_SPREADSHEET.setActiveSheet(destinationSheet);
    SpreadsheetApp.getActiveSpreadsheet().toast(CONFIG.TOAST.T3, 'Success ', 3);
  }
  catch (err) {
    SpreadsheetApp.getActiveSpreadsheet().toast(CONFIG.TOAST.T4, 'Failed ', 3);
  }
};