问:
How to add legend to plot from CausalImpact package?
I see the other post here about this, but I'm relatively new to R so the answers weren't helpful to me. I'd really appreciate some more in-depth help with how to do this.

I've already made a plot using the commands from the Causal Impact package. In the package documentation, it clearly says that the plots are ggplot2 objects and can be customized the same way as any other object like that. I've successfully done that, adding titles and customizing colors. I need to add a legend (it's required at the journal I'm submitting to). Here is an example of what my graph currently looks like and the code I used to get there.

```<code>library(ggplot2)
devtools::install_github("google/CausalImpact")
library(CausalImpact)

## note that I took this example code from the package documentation up until I customize the plot

#create data
set.seed(1)
x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100)
y <- 1.2 * x1 + rnorm(100)
y[71:100] <- y[71:100] + 10
data <- cbind(y, x1)

#causal impact analysis
> pre.period <- c(1, 70)
> post.period <- c(71, 100)
> impact <- CausalImpact(data, pre.period, post.period)

#graph
example<-plot(impact, c("original", "cumulative")) +
    labs(
        x = "Time",
        y = "Clicks (Millions)",
        title = "Figure. Analysis of click behavior after intervention.") +
    theme(plot.title = element_text(hjust = 0.5),
          plot.caption = element_text(hjust = 0),
          panel.background = element_rect(fill = "transparent"), # panel bg
          plot.background = element_rect(fill = "transparent", color = NA), # plot bg
          panel.grid.major = element_blank(), # get rid of major grid
          panel.grid.minor = element_blank())  # get rid of minor grid

</code>```

In my head, the solution I'd like is to have a legend for each panel of the plot. The first legend (next to the 'original' panel) would show a solid line represents the observed data, the dotted line represents the estimated counterfactual, and the colored band represents the 95% CrI around the estimated counterfactual. The second legend (next to the 'cumulative' panel) would show the dotted line represents the estimated change in trend associated with the intervention and the colored band again represents the 95% CrI around the estimation. Maybe there's a better solution than that, but that's what I've thought of.

Here is a section of the underlying code that runs when you plot:

```<code># Initialize plot
  q <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
  q <- q + xlab("") + ylab("")
  if (length(metrics) > 1) {
    q <- q + facet_grid(metric ~ ., scales = "free_y")
  }

  # Add prediction intervals
  q <- q + geom_ribbon(aes(ymin = lower, ymax = upper),
                       data, fill = "slategray2")

  # Add pre-period markers
  xintercept <- CreatePeriodMarkers(impact$model$pre.period,
                                    impact$model$post.period,
                                    time(impact$series))
  q <- q + geom_vline(xintercept = xintercept,
                      colour = "darkgrey", size = 0.8, linetype = "dashed")

  # Add zero line to pointwise and cumulative plot
  q <- q + geom_line(aes(y = baseline),
                     colour = "darkgrey", size = 0.8, linetype = "solid",
                     na.rm = TRUE)

  # Add point predictions
  q <- q + geom_line(aes(y = mean), data,
                     size = 0.6, colour = "darkblue", linetype = "dashed",
                     na.rm = TRUE)

  # Add observed data
  q <- q + geom_line(aes(y = response), size = 0.6,  na.rm = TRUE)
  return(q)
}
</code>```

One of the answers in that older post here said that I'd have to adapt the pre-existing function to get a legend, and I don't really have the skills yet to see what I'd have to change or add. I thought that legends were supposed to be automatically added according to what's in the aes() bit of the ggplot code, so I'm a little confused why there isn't one in the first place. Can someone help me with this?

答:
Here is a rebuild of the CreateImpactPlot() function that will work for all three metrics. The legends can be modified. I introduced more colors and linetypes so that the legends could be applicable across all the facets.

The base case looks like this:

```<code>plot(impact)
</code>```

You will note that the labels in the legend for the ribbons and for the lines refer to the metrics. These are placeholder labels that you can then modify.

```<code>line_labels <- c("cumulative_mean" = "change in trend", "baseline" = "baseline", "original_mean" =
                     "estimated counterfactual", "original_response" = "observed")

plot(impact, c("original", "cumulative")) +
    labs(
        x = "Time",
        y = "Clicks (Millions)",
        title = "Figure. Analysis of click behavior after intervention.") +
    theme(plot.title = element_text(hjust = 0.5),
          plot.caption = element_text(hjust = 0),
          panel.background = element_rect(fill = "transparent"), # panel bg
          plot.background = element_rect(fill = "transparent", color = NA), # plot bg
          panel.grid.major = element_blank(), # get rid of major grid
          panel.grid.minor = element_blank()) + # get rid of minor grid

        scale_fill_manual(name = "95% Crl", values = c("original" = "slategray2", "cumulative" = "darkseagreen"),
                      labels = c("original" = "counterfactual", "cumulative" = "estimation")) +

        scale_linetype_manual(name = "Legend", labels = line_labels,
                          values = c("cumulative_mean" = "dotted", "baseline" = "solid", "original_mean" =
                                         "dotted", "original_response" = "solid")) +

        scale_color_manual(name = "Legend", labels = line_labels,
                       values = c("cumulative_mean" = "red", "baseline" = "darkgrey", "original_mean"= "darkblue", "original_response" = "goldenrod"))
</code>```

The vector "line_labels" is where you define the text you want to appear in the Legend. You will note that I removed the pointwise related values as I am excluding the pointwise metric from the plot. The scale_linetype_manual and scale_color_manual have to have the Name and labels kept in synch in order to have a combined legend, otherwise you will have two separate legends. The scale_fill_manual is for the ribbons.  For these scales, you can change the names, the labels and the values as you desire. You can copy the code out of the function, revise it, and add it to the plot call as shown above.

Here is the code for the revised function. In the example, everything should be run and "impact" generated from the CausalImpact package. Then all of the package code needs to be loaded into memory including impact_analysis.R, impact_misc.R, impact_model.R, impact_inference.R and impact_plot.R. Then load the code below.

```<code>CreateImpactPlot2 <- function(impact, metrics = c("original", "pointwise","cumulative")) {
    # Creates a plot of observed data and counterfactual predictions.
    #
    # Args:
    #   impact:  \code{CausalImpact} results object returned by
    #            \code{CausalImpact()}.
    #   metrics: Which metrics to include in the plot. Can be any combination of
    #            "original", "pointwise", and "cumulative".
    #
    # Returns:
    #   A ggplot2 object that can be plotted using plot().

    # Create data frame of: time, response, mean, lower, upper, metric
    data <- CreateDataFrameForPlot(impact)

    # Select metrics to display (and their order)
    assert_that(is.vector(metrics))
    metrics <- match.arg(metrics, several.ok = TRUE)
    data <- data[data$metric %in% metrics, , drop = FALSE]
    data$metric <- factor(data$metric, metrics)

    data_long <- data %>%
        tidyr::pivot_longer(cols = c("baseline", "mean", "response"), names_to = "variable",
                            values_to = "value", values_drop_na = TRUE) %>%
        mutate(variable2 = factor(ifelse(variable == "baseline", variable, paste0(metric,"_", variable))),
               variable = factor(variable))

    # Initialize plot
    q <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
    q <- q + xlab("") + ylab("")
    if (length(metrics) > 1) {
        q <- q + facet_grid(metric ~ ., scales = "free_y")
    }

     #Add prediction intervals
    q <- q + geom_ribbon(aes(x = time, ymin = lower, ymax = upper, fill = metric), data_long)

    # Add pre-period markers
    xintercept <- CreatePeriodMarkers(impact$model$pre.period,
                                      impact$model$post.period,
                                      time(impact$series))

    q <- q + geom_vline(xintercept = xintercept,
                        colour = "darkgrey", size = 0.8, linetype = "dashed")

    # Add zero line to pointwise and cumulative plot
    q <- q + geom_line(data = data_long %>% dplyr::filter(variable == "baseline"),
                       aes(x = time, y = value, linetype = variable2, group = variable2, size = variable2, color = variable2),
                       na.rm = TRUE)

    # Add point predictions
    q <- q + geom_line(data = data_long %>% dplyr::filter(variable == "mean"),
                       aes(x = time, y = value, linetype = variable2, group = variable2, size = variable2, color = variable2),
                       na.rm = TRUE)

    # Add observed data
    q <- q + geom_line(data = data_long %>% dplyr::filter(variable == "response"),
                       aes(x = time, y = value, linetype = variable2, group = variable2, size = variable2, color = variable2),
                       na.rm = TRUE)

    #Add scales
    line_labels <- c("cumulative_mean" = "cumulative_mean", "baseline" = "baseline", "original_mean" =
                         "original_mean", "original_response" = "original_response", "pointwise_mean"=
                         "pointwise_mean")

    q <- q + scale_linetype_manual(name = "Legend", labels = line_labels,
                                                        values = c("cumulative_mean" = "dotted", "baseline" = "solid", "original_mean" =
                                                                       "dotted", "original_response" = "solid", "pointwise_mean"=
                                                                       "solid")) +

            scale_size_manual(values = c("cumulative_mean" = 0.6, "baseline" = 0.8, "original_mean"= 0.6, "original_response" = 0.5,
                                         "pointwise_mean"= 0.6)) +

            scale_color_manual(name = "Legend", labels = line_labels,
                                                values = c("cumulative_mean" = "red", "baseline" = "darkgrey", "original_mean"= "darkblue", "original_response" = "goldenrod",
                                                            "pointwise_mean"= "darkgreen")) +

            scale_fill_manual(name = "95% Crl", values = c("original" = "slategray2", "pointwise" = "pink3", "cumulative" = "darkseagreen"),
                                         labels = c("original" = "original", "pointwise" = "pointwise", "cumulative" = "cumulative")) +

            guides(size = "none")

    return(q)
}

plot.CausalImpact <- function(x, ...) {
    # Creates a plot of observed data and counterfactual predictions.
    #
    # Args:
    #   x:   A \code{CausalImpact} results object, as returned by
    #        \code{CausalImpact()}.
    #   ...: Can be used to specify \code{metrics}, which determines which panels
    #        to include in the plot. The argument \code{metrics} can be any
    #        combination of "original", "pointwise", "cumulative". Partial matches
    #        are allowed.
    #
    # Returns:
    #   A ggplot2 object that can be plotted using plot().
    #
    # Examples:
    #   \dontrun{
    #   impact <- CausalImpact(...)
    #
    #   # Default plot:
    #   plot(impact)
    #
    #   # Customized plot:
    #   impact.plot <- plot(impact) + ylab("Sales")
    #   plot(impact.plot)
    #   }

    return(CreateImpactPlot2(x, ...))
}

</code>```

