答:
As you are already using a pipe, you don't need to specify data = shann inside select().

Removing that part from the code inside select() and using group_by() and summarise() (so you use only functions that are part of dplyr) the following returns your expected output.

```<code>Shann_in_corn <-
  shann %>%
  select(Crop_Rot, Herb, Year, Rot, Rep, value, Crop) %>%
  filter(Crop == "corn") %>%
  group_by(Rot, Herb, Year) %>%
  summarise(N = length(value),
            mean = mean(value),
            sd = sd(value),
            se = sd / sqrt(N))
</code>```

Title: unrecognized columns in data frame with a column that was originally a separate string

Body:
I'm trying to calculate the means and se of the value column in this attached dataframe with this code

library(plyr); library(dplyr)
library(tidyverse); library(ggplot2)

Shann_in_corn <-shann%>%
  select_(data=shann, Crop_Rot, Herb, Year, Rot, Rep, value, Crop)%>%
  filter(Crop=="corn")%>%
  ddply(.(Rot, Herb, Year), summarise,
        N=length(value),
        mean=mean(value),
        sd=sd(value),
        se=sd/sqrt(N))

structure(list(Plot = c(11L, 11L, 13L, 13L, 18L, 18L, 23L, 23L,
24L, 24L, 28L, 28L, 34L, 34L, 37L, 37L, 38L, 38L, 44L, 44L, 46L,
46L, 48L, 48L, 14L, 14L, 16L, 16L, 19L, 19L, 25L, 25L, 27L, 27L,
29L, 29L, 32L, 32L, 33L, 33L, 35L, 35L, 42L, 42L, 45L, 45L, 49L,
49L, 12L, 12L, 15L, 15L, 17L, 17L, 21L, 21L, 22L, 22L, 26L, 26L,
31L, 31L, 36L, 36L, 39L, 39L, 41L, 41L, 43L, 43L, 47L, 47L, 11L,
11L, 13L, 13L, 18L, 18L, 23L, 23L, 24L, 24L, 28L, 28L, 34L, 34L,
37L, 37L, 38L, 38L, 44L, 44L, 46L, 46L, 48L, 48L, 12L, 12L, 15L,
15L, 19L, 19L, 21L, 21L, 26L, 26L, 27L, 27L, 31L, 31L, 35L, 35L,
36L, 36L, 43L, 43L, 45L, 45L, 47L, 47L, 17L, 17L, 16L, 16L, 14L,
14L, 22L, 22L, 29L, 29L, 25L, 25L, 39L, 39L, 33L, 33L, 32L, 32L,
49L, 49L, 41L, 41L, 42L, 42L, 12L, 12L, 15L, 15L, 19L, 19L, 21L,
21L, 26L, 26L, 27L, 27L, 31L, 31L, 35L, 35L, 36L, 36L, 43L, 43L,
45L, 45L, 47L, 47L, 13L, 13L, 16L, 16L, 17L, 17L, 22L, 22L, 24L,
24L, 25L, 25L, 33L, 33L, 34L, 34L, 39L, 39L, 41L, 41L, 42L, 42L,
44L, 44L, 11L, 11L, 14L, 14L, 18L, 18L, 23L, 23L, 28L, 28L, 29L,
29L, 32L, 32L, 37L, 37L, 38L, 38L, 46L, 46L, 48L, 48L, 49L, 49L
), Side = structure(c(2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L), .Label = c("E",
"W"), class = "factor"), Crop = structure(c(2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 3L, 3L, 3L,
3L, 1L, 1L, 3L, 3L, 3L, 3L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 1L,
1L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 1L, 1L, 3L, 3L, 3L, 3L, 1L, 1L, 3L, 3L, 3L, 3L, 1L,
1L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 3L, 3L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 1L, 1L, 3L,
3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 1L, 1L), .Label = c("alfalfa", "corn", "oat", "soybean"), class = "factor"),
    Crop_Rot = structure(c(3L, 3L, 2L, 2L, 4L, 4L, 3L, 3L, 2L,
    2L, 4L, 4L, 2L, 2L, 4L, 4L, 3L, 3L, 2L, 2L, 4L, 4L, 3L, 3L,
    9L, 9L, 8L, 8L, 7L, 7L, 8L, 8L, 7L, 7L, 9L, 9L, 9L, 9L, 8L,
    8L, 7L, 7L, 8L, 8L, 7L, 7L, 9L, 9L, 1L, 1L, 5L, 5L, 6L, 6L,
    1L, 1L, 6L, 6L, 5L, 5L, 1L, 1L, 5L, 5L, 6L, 6L, 6L, 6L, 1L,
    1L, 5L, 5L, 8L, 8L, 7L, 7L, 9L, 9L, 8L, 8L, 7L, 7L, 9L, 9L,
    7L, 7L, 9L, 9L, 8L, 8L, 7L, 7L, 9L, 9L, 8L, 8L, 4L, 4L, 3L,
    3L, 2L, 2L, 4L, 4L, 3L, 3L, 2L, 2L, 4L, 4L, 2L, 2L, 3L, 3L,
    4L, 4L, 2L, 2L, 3L, 3L, 1L, 1L, 5L, 5L, 6L, 6L, 1L, 1L, 6L,
    6L, 5L, 5L, 1L, 1L, 5L, 5L, 6L, 6L, 6L, 6L, 1L, 1L, 5L, 5L,
    9L, 9L, 8L, 8L, 7L, 7L, 9L, 9L, 8L, 8L, 7L, 7L, 9L, 9L, 7L,
    7L, 8L, 8L, 9L, 9L, 7L, 7L, 8L, 8L, 2L, 2L, 3L, 3L, 4L, 4L,
    4L, 4L, 2L, 2L, 3L, 3L, 3L, 3L, 2L, 2L, 4L, 4L, 4L, 4L, 3L,
    3L, 2L, 2L, 5L, 5L, 1L, 1L, 6L, 6L, 5L, 5L, 6L, 6L, 1L, 1L,
    1L, 1L, 6L, 6L, 5L, 5L, 6L, 6L, 5L, 5L, 1L, 1L), .Label = c("A4",
    "C2", "C3", "C4", "O3", "O4", "S2", "S3", "S4"), class = "factor"),
    Herb = structure(c(1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L,
    1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L,
    1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L,
    2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L,
    1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L,
    1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L,
    1L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L,
    2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L,
    2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L,
    2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L,
    2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L,
    2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L,
    2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L,
    1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L,
    1L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L), .Label = c("conv",
    "low"), class = "factor"), kg.ha = c(0.27, 160.1, 12.84,
    0.05, 22.5, 0.22, 0.12, 25.05, 3.48, 1.21, 4.85, 21.97, 2.67,
    0.23, 9, 0.28, 0.28, 21.04, 0.23, 45.91, 64.39, 2.51, 130.57,
    54.86, 54.36, 0.96, 2.19, 177.1, 16.3, 1.86, 221.35, 0.62,
    0.33, 85.59, 0.93, 60.6, 0, 0, 7.23, 0.05, 1.09, 0.03, 0.48,
    21.3, 0.61, 0, 0.07, 0.25, 61, 54.25, 100.35, 75.55, 221.8,
    162.75, 46.45, 84.1, 208.1, 372.35, 107, 65.35, 108.05, 58.5,
    141, 67.65, 420, 379.4, 318.35, 248.8, 258.4, 102.35, 62.05,
    141.05, 2.92, 1499.22, 40.77, 61.97, 57.98, 15.76, 2.94,
    1991.43, 160.85, 1.14, 1.61, 79.03, 77.5, 31.12, 0.52, 0.38,
    23.08, 396.81, 5.58, 192.42, 29.6, 70.43, 282.39, 40.34,
    2.36, 38.78, 20.98, 156.06, 20.25, 0.81, 221.5, 39.32, 10.11,
    57.23, 0.14, 37.93, 7.39, 5.22, 2.81, 0.59, 31.59, 2.14,
    10.6, 110.94, 4.37, 0.73, 1.11, 40.43, 85.6, 74.5, 85.85,
    84.25, 1115.45, 815.5, 123.45, 41.75, 913.15, 1021.25, 230.25,
    98.1, 152.6, 274.1, 48.8, 16.9, 648.6, 766.75, 658.95, 606.35,
    334.1, 199, 117.9, 60.65, 5.27, 40.09, 1.46, 143.89, 333.49,
    67.11, 276.13, 59.22, 8.67, 134.32, 38.21, 128.22, 177.3,
    129.8, 1.59, 107.34, 518.77, 0.4, 31.1, 14.76, 98.15, 0.01,
    28.66, 63.05, 4.44, 29.81, 12.73, 282.57, 1.33, 0.2, 0.45,
    55.73, 88.82, 8.27, 203.12, 1.57, 68.78, 0.78, 166.13, 2.22,
    211.03, 1.59, 10.14, 17.9, 2.05, 309.57, 6.32, 19.35, 55,
    144.9, 111, 110.5, 1149.15, 1256.1, 45.7, 32.05, 1227.85,
    1418.1, 104.95, 132.15, 115.4, 134.85, 1369, 795.15, 50.8,
    86.65, 869.1, 1121.25, 129.7, 116.5, 111.05, 176.05), Rep = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L,
    3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
    2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L,
    4L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L,
    3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L,
    4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
    2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 1L,
    1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L,
    3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
    2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L,
    4L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L,
    3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L,
    4L, 4L, 4L, 4L, 4L), .Label = c("rep1", "rep2", "rep3", "rep4"
    ), class = "factor"), Rot = structure(c(2L, 2L, 1L, 1L, 3L,
    3L, 2L, 2L, 1L, 1L, 3L, 3L, 1L, 1L, 3L, 3L, 2L, 2L, 1L, 1L,
    3L, 3L, 2L, 2L, 3L, 3L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 3L,
    3L, 3L, 3L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 3L, 3L, 3L, 3L,
    2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 3L, 3L, 2L, 2L, 3L,
    3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 1L, 1L, 3L, 3L, 2L, 2L,
    1L, 1L, 3L, 3L, 1L, 1L, 3L, 3L, 2L, 2L, 1L, 1L, 3L, 3L, 2L,
    2L, 3L, 3L, 2L, 2L, 1L, 1L, 3L, 3L, 2L, 2L, 1L, 1L, 3L, 3L,
    1L, 1L, 2L, 2L, 3L, 3L, 1L, 1L, 2L, 2L, 3L, 3L, 2L, 2L, 3L,
    3L, 3L, 3L, 3L, 3L, 2L, 2L, 3L, 3L, 2L, 2L, 3L, 3L, 3L, 3L,
    3L, 3L, 2L, 2L, 3L, 3L, 2L, 2L, 1L, 1L, 3L, 3L, 2L, 2L, 1L,
    1L, 3L, 3L, 1L, 1L, 2L, 2L, 3L, 3L, 1L, 1L, 2L, 2L, 1L, 1L,
    2L, 2L, 3L, 3L, 3L, 3L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 3L,
    3L, 3L, 3L, 2L, 2L, 1L, 1L, 2L, 2L, 3L, 3L, 3L, 3L, 2L, 2L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 3L, 3L, 2L, 2L, 3L,
    3L), .Label = c("2-year", "3-year", "4-year"), class = "factor"),
    Year = c(2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L,
    2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L,
    2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L,
    2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L,
    2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L,
    2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L,
    2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L,
    2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L,
    2014L, 2014L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L,
    2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L,
    2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L,
    2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L,
    2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L,
    2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L,
    2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L,
    2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L, 2015L,
    2015L, 2015L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L,
    2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L,
    2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L,
    2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L,
    2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L,
    2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L,
    2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L,
    2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L,
    2016L, 2016L), H_R = structure(c(2L, 5L, 4L, 1L, 6L, 3L,
    2L, 5L, 4L, 1L, 3L, 6L, 4L, 1L, 6L, 3L, 2L, 5L, 1L, 4L, 6L,
    3L, 5L, 2L, 6L, 3L, 2L, 5L, 4L, 1L, 5L, 2L, 1L, 4L, 3L, 6L,
    6L, 3L, 5L, 2L, 4L, 1L, 2L, 5L, 4L, 1L, 6L, 3L, 3L, 6L, 2L,
    5L, 6L, 3L, 6L, 3L, 3L, 6L, 2L, 5L, 3L, 6L, 5L, 2L, 6L, 3L,
    6L, 3L, 3L, 6L, 2L, 5L, 2L, 5L, 4L, 1L, 6L, 3L, 2L, 5L, 4L,
    1L, 3L, 6L, 4L, 1L, 6L, 3L, 2L, 5L, 1L, 4L, 6L, 3L, 5L, 2L,
    3L, 6L, 2L, 5L, 4L, 1L, 6L, 3L, 2L, 5L, 1L, 4L, 3L, 6L, 4L,
    1L, 5L, 2L, 3L, 6L, 4L, 1L, 2L, 5L, 6L, 3L, 2L, 5L, 6L, 3L,
    3L, 6L, 3L, 6L, 5L, 2L, 6L, 3L, 5L, 2L, 6L, 3L, 6L, 3L, 3L,
    6L, 2L, 5L, 3L, 6L, 2L, 5L, 4L, 1L, 6L, 3L, 2L, 5L, 1L, 4L,
    3L, 6L, 4L, 1L, 5L, 2L, 3L, 6L, 4L, 1L, 2L, 5L, 4L, 1L, 2L,
    5L, 6L, 3L, 3L, 6L, 4L, 1L, 5L, 2L, 5L, 2L, 4L, 1L, 6L, 3L,
    6L, 3L, 2L, 5L, 1L, 4L, 2L, 5L, 6L, 3L, 6L, 3L, 2L, 5L, 3L,
    6L, 3L, 6L, 6L, 3L, 6L, 3L, 2L, 5L, 6L, 3L, 5L, 2L, 6L, 3L
    ), .Label = c("conv - 2-year", "conv - 3-year", "conv - 4-year",
    "low - 2-year", "low - 3-year", "low - 4-year"), class = "factor"),
    H_R_Y = structure(c(4L, 13L, 10L, 1L, 16L, 7L, 4L, 13L, 10L,
    1L, 7L, 16L, 10L, 1L, 16L, 7L, 4L, 13L, 1L, 10L, 16L, 7L,
    13L, 4L, 16L, 7L, 4L, 13L, 10L, 1L, 13L, 4L, 1L, 10L, 7L,
    16L, 16L, 7L, 13L, 4L, 10L, 1L, 4L, 13L, 10L, 1L, 16L, 7L,
    7L, 16L, 4L, 13L, 16L, 7L, 16L, 7L, 7L, 16L, 4L, 13L, 7L,
    16L, 13L, 4L, 16L, 7L, 16L, 7L, 7L, 16L, 4L, 13L, 5L, 14L,
    11L, 2L, 17L, 8L, 5L, 14L, 11L, 2L, 8L, 17L, 11L, 2L, 17L,
    8L, 5L, 14L, 2L, 11L, 17L, 8L, 14L, 5L, 8L, 17L, 5L, 14L,
    11L, 2L, 17L, 8L, 5L, 14L, 2L, 11L, 8L, 17L, 11L, 2L, 14L,
    5L, 8L, 17L, 11L, 2L, 5L, 14L, 17L, 8L, 5L, 14L, 17L, 8L,
    8L, 17L, 8L, 17L, 14L, 5L, 17L, 8L, 14L, 5L, 17L, 8L, 17L,
    8L, 8L, 17L, 5L, 14L, 9L, 18L, 6L, 15L, 12L, 3L, 18L, 9L,
    6L, 15L, 3L, 12L, 9L, 18L, 12L, 3L, 15L, 6L, 9L, 18L, 12L,
    3L, 6L, 15L, 12L, 3L, 6L, 15L, 18L, 9L, 9L, 18L, 12L, 3L,
    15L, 6L, 15L, 6L, 12L, 3L, 18L, 9L, 18L, 9L, 6L, 15L, 3L,
    12L, 6L, 15L, 18L, 9L, 18L, 9L, 6L, 15L, 9L, 18L, 9L, 18L,
    18L, 9L, 18L, 9L, 6L, 15L, 18L, 9L, 15L, 6L, 18L, 9L), .Label = c("conv - 2-year - 2014",
    "conv - 2-year - 2015", "conv - 2-year - 2016", "conv - 3-year - 2014",
    "conv - 3-year - 2015", "conv - 3-year - 2016", "conv - 4-year - 2014",
    "conv - 4-year - 2015", "conv - 4-year - 2016", "low - 2-year - 2014",
    "low - 2-year - 2015", "low - 2-year - 2016", "low - 3-year - 2014",
    "low - 3-year - 2015", "low - 3-year - 2016", "low - 4-year - 2014",
    "low - 4-year - 2015", "low - 4-year - 2016"), class = "factor"),
    value = c(1.33217904021012, 0.819956535422326, 0.878672353634429,
    0, 1.1676557909425, 0, 1.09657543425772, 0.367756349734082,
    0.469982787668461, 0.782685621948506, 0.802344573460662,
    0.791263673777807, 0.947133570514693, 0.876005765643174,
    1.20426433468651, 0.876886231229689, 0.967488251410454, 0.889846458201103,
    1.12525740546882, 0.754443002292786, 0.900825263623699, 0.892923886768289,
    0.984370001654131, 0.00617142643859088, 0.614763436435568,
    0.456194410390592, 0.836757269954837, 0.502339303931386,
    1.3132238923146, 0.692318801445808, 0.933920405167339, 0.45351246445217,
    0.813278221693497, 1.13250222818216, 0.205306663281312, 0,
    0, 0, 1.23155253902969, 0, 0, 0, 0.275463905473084, 0.705372055960579,
    0.122532269126764, 0, 0, 1.38185016510291, 0.650955925769806,
    1.28403627835479, 1.53476589108218, 1.30710631497493, 1.18382662133399,
    0.94550740378002, 0.763942021696703, 1.34997100108116, 0.925498006822258,
    1.54344786550954, 1.69789271171287, 1.15927452074438, 1.66647156565305,
    1.57126887627203, 1.13159072037213, 1.1981206060242, 1.1098887443971,
    1.46626401787677, 0.888995736052264, 0.958143649371997, 1.04071715969811,
    0.177331997763176, 1.19359793017755, 1.15816293846566, 0.660757564761445,
    0.0774370521861312, 0.750130172619606, 0.747999160052096,
    0.368336516079475, 0.170031685852736, 1.34901080584795, 0.137505320397941,
    0.760703849217967, 0.47392376581098, 0.933924671593655, 1.1122565131489,
    0.0827765852948456, 0.388096169582111, 1.13595490455717,
    1.15084015515628, 0.734433609106438, 0.630832207014761, 1.01479884050622,
    0.835542396388489, 0.495330682158045, 0.163500407042419,
    1.41636948337545, 0.892045151226941, 0.716084081938979, 0.939628908971045,
    0.906298297573505, 0.644949387369248, 0.997848789634358,
    0.204704845662185, 0.752232637168957, 0.976079199103695,
    1.11555585274383, 1.25058193384111, 1.06137359241618, 1.06741907524703,
    0.865407811273895, 0.781079213937551, 0.444838021569131,
    0.194560072364346, 1.23354961570624, 0.861153436736848, 1.30024301119404,
    0.731788183353856, 0.961392748554241, 0.408370796814235,
    0.758478149152187, 1.48316598811438, 1.19322505267225, 1.03915306062704,
    0.844221639816559, 0.816313894600871, 1.51914393559838, 1.29824399835146,
    1.46391529366185, 1.17052001372219, 1.23911462099854, 1.57773688476882,
    1.18000790476928, 0.545584952266138, 0.960394676512275, 0.908928148155333,
    0.891344858432891, 0.674885394662156, 1.35750771431797, 1.2394182437946,
    1.44221693894728, 1.17709146848065, 0.893904973695966, 0.690859530265238,
    0.905280194700945, 0.723077643196438, 1.12763579437248, 0.553661671365167,
    0.996127300734851, 1.06586343226575, 1.46851526392938, 0.995660475041175,
    0.743043195150989, 0.642562205054313, 0.900920573378399,
    1.0017090896094, 0.358013969719735, 0.748025241066811, 0.509760219944739,
    0.859630378008836, 1.29477364211756, 0.809710431130026, 0.677111916099108,
    0.681941302111554, 1.06267087728613, 0.8610734335126, 0.771315681848917,
    0.0313473294043128, 1.26458989555429, 0.404100340088279,
    1.42168721241312, 1.03717479360106, 0.715994525966914, 0.890391761636334,
    0.264235080879163, 0.733165115027097, 0.0456079066044284,
    1.05008975930881, 0.371317060575211, 0.970011896311126, 0.699615296292664,
    1.07007075427315, 1.2027650888541, 0.425328293373262, 1.20842703880595,
    0.213554478767209, 1.00243714224353, 0.668606096680166, 1.14366520332059,
    0.132179411089192, 0.0906569219857244, 0.282572181768919,
    0.967232529394703, 1.29289933452463, 0.902298373878638, 1.31186714164,
    1.15788467850277, 0.555727833344835, 2.15076429424205, 1.55095532718784,
    0.692430589698105, 0.823320736098347, 1.84109402581388, 1.65730901322916,
    0.91456410716298, 0.941366626170298, 0.513589722402605, 0.302259733773694,
    1.60636378966858, 1.46488638777445, 0.916062014515128, 0.955711747961097,
    1.40012264704695, 1.48718022397172, 1.02329832697661, 1.37396763939004,
    1.03430312858319, 0.832535188647181)), .Names = c("Plot",
"Side", "Crop", "Crop_Rot", "Herb", "kg.ha", "Rep", "Rot", "Year",
"H_R", "H_R_Y", "value"), class = "data.frame", row.names = c(NA,
-216L))