Body:
I see the other post here about this, but I'm relatively new to R so the answers weren't helpful to me. I'd really appreciate some more in-depth help with how to do this.

I've already made a plot using the commands from the Causal Impact package. In the package documentation, it clearly says that the plots are ggplot2 objects and can be customized the same way as any other object like that. I've successfully done that, adding titles and customizing colors. I need to add a legend (it's required at the journal I'm submitting to). Here is an example of what my graph currently looks like and the code I used to get there.

library(ggplot2)
devtools::install_github("google/CausalImpact")
library(CausalImpact)

## note that I took this example code from the package documentation up until I customize the plot

#create data
set.seed(1)
x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100)
y <- 1.2 * x1 + rnorm(100)
y[71:100] <- y[71:100] + 10
data <- cbind(y, x1)

#causal impact analysis
> pre.period <- c(1, 70)
> post.period <- c(71, 100)
> impact <- CausalImpact(data, pre.period, post.period)

#graph
example<-plot(impact, c("original", "cumulative")) +
    labs(
        x = "Time",
        y = "Clicks (Millions)",
        title = "Figure. Analysis of click behavior after intervention.") +
    theme(plot.title = element_text(hjust = 0.5),
          plot.caption = element_text(hjust = 0),
          panel.background = element_rect(fill = "transparent"), # panel bg
          plot.background = element_rect(fill = "transparent", color = NA), # plot bg
          panel.grid.major = element_blank(), # get rid of major grid
          panel.grid.minor = element_blank())  # get rid of minor grid

In my head, the solution I'd like is to have a legend for each panel of the plot. The first legend (next to the 'original' panel) would show a solid line represents the observed data, the dotted line represents the estimated counterfactual, and the colored band represents the 95% CrI around the estimated counterfactual. The second legend (next to the 'cumulative' panel) would show the dotted line represents the estimated change in trend associated with the intervention and the colored band again represents the 95% CrI around the estimation. Maybe there's a better solution than that, but that's what I've thought of.

Here is a section of the underlying code that runs when you plot:

# Initialize plot
  q <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
  q <- q + xlab("") + ylab("")
  if (length(metrics) > 1) {
    q <- q + facet_grid(metric ~ ., scales = "free_y")
  }

  # Add prediction intervals
  q <- q + geom_ribbon(aes(ymin = lower, ymax = upper),
                       data, fill = "slategray2")

  # Add pre-period markers
  xintercept <- CreatePeriodMarkers(impact$model$pre.period,
                                    impact$model$post.period,
                                    time(impact$series))
  q <- q + geom_vline(xintercept = xintercept,
                      colour = "darkgrey", size = 0.8, linetype = "dashed")

  # Add zero line to pointwise and cumulative plot
  q <- q + geom_line(aes(y = baseline),
                     colour = "darkgrey", size = 0.8, linetype = "solid",
                     na.rm = TRUE)

  # Add point predictions
  q <- q + geom_line(aes(y = mean), data,
                     size = 0.6, colour = "darkblue", linetype = "dashed",
                     na.rm = TRUE)

  # Add observed data
  q <- q + geom_line(aes(y = response), size = 0.6,  na.rm = TRUE)
  return(q)
}

One of the answers in that older post here said that I'd have to adapt the pre-existing function to get a legend, and I don't really have the skills yet to see what I'd have to change or add. I thought that legends were supposed to be automatically added according to what's in the aes() bit of the ggplot code, so I'm a little confused why there isn't one in the first place. Can someone help me with this?

Body:
Here is a rebuild of the CreateImpactPlot() function that will work for all three metrics. The legends can be modified. I introduced more colors and linetypes so that the legends could be applicable across all the facets.

The base case looks like this:

plot(impact)

You will note that the labels in the legend for the ribbons and for the lines refer to the metrics. These are placeholder labels that you can then modify.

line_labels <- c("cumulative_mean" = "change in trend", "baseline" = "baseline", "original_mean" =
                     "estimated counterfactual", "original_response" = "observed")

plot(impact, c("original", "cumulative")) +
    labs(
        x = "Time",
        y = "Clicks (Millions)",
        title = "Figure. Analysis of click behavior after intervention.") +
    theme(plot.title = element_text(hjust = 0.5),
          plot.caption = element_text(hjust = 0),
          panel.background = element_rect(fill = "transparent"), # panel bg
          plot.background = element_rect(fill = "transparent", color = NA), # plot bg
          panel.grid.major = element_blank(), # get rid of major grid
          panel.grid.minor = element_blank()) + # get rid of minor grid

        scale_fill_manual(name = "95% Crl", values = c("original" = "slategray2", "cumulative" = "darkseagreen"),
                      labels = c("original" = "counterfactual", "cumulative" = "estimation")) +

        scale_linetype_manual(name = "Legend", labels = line_labels,
                          values = c("cumulative_mean" = "dotted", "baseline" = "solid", "original_mean" =
                                         "dotted", "original_response" = "solid")) +

        scale_color_manual(name = "Legend", labels = line_labels,
                       values = c("cumulative_mean" = "red", "baseline" = "darkgrey", "original_mean"= "darkblue", "original_response" = "goldenrod"))

The vector "line_labels" is where you define the text you want to appear in the Legend. You will note that I removed the pointwise related values as I am excluding the pointwise metric from the plot. The scale_linetype_manual and scale_color_manual have to have the Name and labels kept in synch in order to have a combined legend, otherwise you will have two separate legends. The scale_fill_manual is for the ribbons.  For these scales, you can change the names, the labels and the values as you desire. You can copy the code out of the function, revise it, and add it to the plot call as shown above.

Here is the code for the revised function. In the example, everything should be run and "impact" generated from the CausalImpact package. Then all of the package code needs to be loaded into memory including impact_analysis.R, impact_misc.R, impact_model.R, impact_inference.R and impact_plot.R. Then load the code below.

CreateImpactPlot2 <- function(impact, metrics = c("original", "pointwise","cumulative")) {
    # Creates a plot of observed data and counterfactual predictions.
    #
    # Args:
    #   impact:  \code{CausalImpact} results object returned by
    #            \code{CausalImpact()}.
    #   metrics: Which metrics to include in the plot. Can be any combination of
    #            "original", "pointwise", and "cumulative".
    #
    # Returns:
    #   A ggplot2 object that can be plotted using plot().

    # Create data frame of: time, response, mean, lower, upper, metric
    data <- CreateDataFrameForPlot(impact)

    # Select metrics to display (and their order)
    assert_that(is.vector(metrics))
    metrics <- match.arg(metrics, several.ok = TRUE)
    data <- data[data$metric %in% metrics, , drop = FALSE]
    data$metric <- factor(data$metric, metrics)

    data_long <- data %>%
        tidyr::pivot_longer(cols = c("baseline", "mean", "response"), names_to = "variable",
                            values_to = "value", values_drop_na = TRUE) %>%
        mutate(variable2 = factor(ifelse(variable == "baseline", variable, paste0(metric,"_", variable))),
               variable = factor(variable))

    # Initialize plot
    q <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
    q <- q + xlab("") + ylab("")
    if (length(metrics) > 1) {
        q <- q + facet_grid(metric ~ ., scales = "free_y")
    }

     #Add prediction intervals
    q <- q + geom_ribbon(aes(x = time, ymin = lower, ymax = upper, fill = metric), data_long)

    # Add pre-period markers
    xintercept <- CreatePeriodMarkers(impact$model$pre.period,
                                      impact$model$post.period,
                                      time(impact$series))

    q <- q + geom_vline(xintercept = xintercept,
                        colour = "darkgrey", size = 0.8, linetype = "dashed")

    # Add zero line to pointwise and cumulative plot
    q <- q + geom_line(data = data_long %>% dplyr::filter(variable == "baseline"),
                       aes(x = time, y = value, linetype = variable2, group = variable2, size = variable2, color = variable2),
                       na.rm = TRUE)

    # Add point predictions
    q <- q + geom_line(data = data_long %>% dplyr::filter(variable == "mean"),
                       aes(x = time, y = value, linetype = variable2, group = variable2, size = variable2, color = variable2),
                       na.rm = TRUE)

    # Add observed data
    q <- q + geom_line(data = data_long %>% dplyr::filter(variable == "response"),
                       aes(x = time, y = value, linetype = variable2, group = variable2, size = variable2, color = variable2),
                       na.rm = TRUE)

    #Add scales
    line_labels <- c("cumulative_mean" = "cumulative_mean", "baseline" = "baseline", "original_mean" =
                         "original_mean", "original_response" = "original_response", "pointwise_mean"=
                         "pointwise_mean")

    q <- q + scale_linetype_manual(name = "Legend", labels = line_labels,
                                                        values = c("cumulative_mean" = "dotted", "baseline" = "solid", "original_mean" =
                                                                       "dotted", "original_response" = "solid", "pointwise_mean"=
                                                                       "solid")) +

            scale_size_manual(values = c("cumulative_mean" = 0.6, "baseline" = 0.8, "original_mean"= 0.6, "original_response" = 0.5,
                                         "pointwise_mean"= 0.6)) +

            scale_color_manual(name = "Legend", labels = line_labels,
                                                values = c("cumulative_mean" = "red", "baseline" = "darkgrey", "original_mean"= "darkblue", "original_response" = "goldenrod",
                                                            "pointwise_mean"= "darkgreen")) +

            scale_fill_manual(name = "95% Crl", values = c("original" = "slategray2", "pointwise" = "pink3", "cumulative" = "darkseagreen"),
                                         labels = c("original" = "original", "pointwise" = "pointwise", "cumulative" = "cumulative")) +

            guides(size = "none")

    return(q)
}

plot.CausalImpact <- function(x, ...) {
    # Creates a plot of observed data and counterfactual predictions.
    #
    # Args:
    #   x:   A \code{CausalImpact} results object, as returned by
    #        \code{CausalImpact()}.
    #   ...: Can be used to specify \code{metrics}, which determines which panels
    #        to include in the plot. The argument \code{metrics} can be any
    #        combination of "original", "pointwise", "cumulative". Partial matches
    #        are allowed.
    #
    # Returns:
    #   A ggplot2 object that can be plotted using plot().
    #
    # Examples:
    #   \dontrun{
    #   impact <- CausalImpact(...)
    #
    #   # Default plot:
    #   plot(impact)
    #
    #   # Customized plot:
    #   impact.plot <- plot(impact) + ylab("Sales")
    #   plot(impact.plot)
    #   }

    return(CreateImpactPlot2(x, ...))
}


来源: stackexchange

问:
Use multiple MAX() and MIN() in a query, or am I using >= NOW() - INTERVAL 1 DAY wrong?
Can I use multiple MAX() and MIN() in a query? Or am I doing something else wrong in my code?
I get the wrong results...

The code below gives me for t1 MAX 9.63 and MIN 10.00 in temperature.

9.63 is found at 2022-02-09 15:21:29
10 min before, it was 9.06, and 10 after it was 10.38
So, 9.63 is not a MAX nor a MIN number

10.0 is found at 2022-02-09 12:40:09 with higher and lower temps over and under.

```<code>//-----Get Max and Min------

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT
MIN(t1) AS t1min, MAX(t1) AS t1max ,
MIN(t2) AS t2min, MAX(t2) AS t2max ,
MIN(t3) AS t3min, MAX(t3) AS t3max ,
MIN(t4) AS t4min, MAX(t4) AS t4max ,
MIN(t5) AS t5min, MAX(t5) AS t5max
FROM ".$idpass." WHERE logdate >= NOW() - INTERVAL 1 DAY";  //Where i get $idpass = ($idpass <> "") ? $idpass : "Buapas";
//Tried CURDATE() - INTERVAL 1 DAY";
//Tried NOW() - INTERVAL 1 DAY";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
   // output data of each row
   while($row = $result->fetch_assoc())    {

   $lastlogdate= $row['logdate'] ;
   $T1min= $row['t1min'] ;
   $T2min= $row['t2min'] ;
   $T3min= $row['t3min'] ;
   $T4min= $row['t4min'] ;
   $T5min= $row['t5min'] ;
   $T1max= $row['t1max'] ;
   $T2max= $row['t2max'] ;
   $T3max= $row['t3max'] ;
   $T4max= $row['t4max'] ;
   $T5max= $row['t5max'] ;
                                           }
                           } else {
   echo "0 results hentet fra databasen";
                                   }
$conn->close();
</code>```

If i remove the

```<code>, MAX(t1) AS t1max ,
MIN(t2) AS t2min, MAX(t2) AS t2max ,
MIN(t3) AS t3min, MAX(t3) AS t3max ,
MIN(t4) AS t4min, MAX(t4) AS t4max ,
MIN(t5) AS t5min, MAX(t5) AS t5max
</code>```

from my code, it still says 10.0 in the MIN t1

答:
When you define your columns as strings, sorting behaves different then you'd expect.

In strings, '10' < '9' as '1' < '9'. (first character is compared, then the secend etc.) This means that MAX('9.63' , '10.0') is '9.63' as 9 is larger than 1.

Change to a different data-type, and you are good to go.

Use for example Decimal(5,2) when you need precision and not more than two decimals. Use float is you can accept small rounding errors but need more digits.

More on data-types: https://dev.mysql.com/doc/refman/8.0/en/numeric-types.html

ContentLicense: CC BY-SA 4.0

Body:
Can I use multiple MAX() and MIN() in a query? Or am I doing something else wrong in my code?
I get the wrong results...

The code below gives me for t1 MAX 9.63 and MIN 10.00 in temperature.

9.63 is found at 2022-02-09 15:21:29
10 min before, it was 9.06, and 10 after it was 10.38
So, 9.63 is not a MAX nor a MIN number

10.0 is found at 2022-02-09 12:40:09 with higher and lower temps over and under.

//-----Get Max and Min------

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT
MIN(t1) AS t1min, MAX(t1) AS t1max ,
MIN(t2) AS t2min, MAX(t2) AS t2max ,
MIN(t3) AS t3min, MAX(t3) AS t3max ,
MIN(t4) AS t4min, MAX(t4) AS t4max ,
MIN(t5) AS t5min, MAX(t5) AS t5max
FROM ".$idpass." WHERE logdate >= NOW() - INTERVAL 1 DAY";  //Where i get $idpass = ($idpass <> "") ? $idpass : "Buapas";
//Tried CURDATE() - INTERVAL 1 DAY";
//Tried NOW() - INTERVAL 1 DAY";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
   // output data of each row
   while($row = $result->fetch_assoc())    {

   $lastlogdate= $row['logdate'] ;
   $T1min= $row['t1min'] ;
   $T2min= $row['t2min'] ;
   $T3min= $row['t3min'] ;
   $T4min= $row['t4min'] ;
   $T5min= $row['t5min'] ;
   $T1max= $row['t1max'] ;
   $T2max= $row['t2max'] ;
   $T3max= $row['t3max'] ;
   $T4max= $row['t4max'] ;
   $T5max= $row['t5max'] ;
                                           }
                           } else {
   echo "0 results hentet fra databasen";
                                   }
$conn->close();

If i remove the

, MAX(t1) AS t1max ,
MIN(t2) AS t2min, MAX(t2) AS t2max ,
MIN(t3) AS t3min, MAX(t3) AS t3max ,
MIN(t4) AS t4min, MAX(t4) AS t4max ,
MIN(t5) AS t5min, MAX(t5) AS t5max

from my code, it still says 10.0 in the MIN t1


答:
You are using transform and transform-origin as defined in the CSS Transforms Level 1 Candidate Recommendation, and you are using them as presentation attributes. transform-origin as a presentation attribute was only introduced in the 2017 working draft. While browser vendors have the capacity to bring up their products to new spec standards even before they reach recommendation status, most open source projects have not. For Inkscape, you have to live with the implementation according to the SVG 1.1 attribute standard, which is incompatible to CSS.

But that is not really a problem in your case. You only use transform-origin in conjunction with the rotate() function. And for that there is a helpful difference between the SVG attribute syntax and the CSS property functional notation: you can define the center of rotation inside the function. (This syntax only exists for rotate(), but not for scale(), skewX() or skewY().)

A CSS rule (note the obligatory units) of

```<code>style="transform:rotate(51deg);transform-origin:113.38582677299999px 113.38582677299999px;"
</code>```

can be written as a SVG attribute

```<code>transform="rotate(51 113.38582677299999 113.38582677299999)"
</code>```

But take care that

this second form cannot be used as a CSS property, and

all numbers must be unitless and expressed in the current user coordinate system of the parent.

The second condition means you cannot use mm units, but need to recompute them to px units.

Title: SVG transform-origin broken in Inkscape

Body:
I have this SVG file:
xml

<svg xmlns="http://www.w3.org/2000/svg" width="300mm" height="300mm" id="image">
  <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

  <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865" transform="rotate(51)"
    transform-origin="113.38582677299999 113.38582677299999"></rect>

  <path d="
        M 170.0787401595,113.38582677299999
        Q 109.97448081636158,111.75869821811467 149.06383319514674,157.4444954545483
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  <g transform="rotate(1.6451612903225807)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(47.70967741935484)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.9291728801154,111.85730708558926 151.53378395847778,155.32411227472434
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>

  <g transform="rotate(3.2903225806451615)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(44.41935483870968)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.88671463478482,111.95717607594642 153.8779628220461,153.06546067295844
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>

  <g transform="rotate(4.935483870967742)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(41.12903225806451)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.84714108325986,112.0582228564553 156.08864114581934,150.6759873101943
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>

  <g transform="rotate(6.580645161290323)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(37.83870967741935)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.81048485026771,112.16036412340621 158.158530434343,148.16357016015428
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>

  <g transform="rotate(8.225806451612904)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(34.54838709677419)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.7767761554767,112.26351567078673 160.08080636654395,145.5364925360554
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>

  <g transform="rotate(9.870967741935484)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(31.258064516129032)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.74604278858297,112.36759245970185 161.84913129517457,142.80341578094155
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>

  <g transform="rotate(11.516129032258066)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(27.96774193548387)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.71831008640042,112.47250868848064 163.45767514171737,139.97335071167026
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>

  <g transform="rotate(13.161290322580646)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(24.677419354838708)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.6936009119729,112.57817786341175 164.90113461786132,137.05562791070196
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>

  <g transform="rotate(14.806451612903226)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(21.387096774193548)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.67193563572567,112.68451287004946 166.1747507101772,134.0598669636379
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>

  <g transform="rotate(16.451612903225808)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(18.096774193548384)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.65333211867201,112.79142604503151 167.27432437034577,130.99594474392939
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>

  <g transform="rotate(18.096774193548388)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(14.806451612903224)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.6378056976883,112.89882924834941 168.19623035920955,127.87396284932184
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>

  <g transform="rotate(19.741935483870968)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(11.516129032258064)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.6253691728703,113.0066339360117 168.9374291990041,124.70421429739422
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>

  <g transform="rotate(21.387096774193548)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(8.225806451612904)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.61603279698062,113.11475123304022 169.49547719436387,121.49714958999664
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>

  <g transform="rotate(23.03225806451613)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(4.935483870967737)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.60980426699628,113.22309200673944 169.86853448906282,118.26334225847053
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>

  <g transform="rotate(24.67741935483871)" transform-origin="30mm 30mm">

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"></rect>

    <rect x="170.0787401595" y="112.81889763913499" width="555.5905511877" height="0.566929133865"
      transform="rotate(1.6451612903225765)" transform-origin="113.38582677299999 113.38582677299999"></rect>

    <path d="
        M 170.0787401595,113.38582677299999
        Q 109.60668871776325,113.33156694017794 170.05537113192838,115.01345400324652
      " fill="none" stroke-width="0.566929133865" stroke="#000000"></path>

  </g>
</svg>

Here is how it renders in Chrome and Firefox (and how I want it to look):

(the screenshot is cropped by hand, this is not the actual rendered size)

And here is how it is rendered in GIMP, Inkscape, Blender, Gwenview and probably many other apps:

Using some geometry I found out that browsers interpret transform-origin as coordinates relative to the document edges (as I expect), while in GIMP and others the rotation pivot is located in the upper left corner regardless of transform-origin.

This SVG is generated by a script. I could rewrite it to avoid using transforms, but I wonder if there is an easier way to make transform-origin work.

Body:
You are using transform and transform-origin as defined in the CSS Transforms Level 1 Candidate Recommendation, and you are using them as presentation attributes. transform-origin as a presentation attribute was only introduced in the 2017 working draft. While browser vendors have the capacity to bring up their products to new spec standards even before they reach recommendation status, most open source projects have not. For Inkscape, you have to live with the implementation according to the SVG 1.1 attribute standard, which is incompatible to CSS.