R gave me an error Error in as.lazy_dots(list(...)) : object 'Crop_Rot' not found

Changing select() to select_()gave a different error
 Error: All select() inputs must resolve to integer column positions.
The following do not:
*  shann

The column value was a string so after I consolidate the dataframe (column 1 to 11) and value, I used shann <- as.data.frame(shann). Please see where I might change my code. Any help is greatly appreciated.

Body:
As you are already using a pipe, you don't need to specify data = shann inside select().

Removing that part from the code inside select() and using group_by() and summarise() (so you use only functions that are part of dplyr) the following returns your expected output.

Shann_in_corn <-
  shann %>%
  select(Crop_Rot, Herb, Year, Rot, Rep, value, Crop) %>%
  filter(Crop == "corn") %>%
  group_by(Rot, Herb, Year) %>%
  summarise(N = length(value),
            mean = mean(value),
            sd = sd(value),
            se = sd / sqrt(N))


来源: stackexchange

问:
Converting foreach loop to for loop
I'm really new to Java, and was wondering if someone could help me convert the following to foreach loops into for loops?

Assuming expression is a collection of items:

```<code>for(Type x: expression){
   ...
   for(Type y: x.expression){
     .....
    }
}
</code>```

答:
expression needs to be some kind of collection of items. The for (Type item : items) loop just iterates over all of them.