But that is not really a problem in your case. You only use transform-origin in conjunction with the rotate() function. And for that there is a helpful difference between the SVG attribute syntax and the CSS property functional notation: you can define the center of rotation inside the function. (This syntax only exists for rotate(), but not for scale(), skewX() or skewY().)

A CSS rule (note the obligatory units) of

style="transform:rotate(51deg);transform-origin:113.38582677299999px 113.38582677299999px;"

can be written as a SVG attribute

transform="rotate(51 113.38582677299999 113.38582677299999)"

But take care that

this second form cannot be used as a CSS property, and

all numbers must be unitless and expressed in the current user coordinate system of the parent.

The second condition means you cannot use mm units, but need to recompute them to px units.


问:
How to count networkdays in a subset of a date range with restrictions?
Demo workbook is here, now with formulas: https://docs.google.com/spreadsheets/d/1uj5P17iIesV6tEIwt00jUqJQdipxubk18CfV0uZshgU/edit?usp=sharing

This question is very similar to, but different from: Expand/explode a Google Sheets table with ticket open and close stats to show all tickets open each month .

I have a list of job openings (Inputs tab) that I need to track for monthly metrics. My metrics need to count the number of job openings that were open for <=10 business days and those that are open for >10 business days in each month, ignoring holidays.

Each monthly total needs to count the net work days for said month and for any prior month. However it can't count any days after the end of said month. Any opening that hasn't closed needs to be counted from opening day to today().

For example, a job opens 12/31/2020 and closes 1/14/2021. Even though that job is open only 10 work days in January, it's counted as >10 because of the 1 extra work day from prior months.

A job that opens 1/29/2021 and closes 3/1/2021 would count as <=10 days for January because there's only 1 work day; >10 for February because there are 21 total work days; and >10 for March because there are 22 work days.

On the Monthly Metrics tab in the demo workbook, I need a formula to make B8:D9 match the answers in B2:D3 using the data from the Inputs tab.

The formula I have in B8 for counting jobs in December open <=10 days is:

=if(EOMonth(B$7,0)<Today(),(countA(filter(Inputs!$A$2:$A,Inputs!$B$2:$B="open", Inputs!$C$2:$C<=EOMonth(B$7,0), networkdays(Inputs!$C$2:$C,EOMonth(B$7,0))<=10))), (countA(filter(Inputs!$A$2:$A,Inputs!$B$2:$B="open", Inputs!$C$2:$C<=EOMonth(B$7,0), networkdays(Inputs!$C$2:$C,today())<=10))))

+if(EOMonth(B$7,0)<Today(),(countA(filter(Inputs!$A$2:$A,Inputs!$B$2:$B="closed", Inputs!$D$2:$D<=EOMonth(B$7,0), Inputs!$D$2:$D>=B$7, networkdays(Inputs!$C$2:$C,EOMonth(B$7,0))<=10))),(countA(filter(Inputs!$A$2:$A,Inputs!$B$2:$B="closed", Inputs!$D$2:$D<=EOMonth(B$7,0), Inputs!$D$2:$D>=B$7, networkdays(Inputs!$C$2:$C,Inputs!$D$2:$D)<=10))))

The formula I have in B9 for counting jobs in December open >10 days is:

=if(EOMonth(B$7,0)<Today(),(countA(filter(Inputs!$A$2:$A,Inputs!$B$2:$B="open", Inputs!$C$2:$C<=EOMonth(B$7,0), networkdays(Inputs!$C$2:$C,EOMonth(B$7,0))>10))), (countA(filter(Inputs!$A$2:$A,Inputs!$B$2:$B="open", Inputs!$C$2:$C<=EOMonth(B$7,0), networkdays(Inputs!$C$2:$C,today())>10))))

+if(EOMonth(B$7,0)<Today(),(countA(filter(Inputs!$A$2:$A,Inputs!$B$2:$B="closed", Inputs!$D$2:$D<=EOMonth(B$7,0), Inputs!$D$2:$D>=B$7, networkdays(Inputs!$C$2:$C,EOMonth(B$7,0))>10))),(countA(filter(Inputs!$A$2:$A,Inputs!$B$2:$B="closed", Inputs!$D$2:$D<=EOMonth(B$7,0), Inputs!$D$2:$D>=B$7, networkdays(Inputs!$C$2:$C,Inputs!$D$2:$D)>10))))

As you can see, The counts are way off, and I can't keep the logic straight in my head, or on paper, well enough to figure it out.

答:
checksum - networkdays per period:

```<code>={"Checksum"; INDEX(NETWORKDAYS(C2:C11, IF(D2:D11="", TODAY(), D2:D11)))}
</code>```

networkdays per each month:

```<code>=INDEX(IFNA(VLOOKUP(ROW(A1:A11)&"", QUERY({TEXT(SPLIT(QUERY(FLATTEN(IF(DAYS(IF(D2:D11="",TODAY(), D2:D11), C2:C11)>=
 SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), ROW(C2:C11)&"×"&C2:C11+SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), NA())),
 "where Col1 matches '"&TEXTJOIN("|", 1, ROW(C2:C11)&"×"&C2:C11, ".*"&VALUE(UNIQUE(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), -1)+1)))&"'"), "×"), {"#", "yyy-mm"}), NETWORKDAYS(
 INDEX(SPLIT(QUERY(FLATTEN(IF(DAYS(IF(D2:D11="",TODAY(), D2:D11), C2:C11)>=
 SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), ROW(C2:C11)&"×"&C2:C11+SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), NA())),
 "where Col1 matches '"&TEXTJOIN("|", 1, ROW(C2:C11)&"×"&C2:C11, ".*"&VALUE(UNIQUE(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), -1)+1)))&"'"), "×"),,2),
 INDEX(SPLIT(QUERY(FLATTEN(IF(DAYS(IF(D2:D11="",TODAY(), D2:D11), C2:C11)>=
 SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), ROW(C2:C11)&"×"&C2:C11+SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), NA())),
 "where Col1 matches '"&TEXTJOIN("|", 1, ROW(D2:D11)&"×"&IF(D2:D11="", TODAY(), D2:D11), ".*"&VALUE(UNIQUE(FLATTEN(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), )))))&"'"), "×"),,2))},
 "select Col1,sum(Col3) group by Col1 pivot Col2 label Col1'1'"), SEQUENCE(1, COUNTUNIQUE(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), )))+1, 0)))
</code>```

and your monthly metrics would be:

```<code>=INDEX(REGEXREPLACE(QUERY(QUERY(SPLIT(FLATTEN(TEXT(TRANSPOSE(UNIQUE(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), ))), "yyymm\¤mmm-yyy")&"×"&
 REGEXREPLACE(REGEXREPLACE(QUERY(QUERY({TEXT(SPLIT(QUERY(FLATTEN(IF(DAYS(IF(D2:D11="",TODAY(), D2:D11), C2:C11)>=
 SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), ROW(C2:C11)&"×"&C2:C11+SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), NA())),
 "where Col1 matches '"&TEXTJOIN("|", 1, ROW(C2:C11)&"×"&C2:C11, ".*"&VALUE(UNIQUE(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), -1)+1)))&"'"), "×"), {"#", "yyy-mm"}), NETWORKDAYS(
 INDEX(SPLIT(QUERY(FLATTEN(IF(DAYS(IF(D2:D11="",TODAY(), D2:D11), C2:C11)>=
 SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), ROW(C2:C11)&"×"&C2:C11+SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), NA())),
 "where Col1 matches '"&TEXTJOIN("|", 1, ROW(C2:C11)&"×"&C2:C11, ".*"&VALUE(UNIQUE(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), -1)+1)))&"'"), "×"),,2),
 INDEX(SPLIT(QUERY(FLATTEN(IF(DAYS(IF(D2:D11="",TODAY(), D2:D11), C2:C11)>=
 SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), ROW(C2:C11)&"×"&C2:C11+SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), NA())),
 "where Col1 matches '"&TEXTJOIN("|", 1, ROW(D2:D11)&"×"&IF(D2:D11="", TODAY(), D2:D11), ".*"&VALUE(UNIQUE(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), ))))&"'"), "×"),,2))},
 "select sum(Col3) group by Col1 pivot Col2"), "offset 1", 0)&"", "(\b([0-9]|10)\b)", "$1×# Jobs open <= 10 business days")&"", "(.*\d$)", "$1×# Jobs open > 10 business days")), "×"),
 "where Col2 is not null"), "select Col3,count(Col2) group by Col3 pivot Col1")&"", "(.*¤)", ))
</code>```

Body:
checksum - networkdays per period:

={"Checksum"; INDEX(NETWORKDAYS(C2:C11, IF(D2:D11="", TODAY(), D2:D11)))}

networkdays per each month:

=INDEX(IFNA(VLOOKUP(ROW(A1:A11)&"", QUERY({TEXT(SPLIT(QUERY(FLATTEN(IF(DAYS(IF(D2:D11="",TODAY(), D2:D11), C2:C11)>=
 SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), ROW(C2:C11)&"×"&C2:C11+SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), NA())),
 "where Col1 matches '"&TEXTJOIN("|", 1, ROW(C2:C11)&"×"&C2:C11, ".*"&VALUE(UNIQUE(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), -1)+1)))&"'"), "×"), {"#", "yyy-mm"}), NETWORKDAYS(
 INDEX(SPLIT(QUERY(FLATTEN(IF(DAYS(IF(D2:D11="",TODAY(), D2:D11), C2:C11)>=
 SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), ROW(C2:C11)&"×"&C2:C11+SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), NA())),
 "where Col1 matches '"&TEXTJOIN("|", 1, ROW(C2:C11)&"×"&C2:C11, ".*"&VALUE(UNIQUE(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), -1)+1)))&"'"), "×"),,2),
 INDEX(SPLIT(QUERY(FLATTEN(IF(DAYS(IF(D2:D11="",TODAY(), D2:D11), C2:C11)>=
 SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), ROW(C2:C11)&"×"&C2:C11+SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), NA())),
 "where Col1 matches '"&TEXTJOIN("|", 1, ROW(D2:D11)&"×"&IF(D2:D11="", TODAY(), D2:D11), ".*"&VALUE(UNIQUE(FLATTEN(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), )))))&"'"), "×"),,2))},
 "select Col1,sum(Col3) group by Col1 pivot Col2 label Col1'1'"), SEQUENCE(1, COUNTUNIQUE(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), )))+1, 0)))

and your monthly metrics would be:

=INDEX(REGEXREPLACE(QUERY(QUERY(SPLIT(FLATTEN(TEXT(TRANSPOSE(UNIQUE(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), ))), "yyymm\¤mmm-yyy")&"×"&
 REGEXREPLACE(REGEXREPLACE(QUERY(QUERY({TEXT(SPLIT(QUERY(FLATTEN(IF(DAYS(IF(D2:D11="",TODAY(), D2:D11), C2:C11)>=
 SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), ROW(C2:C11)&"×"&C2:C11+SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), NA())),
 "where Col1 matches '"&TEXTJOIN("|", 1, ROW(C2:C11)&"×"&C2:C11, ".*"&VALUE(UNIQUE(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), -1)+1)))&"'"), "×"), {"#", "yyy-mm"}), NETWORKDAYS(
 INDEX(SPLIT(QUERY(FLATTEN(IF(DAYS(IF(D2:D11="",TODAY(), D2:D11), C2:C11)>=
 SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), ROW(C2:C11)&"×"&C2:C11+SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), NA())),
 "where Col1 matches '"&TEXTJOIN("|", 1, ROW(C2:C11)&"×"&C2:C11, ".*"&VALUE(UNIQUE(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), -1)+1)))&"'"), "×"),,2),
 INDEX(SPLIT(QUERY(FLATTEN(IF(DAYS(IF(D2:D11="",TODAY(), D2:D11), C2:C11)>=
 SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), ROW(C2:C11)&"×"&C2:C11+SEQUENCE(1, MAX(DAYS(IF(D2:D11="", TODAY(), D2:D11), C2:C11)+1), ), NA())),
 "where Col1 matches '"&TEXTJOIN("|", 1, ROW(D2:D11)&"×"&IF(D2:D11="", TODAY(), D2:D11), ".*"&VALUE(UNIQUE(EOMONTH(SEQUENCE(TODAY()-MIN(C2:C11), 1, MIN(C2:C11)), ))))&"'"), "×"),,2))},
 "select sum(Col3) group by Col1 pivot Col2"), "offset 1", 0)&"", "(\b([0-9]|10)\b)", "$1×# Jobs open <= 10 business days")&"", "(.*\d$)", "$1×# Jobs open > 10 business days")), "×"),
 "where Col2 is not null"), "select Col3,count(Col2) group by Col3 pivot Col1")&"", "(.*¤)", ))


问:
timer plugin for a game
I am looking for a jQuery plugin that can display a timer with miliseconds and also return that time to save a highscore. does anyone know a good one? It should also at least try to avoid cheating.

Thanks

答:
I think that to make a tamper-proof timer, it is not enough to use a client-side JS plugin, you will have to check the time on the server. For example, send an AJAX request on start and on finish and measure the time between them.

As for the clock plugin, you can for example use epiclock, but do not rely on it to measure the time.

ContentLicense: CC BY-SA 3.0

Title: timer plugin for a game


问:
Reduce boolean Iterator
How can I reduce an Iterator of booleans using the && operator? Here is an example (just the relevant part):

let row: Vec<(u32, bool)> = vec![(12, true), (13, false), (15, true)];

row.iter()
    .map(|it| {
        let (_, marked) = it;
        marked
    })
    .reduce(|acc, mk | acc && mk);
```

The compiler recommends dereferencing acc first, then dereferencing mk, and finally borrowing the whole expression. It's a quite simple operation but I'm unable to find the Rustacean way to do it.

答:
Here's an alternative solution that uses fold to specify an initial value:

let val: bool = row.iter()
    .map(|it| {
        let (_, marked) = it;
        marked
    })
    .fold(true, |acc, mk| acc && *mk);
```
<p>The reason <code>acc && mk</code> doesn't work is because you have an iterator over <code>&bool</code> but you want a <code>bool</code>. <code>*acc && *mk</code> doesn't work because the accumulator is of type <code>bool</code>, so you want <code>acc && *mk</code>. However, you can no longer use <code>reduce</code> since the accumulator and values aren't the same type (<code>bool</code> vs <code>&bool</code>), hence the need for <code>fold</code>.</p>
<p>Also note that <code>fold</code> and <code>map</code> can be combined:</p>
<pre class="lang-rust prettyprint-override"><code>let val: bool = row.iter()
    .fold(true, |acc, (_, mk)| acc && *mk);
</code>```

Title: Reduce boolean Iterator

Body:
How can I reduce an Iterator of booleans using the && operator? Here is an example (just the relevant part):

let row: Vec<(u32, bool)> = vec![(12, true), (13, false), (15, true)];

row.iter()
    .map(|it| {
        let (_, marked) = it;
        marked
    })
    .reduce(|acc, mk | acc && mk);

The compiler recommends dereferencing acc first, then dereferencing mk, and finally borrowing the whole expression. It's a quite simple operation but I'm unable to find the Rustacean way to do it.

Body:
Here's an alternative solution that uses fold to specify an initial value:

let val: bool = row.iter()
    .map(|it| {
        let (_, marked) = it;
        marked
    })
    .fold(true, |acc, mk| acc && *mk);

The reason acc && mk doesn't work is because you have an iterator over &bool but you want a bool. *acc && *mk doesn't work because the accumulator is of type bool, so you want acc && *mk. However, you can no longer use reduce since the accumulator and values aren't the same type (bool vs &bool), hence the need for fold.

Also note that fold and map can be combined:

let val: bool = row.iter()
    .fold(true, |acc, (_, mk)| acc && *mk);


问:
Display button value in div onclick. Javascript/HTML
I have a set of buttons with different values. When I press a button I want the value of the button to be displayed in the div picked_letters, but nothing is showing. The code is divided in an html file and a javascript file.

html file looks like this:

```<code><body>

<script src="cases.js"></script>

<div id="written_word">
</div>

<div id="list_of_letters">
</div>

<div id="picked_letters">

</div>

</body>
</code>```

and the onclick in the javascript file looks like this:

```<code>for(let i = 0; i < 26; i++) {
    let btn = document.createElement("button");
    btn.style.background = 'silver';
    btn.style.width = '15%';
    btn.style.fontWeight = 'bold';
    btn.style.fontSize = '135%';
    btn.style.display = 'inline-block';
    btn.value = case_values[i];
    btn.onmouseover = function (){
        btn.style.background = 'goldenrod';
    }
    btn.onmouseleave = function() {
        btn.style.background = 'silver';
    }
    btn.onclick = function() {
        btn.style.background = 'darkgrey';
        btn.disabled = true;
        btn.innerHTML = String(btn.value);
        document.getElementById("picked_letters").innerHTML =
            String(btn.value);
    }
    btn.innerHTML = String(i+1);
    document.body.appendChild(btn);
}
</code>```

The button changes color, becomes disabled and displays the value inside the button but it's the last line with getting the button value into a div that I am having problems with. Have looked around but haven't found a solution that solves this problem.

##Edit: The problem seems to have been fixed when I put the script import at the end of the body (and some other minor changes).

答:
Where are you setting the value of the button?
Can you share the button code?

Does your button look like this?

```<code><button>My Button</button>
</code>```

or do you set your value like this?

```<code><button value="my button value">My button</button>
</code>```

If you have a value set - you can do this:

```<code>btn.onclick = function () {
  console.log(btn.innerHTML);
  btn.style.background = "darkgrey";
  btn.disabled = true;
  document.getElementById("picked_letters").innerHTML = btn.value;
};
</code>```

If you don't have a value set - using btn.value won't return anything.
I would try adding a value to your button if you dont have one. Or if you want to call the innerhtml of the button:

```<code><button>My button</button>
</code>```

and then

```<code>btn.onclick = function () {
  console.log(btn.innerHTML);
  btn.style.background = "darkgrey";
  btn.disabled = true;
  document.getElementById("picked_letters").innerHTML = btn.innerHTML;
};
</code>```

Body:
I have a set of buttons with different values. When I press a button I want the value of the button to be displayed in the div picked_letters, but nothing is showing. The code is divided in an html file and a javascript file.

html file looks like this:

and the onclick in the javascript file looks like this:

for(let i = 0; i < 26; i++) {
    let btn = document.createElement("button");
    btn.style.background = 'silver';
    btn.style.width = '15%';
    btn.style.fontWeight = 'bold';
    btn.style.fontSize = '135%';
    btn.style.display = 'inline-block';
    btn.value = case_values[i];
    btn.onmouseover = function (){
        btn.style.background = 'goldenrod';
    }
    btn.onmouseleave = function() {
        btn.style.background = 'silver';
    }
    btn.onclick = function() {
        btn.style.background = 'darkgrey';
        btn.disabled = true;
        btn.innerHTML = String(btn.value);
        document.getElementById("picked_letters").innerHTML =
            String(btn.value);
    }
    btn.innerHTML = String(i+1);
    document.body.appendChild(btn);
}

The button changes color, becomes disabled and displays the value inside the button but it's the last line with getting the button value into a div that I am having problems with. Have looked around but haven't found a solution that solves this problem.

##Edit: The problem seems to have been fixed when I put the script import at the end of the body (and some other minor changes).

Body:
Where are you setting the value of the button?
Can you share the button code?

Does your button look like this?

<button>My Button</button>

or do you set your value like this?

<button value="my button value">My button</button>

If you have a value set - you can do this:

btn.onclick = function () {
  console.log(btn.innerHTML);
  btn.style.background = "darkgrey";
  btn.disabled = true;
  document.getElementById("picked_letters").innerHTML = btn.value;
};

If you don't have a value set - using btn.value won't return anything.
I would try adding a value to your button if you dont have one. Or if you want to call the innerhtml of the button:

<button>My button</button>

and then

btn.onclick = function () {
  console.log(btn.innerHTML);
  btn.style.background = "darkgrey";
  btn.disabled = true;
  document.getElementById("picked_letters").innerHTML = btn.innerHTML;
};


问:
How can I stop isNaN from returning an error for a blank field?
EDIT:

Ok so I'm updating this question, to show what I've built as I've still not been able to fix this issue. Here is an image of what I've got. So as you can see,

When the user enters a value, the calculation (they are just percentage and total calculations are done "onkeyup". As you can see because of this they return "NaN". Is there a way for me to stop the field displaying a NaN and then subsequently only showing the total values?

I have thought about this and I could just get all the fields to calculate as soon as something is input into the final field? What do you think. Apologies to all those that had perviously answered my question, I am still trying to figure out the best approach, I'm just not as good with JavaScript as I am with HTML/CSS!!

答: Can't you just initialize the text box with a default value, say 0?</p>


问:
Rails friendly_id gem not working with link_to helpers?
I’ve set the friendly_id gem up, and generated slugs for my model.

The slugs are all shown in my DB column, and if I run Event.friendly.find('my-event-name') in the console, it works perfectly.

My URL’s are still showing as organisation/1/events/1 though, when I check the result of the following link_to:-

```<code><%= link_to organisation_event_path(event.organisation.id, event.id), class: 'btn btn-primary' do %>
</code>```

I’ve also added

```<code>  extend FriendlyId
  friendly_id :title, use: :slugged