To manually loop over the collection you just need the length of the collection and can use:

```<code>for (int i = 0; i < collection.size(); i++) { // or .length() if it is an array
  Type item = collection.get(i); // or collection[i] if it is an array
}
</code>```

Type needs to be the type of the items in the collection.

ContentLicense: CC BY-SA 3.0

Title: Converting foreach loop to for loop

Body:
I'm really new to Java, and was wondering if someone could help me convert the following to foreach loops into for loops?

Assuming expression is a collection of items:

for(Type x: expression){
   ...
   for(Type y: x.expression){
     .....
    }
}

Body:
expression needs to be some kind of collection of items. The for (Type item : items) loop just iterates over all of them.

To manually loop over the collection you just need the length of the collection and can use:

for (int i = 0; i < collection.size(); i++) { // or .length() if it is an array
  Type item = collection.get(i); // or collection[i] if it is an array
}

Type needs to be the type of the items in the collection.


问:
Color scale with conditional formatting in Google Spreadsheet
I need a color scale on a row or column in Google Spreadsheet, like the one provided by Microsoft Office Excel conditional formatting with color scale:

I couldn't find a Google Script Gallery Script that can do exactly this job. Setting conditional formatting manually for all possible values is not a solution.

My abilities are limited to write a proper script. Therefore I came up with this pseudo code:

```<code>colorRangeFormatting(cellRange, minColorHex, maxColorHex)
{
  float cellValueMax = getHighestValue(cellRange);
  float cellValueMin = getLowestValue(cellRange);
  int cellCount = range.length;
  int colorValueMax = maxColorHex.toInt();
  int colorValueMin = minColorHex.toInt();

  int colorSize = colorValueMax - colorValueMin;
  cellValueSize = cellValueMax - celLValueMin;

  int colorIncrement = (colorSize/cellValueSize).Round();
  int[] colorGradients = colorGradients[colorSize];

  foreach(int color in colorGradients)
  {
    color = colorValueMin + colorIncrement;
    colorIncrement = colorIncrement + colorIncrement;
  }

  int i = 0;
  foreach(Cell c in cellRange)
  {
    c.setBackgroundColor(colorGradients[i].ToHex());
    i++;
  }
}
</code>```

Is there any way to do it natively?

or are there any google app scripts that do this (which I overlooked)?

or is someone willing to help me bring my pseudo-code to a proper
google app script for spreadsheet?

Thanks

答:
@Underlines shows only a single colour for the example but Sheets can achieve:

when applying the options as shown.

Body:
I need a color scale on a row or column in Google Spreadsheet, like the one provided by Microsoft Office Excel conditional formatting with color scale:

I couldn't find a Google Script Gallery Script that can do exactly this job. Setting conditional formatting manually for all possible values is not a solution.

My abilities are limited to write a proper script. Therefore I came up with this pseudo code:

colorRangeFormatting(cellRange, minColorHex, maxColorHex)
{
  float cellValueMax = getHighestValue(cellRange);
  float cellValueMin = getLowestValue(cellRange);
  int cellCount = range.length;
  int colorValueMax = maxColorHex.toInt();
  int colorValueMin = minColorHex.toInt();

  int colorSize = colorValueMax - colorValueMin;
  cellValueSize = cellValueMax - celLValueMin;

  int colorIncrement = (colorSize/cellValueSize).Round();
  int[] colorGradients = colorGradients[colorSize];

  foreach(int color in colorGradients)
  {
    color = colorValueMin + colorIncrement;
    colorIncrement = colorIncrement + colorIncrement;
  }

  int i = 0;
  foreach(Cell c in cellRange)
  {
    c.setBackgroundColor(colorGradients[i].ToHex());
    i++;
  }
}

Is there any way to do it natively?

or are there any google app scripts that do this (which I overlooked)?

or is someone willing to help me bring my pseudo-code to a proper
google app script for spreadsheet?

Thanks


问:
disabling one of the options in WTForms SelectField
What is the simplest way to assign 'disabled' html attribute to one of the options in SelectField in WTForms?

This is my previous code

```<code><select class="form-control" name="division" data-error="Required!" required>
     <option value="default" disabled selected>Select something</option>
     <option value="option1">Option 1</option>
     <option value="option2">Option 2</option>
 </select>
</code>```

As you can see I would like to set 'disabled' only to first option.

My code for this task is:

```<code>next(form.division.__iter__())(**{'disabled':'true'})
</code>```

And using print function in console I can see the proper output:

```<code><option disabled="true" selected value="default">Select something</option>
</code>```

The line is working, but somehow this output is not passed to the template.
Instead this is what's passed:

```<code><option selected value="default">Select something</option>
</code>```

Please someone make it clear.

答:
When you disable the field the values are no longer passed. What you might want to do is pass the variable by using read only instead of disabled. Here's how do to it with jquery :

```<code>$('#id_of_option').prop('readonly', true);
</code>```

Also what I've done is set choices in Wtforms where

```<code>choices = [('', 'please select an option'), ('1', 'option 1'),  ('2', 'option 2')]
</code>```

and this way a user has to select a value.

Body:
What is the simplest way to assign 'disabled' html attribute to one of the options in SelectField in WTForms?

This is my previous code

<select class="form-control" name="division" data-error="Required!" required>
     <option value="default" disabled selected>Select something</option>
     <option value="option1">Option 1</option>
     <option value="option2">Option 2</option>
 </select>

As you can see I would like to set 'disabled' only to first option.

My code for this task is:

next(form.division.__iter__())(**{'disabled':'true'})

And using print function in console I can see the proper output:

<option disabled="true" selected value="default">Select something</option>

The line is working, but somehow this output is not passed to the template.
Instead this is what's passed:

<option selected value="default">Select something</option>

Please someone make it clear.

Body:
When you disable the field the values are no longer passed. What you might want to do is pass the variable by using read only instead of disabled. Here's how do to it with jquery :

$('#id_of_option').prop('readonly', true);

Also what I've done is set choices in Wtforms where

choices = [('', 'please select an option'), ('1', 'option 1'),  ('2', 'option 2')]

and this way a user has to select a value.


问:
Why aren't Swift classes hashable by default?
Classes have an identity and their hashValue could easily be their address in the memory. Why isn't it so? </p>

答:
Because it's simply not very useful to have hashValue based on identity.

Here's an example:

Say I'm combining two sets of data from two different sources and checking for duplicates. A common way to do that is to add both to a Set. These objects will most certainly have unique identities (i.e. different addresses). If that implied they also had unique hashValues, then none of the duplicates will be detected.

The whole reason using a Set for reduplication works in the first place is because hashValue implies a definition for what a duplicate is. Your proposal would break this.

ContentLicense: CC BY-SA 4.0


问:
Need help writing simple callback function for Webtask
I am trying to make a webtask function of a node app I have working locally.  Webtask provides a template, which has a context (ctx) and a callback (cb) as the two arguments:

```<code>module.exports = function(ctx, cb) {
  cb(null, { hello: ctx.data.name || 'Anonymous' });
};
</code>```

I have semi-working code that looks like this:

```<code>const PDFParser = require('pdf2json@1.1.7')
const request = require('request')

module.exports = function(ctx, cb) {

  const pdfParser = new PDFParser();
  const pdfUrl = ctx.body.data.url;
  const pdfPipe = request({url: pdfUrl, encoding:null}).pipe(pdfParser);
  const data = []; //define empty array for response data

  pdfPipe.on("pdfParser_dataError", err => console.error(err) );
  pdfPipe.on("pdfParser_dataReady", pdf => {
    data.push(pdfParser.getAllFieldsTypes()); //push data into array
    console.log("data", data); //log the result
  });

  cb(null, data );
};
</code>```

I need to send the updated "data" to the callback function, but cannot figure out how.  I am currently getting back an empty array (the initial const data = []), but my console.log("data", data) returns the desired result.

答:
In order to fix your code, what you need to do is to invoke the callback when the on (emitter) is invoked:</p>

```<code>const request = require('request')

module.exports = function(ctx, cb) {

  const pdfParser = new PDFParser();
  const pdfUrl = ctx.body.data.url;
  const pdfPipe = request({url: pdfUrl, encoding:null}).pipe(pdfParser);
  const data = []; //define empty array for response data

  pdfPipe.on("pdfParser_dataError", err => console.error(err) );
  pdfPipe.on("pdfParser_dataReady", pdf => {
    data.push(pdfParser.getAllFieldsTypes()); //push data into array
    console.log("data", data); //log the result
    cb(null, data );
  });

};
</code>```

Body:
I am trying to make a webtask function of a node app I have working locally.  Webtask provides a template, which has a context (ctx) and a callback (cb) as the two arguments:

module.exports = function(ctx, cb) {
  cb(null, { hello: ctx.data.name || 'Anonymous' });
};

I have semi-working code that looks like this:

const PDFParser = require('pdf2json@1.1.7')
const request = require('request')

module.exports = function(ctx, cb) {

  const pdfParser = new PDFParser();
  const pdfUrl = ctx.body.data.url;
  const pdfPipe = request({url: pdfUrl, encoding:null}).pipe(pdfParser);
  const data = []; //define empty array for response data

  pdfPipe.on("pdfParser_dataError", err => console.error(err) );
  pdfPipe.on("pdfParser_dataReady", pdf => {
    data.push(pdfParser.getAllFieldsTypes()); //push data into array
    console.log("data", data); //log the result
  });

  cb(null, data );
};

I need to send the updated "data" to the callback function, but cannot figure out how.  I am currently getting back an empty array (the initial const data = []), but my console.log("data", data) returns the desired result.

Body:
In order to fix your code, what you need to do is to invoke the callback when the on (emitter) is invoked:

const request = require('request')

module.exports = function(ctx, cb) {

  const pdfParser = new PDFParser();
  const pdfUrl = ctx.body.data.url;
  const pdfPipe = request({url: pdfUrl, encoding:null}).pipe(pdfParser);
  const data = []; //define empty array for response data

  pdfPipe.on("pdfParser_dataError", err => console.error(err) );
  pdfPipe.on("pdfParser_dataReady", pdf => {
    data.push(pdfParser.getAllFieldsTypes()); //push data into array
    console.log("data", data); //log the result
    cb(null, data );
  });

};


问:
Import mxnet error in python windows10
I installed mxnet in python in windows.

```<code>>>> import mxnet
</code>```

There is a mistake.

Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "d:\Anaconda2\lib\site-packages\mxnet-0.7.0-    py2.7.egg\mxnet\__init__.py", line 7, in <module>
    from .base import MXNetError
     File "d:\Anaconda2\lib\site-packages\mxnet-0.7.0-py2.7.egg\mxnet\base.py", line 43, in <module>
      _LIB = _load_lib()
     File "d:\Anaconda2\lib\site-packages\mxnet-0.7.0-py2.7.egg\mxnet\base.py", line 35, in _load_lib
     lib = ctypes.cdll.LoadLibrary(lib_path[0])
     File "d:\Anaconda2\lib\ctypes\__init__.py", line 440, in LoadLibrary
    return self._dlltype(name)
     File "d:\Anaconda2\lib\ctypes\__init__.py", line 362, in __init__
    self._handle = _dlopen(self._name, mode)
    WindowsError: [Error 126]

I  have reinstalled mxnet and anaconda2 many times but it is still wrong.I made mxnet install successfully once 5 months ago.
I used Dependency Walker to see what lost,but there are too many to find files.I don't know where to find these DLL files.

I want to know which step i do wrong.

答:
I had the same issue, and it got solved by using anaconda prompt:

python

import mxnet

Title: Import mxnet error in python windows10

Body:
I installed mxnet in python in windows.

>>> import mxnet

There is a mistake.

Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "d:\Anaconda2\lib\site-packages\mxnet-0.7.0-    py2.7.egg\mxnet\__init__.py", line 7, in <module>
    from .base import MXNetError
     File "d:\Anaconda2\lib\site-packages\mxnet-0.7.0-py2.7.egg\mxnet\base.py", line 43, in <module>
      _LIB = _load_lib()
     File "d:\Anaconda2\lib\site-packages\mxnet-0.7.0-py2.7.egg\mxnet\base.py", line 35, in _load_lib
     lib = ctypes.cdll.LoadLibrary(lib_path[0])
     File "d:\Anaconda2\lib\ctypes\__init__.py", line 440, in LoadLibrary
    return self._dlltype(name)
     File "d:\Anaconda2\lib\ctypes\__init__.py", line 362, in __init__
    self._handle = _dlopen(self._name, mode)
    WindowsError: [Error 126]

I  have reinstalled mxnet and anaconda2 many times but it is still wrong.I made mxnet install successfully once 5 months ago.
I used Dependency Walker to see what lost,but there are too many to find files.I don't know where to find these DLL files.

I want to know which step i do wrong.


问:
Executing wait-for-it.sh in python Docker container
I have a Python docker container that needs to wait until another container (postgres server) finishes setup.  I tried the standard wait-for-it.sh but several commands weren't included. I tried a basic sleep (again in an sh file) but now it's reporting exec: 300: not found when trying to finally execute the command I'm waiting on.

How do I get around this (preferably without changing the image, or having to extend an image.)

I know I could also just run a Python script, but ideally I'd like to use wait-for-it.sh to wait for the server to turn up rather than just sleep.

Dockerfile (for stuffer):

```<code> FROM python:2.7.13

 ADD ./stuff/bin /usr/local/bin/
 ADD ./stuff /usr/local/stuff
 WORKDIR /usr/local/bin

 COPY requirements.txt /opt/updater/requirements.txt
 COPY internal_requirements.txt /opt/stuff/internal_requirements.txt

 RUN pip install -r /opt/stuff/requirements.txt
 RUN pip install -r /opt/stuff/other_requirements.txt
</code>```

docker-compose.yml:

```<code> version: '3'
 services:
   local_db:
     build: ./local_db
     ports:
     - "localhost:5432:5432"

   stuffer:
     build: ./
     depends_on:
     - local_db
     command: ["./wait-for-postgres.sh", "-t", "300", "localhost:5432", "--", "python", "./stuffing.py", "--file", "./afile"]
</code>```