</code>```

to my model.

When I visit the URL manually, it works with the friendly id - so it seems to be just the link_to helper that isn't working.

Could possibly be related to some additional setup required for nested routes here - but I can’t seem to find anything when I search.

```<code>  resources :organisations do
    resources :events
  end
</code>```

答:
The answer seems to be that I need to change the .id in my link_to, to .friendly_id like so:-

```<code><%= link_to organisation_event_path(event.organisation.id, event.friendly_id), class: 'btn btn-primary' do %>

</code>```

Would expected it to work without this but perhaps not.

Body:
I’ve set the friendly_id gem up, and generated slugs for my model.

The slugs are all shown in my DB column, and if I run Event.friendly.find('my-event-name') in the console, it works perfectly.

My URL’s are still showing as organisation/1/events/1 though, when I check the result of the following link_to:-

<%= link_to organisation_event_path(event.organisation.id, event.id), class: 'btn btn-primary' do %>

I’ve also added

  extend FriendlyId
  friendly_id :title, use: :slugged

to my model.

When I visit the URL manually, it works with the friendly id - so it seems to be just the link_to helper that isn't working.

Could possibly be related to some additional setup required for nested routes here - but I can’t seem to find anything when I search.

  resources :organisations do
    resources :events
  end

Body:
The answer seems to be that I need to change the .id in my link_to, to .friendly_id like so:-

<%= link_to organisation_event_path(event.organisation.id, event.friendly_id), class: 'btn btn-primary' do %>

Would expected it to work without this but perhaps not.


问:
Golang: Can channels be closed in a deferred function?
I was working on some Go code and wanted to close a channel at the end of it. However, I wanted to test if it'd actually close the channel if I use an anonymous function, passing the channel as an argument and use the function with the defer keyword.

```<code>channel := make(chan string, 2)

defer func (channel chan string) {
        close(channel)
        value, ok := <-channel
        fmt.Println("Value:", value, "Open channel?", ok)
    }(channel)
</code>```

To my understanding everything in Go is passed by value and not by reference, and make's documentation says that it returns a channel when used to spawn a channel, not a pointer to a channel. Does this imply that if I pass the channel as argument to a function and close the channel within that function, the channel outside the function would remain open? If so, I'm guessing I'd need to pass the channel as a pointer to the function to achieve that behavior?

I'm new to Go, so I'd appreciate if you can explain me the "why" rather than "Oh, just swap this chunk for this other chunk of code" just so I can better understand how it's actually working:)

Thanks!

答:
Channels behaves like slice, map, strings or functions, as in they actually store a wrapped pointer to the underlying data. They behave like opaque pointers.

So passing a channel is copying it by value, but just like a slice, it's "value" is literally just a reference to the actual low-level channel data structure. So there is no need to explicitly pass a channel pointer, since that would be like passing a pointer of a pointer.

To answer your questions: Yes it can and yes it's safe to pass channels by value because they are "pointers" in and of themselves.

You can also verify it with a slightly modified version of your code:

package main

import "fmt"

func main() {
    channel := make(chan string, 2)

    // channel is open here.

    // close the channel by passing it into a function
    // by value and closing it within the function.
    func(channel chan string) {
        close(channel)
    }(channel)

    // is the channel closed?
    value, ok := <-channel
    fmt.Println("Value:", value, "Open channel?", ok)
}
```
<p>Output (go version go1.16 darwin/amd64):</p>
```
Value:  Open channel? false
```

Body:
I was working on some Go code and wanted to close a channel at the end of it. However, I wanted to test if it'd actually close the channel if I use an anonymous function, passing the channel as an argument and use the function with the defer keyword.

channel := make(chan string, 2)

defer func (channel chan string) {
        close(channel)
        value, ok := <-channel
        fmt.Println("Value:", value, "Open channel?", ok)
    }(channel)

To my understanding everything in Go is passed by value and not by reference, and make's documentation says that it returns a channel when used to spawn a channel, not a pointer to a channel. Does this imply that if I pass the channel as argument to a function and close the channel within that function, the channel outside the function would remain open? If so, I'm guessing I'd need to pass the channel as a pointer to the function to achieve that behavior?

I'm new to Go, so I'd appreciate if you can explain me the "why" rather than "Oh, just swap this chunk for this other chunk of code" just so I can better understand how it's actually working:)

Thanks!

Body:
Channels behaves like slice, map, strings or functions, as in they actually store a wrapped pointer to the underlying data. They behave like opaque pointers.

So passing a channel is copying it by value, but just like a slice, it's "value" is literally just a reference to the actual low-level channel data structure. So there is no need to explicitly pass a channel pointer, since that would be like passing a pointer of a pointer.

To answer your questions: Yes it can and yes it's safe to pass channels by value because they are "pointers" in and of themselves.

You can also verify it with a slightly modified version of your code:

package main

import "fmt"

func main() {
    channel := make(chan string, 2)

    // channel is open here.

    // close the channel by passing it into a function
    // by value and closing it within the function.
    func(channel chan string) {
        close(channel)
    }(channel)

    // is the channel closed?
    value, ok := <-channel
    fmt.Println("Value:", value, "Open channel?", ok)
}

Output (go version go1.16 darwin/amd64):

Value:  Open channel? false


答:
The code above is perfectly fine, the is definately being displayed in the "picked_letters" div, but the value of btn is ""(empty) so the value set to the div is also empty. To solve this issue, add value to the button by doing:-
. and the issue will be gone.