Script I want to use (but can't because no psql or exec):

```<code> #!/bin/bash
 # wait-for-postgres.sh

 set -e

 host="$1"
 shift
 cmd="$@"

 until psql -h "$host" -U "postgres" -c '\l'; do >&2 echo "Postgres is unavailable - sleeping"
   sleep 1
 done

 >&2 echo "Postgres is up - executing command"
 exec $cmd
</code>```

答:
I made an example so you can see it working:

https://github.com/nitzap/wait-for-postgres

On the other hand also you can have errors inside the execution of the script to validate that the service is working. You should not refer as localhost .... because that is within the contexts of containers, if you want to point to another container has to be through the name of the service.

Body:
I have a Python docker container that needs to wait until another container (postgres server) finishes setup.  I tried the standard wait-for-it.sh but several commands weren't included. I tried a basic sleep (again in an sh file) but now it's reporting exec: 300: not found when trying to finally execute the command I'm waiting on.

How do I get around this (preferably without changing the image, or having to extend an image.)

I know I could also just run a Python script, but ideally I'd like to use wait-for-it.sh to wait for the server to turn up rather than just sleep.

Dockerfile (for stuffer):

 FROM python:2.7.13

 ADD ./stuff/bin /usr/local/bin/
 ADD ./stuff /usr/local/stuff
 WORKDIR /usr/local/bin

 COPY requirements.txt /opt/updater/requirements.txt
 COPY internal_requirements.txt /opt/stuff/internal_requirements.txt

 RUN pip install -r /opt/stuff/requirements.txt
 RUN pip install -r /opt/stuff/other_requirements.txt

docker-compose.yml:

 version: '3'
 services:
   local_db:
     build: ./local_db
     ports:
     - "localhost:5432:5432"

   stuffer:
     build: ./
     depends_on:
     - local_db
     command: ["./wait-for-postgres.sh", "-t", "300", "localhost:5432", "--", "python", "./stuffing.py", "--file", "./afile"]

Script I want to use (but can't because no psql or exec):

 #!/bin/bash
 # wait-for-postgres.sh

 set -e

 host="$1"
 shift
 cmd="$@"

 until psql -h "$host" -U "postgres" -c '\l'; do >&2 echo "Postgres is unavailable - sleeping"
   sleep 1
 done

 >&2 echo "Postgres is up - executing command"
 exec $cmd


问:
Conditional statements with too many ifelse statements
I have the following data:

```<code>my.list<-list(a=c(55,17,18,18,18,21),
b=c(11,17,17,17,22,18,22),
c=c(55,17,22,22,22,22,22,21,30))

x<-c(1,1,1,1,2,2,3,3,3,3,3,3,3,3,3)

set.seed(1)

my.function <- function(x) {

ifelse(x == 1,sample(my.list$a,replace = T),
ifelse(x == 2,sample(my.list$b,replace = T),
ifelse(x == 3,sample(my.list$c,replace = T)

)))
}

p<-sapply(x, my.function)
</code>```

In the "real" dataset I have much more ifelse-statements than shown above and the code is too long.

Is there a smarter solution so I don't need to write so many ifelse-statements? Every ifelse-statement is related to a unique list as above with different lengths that I draw samples from.

答:
Edited

To avoid the oddities of ifelse() that @thelatemail pointed out and to avoid reliance on the global environment, I'd propose

```<code>my.list<-list(a=c(55,17,18,18,18,21), b=c(11,17,17,17,22,18,22), c=c(55,17,22,22,22,22,22,21,30))

x<-c(1,1,1,1,2,2,3,3,3,3,3,3,3,3,3)

set.seed(1)

my.function <- function(x, list) {
  sample(list[[x]], replace = T)
}

p<-sapply(x, my.function, list=my.list)
</code>```

Body:
I have the following data:

my.list<-list(a=c(55,17,18,18,18,21),
b=c(11,17,17,17,22,18,22),
c=c(55,17,22,22,22,22,22,21,30))

x<-c(1,1,1,1,2,2,3,3,3,3,3,3,3,3,3)

set.seed(1)

my.function <- function(x) {

ifelse(x == 1,sample(my.list$a,replace = T),
ifelse(x == 2,sample(my.list$b,replace = T),
ifelse(x == 3,sample(my.list$c,replace = T)

)))
}

p<-sapply(x, my.function)

In the "real" dataset I have much more ifelse-statements than shown above and the code is too long.

Is there a smarter solution so I don't need to write so many ifelse-statements? Every ifelse-statement is related to a unique list as above with different lengths that I draw samples from.

Body:
Edited

To avoid the oddities of ifelse() that @thelatemail pointed out and to avoid reliance on the global environment, I'd propose

my.list<-list(a=c(55,17,18,18,18,21), b=c(11,17,17,17,22,18,22), c=c(55,17,22,22,22,22,22,21,30))

x<-c(1,1,1,1,2,2,3,3,3,3,3,3,3,3,3)

set.seed(1)

my.function <- function(x, list) {
  sample(list[[x]], replace = T)
}

p<-sapply(x, my.function, list=my.list)


问:
Selectively disable readthedocs syntax highlighting
I have an RST file for which I do not want any syntax highlighting.  It contains multiple literal blocks and a highlight directive at the top of the file to try to disable syntax highlights:

```<code>.. highlight:: none

::

  Text that happens to contain words like list, None, etc.

::

  Another literal block with words like list, None, etc.
</code>```

Some other RST files in the project use syntax highlighting with directives like this:

```<code>.. highlight:: bash
</code>```

When I build the docs with sphinx on my workstation, sphinx correctly highlights syntax where enabled and disables syntax highlights where it is disabled.  However, when built on readthedocs website there is unwanted Python syntax highlighting within the literal blocks in the RST file containing .. highlight:: none.  Words like "None" and "list" are highlighted.

How can I selectively disable syntax highlighting in this RST file while keeping the syntax highlights elsewhere?

答:
You use two highlighting directives in direct succession, .. highlight:: none followed immediately by ::. The former gets overridden by the latter which applies the latter language's syntax highlighting.

:: uses the default language configured for syntax highlighting, usually Python3.

I would not use two directives in succession.

I would use only one directive, followed by the code I want to highlight.

As far as which syntax to use, you can use text which is just plain old text, none, or make up something that is not one of the Pygments lexers, like moosehair. See Showing code examples for more information.

```<code>.. code-block:: text

    Plain old text
</code>```

Or if you set in your conf.py, highlight_language = 'none', you can use :::

```<code>::

    Plain old text
</code>```

Body:
I have an RST file for which I do not want any syntax highlighting.  It contains multiple literal blocks and a highlight directive at the top of the file to try to disable syntax highlights:

.. highlight:: none

::

  Text that happens to contain words like list, None, etc.

::

  Another literal block with words like list, None, etc.

Some other RST files in the project use syntax highlighting with directives like this:

.. highlight:: bash

When I build the docs with sphinx on my workstation, sphinx correctly highlights syntax where enabled and disables syntax highlights where it is disabled.  However, when built on readthedocs website there is unwanted Python syntax highlighting within the literal blocks in the RST file containing .. highlight:: none.  Words like "None" and "list" are highlighted.

How can I selectively disable syntax highlighting in this RST file while keeping the syntax highlights elsewhere?

Body:
You use two highlighting directives in direct succession, .. highlight:: none followed immediately by ::. The former gets overridden by the latter which applies the latter language's syntax highlighting.

:: uses the default language configured for syntax highlighting, usually Python3.

I would not use two directives in succession.

I would use only one directive, followed by the code I want to highlight.

As far as which syntax to use, you can use text which is just plain old text, none, or make up something that is not one of the Pygments lexers, like moosehair. See Showing code examples for more information.

.. code-block:: text

    Plain old text

Or if you set in your conf.py, highlight_language = 'none', you can use :::

::

    Plain old text


问:
How to print a window in pdf file instead of xps file
when I use the function window.print() to print the content of my html page, It generates me an xps file but I would like it to generate an pdf file.

Can you help me ?

答: You don't have to generate it, just use  http://pdfcrowd.com/#convert_by_input paste your code and you are done!</p>


问:
Getting data in order with Jsoup
I'm trying to get data from html in order from a web. Html code looks like:

First Text

     Written by excedent

quote message

Second Text

Third Text

```

What I want to do is create an Android layout scraping html, but I need to preserve the order of the elements. In this case:

TextView => First Text

TextView => Quote Message

TextView => Second Text

ImageView => img

TextView => Third Text

The problem comes when I try to get html values in order, using JSoup I get a String with "First Text Second Text Third Text" with Element.ownText, an then img at the end, resulting:

TextView => First Text Second Text Third Text

TextView => Quote Message

ImageView => img

What can I do to get that data in order?

Thanks in advance

答:
Try this.

```<code>    String html = ""
        + "<div class=\"text\">"
        + "    First Text"
        + "    <br>"
        + "    <br>"
        + "    <div style=\"margin:20px; margin-top:5px; \">"
        + "    <table cellpadding=\"5\">"
        + "        <tbody><tr>"
        + "            <td class=\"alt2\">"
        + "                <div>"
        + "                    Written by <b>excedent</b>"
        + "                </div>"
        + "                <div style=\"font-style:italic\">quote message</div>"
        + "            </td>"
        + "            </tr></tbody>"
        + "    </table>"
        + "    </div>Second Text<br>"
        + "        <br>"
        + "        <img class=\"img\" src=\"https://developer.android.com/_static/images/android/touchicon-180.png\"><br>"
        + "        <br>"
        + "        Third Text"
        + "    </div>";
    Document doc = Jsoup.parse(html);
    List<String> rootTexts = doc.select("div.text").first().textNodes().stream()
        .map(node -> node.text().trim())
        .filter(s -> !s.isEmpty())
        .collect(Collectors.toList());
    System.out.println(rootTexts);
</code>```

OUTPUT:

```<code>[First Text, Second Text, Third Text]
</code>```

Title: Getting data in order with Jsoup

Body:
I'm trying to get data from html in order from a web. Html code looks like:

First Text

     Written by excedent

quote message

Second Text

Third Text

What I want to do is create an Android layout scraping html, but I need to preserve the order of the elements. In this case:

TextView => First Text

TextView => Quote Message

TextView => Second Text

ImageView => img

TextView => Third Text

The problem comes when I try to get html values in order, using JSoup I get a String with "First Text Second Text Third Text" with Element.ownText, an then img at the end, resulting:

TextView => First Text Second Text Third Text

TextView => Quote Message

ImageView => img

What can I do to get that data in order?

Thanks in advance

Body:
Try this.

    String html = ""
        + "<div class=\"text\">"
        + "    First Text"
        + "    <br>"
        + "    <br>"
        + "    <div style=\"margin:20px; margin-top:5px; \">"
        + "    <table cellpadding=\"5\">"
        + "        <tbody><tr>"
        + "            <td class=\"alt2\">"
        + "                <div>"
        + "                    Written by <b>excedent</b>"
        + "                </div>"
        + "                <div style=\"font-style:italic\">quote message</div>"
        + "            </td>"
        + "            </tr></tbody>"
        + "    </table>"
        + "    </div>Second Text<br>"
        + "        <br>"
        + "        <img class=\"img\" src=\"https://developer.android.com/_static/images/android/touchicon-180.png\"><br>"
        + "        <br>"
        + "        Third Text"
        + "    </div>";
    Document doc = Jsoup.parse(html);
    List<String> rootTexts = doc.select("div.text").first().textNodes().stream()
        .map(node -> node.text().trim())
        .filter(s -> !s.isEmpty())
        .collect(Collectors.toList());
    System.out.println(rootTexts);

OUTPUT:

[First Text, Second Text, Third Text]


问:
How does scope work with try and except blocks in python?
So I am a bit confused about the scoping of variables with try and except blocks. How come my code allows me to use the variables outside of the try block and even the while loop for that matter even though I have not assigned them globally.

```<code>while True:
        try:
            width = int(input("Please enter the width of your floor plan:\n   "))
            height = int(input("Please enter the height of your floor plan:\n   "))
        except:
            print("You have entered and invalid character. Please enter characters only. Press enter to continue\n")
        else:
            print("Success!")
            break
print(width)
print(height)
</code>```

Again I am able to print the variables even if they are defined within a try block which itself is within a while loop. How are they not local?

答:
You need something stronger than try to open a new scope, such as def or class.  Your code has scoping rules similar to this version:

```<code>while True:

    width = int(input("Please enter the width of your floor plan:\n   "))
    height = int(input("Please enter the height of your floor plan:\n   "))
    if width <= 0 or height <= 0:
        print("You have entered and invalid character. Please enter characters only. Press enter to continue\n")
    else:
        print("Success!")
        break

print(width)
print(height)
</code>```

I assume that you're familiar with this scoping.

Body:
So I am a bit confused about the scoping of variables with try and except blocks. How come my code allows me to use the variables outside of the try block and even the while loop for that matter even though I have not assigned them globally.

while True:
        try:
            width = int(input("Please enter the width of your floor plan:\n   "))
            height = int(input("Please enter the height of your floor plan:\n   "))
        except:
            print("You have entered and invalid character. Please enter characters only. Press enter to continue\n")
        else:
            print("Success!")
            break
print(width)
print(height)

Again I am able to print the variables even if they are defined within a try block which itself is within a while loop. How are they not local?

Body:
You need something stronger than try to open a new scope, such as def or class.  Your code has scoping rules similar to this version:

while True:

    width = int(input("Please enter the width of your floor plan:\n   "))
    height = int(input("Please enter the height of your floor plan:\n   "))
    if width <= 0 or height <= 0:
        print("You have entered and invalid character. Please enter characters only. Press enter to continue\n")
    else:
        print("Success!")
        break

print(width)
print(height)

I assume that you're familiar with this scoping.


问:
Making ellipsis to work in a LI
I've been cracking my head here for several hours and I can't seem to find the answer to the issue.

How can I make a LI respect the size of it's parents and correctly use the ellipsis?
Situation is as follows:

```<code><?PHP .... code code code ..?>
    <TABLE>
     <TR>
      <TD width=50%> <!-- other TD's with more data exist -->
       <DIV> <!-- Below this line is from another dynamically created file -->
        <TABLE WIDTH=100%>
         <TBODY>
          <TR>
           <TD> <!-- other TDs even with more data exist -->
            <DIV>
             <OL><?PHP code that echoes the following LIs from a DB ?>
               <LI> <!-- I want this LIs to fill text up to assigned width and then use ellipsis -->
              </LI>
             </OL>
           </DIV>
         </TD>
    ....
</code>```

If I use the CSS:

```<code>  list-style-position:inside;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
</code>```

It will make all the contents of the LI go pass the screen, one loooong line.
If I don't use this CSS, then the LI gets nicely multi-lined (which of course I don't want).

If I change the "WIDTH" of the parent DIV or the parent OL, then the text inside the LI gets cut off but still fills with whitespaces all the space that the full text would occupy.

Update: here is the jsfiddle: https://jsfiddle.net/Fotofobia/kgrccckc/

Any suggestions?

Thanks in advance.

答:
Add the below code update. By doing this you will create a kind of a stage, and all the content that "live" inside of it with now see the nowrap and overflow rules. I guess this will work. Please tell me something!! :)</p>

```<code>list-style-position:inside;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;

// Add this to your code
width: 100%;
table-layout: fixed;
</code>```

Title: Making ellipsis to work in a LI

Body:
I've been cracking my head here for several hours and I can't seem to find the answer to the issue.

How can I make a LI respect the size of it's parents and correctly use the ellipsis?
Situation is as follows:

<?PHP .... code code code ..?>

<?PHP code that echoes the following LIs from a DB ?>

    ....

If I use the CSS:

  list-style-position:inside;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

It will make all the contents of the LI go pass the screen, one loooong line.
If I don't use this CSS, then the LI gets nicely multi-lined (which of course I don't want).

If I change the "WIDTH" of the parent DIV or the parent OL, then the text inside the LI gets cut off but still fills with whitespaces all the space that the full text would occupy.

Update: here is the jsfiddle: https://jsfiddle.net/Fotofobia/kgrccckc/

Any suggestions?

Thanks in advance.

Body:
Add the below code update. By doing this you will create a kind of a stage, and all the content that "live" inside of it with now see the nowrap and overflow rules. I guess this will work. Please tell me something!! :)

list-style-position:inside;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;

// Add this to your code
width: 100%;
table-layout: fixed;


问:
Dynamic variable names for an array in bash
I have an array called "loop".

For each element in "loop" I want to create an array whose name contains the text of the current element.

I then want to loop through each new array and print every element from each array.

This post seems to have a good solution for variables but I do not know how to adapt it to work for arrays.

My Script

```<code>#!/bin/bash
loop=(
first
second
third
)

for word in "${loop[@]}"
do
        declare "${word}_holder=( hello world )"
        var="${word}_holder"
        echo "$var"
        for i in "${!var}[@]"
        do
                echo "$i"
        done
done
</code>```

Current output

```<code>first_holder
( hello world )[@]
second_holder
( hello world )[@]
third_holder
( hello world )[@]
</code>```

Desired Output

```<code>first_holder
hello
world
second_holder
hello
world
third_holder
hello
world
</code>```

答:
It ain't pretty, but it's a start:</p>

```<code>#!/bin/bash
loop=(
first
second
third
)

for word in "${loop[@]}"
do
    var=${word}_holder
    eval "declare -a ${var}"
    eval "${var}=( Hello World )"
    eval 'nEntries=${#'${var}'[@]}'
    echo ${var}
    for (( ii=0; ii<$nEntries; ii++ )); do
       cmd='echo ${'${var}'['$ii']}'
       eval ${cmd}
    done
done
</code>```

Body:
I have an array called "loop".

For each element in "loop" I want to create an array whose name contains the text of the current element.

I then want to loop through each new array and print every element from each array.

This post seems to have a good solution for variables but I do not know how to adapt it to work for arrays.

My Script

#!/bin/bash
loop=(
first
second
third
)

for word in "${loop[@]}"
do
        declare "${word}_holder=( hello world )"
        var="${word}_holder"
        echo "$var"
        for i in "${!var}[@]"
        do
                echo "$i"
        done
done

Current output

first_holder
( hello world )[@]
second_holder
( hello world )[@]
third_holder
( hello world )[@]

Desired Output

first_holder
hello
world
second_holder
hello
world
third_holder
hello
world

Body:
It ain't pretty, but it's a start:

#!/bin/bash
loop=(
first
second
third
)

for word in "${loop[@]}"
do
    var=${word}_holder
    eval "declare -a ${var}"
    eval "${var}=( Hello World )"
    eval 'nEntries=${#'${var}'[@]}'
    echo ${var}
    for (( ii=0; ii<$nEntries; ii++ )); do
       cmd='echo ${'${var}'['$ii']}'
       eval ${cmd}
    done
done


问:
Connecting to Exchange without AutoDiscover?
I need to set up a custom application at my workplace, to read email subject lines from a specific Exchange Server mailbox, and redirect them based on the content. I wrote the following code to test connectivity:

```<code>using System;
using Microsoft.Exchange.WebServices.Data;

namespace TestEmail
{
    class Program
    {
        static void Main(string[] args)
        {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
            service.UseDefaultCredentials = true;
            //service.Credentials = new WebCredentials("user1@contoso.com", "password");

            service.TraceEnabled = true;
            service.TraceFlags = TraceFlags.All;

            service.AutodiscoverUrl("xxx@yyy.com", RedirectionUrlValidationCallback);

            EmailMessage email = new EmailMessage(service);

            email.ToRecipients.Add("xxx@yyy.com");

            email.Subject = "Test mail";
            email.Body = new MessageBody("Sending the test email");

            email.Send();
        }

        private static bool RedirectionUrlValidationCallback(string redirectionUrl)
        {
            // The default for the validation callback is to reject the URL.
            bool result = false;

            Uri redirectionUri = new Uri(redirectionUrl);

            // Validate the contents of the redirection URL. In this simple validation
            // callback, the redirection URL is considered valid if it is using HTTPS
            // to encrypt the authentication credentials.
            if (redirectionUri.Scheme == "https")
            {
                result = true;
            }
            return result;
        }
    }
  }
}
</code>```

But the workplace security settings disallow exposing autodiscovery endpoints, and I was informed that this setting can't be changed.

Is there any other way for me to connect to the Exchange server, without using AutoDiscover?

This is a follow up to my previous question SSL/TLS error when connecting to Exchange from C#

答:
If you know you EWS URL you can just hardcode the setting and get rid of your Autodiscover code e.g.

Remove

```<code>//service.AutodiscoverUrl("xxx@yyy.com", RedirectionUrlValidationCallback);
</code>```

and use:

```<code>service.Url = new Uri("https://computername.domain.contoso.com/EWS/Exchange.asmx");
</code>```

See also https://msdn.microsoft.com/en-us/library/office/dn509511(v=exchg.150).aspx

Body:
I need to set up a custom application at my workplace, to read email subject lines from a specific Exchange Server mailbox, and redirect them based on the content. I wrote the following code to test connectivity:

using System;
using Microsoft.Exchange.WebServices.Data;

namespace TestEmail
{
    class Program
    {
        static void Main(string[] args)
        {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
            service.UseDefaultCredentials = true;
            //service.Credentials = new WebCredentials("user1@contoso.com", "password");

            service.TraceEnabled = true;
            service.TraceFlags = TraceFlags.All;

            service.AutodiscoverUrl("xxx@yyy.com", RedirectionUrlValidationCallback);

            EmailMessage email = new EmailMessage(service);

            email.ToRecipients.Add("xxx@yyy.com");

            email.Subject = "Test mail";
            email.Body = new MessageBody("Sending the test email");

            email.Send();
        }

        private static bool RedirectionUrlValidationCallback(string redirectionUrl)
        {
            // The default for the validation callback is to reject the URL.
            bool result = false;

            Uri redirectionUri = new Uri(redirectionUrl);

            // Validate the contents of the redirection URL. In this simple validation
            // callback, the redirection URL is considered valid if it is using HTTPS
            // to encrypt the authentication credentials.
            if (redirectionUri.Scheme == "https")
            {
                result = true;
            }
            return result;
        }
    }
  }
}

But the workplace security settings disallow exposing autodiscovery endpoints, and I was informed that this setting can't be changed.

Is there any other way for me to connect to the Exchange server, without using AutoDiscover?

This is a follow up to my previous question SSL/TLS error when connecting to Exchange from C#

Body:
If you know you EWS URL you can just hardcode the setting and get rid of your Autodiscover code e.g.

Remove

//service.AutodiscoverUrl("xxx@yyy.com", RedirectionUrlValidationCallback);

and use:

service.Url = new Uri("https://computername.domain.contoso.com/EWS/Exchange.asmx");

See also https://msdn.microsoft.com/en-us/library/office/dn509511(v=exchg.150).aspx


问:
Get month number from name from other language
If I have a month name in a certain language(let's say Albanian), how do I get the number corresponding to it (in PHP)? Besides the obvious method of making an array with the month names of that language (I'm afraid that's quite vulnerable to spelling mistakes) I presume that you can use setlocale but I can't figure out what to do next. </p>

答:
Take a look at the i18n package. It provides classes and functions for internationalization in php.

http://php-flp.sourceforge.net/getting_started_english.htm#dates

ContentLicense: CC BY-SA 2.5


问:
How can I specify the D3 V4 micro library on CDN?
I want to load a microlibrary with cdn.

・Is there a sample code that works normally somewhere?

▼index.html

```<code><script src="https://d3js.org/d3-scale.v1.js"></script>
</code>```

▼js

```<code>var yScale = d3.scaleLinear()
    .domain([10, 1200])
    .range([0, 500]);
console.log(yScale(1200));
console.log(d3.version);
</code>```

Error

Uncaught TypeError: d3Color.cubehelix is not a function

答:
The API is very clear about this: if you want to reference the microlibraries to use d3.scale, you have to reference all these:

```<code><script src="https://d3js.org/d3-array.v1.min.js"></script>
<script src="https://d3js.org/d3-collection.v1.min.js"></script>
<script src="https://d3js.org/d3-color.v1.min.js"></script>
<script src="https://d3js.org/d3-format.v1.min.js"></script>
<script src="https://d3js.org/d3-interpolate.v1.min.js"></script>
<script src="https://d3js.org/d3-time.v1.min.js"></script>
<script src="https://d3js.org/d3-time-format.v2.min.js"></script>
<script src="https://d3js.org/d3-scale.v1.min.js"></script>
</code>```

Furthermore, the API says:

You can omit d3-time and d3-time-format if you’re not using d3.scaleTime or d3.scaleUtc

Here is a demo:

var yScale = d3.scaleLinear()
  .domain([10, 1200])
  .range([0, 500]);
console.log(yScale(1200));
console.log(d3.version);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3-array.v1.min.js"></script>
<script src="https://d3js.org/d3-collection.v1.min.js"></script>
<script src="https://d3js.org/d3-color.v1.min.js"></script>
<script src="https://d3js.org/d3-format.v1.min.js"></script>
<script src="https://d3js.org/d3-interpolate.v1.min.js"></script>
<script src="https://d3js.org/d3-time.v1.min.js"></script>
<script src="https://d3js.org/d3-time-format.v2.min.js"></script>
<script src="https://d3js.org/d3-scale.v1.min.js"></script></code>```

As you can see, d3.version only works with the default bundle, and will return undefined here.

Thus, an easier solution is just referencing the default bundle. For the minified one:

```<code><script src="https://d3js.org/d3.v4.min.js"></script>
</code>```

And for the non-minified one:

```<code><script src="https://d3js.org/d3.v4.js"></script>
</code>```

Body:
I want to load a microlibrary with cdn.

・Is there a sample code that works normally somewhere?

▼index.html

▼js

var yScale = d3.scaleLinear()
    .domain([10, 1200])
    .range([0, 500]);
console.log(yScale(1200));
console.log(d3.version);

Error

Uncaught TypeError: d3Color.cubehelix is not a function

Body:
The API is very clear about this: if you want to reference the microlibraries to use d3.scale, you have to reference all these:

<script src="https://d3js.org/d3-array.v1.min.js"></script>
<script src="https://d3js.org/d3-collection.v1.min.js"></script>
<script src="https://d3js.org/d3-color.v1.min.js"></script>
<script src="https://d3js.org/d3-format.v1.min.js"></script>
<script src="https://d3js.org/d3-interpolate.v1.min.js"></script>
<script src="https://d3js.org/d3-time.v1.min.js"></script>
<script src="https://d3js.org/d3-time-format.v2.min.js"></script>
<script src="https://d3js.org/d3-scale.v1.min.js"></script>

Furthermore, the API says:

You can omit d3-time and d3-time-format if you’re not using d3.scaleTime or d3.scaleUtc

Here is a demo:

var yScale = d3.scaleLinear()
  .domain([10, 1200])
  .range([0, 500]);
console.log(yScale(1200));
console.log(d3.version);

<script src="https://d3js.org/d3-array.v1.min.js"></script>
<script src="https://d3js.org/d3-collection.v1.min.js"></script>
<script src="https://d3js.org/d3-color.v1.min.js"></script>
<script src="https://d3js.org/d3-format.v1.min.js"></script>
<script src="https://d3js.org/d3-interpolate.v1.min.js"></script>
<script src="https://d3js.org/d3-time.v1.min.js"></script>
<script src="https://d3js.org/d3-time-format.v2.min.js"></script>
<script src="https://d3js.org/d3-scale.v1.min.js"></script>

As you can see, d3.version only works with the default bundle, and will return undefined here.

Thus, an easier solution is just referencing the default bundle. For the minified one:

<script src="https://d3js.org/d3.v4.min.js"></script>

And for the non-minified one:

<script src="https://d3js.org/d3.v4.js"></script>


问:
SharpCompress & LZMA2 7z archive - very slow extraction of specific file. Why? Alternatives?
I have a 7zip archive craeted with LZMA2 compression (compression level: ultra).
The archive contains 1,749 files, which in total originally had a size of 661mb.
The zipped file is 39mb in size.

Now I'm trying to use C# to extract a tiny (~200kb'ish) single file from this archive.

I'm getting the corresponding IArchiveEntry from the IArchive (which works relatively fast),
but then calling IArchiveEntry.WriteToFile(targetPath) takes around 33 seconds! And similarly long if I write to a memory stream instead. (edit: When I'm running this on a 7z LZMA2 archive with compression level = normal, it still takes 9 seconds)

When I'm opening the same archive in the actual 7zip application and extract the same file from there, it takes around 2-3 seconds only.
I suspected it's some sort of multicore (7zip) vs single core (SharpCompress probably?) thing, but I don't notice any CPU usage spike during decompression with 7zip.. maybe its too fast to be noticeable though..

Does anyone know what could be the issue for such slow speeds with SharpCompress? Am I maybe missing some setting or using a wrong factory (ArchiveFactory) ?

If not - is there any C# library out there that might be significantly faster at decompressing this?

For reference, here's a sketch of how I'm using SharpCompress to extract:

```<code>private void Extract()
    {
        using(var archive = GetArchive())
        {
          var entryPath = /* ... path to entry .. */
          var entry = TryGetEntry(archive, entryPath);
          entry.WriteToFile(some_target_path);
        }
    }

    private IArchive GetArchive()
    {
        string path = /* .. path to my .7z file */;
        return ArchiveFactory.Open(path);
    }

    private IArchiveEntry TryGetEntry(IArchive archive, string path)
    {
        path = path.Replace("\\", "/");

        foreach (var entry in archive.Entries)
        {
            if (!entry.IsDirectory)
            {
                if (entry.Key == path)
                    return entry;
            }
        }

        return null;
    }
</code>```

Update: For a temporary solution, I'm now including the 7zr.exe from the 7zip SDK in my application, and run this in a new process to extract a single file, reading the process' output into a binary stream.
This works in around ~3 seconds compared to the ~33seconds with SharpCompress. Works for now, but kind of ugly.. so still curious why SharpCompress seems to be so slow there

答:
This line is the problem

```<code>foreach (var entry in archive.Entries)
</code>```

The problem is described here (ie. If there are 100 files, it decompresses the 1st file 100 times, 2nd file 99 times, and so on)

You need to use reader (forward-only). See the API.

But the sample code there doesn't support 7z.

For 7z you can use archive.ExtractAllEntries(), eg.

```<code>var reader = archive.ExtractAllEntries();
while (reader.MoveToNextEntry())
{
    if (!reader.Entry.IsDirectory)
        reader.WriteEntryToDirectory(extractDir, new ExtractionOptions() { ExtractFullPath = false, Overwrite = true });
}
</code>```

It will be much faster.

Body:
I have a 7zip archive craeted with LZMA2 compression (compression level: ultra).
The archive contains 1,749 files, which in total originally had a size of 661mb.
The zipped file is 39mb in size.

Now I'm trying to use C# to extract a tiny (~200kb'ish) single file from this archive.