const btn = document.querySelector('#btn')
btn.onclick = function() {
  btn.style.background = 'darkgrey';
  btn.disabled = true;
  console.log(btn.value)
  btn.innerHTML = String(btn.value);
  document.getElementById("picked_letters").innerHTML =
    String(btn.value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

<div id="written_word">

</div>

<div id="list_of_letters">
</div>

<div id="picked_letters">

</div>
  <button id='btn' value='5'>Tap me</button>

</body></code>```

Title: Display button value in div onclick. Javascript/HTML

Body:
The code above is perfectly fine, the is definately being displayed in the "picked_letters" div, but the value of btn is ""(empty) so the value set to the div is also empty. To solve this issue, add value to the button by doing:-
. and the issue will be gone.

const btn = document.querySelector('#btn')
btn.onclick = function() {
  btn.style.background = 'darkgrey';
  btn.disabled = true;
  console.log(btn.value)
  btn.innerHTML = String(btn.value);
  document.getElementById("picked_letters").innerHTML =
    String(btn.value);
}

<body>

<div id="written_word">

</div>

<div id="list_of_letters">
</div>

<div id="picked_letters">

</div>
  <button id='btn' value='5'>Tap me</button>

</body>


问:
In JULIA how do I preallocate a Measurements.jl vector with n rows?
I want to preallocate a vector with n rows (e.g. A below) ready for filling in a loop with Measurements.jl variables, i.e. variables of the form a ± b. For example:</p>
```<code>using Measurements
A = zeros(5,1) # this doesn't work
for n = 1:5
  local B = rand() ± rand()
  local C = rand() ± rand()
  global A[n,1] = sqrt.((B-C).^2)
end
println(A)
</code>```

答:
You can make an array of Measurements.jl Measurements is several ways, including

```<code>A = fill(0±0, size)
</code>```

or

```<code>A = Array{Measurement}(undef, size)
</code>```

For example

```<code>using Measurements
A = fill(0±0, 5, 1)
for n = 1:5
  B = rand() ± rand()
  C = rand() ± rand()
  A[n,1] = sqrt.((B-C).^2)
end
</code>```
```<code>julia> A
5×1 Matrix{Measurement{Float64}}:
 0.28 ± 1.0
 0.45 ± 0.87
 0.67 ± 0.58
 0.28 ± 0.62
  0.3 ± 0.67
</code>```

N.B., you shouldn't generally need those global and local annotations here, unless you're running in global scope in a script (as opposed to in a REPL, in a function, a let block, or really anywhere else).

Body:
I want to preallocate a vector with n rows (e.g. A below) ready for filling in a loop with Measurements.jl variables, i.e. variables of the form a ± b. For example:

using Measurements
A = zeros(5,1) # this doesn't work
for n = 1:5
  local B = rand() ± rand()
  local C = rand() ± rand()
  global A[n,1] = sqrt.((B-C).^2)
end
println(A)

Body:
You can make an array of Measurements.jl Measurements is several ways, including

A = fill(0±0, size)

or

A = Array{Measurement}(undef, size)

For example

using Measurements
A = fill(0±0, 5, 1)
for n = 1:5
  B = rand() ± rand()
  C = rand() ± rand()
  A[n,1] = sqrt.((B-C).^2)
end

julia> A
5×1 Matrix{Measurement{Float64}}:
 0.28 ± 1.0
 0.45 ± 0.87
 0.67 ± 0.58
 0.28 ± 0.62
  0.3 ± 0.67

N.B., you shouldn't generally need those global and local annotations here, unless you're running in global scope in a script (as opposed to in a REPL, in a function, a let block, or really anywhere else).


问:
The import org.junit cannot be resolved
I need to solve a Java problem for an interview, and they have sent me the test class. It starts with

```<code>import org.junit.Before;
</code>```

and also has the following syntax at places:

```<code>@RunWith(JUnit4.class)
...
@Before
...
@Test
</code>```

I haven't used Java for a while, so this confuses me a little. I downloaded eclipse and when I tried to compile this test file, there are errors at the import and at the '@' signs. The import error throws:

```<code>The import org.junit cannot be resolved.
</code>```

And the @RunWith is not even recognized, as it tries to resolve it to a type.

答:
If you use Maven with Eclipse then You need to follow the below steps.

1). Add Junit dependency to the pom.xml file

```<code><dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</code>```

Note : Please get the latest from the following link
https://mvnrepository.com/artifact/junit/junit

2).On your test class (Ex. AdditionTest.class), you need to annotate with @Test on your test method (Ex. testAdd() )

Note :  The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case.

public class AdditionTest {

```<code>@Test
public void testAdd()
{
</code>```

// Test code here...

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

The moment/ the first time you annotate as "@Test" the IDE asks whether you need to Add Junit jar files to Class path. Once you accept this it will add the   Junit jar file into the class path.

With this you can achieve the following imports
import org.junit.Test;
import static org.junit.Assert.*;
Regards

Title: The import org.junit cannot be resolved

Body:
I need to solve a Java problem for an interview, and they have sent me the test class. It starts with

import org.junit.Before;

and also has the following syntax at places:

@RunWith(JUnit4.class)
...
@Before
...
@Test

I haven't used Java for a while, so this confuses me a little. I downloaded eclipse and when I tried to compile this test file, there are errors at the import and at the '@' signs. The import error throws:

The import org.junit cannot be resolved.

And the @RunWith is not even recognized, as it tries to resolve it to a type.

Body:
If you use Maven with Eclipse then You need to follow the below steps.

1). Add Junit dependency to the pom.xml file

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>

Note : Please get the latest from the following link
https://mvnrepository.com/artifact/junit/junit

2).On your test class (Ex. AdditionTest.class), you need to annotate with @Test on your test method (Ex. testAdd() )

Note :  The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case.

public class AdditionTest {

@Test
public void testAdd()
{

// Test code here...

}

The moment/ the first time you annotate as "@Test" the IDE asks whether you need to Add Junit jar files to Class path. Once you accept this it will add the   Junit jar file into the class path.

With this you can achieve the following imports
import org.junit.Test;
import static org.junit.Assert.*;
Regards


问:
How to fix "E: Unable to locate package python" on termux?
I am installing python on termux but I am getting this error:</p>
```<code>$ pkg install python
Checking availability of current mirror: ok
Reading package lists... Done
Building dependency tree... Done
E: Unable to locate package python
</code>```

答:
The following combination of answers from this post worked for me:

termux-setup-storage

termux-change-repo (I selected Albatros)

pkg update and pkg upgrade

exit and then restart termux

pkg install python -y

Body:
I am installing python on termux but I am getting this error:

$ pkg install python
Checking availability of current mirror: ok
Reading package lists... Done
Building dependency tree... Done
E: Unable to locate package python


问:
"nvm use 16.13.0" will return this error "exit status 145: The directory is not empty."
I have 2 versions of node.js , as follow:-

```<code>Your environment has been set up for using Node.js 17.1.0 (x64) and npm.

C:\Windows\System32>nvm list

    16.13.0
    8.16.2
</code>```

but when i try to use the first version i got this error:-

```<code>C:\Windows\System32>nvm use 8.16.2
node v8.16.2 (64-bit) is not installed.
</code>```

and when i try to use the second version i got this:-

```<code>C:\Windows\System32>nvm use 16.13.0
exit status 145: The directory is not empty.
</code>```

so what is going on? thanks

答:
When this happen:

```<code>C:\Windows\System32>nvm use 16.13.0
exit status 145: The directory is not empty.
</code>```

Just make sure, the nodejs folder is empty, check C:\Program Files\nodejs or C:\Program Files (x86)\nodejs, otherwise delete the content. Then try again nvm use XXXX  (xxxx is the version)

Body:
I have 2 versions of node.js , as follow:-

Your environment has been set up for using Node.js 17.1.0 (x64) and npm.

C:\Windows\System32>nvm list

    16.13.0
    8.16.2

but when i try to use the first version i got this error:-

C:\Windows\System32>nvm use 8.16.2
node v8.16.2 (64-bit) is not installed.

and when i try to use the second version i got this:-

C:\Windows\System32>nvm use 16.13.0
exit status 145: The directory is not empty.

so what is going on? thanks

Body:
When this happen:

C:\Windows\System32>nvm use 16.13.0
exit status 145: The directory is not empty.

Just make sure, the nodejs folder is empty, check C:\Program Files\nodejs or C:\Program Files (x86)\nodejs, otherwise delete the content. Then try again nvm use XXXX  (xxxx is the version)


问:
How can I launch a fragment with safe args in an instrumentation test?
Below I have a test class designed to launch a fragment in isolation and test the navController's ability to navigate.

The first test, landingToGameFragmentTest() works perfectly!

The second test launches a fragment that depends on safe args to be passed to it. Aside from that, there is no difference I can perceive in how they are executed.

```<code>// Declare navController at top level so it can be accessed from any test in the class
private lateinit var navController: TestNavHostController

// Use Generic type with fragment as upper bound to pass any type of FragmentScenario
private fun <T : Fragment> init(scenario: FragmentScenario<T>) {

    // Create a test navController
    navController = TestNavHostController(
        ApplicationProvider.getApplicationContext()
    )

    scenario.onFragment { fragment ->
        // Link navController to its graph
        navController.setGraph(R.navigation.nav_graph)
        // Link fragment to its navController
        Navigation.setViewNavController(fragment.requireView(), navController)
    }
}

@Test
fun landingToGameFragmentTest() {

    init(launchFragmentInContainer<LandingFragment>(themeResId = THEME))

    // Click button to navigate to GameFragment
    onView(withId(R.id.button_start_game))
        .perform(click())

    assertEquals("Navigation to GameFragment failed",
        R.id.gameFragment,
        navController.currentDestination?.id)
}

@Test
fun gameToLandingFragmentTest() {

    init(launchFragmentInContainer<GameFragment>(themeResId = THEME, fragmentArgs = Bundle()))

    onView(withId(R.id.button_end_game))
        .perform(click())

    assertEquals("Navigation to LandingFragment failed",
        R.id.landingFragment,
        navController.currentDestination?.id)
}
</code>```

I set a default value for its arguments, but I still got a null arguments exception until I passed it an empty bundle. Now the fragment will launch but it appears not to be able to navigate to any other fragment!

I could find no similar questions on SO, and the stack output is beyond me.

After the init(launchFragmentInContainer()) line I stepped through the code and found this throwing an illegalArgumentException:

```<code>public static int parseInt(@RecentlyNonNull String s, int radix) throws NumberFormatException {
    throw new RuntimeException("Stub!");
}
</code>```

Which then leads to getNavigator(), which passes the name "fragment".
However the only navigators are "navigation" and "test", of which I believe it should be test.
The illegalStateException is then thrown:

```<code>/**
 * Retrieves a registered [Navigator] by name.
 *
 * @param name name of the navigator to return
 * @return the registered navigator with the given name
 *
 * @throws IllegalStateException if the Navigator has not been added
 *
 * @see NavigatorProvider.addNavigator
 */
@Suppress("UNCHECKED_CAST")
@CallSuper
public open fun <T : Navigator<*>> getNavigator(name: String): T {
    require(validateName(name)) { "navigator name cannot be an empty string" }
    val navigator = _navigators[name]
        ?: throw IllegalStateException(
            "Could not find Navigator with name \"$name\". You must call " +
                "NavController.addNavigator() for each navigation type."
        )
    return navigator as T
}
</code>```

Finally navigate() is called on onView(withId(R.id.button_end_game)) generating:

I likely don't have to keep this test in this specific instance. However, I certainly will need to know how to launch a Fragment in isolation (that depends on safe args) in the future.

Thank you for your consideration!!

答:
You have two entirely separate problems here:

Your Fragment needs to have arguments passed to it.

Arguments are passed to your fragment via the fragmentArgs parameter of launchFragmentInContainer as explained in the Fragment testing guide.

Each Args class, such as your LandingFragmentArgs has a constructor that lets you construct that Args class directly. You can then use the toBundle() method to make the Bundle that you pass to launchFragmentInContainer:

```<code>val args = GameFragmentArgs(/* pass in your required args here */)
val bundle = args.toBundle()
init(launchFragmentInContainer<GameFragment>(fragmentArgs = bundle, themeResId = THEME))
</code>```

Your NavController needs to have its state set to the GameFragment destination

Your TestNavHostController doesn't know that your test needs to start on the destination associated with GameFragment - by default, it will just be on the startDestination of your graph (where whatever action you are trying to trigger doesn't exist).

As per the Test Navigation documentation:

TestNavHostController provides a setCurrentDestination method that allows you to set the current destination so that the NavController is in the correct state before your test begins.

So you need to make sure you call setCurrentDestination after your init call:

```<code>val args = GameFragmentArgs(/* pass in your required args here */)
val bundle = args.toBundle()
val scenario = launchFragmentInContainer<GameFragment>(fragmentArgs = bundle, themeResId = THEME)
init(scenario)

// Ensure that the NavController is set to the expected destination
// using the ID from your navigation graph associated with GameFragment
scenario.onFragment {
  // Just like setGraph(), this needs to be called on the main thread
  navController.setCurrentDestination(R.id.game_fragment, bundle)
}
</code>```

Body:
Below I have a test class designed to launch a fragment in isolation and test the navController's ability to navigate.

The first test, landingToGameFragmentTest() works perfectly!

The second test launches a fragment that depends on safe args to be passed to it. Aside from that, there is no difference I can perceive in how they are executed.

// Declare navController at top level so it can be accessed from any test in the class
private lateinit var navController: TestNavHostController

// Use Generic type with fragment as upper bound to pass any type of FragmentScenario
private fun <T : Fragment> init(scenario: FragmentScenario<T>) {

    // Create a test navController
    navController = TestNavHostController(
        ApplicationProvider.getApplicationContext()
    )

    scenario.onFragment { fragment ->
        // Link navController to its graph
        navController.setGraph(R.navigation.nav_graph)
        // Link fragment to its navController
        Navigation.setViewNavController(fragment.requireView(), navController)
    }
}

@Test
fun landingToGameFragmentTest() {

    init(launchFragmentInContainer<LandingFragment>(themeResId = THEME))

    // Click button to navigate to GameFragment
    onView(withId(R.id.button_start_game))
        .perform(click())

    assertEquals("Navigation to GameFragment failed",
        R.id.gameFragment,
        navController.currentDestination?.id)
}

@Test
fun gameToLandingFragmentTest() {

    init(launchFragmentInContainer<GameFragment>(themeResId = THEME, fragmentArgs = Bundle()))

    onView(withId(R.id.button_end_game))
        .perform(click())

    assertEquals("Navigation to LandingFragment failed",
        R.id.landingFragment,
        navController.currentDestination?.id)
}

I set a default value for its arguments, but I still got a null arguments exception until I passed it an empty bundle. Now the fragment will launch but it appears not to be able to navigate to any other fragment!

I could find no similar questions on SO, and the stack output is beyond me.

After the init(launchFragmentInContainer()) line I stepped through the code and found this throwing an illegalArgumentException:

public static int parseInt(@RecentlyNonNull String s, int radix) throws NumberFormatException {
    throw new RuntimeException("Stub!");
}

Which then leads to getNavigator(), which passes the name "fragment".
However the only navigators are "navigation" and "test", of which I believe it should be test.
The illegalStateException is then thrown:

/**
 * Retrieves a registered [Navigator] by name.
 *
 * @param name name of the navigator to return
 * @return the registered navigator with the given name
 *
 * @throws IllegalStateException if the Navigator has not been added
 *
 * @see NavigatorProvider.addNavigator
 */
@Suppress("UNCHECKED_CAST")
@CallSuper
public open fun <T : Navigator<*>> getNavigator(name: String): T {
    require(validateName(name)) { "navigator name cannot be an empty string" }
    val navigator = _navigators[name]
        ?: throw IllegalStateException(
            "Could not find Navigator with name \"$name\". You must call " +
                "NavController.addNavigator() for each navigation type."
        )
    return navigator as T
}

Finally navigate() is called on onView(withId(R.id.button_end_game)) generating:

I likely don't have to keep this test in this specific instance. However, I certainly will need to know how to launch a Fragment in isolation (that depends on safe args) in the future.

Thank you for your consideration!!

Body:
You have two entirely separate problems here:

Your Fragment needs to have arguments passed to it.

Arguments are passed to your fragment via the fragmentArgs parameter of launchFragmentInContainer as explained in the Fragment testing guide.

Each Args class, such as your LandingFragmentArgs has a constructor that lets you construct that Args class directly. You can then use the toBundle() method to make the Bundle that you pass to launchFragmentInContainer:

val args = GameFragmentArgs(/* pass in your required args here */)
val bundle = args.toBundle()
init(launchFragmentInContainer<GameFragment>(fragmentArgs = bundle, themeResId = THEME))

Your NavController needs to have its state set to the GameFragment destination

Your TestNavHostController doesn't know that your test needs to start on the destination associated with GameFragment - by default, it will just be on the startDestination of your graph (where whatever action you are trying to trigger doesn't exist).

As per the Test Navigation documentation:

TestNavHostController provides a setCurrentDestination method that allows you to set the current destination so that the NavController is in the correct state before your test begins.

So you need to make sure you call setCurrentDestination after your init call:

val args = GameFragmentArgs(/* pass in your required args here */)
val bundle = args.toBundle()
val scenario = launchFragmentInContainer<GameFragment>(fragmentArgs = bundle, themeResId = THEME)
init(scenario)

// Ensure that the NavController is set to the expected destination
// using the ID from your navigation graph associated with GameFragment
scenario.onFragment {
  // Just like setGraph(), this needs to be called on the main thread
  navController.setCurrentDestination(R.id.game_fragment, bundle)
}


问:
Design movable view : Android
How to design movable (Drag/Drop) view in android.

In my case

There will be four rows and all will be movable.

User can arrange all 4 rows like 1234, 2341, 3421, 1243...... any combination of 1234.

So how can it will be?

All rows are layouts.

答:
Have a members declared for holding the currently dragging bitmap, view, and current dragging x and y coords.

Override the onTouch of the parent view.

In ACTION_DOWN event get the drawing cache(Bitmap) of the dragging view by calling getDrawingCache() and set to the drag bitmap member. Invalidate the layout (so that onDraw gets called, where you draw the currently dragging view). Hide the current dragging view.

In ACTION_MOVE draw (invalidate) the dragging view bitmap at current x and y coordinates.

In ACTION_UP destroy the dragging bitmap. calculate the current drop location and add the current dragging view to that position in the layout. UnHide the current dragging view. Reset the dragging members.

In onDraw of parent layout.

```<code>canvas.save();
canvas.drawBitmap(mDragBmp, mDragX, mDragY);
canvas.restore();
</code>```

Title: Design movable view : Android

Body:
Have a members declared for holding the currently dragging bitmap, view, and current dragging x and y coords.

Override the onTouch of the parent view.

In ACTION_DOWN event get the drawing cache(Bitmap) of the dragging view by calling getDrawingCache() and set to the drag bitmap member. Invalidate the layout (so that onDraw gets called, where you draw the currently dragging view). Hide the current dragging view.

In ACTION_MOVE draw (invalidate) the dragging view bitmap at current x and y coordinates.

In ACTION_UP destroy the dragging bitmap. calculate the current drop location and add the current dragging view to that position in the layout. UnHide the current dragging view. Reset the dragging members.

In onDraw of parent layout.

canvas.save();
canvas.drawBitmap(mDragBmp, mDragX, mDragY);
canvas.restore();


问:
unrecognized command line option '-Zc:__cplusplus' and unrecognized command line option '-permissive-'
I am trying to run and debug Qt6 widget application in clion.
I tried the things that u would get when do a simple search but no success.
Recently my friend told my to do this :
Add "C:\Qt\Tools\mingw810_64" to toolchain environment like this :

now when I create a Qt widget project like this :

I get these error :

```<code>Problems were encountered while collecting compiler information:
  g++.exe: error: unrecognized command line option '-Zc:__cplusplus'
  g++.exe: error: unrecognized command line option '-permissive-'; did you mean '-fpermissive'?
</code>```

What should I do now ?
Why doesn't it recognize these options ?
I cannot change g++.exe file (or can I?) What can do about it?

I have been struggling to manage to run and debugg Qt6 project on clion the past few weeks.

God bless anyone who help me to do this.
Please Help!

答:
The problem is that you use MSVC-build of Qt and not the MinGW one. Update your CMakeLists.txt file:

set(CMAKE_PREFIX_PATH $ENV{QTDIR})

the environment variable QTDIR is set to Qt MinGW path (e.g. D:\Qt\6.2.3\mingw_64).

Don't forget to add the corresponding directory bin (%QTDIR%\bin) to the path environment variable.

Body:
I am trying to run and debug Qt6 widget application in clion.
I tried the things that u would get when do a simple search but no success.
Recently my friend told my to do this :
Add "C:\Qt\Tools\mingw810_64" to toolchain environment like this :

now when I create a Qt widget project like this :

I get these error :

Problems were encountered while collecting compiler information:
  g++.exe: error: unrecognized command line option '-Zc:__cplusplus'
  g++.exe: error: unrecognized command line option '-permissive-'; did you mean '-fpermissive'?

What should I do now ?
Why doesn't it recognize these options ?
I cannot change g++.exe file (or can I?) What can do about it?

I have been struggling to manage to run and debugg Qt6 project on clion the past few weeks.

God bless anyone who help me to do this.
Please Help!


问:
Sending and Receiving arrays via Sockets
Is it possible to send an array through UDP Sockets using Python? I am using Python 2.5 and trying to send a simple array but it's not working. It can send the array successfully but when I try to print it with an item of the array the program crashes. I'm not sure what the error is as I take the precaution of converting the data into an array but it's not working. Hope I explained the problem as clearly as possible. I would appreciate the help!</p>

```<code># Client program

from socket import *
import numpy
from array import*

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)

def_msg = "===Enter message to send to server===";
print "\n",def_msg
a = array('i',[1,3,2])
# Send messages
while (1):
    data = raw_input('yes or now')
    if data!= "yes":
        break
    else:
        if(UDPSock.sendto(a,addr)):
            print "Sending message"

# Close socket
UDPSock.close()

# Server program

from socket import *

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while 1:
    data,addr = UDPSock.recvfrom(buf)
    L = eval(data)
    if not data:
        print "Client has exited!"
        break
    else:
        print "\nReceived message '", L[1],"'"

# Close socket
UDPSock.close()
</code>```

答: I would personally use tostring and fromstring since the built-in serialization methods are many times faster and pickle may not support NaN, Inf and other undefined values.

Body:
Is it possible to send an array through UDP Sockets using Python? I am using Python 2.5 and trying to send a simple array but it's not working. It can send the array successfully but when I try to print it with an item of the array the program crashes. I'm not sure what the error is as I take the precaution of converting the data into an array but it's not working. Hope I explained the problem as clearly as possible. I would appreciate the help!

# Client program

from socket import *
import numpy
from array import*

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)

def_msg = "===Enter message to send to server===";
print "\n",def_msg
a = array('i',[1,3,2])
# Send messages
while (1):
    data = raw_input('yes or now')
    if data!= "yes":
        break
    else:
        if(UDPSock.sendto(a,addr)):
            print "Sending message"

# Close socket
UDPSock.close()

# Server program

from socket import *

# Set the socket parameters
host = "localhost"
port = 21567
buf = 4096
addr = (host,port)

# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while 1:
    data,addr = UDPSock.recvfrom(buf)
    L = eval(data)
    if not data:
        print "Client has exited!"
        break
    else:
        print "\nReceived message '", L[1],"'"

# Close socket
UDPSock.close()


答:
We can also provide a type for the function zeros. If we execute the follwing code.

```<code>using Measurements
A = zeros(Measurement,5,1) # provide the type Measurement here
for n = 1:5
  local B = rand() ± rand()
  local C = rand() ± rand()
  global A[n,1] = sqrt.((B-C).^2)
end
</code>```

yields to

```<code>5×1 Matrix{Measurement}:
 0.068 ± 1.1
  0.63 ± 0.95
  0.88 ± 0.43
  0.73 ± 0.17
 0.069 ± 0.95
</code>```

We can also be more strict if we provide the types inside the measurements by providing using A = zeros(Measurement{Float64},5,1) which yields a 5×1 Matrix{Measurement{Float64}}.

It also works if we provide the type Real yielding in a 5x1 Matrix of type Real.

Title: In JULIA how do I preallocate a Measurements.jl vector with n rows?

Body:
We can also provide a type for the function zeros. If we execute the follwing code.

using Measurements
A = zeros(Measurement,5,1) # provide the type Measurement here
for n = 1:5
  local B = rand() ± rand()
  local C = rand() ± rand()
  global A[n,1] = sqrt.((B-C).^2)
end

yields to

5×1 Matrix{Measurement}:
 0.068 ± 1.1
  0.63 ± 0.95
  0.88 ± 0.43
  0.73 ± 0.17
 0.069 ± 0.95

We can also be more strict if we provide the types inside the measurements by providing using A = zeros(Measurement{Float64},5,1) which yields a 5×1 Matrix{Measurement{Float64}}.

It also works if we provide the type Real yielding in a 5x1 Matrix of type Real.