I'm getting the corresponding IArchiveEntry from the IArchive (which works relatively fast),
but then calling IArchiveEntry.WriteToFile(targetPath) takes around 33 seconds! And similarly long if I write to a memory stream instead. (edit: When I'm running this on a 7z LZMA2 archive with compression level = normal, it still takes 9 seconds)

When I'm opening the same archive in the actual 7zip application and extract the same file from there, it takes around 2-3 seconds only.
I suspected it's some sort of multicore (7zip) vs single core (SharpCompress probably?) thing, but I don't notice any CPU usage spike during decompression with 7zip.. maybe its too fast to be noticeable though..

Does anyone know what could be the issue for such slow speeds with SharpCompress? Am I maybe missing some setting or using a wrong factory (ArchiveFactory) ?

If not - is there any C# library out there that might be significantly faster at decompressing this?

For reference, here's a sketch of how I'm using SharpCompress to extract:

private void Extract()
    {
        using(var archive = GetArchive())
        {
          var entryPath = /* ... path to entry .. */
          var entry = TryGetEntry(archive, entryPath);
          entry.WriteToFile(some_target_path);
        }
    }

    private IArchive GetArchive()
    {
        string path = /* .. path to my .7z file */;
        return ArchiveFactory.Open(path);
    }

    private IArchiveEntry TryGetEntry(IArchive archive, string path)
    {
        path = path.Replace("\\", "/");

        foreach (var entry in archive.Entries)
        {
            if (!entry.IsDirectory)
            {
                if (entry.Key == path)
                    return entry;
            }
        }

        return null;
    }

Update: For a temporary solution, I'm now including the 7zr.exe from the 7zip SDK in my application, and run this in a new process to extract a single file, reading the process' output into a binary stream.
This works in around ~3 seconds compared to the ~33seconds with SharpCompress. Works for now, but kind of ugly.. so still curious why SharpCompress seems to be so slow there

Body:
This line is the problem

foreach (var entry in archive.Entries)

The problem is described here (ie. If there are 100 files, it decompresses the 1st file 100 times, 2nd file 99 times, and so on)

You need to use reader (forward-only). See the API.

But the sample code there doesn't support 7z.

For 7z you can use archive.ExtractAllEntries(), eg.

var reader = archive.ExtractAllEntries();
while (reader.MoveToNextEntry())
{
    if (!reader.Entry.IsDirectory)
        reader.WriteEntryToDirectory(extractDir, new ExtractionOptions() { ExtractFullPath = false, Overwrite = true });
}

It will be much faster.


问:
Recursive Loop - Parent/Child Tree
I'm trying to recursively loop through and return all child_id's that have the root element of 9.

The structure:

```<code> +-- 9
 |   +-- 8
 |       +-- 17
 |       +-- 33
 |       +-- 18
 |   +-- 22
 |       +-- 11
 |       +-- 4
</code>```

Parent Child Link Table: (table name: elements_children)

```<code>+----+-----------+----------+
| id | parent_id | child_id |
+----+-----------+----------+
|  1 |         9 |        8 |
|  2 |         8 |       17 |
|  3 |         8 |       33 |
|  4 |         8 |       18 |
|  5 |         9 |       22 |
|  6 |        22 |       11 |
|  7 |        22 |        4 |
|  8 |         3 |        5 |
+----+-----------+----------+
</code>```

The Desired Output - [8,17,33,18,22,11,4]

Procedure 1 (getChildren):

```<code>BEGIN

-- CREATE TEMP TABLE
DROP TABLE IF EXISTS total_children;
CREATE TEMPORARY TABLE total_children(
    id INT(11) NOT NULL auto_increment PRIMARY KEY,
    child_id VARCHAR(255)
);

-- CALL TO PROCEDURE 2
CALL getNodes(rootNode);

-- SELECT child_id's FROM the temp table, then drop the table
SELECT child_id FROM total_children;
DROP TABLE total_children;

END
</code>```

Procedure 2 (getNodes):

```<code>BEGIN
-- VARIABLES
DECLARE done BOOLEAN DEFAULT FALSE;
DECLARE childNode VARCHAR(255);

-- CURSOR1
DECLARE cur1 CURSOR FOR SELECT child_id FROM elements_children WHERE parent_id = parentNode;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN cur1;

-- START LOOP
myloop:LOOP
    FETCH cur1 INTO childNode;
    -- CHECK IF DONE IS TRUE
    IF(done) THEN
        LEAVE myloop;
    END IF;
    -- APPEND TO TOTAL
    INSERT INTO total_children(child_id) SELECT childNode;
    -- RECURSIVE
    CALL getNodes(childNode);
END LOOP myloop;
-- END LOOP

-- END CURSOR1
CLOSE cur1;

END
</code>```

I'm getting error: recursion limit exceeded 200

I set the recursion limit to 200 and I know the procedure shouldn't recurse 200 times so there has to be an error in my code that isn't stopping the recursion, I believe something to do with the done variable in the myloop: LOOP.

Question: Why is my procedure generating this recursion error?

答:
I think the following stored procedure will yield the results you are asking for. I setup a table, and populated it with the data from your question:

```<code>DROP TABLE IF EXISTS `parent_child`;

CREATE TABLE `parent_child` (
    `id`            INT(10) UNSIGNED        NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    `parent_id`     INT(10) UNSIGNED        NOT NULL,
    `child_id`      INT(10) UNSIGNED        NOT NULL,
    PRIMARY KEY (`id`),
    KEY `idx_parent_child_parent_id` (`parent_id`)
)
    ENGINE=MyISAM
    AUTO_INCREMENT=1
    DEFAULT CHARSET=utf8
    COLLATE=utf8_unicode_ci
    COMMENT '';

INSERT INTO `parent_child`
(`id`,`parent_id`,`child_id`)
VALUES
('1','9','8'),
('2','8','17'),
('3','8','33'),
('4','8','18'),
('5','9','22'),
('6','22','11'),
('7','22','4'),
('8','3','5');
</code>```

Then I created a procedure to progressively get children until there aren't any left to get.

```<code>DROP PROCEDURE GetChildren;

DELIMITER //

CREATE PROCEDURE GetChildren(root_id INT)
    BEGIN
        SET @list = root_id;
        SET @new_list = root_id;
        SET @maxDepth = 4;
        SET @depth = 0;

        WHILE (@new_list <> "" AND @depth < @maxDepth) DO
            SELECT @new_list as `new_list_before`,@list as `whole_list_before`;
            SET @depth = @depth + 1;
            SET @querystr = CONCAT("SELECT GROUP_CONCAT(`child_id`) as `children` INTO @c FROM `parent_child` WHERE `parent_id` in (?) AND (NOT (`child_id` IN (?)));");
            PREPARE stmt1 FROM @querystr;
            EXECUTE stmt1 USING @new_list,@list;
            IF @c <> "" THEN
                SET @list = CONCAT(@list,",",@c);
            END IF;
            SET @new_list = @c;
            SELECT @new_list as `new_list`,@list as `whole_list`;
            DEALLOCATE PREPARE stmt1;
        END WHILE;

        SELECT @list;
    END //
DELIMITER ;
</code>```

Finally, here's how it would be called for a root id of 9:

```<code>CALL GetChildren(9);
</code>```

This produces:

```<code>@list:
9,8,22,17,33,18
</code>```

For reference, here's one of the selects executed:

```<code>SELECT GROUP_CONCAT(`child_id`) as `children`
FROM `parent_child`
WHERE `parent_id` in (9,8,22) AND (NOT `child_id` IN (9,8,22))
GROUP BY `parent_id`;
</code>```

Title: Recursive Loop - Parent/Child Tree

Body:
I'm trying to recursively loop through and return all child_id's that have the root element of 9.

The structure:

 +-- 9
 |   +-- 8
 |       +-- 17
 |       +-- 33
 |       +-- 18
 |   +-- 22
 |       +-- 11
 |       +-- 4

Parent Child Link Table: (table name: elements_children)

+----+-----------+----------+
| id | parent_id | child_id |
+----+-----------+----------+
|  1 |         9 |        8 |
|  2 |         8 |       17 |
|  3 |         8 |       33 |
|  4 |         8 |       18 |
|  5 |         9 |       22 |
|  6 |        22 |       11 |
|  7 |        22 |        4 |
|  8 |         3 |        5 |
+----+-----------+----------+

The Desired Output - [8,17,33,18,22,11,4]

Procedure 1 (getChildren):

BEGIN

-- CREATE TEMP TABLE
DROP TABLE IF EXISTS total_children;
CREATE TEMPORARY TABLE total_children(
    id INT(11) NOT NULL auto_increment PRIMARY KEY,
    child_id VARCHAR(255)
);

-- CALL TO PROCEDURE 2
CALL getNodes(rootNode);

-- SELECT child_id's FROM the temp table, then drop the table
SELECT child_id FROM total_children;
DROP TABLE total_children;

END

Procedure 2 (getNodes):

BEGIN
-- VARIABLES
DECLARE done BOOLEAN DEFAULT FALSE;
DECLARE childNode VARCHAR(255);

-- CURSOR1
DECLARE cur1 CURSOR FOR SELECT child_id FROM elements_children WHERE parent_id = parentNode;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN cur1;

-- START LOOP
myloop:LOOP
    FETCH cur1 INTO childNode;
    -- CHECK IF DONE IS TRUE
    IF(done) THEN
        LEAVE myloop;
    END IF;
    -- APPEND TO TOTAL
    INSERT INTO total_children(child_id) SELECT childNode;
    -- RECURSIVE
    CALL getNodes(childNode);
END LOOP myloop;
-- END LOOP

-- END CURSOR1
CLOSE cur1;

END

I'm getting error: recursion limit exceeded 200

I set the recursion limit to 200 and I know the procedure shouldn't recurse 200 times so there has to be an error in my code that isn't stopping the recursion, I believe something to do with the done variable in the myloop: LOOP.

Question: Why is my procedure generating this recursion error?

Body:
I think the following stored procedure will yield the results you are asking for. I setup a table, and populated it with the data from your question:

DROP TABLE IF EXISTS `parent_child`;

CREATE TABLE `parent_child` (
    `id`            INT(10) UNSIGNED        NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    `parent_id`     INT(10) UNSIGNED        NOT NULL,
    `child_id`      INT(10) UNSIGNED        NOT NULL,
    PRIMARY KEY (`id`),
    KEY `idx_parent_child_parent_id` (`parent_id`)
)
    ENGINE=MyISAM
    AUTO_INCREMENT=1
    DEFAULT CHARSET=utf8
    COLLATE=utf8_unicode_ci
    COMMENT '';

INSERT INTO `parent_child`
(`id`,`parent_id`,`child_id`)
VALUES
('1','9','8'),
('2','8','17'),
('3','8','33'),
('4','8','18'),
('5','9','22'),
('6','22','11'),
('7','22','4'),
('8','3','5');

Then I created a procedure to progressively get children until there aren't any left to get.

DROP PROCEDURE GetChildren;

DELIMITER //

CREATE PROCEDURE GetChildren(root_id INT)
    BEGIN
        SET @list = root_id;
        SET @new_list = root_id;
        SET @maxDepth = 4;
        SET @depth = 0;

        WHILE (@new_list <> "" AND @depth < @maxDepth) DO
            SELECT @new_list as `new_list_before`,@list as `whole_list_before`;
            SET @depth = @depth + 1;
            SET @querystr = CONCAT("SELECT GROUP_CONCAT(`child_id`) as `children` INTO @c FROM `parent_child` WHERE `parent_id` in (?) AND (NOT (`child_id` IN (?)));");
            PREPARE stmt1 FROM @querystr;
            EXECUTE stmt1 USING @new_list,@list;
            IF @c <> "" THEN
                SET @list = CONCAT(@list,",",@c);
            END IF;
            SET @new_list = @c;
            SELECT @new_list as `new_list`,@list as `whole_list`;
            DEALLOCATE PREPARE stmt1;
        END WHILE;

        SELECT @list;
    END //
DELIMITER ;

Finally, here's how it would be called for a root id of 9:

CALL GetChildren(9);

This produces:

@list:
9,8,22,17,33,18

For reference, here's one of the selects executed:

SELECT GROUP_CONCAT(`child_id`) as `children`
FROM `parent_child`
WHERE `parent_id` in (9,8,22) AND (NOT `child_id` IN (9,8,22))
GROUP BY `parent_id`;


问:
Trigger new apex
I am trying to write a Trigger for before insert event on Account object.

```<code>  trigger DeduplicationAccount on Account (before insert) {
       //Get all the accounts in action in 'insert'
       Account[] inputAccountList = Trigger.NEW;
</code>```

I am trying to get a relative list of accounts in my input list of accounts.
Say for eample, I am trying to get such accounts where the last name = 'XXX' in my trigger new.

So, i am writing like this:
// Here, listOfSurname is containing a list of surname with 'XXX'

```<code>for(Account ac: Trigger.new){
       List<Account> accountDuplicate = [Select ac.rr_First_Name__c, ac.rr_Last_Name__c  From
       Account ac where ac.rr_Last_Name__c IN : listOfSurname];
       System.debug('accountDuplicate: '+ accountDuplicate);
       }
</code>```

But, this list is always coming as 0 though im my input,an account have surname as 'XXX'.

答:
Trigger.New has all the information for the record and we could use that to verify against any condition. I rephrased your query below to check if each account's lastname in Trigger.new is part of the list. </p>

```<code>for(Account ac: Trigger.new){
   for(String s: listOfSurname){
      if (ac.rr_Last_Name__c == s){
         System.debug('accountDuplicate: '+ ac);
         break;
      }
   }
}
</code>```

Title: Trigger new apex

Body:
I am trying to write a Trigger for before insert event on Account object.

  trigger DeduplicationAccount on Account (before insert) {
       //Get all the accounts in action in 'insert'
       Account[] inputAccountList = Trigger.NEW;

I am trying to get a relative list of accounts in my input list of accounts.
Say for eample, I am trying to get such accounts where the last name = 'XXX' in my trigger new.

So, i am writing like this:
// Here, listOfSurname is containing a list of surname with 'XXX'

for(Account ac: Trigger.new){
       List<Account> accountDuplicate = [Select ac.rr_First_Name__c, ac.rr_Last_Name__c  From
       Account ac where ac.rr_Last_Name__c IN : listOfSurname];
       System.debug('accountDuplicate: '+ accountDuplicate);
       }

But, this list is always coming as 0 though im my input,an account have surname as 'XXX'.

Body:
Trigger.New has all the information for the record and we could use that to verify against any condition. I rephrased your query below to check if each account's lastname in Trigger.new is part of the list.

for(Account ac: Trigger.new){
   for(String s: listOfSurname){
      if (ac.rr_Last_Name__c == s){
         System.debug('accountDuplicate: '+ ac);
         break;
      }
   }
}


问:
Is there a way to tell aws-cli to run a command to get a new session token if the current token is expired?
At my work, our AWS authentication is integrated with our corporate sign-sign-on (SSO) system. In other words, when we want to access AWS, we do something that authenticates to our corporate system and then issues an AWS session token. The tokens expire after an hour so every so often an AWS command will fail because of an expired token and then I have to grab a new token and then repeat the command.

This isn't horrible, but being that I'm an engineer, I wrote a "aws" wrapper script that detects if the token is expired and if it is, it can run a configurable command to grab a new token and then execute the given command. Here's the script:

```<code>#!/bin/bash

AWS=${AWS:-"/usr/local/bin/aws"}

if [ -z "$AWS_FORCE_GET_TOKEN" ] && ${AWS} sts get-caller-identity > /dev/null 2>&1; then
    ${AWS} "$@"
else
    CMD=$($AWS configure get get_token_command)
    echo "Error doing \"${AWS} sts get-caller-identity\"; Going to try running \"$CMD\"" > /dev/tty
    if $CMD 1>&2; then
        ${AWS} "$@"
    else
        echo "Failed to renew token with \"$CMD\"" 1>&2
    fi
fi
</code>```

This script seems pretty good, though one limitation is that it only works if the "aws" executable is called. It will not work say if I have a Python program that uses boto3 to interact with AWS.

Now I'm wondering if I missed something built into the AWS tools (botocore perhaps?) that would do this?

I'm a Python programmer so I'd be open to adding it if it's not already there and it's deemed to be a good idea. But I wanted to check first to see if it already exists and if it's a sane thing to do.

答:
Assuming you are using the aws sts get-federation-token CLI to get the token, you could set file with the token expire timestamp and have cron run the script to get new tokens every 20 mins; Compare the timestamp to the current time and update if they're going to expire.

Expiration -> (timestamp)
  The date on which the current credentials expire.

http://docs.aws.amazon.com/cli/latest/reference/sts/get-federation-token.html

Body:
At my work, our AWS authentication is integrated with our corporate sign-sign-on (SSO) system. In other words, when we want to access AWS, we do something that authenticates to our corporate system and then issues an AWS session token. The tokens expire after an hour so every so often an AWS command will fail because of an expired token and then I have to grab a new token and then repeat the command.

This isn't horrible, but being that I'm an engineer, I wrote a "aws" wrapper script that detects if the token is expired and if it is, it can run a configurable command to grab a new token and then execute the given command. Here's the script:

#!/bin/bash

AWS=${AWS:-"/usr/local/bin/aws"}

if [ -z "$AWS_FORCE_GET_TOKEN" ] && ${AWS} sts get-caller-identity > /dev/null 2>&1; then
    ${AWS} "$@"
else
    CMD=$($AWS configure get get_token_command)
    echo "Error doing \"${AWS} sts get-caller-identity\"; Going to try running \"$CMD\"" > /dev/tty
    if $CMD 1>&2; then
        ${AWS} "$@"
    else
        echo "Failed to renew token with \"$CMD\"" 1>&2
    fi
fi

This script seems pretty good, though one limitation is that it only works if the "aws" executable is called. It will not work say if I have a Python program that uses boto3 to interact with AWS.

Now I'm wondering if I missed something built into the AWS tools (botocore perhaps?) that would do this?

I'm a Python programmer so I'd be open to adding it if it's not already there and it's deemed to be a good idea. But I wanted to check first to see if it already exists and if it's a sane thing to do.


问:
Explaining the math behind an algorithm
Given a sorted array of integers a, find such an integer x that the value of

abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[a.length - 1] - x)
is the smallest possible (here abs denotes the absolute value).
If there are several possible answers, output the smallest one.

Example

For a = [2, 4, 7], the output should be
absoluteValuesSumMinimization(a) = 4.

I was able to solve this by brute forcing it but then i came upon this

```<code>function absoluteValuesSumMinimization(A) {
    return A[Math.ceil(A.length/2)-1];
}
</code>```

looking to learn how/why this works.

答:
Let's break it down.

A.length/2 returns half the length, used to find the middle of the array. For even-length arrays, this will be to the right of the middle. For odd-length arrays, it'll be the middle.

Math.ceil(A.length/2) rounds up if necessary, so the middle of an array of 5 would be 2.5 -> 3. This makes the odd-length arrays off by one.

Math.ceil(A.length/2)-1 goes down one index. This corrects off-by-one errors for all the arrays.

All this solution is saying is that in an array of even length, the value you're looking for will always be to the left of the middle. In an array of odd length, it will always be the middle item.

This makes sense intuitively. Subtracting the middle item in the array from each item will always result in the lowest sum. In an even length array, the two center items will always result in an identical sum, so the lowest number will be to the left of the center.

To see this, remove the console.log comment from this brute-force solution and try several arrays:

```<code>function absoluteValuesSumMinimization(ints) {
  const vals = [];

  ints.forEach(int => {
    const sum = ints.reduce((accum, next) => {
      return accum + Math.abs(next  - int);
    }, 0);

    vals.push(sum);
  });

  // console.log(vals);
  const lowest = Math.min(...vals);
  return ints[vals.indexOf(lowest)];
}
</code>```

Title: Explaining the math behind an algorithm

Body:
Given a sorted array of integers a, find such an integer x that the value of

abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[a.length - 1] - x)
is the smallest possible (here abs denotes the absolute value).
If there are several possible answers, output the smallest one.

Example

For a = [2, 4, 7], the output should be
absoluteValuesSumMinimization(a) = 4.

I was able to solve this by brute forcing it but then i came upon this

function absoluteValuesSumMinimization(A) {
    return A[Math.ceil(A.length/2)-1];
}

looking to learn how/why this works.

Body:
Let's break it down.

A.length/2 returns half the length, used to find the middle of the array. For even-length arrays, this will be to the right of the middle. For odd-length arrays, it'll be the middle.

Math.ceil(A.length/2) rounds up if necessary, so the middle of an array of 5 would be 2.5 -> 3. This makes the odd-length arrays off by one.

Math.ceil(A.length/2)-1 goes down one index. This corrects off-by-one errors for all the arrays.

All this solution is saying is that in an array of even length, the value you're looking for will always be to the left of the middle. In an array of odd length, it will always be the middle item.

This makes sense intuitively. Subtracting the middle item in the array from each item will always result in the lowest sum. In an even length array, the two center items will always result in an identical sum, so the lowest number will be to the left of the center.

To see this, remove the console.log comment from this brute-force solution and try several arrays:

function absoluteValuesSumMinimization(ints) {
  const vals = [];

  ints.forEach(int => {
    const sum = ints.reduce((accum, next) => {
      return accum + Math.abs(next  - int);
    }, 0);

    vals.push(sum);
  });

  // console.log(vals);
  const lowest = Math.min(...vals);
  return ints[vals.indexOf(lowest)];
}


问:
Performance issues at extracting 7z file to a directory c#
I'm using SharpCompress library for extracting .7z files but it takes about 35 mins to extract 60mb .7z file. Is this normal or am I doing something wrong in terms of performance? .7z file is compressed in high compress mode and LZMA type. </p>

```<code> using (var archive2 = ArchiveFactory.Open(source))
 {
     foreach (var entry in archive2.Entries)
     {
         if (!entry.IsDirectory)
         {
             entry.WriteToDirectory(destination, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
             }
         }
      }
  }
</code>```

答:
This is an old post, but I just had the same problem.

This line is the problem

```<code>foreach (var entry in archive2.Entries)
</code>```

The problem is described here (ie. If there are 100 files, it decompresses the 1st file 100 times, 2nd file 99 times, and so on)

The solution is to use reader (forward-only). See the API.

But the sample code there doesn't support 7z.

For 7z you can use archive.ExtractAllEntries(), eg.

```<code>using (var archive = ArchiveFactory.Open(movedZipFile))
{
    var reader = archive.ExtractAllEntries();
    while (reader.MoveToNextEntry())
    {
        if (!reader.Entry.IsDirectory)
            reader.WriteEntryToDirectory(extractDir, new ExtractionOptions() { ExtractFullPath = false, Overwrite = true });
    }
}
</code>```

It will be much faster.

Body:
I'm using SharpCompress library for extracting .7z files but it takes about 35 mins to extract 60mb .7z file. Is this normal or am I doing something wrong in terms of performance? .7z file is compressed in high compress mode and LZMA type.

 using (var archive2 = ArchiveFactory.Open(source))
 {
     foreach (var entry in archive2.Entries)
     {
         if (!entry.IsDirectory)
         {
             entry.WriteToDirectory(destination, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
             }
         }
      }
  }

Body:
This is an old post, but I just had the same problem.

This line is the problem

foreach (var entry in archive2.Entries)

The problem is described here (ie. If there are 100 files, it decompresses the 1st file 100 times, 2nd file 99 times, and so on)

The solution is to use reader (forward-only). See the API.

But the sample code there doesn't support 7z.

For 7z you can use archive.ExtractAllEntries(), eg.

using (var archive = ArchiveFactory.Open(movedZipFile))
{
    var reader = archive.ExtractAllEntries();
    while (reader.MoveToNextEntry())
    {
        if (!reader.Entry.IsDirectory)
            reader.WriteEntryToDirectory(extractDir, new ExtractionOptions() { ExtractFullPath = false, Overwrite = true });
    }
}

It will be much faster.