问:
How can Vue router get current route path of lazy-loaded modules on page load?
I have a vue app with router set up like:

```<code>import index from './components/index.vue';
import http404 from './components/http404.vue';

// module lazy-loading
const panda= () => import(/* webpackChunkName: "group-panda" */ "./components/panda/panda.vue");
// ...

export const appRoute = [
  {
    path: "",
    name: "root",
    redirect: '/index'
  },
  {
    path: "/index",
    name: "index",
    component: index
  },
  {
    path: "/panda",
    name: "panda",
    component: panda
  },
  //...
  {
    path: "**",
    name: "http404",
    component: http404
  }
];
</code>```

So the panda module is lazy-loaded. However, when I navigate to panda page, a console.log() of this.$route.path in App.vue's mounted() lifecycle only outputs

"/"

instead of

"/panda"

But index page works well, it shows exactly

"/index"

as expected.

So how can Vue router get current path correctly of a lazy-loaded page, when page is initially loaded? Did I miss something?

Edit:

It can, however, catch the correct path after Webpack hot-reloads. It catches "/" on first visit of panda, but after I change something in source code, webpack-dev-server hot-reloads, then it gets "/panda".

So I guess it has something to do with Vue life-cycle.

答:
Hide Header in some components using the current route path.

get current route path using this.$route.path

```<code><navigation v-if="showNavigation"></navigation>
</code>```
```<code>data() {
    this.$route.path === '/' ? this.showNavigation = false : this.showNavigation = true
}
</code>```

Body:
I have a vue app with router set up like:

import index from './components/index.vue';
import http404 from './components/http404.vue';

// module lazy-loading
const panda= () => import(/* webpackChunkName: "group-panda" */ "./components/panda/panda.vue");
// ...

export const appRoute = [
  {
    path: "",
    name: "root",
    redirect: '/index'
  },
  {
    path: "/index",
    name: "index",
    component: index
  },
  {
    path: "/panda",
    name: "panda",
    component: panda
  },
  //...
  {
    path: "**",
    name: "http404",
    component: http404
  }
];

So the panda module is lazy-loaded. However, when I navigate to panda page, a console.log() of this.$route.path in App.vue's mounted() lifecycle only outputs

"/"

instead of

"/panda"

But index page works well, it shows exactly

"/index"

as expected.

So how can Vue router get current path correctly of a lazy-loaded page, when page is initially loaded? Did I miss something?

Edit:

It can, however, catch the correct path after Webpack hot-reloads. It catches "/" on first visit of panda, but after I change something in source code, webpack-dev-server hot-reloads, then it gets "/panda".

So I guess it has something to do with Vue life-cycle.

Body:
Hide Header in some components using the current route path.

get current route path using this.$route.path

<navigation v-if="showNavigation"></navigation>

data() {
    this.$route.path === '/' ? this.showNavigation = false : this.showNavigation = true
}


来源: stackexchange

答:
In dplyr, you can refer to values in each row by inserting single or range position values in []. For example, the first value of mean column can be obtained by mean[1], the second by mean[2], both by mean[1:2] or mean[c(1, 2)], etc.

If you only have two rows, you can also access the second one by last(mean), the first by first(mean).

When you have a group_by statement before, these indices refer to row indices per each group. In your case you don't need to worry, since summarize automatically drops one grouping level per call - so you essentially end up with a tibble without groups.

However, the best way of doing this would be with just basic vectorized operations. For example, you can calculate the exponents and sum them up for se, while you can just use the diff function for mean.

See below:

```<code>group_stats <- fev %>%
  group_by(smoking) %>%
  summarize(mean = mean(fev), n = n(), sd = sd(fev), se = sd / sqrt(n)) %>%
  mutate(se_sum = sum(se ^ 2),
         se_idx = se[1] ^ 2 + se[2] ^ 2,
         mean_diff = diff(mean),
         mean_idx = mean[2] - mean[1],
         mean_diffLast = last(mean) - first(mean))
</code>```

Output:

```<code>group_stats

# A tibble: 2 x 10
  smoking  mean     n    sd     se se_sum se_idx mean_diff mean_idx mean_diffLast
  <fct>   <dbl> <int> <dbl>  <dbl>  <dbl>  <dbl>     <dbl>    <dbl>         <dbl>
1 ns       2.61   539 0.788 0.0339 0.0111 0.0111     0.628    0.628         0.628
2 s        3.24    59 0.764 0.0995 0.0111 0.0111     0.628    0.628         0.628
</code>```

ContentLicense: CC BY-SA 4.0

Title: How do I perform calculations after summarising with dplyr?

Body:
I have performed group-wise calculations on two groups the following way:

group_stats <- fev %>%
  group_by(smoking) %>%
  summarize(mean = mean(fev), n = n(), sd = sd(fev), se = sd / sqrt(n))

Which produces data frame with 2 rows. Now I want to calculate the following:

The difference in means between two rows

The new se value like se[row_1] ^ 2 + se[row_2] ^ 2.

Is there a tidyverse way of doing it?

dput output:

structure(list(age = c(8, 13, 8, 11, 8, 8, 9, 11, 15, 8, 6, 8,
12, 8, 7, 9, 10, 8, 12, 13, 11, 12, 9, 7, 11, 14, 12, 9, 10,
8, 10, 11, 6, 9, 11, 14, 11, 10, 9, 11, 11, 11, 8, 15, 7, 9,
11, 11, 8, 8, 9, 11, 8, 11, 8, 8, 9, 14, 9, 10, 16, 13, 16, 10,
8, 12, 9, 11, 8, 8, 12, 7, 13, 9, 7, 8, 10, 7, 13, 13, 8, 8,
8, 16, 12, 10, 14, 9, 8, 7, 9, 11, 12, 13, 13, 10, 6, 13, 9,
7, 6, 8, 6, 12, 11, 10, 11, 9, 10, 9, 13, 10, 12, 6, 13, 13,
10, 11, 11, 8, 9, 9, 15, 7, 8, 15, 15, 8, 14, 10, 6, 10, 8, 6,
12, 8, 13, 9, 16, 10, 11, 8, 6, 11, 10, 13, 12, 11, 10, 8, 8,
10, 12, 10, 7, 9, 9, 12, 8, 7, 8, 9, 6, 11, 13, 8, 10, 12, 9,
11, 13, 6, 13, 10, 8, 12, 6, 9, 9, 13, 11, 15, 6, 11, 10, 10,
10, 7, 7, 12, 12, 10, 13, 10, 10, 10, 11, 10, 13, 9, 11, 12,
10, 8, 11, 11, 10, 13, 13, 9, 8, 11, 9, 7, 10, 11, 9, 9, 11,
14, 9, 7, 10, 7, 15, 14, 11, 9, 8, 7, 13, 13, 9, 9, 7, 11, 11,
16, 9, 15, 7, 12, 7, 6, 8, 12, 8, 14, 9, 9, 8, 15, 10, 12, 13,
11, 8, 11, 8, 11, 13, 8, 11, 9, 6, 10, 11, 10, 11, 9, 8, 12,
12, 12, 8, 9, 15, 12, 14, 14, 9, 9, 10, 13, 8, 13, 13, 9, 9,
8, 11, 9, 7, 7, 9, 9, 9, 9, 7, 8, 9, 15, 16, 10, 6, 9, 12, 9,
8, 8, 8, 9, 11, 7, 15, 7, 11, 12, 8, 11, 14, 7, 6, 8, 7, 12,
11, 13, 15, 14, 12, 8, 11, 10, 11, 9, 7, 9, 8, 10, 7, 8, 15,
11, 11, 16, 13, 11, 9, 6, 9, 6, 11, 11, 11, 11, 7, 16, 11, 10,
8, 7, 11, 10, 8, 14, 6, 14, 10, 12, 6, 13, 9, 7, 11, 12, 10,
6, 9, 10, 12, 13, 8, 7, 12, 11, 8, 11, 6, 11, 12, 7, 13, 7, 14,
7, 10, 12, 10, 6, 9, 9, 9, 12, 8, 9, 6, 12, 7, 10, 9, 10, 11,
11, 7, 10, 7, 10, 10, 16, 6, 6, 6, 10, 14, 12, 7, 10, 13, 11,
9, 7, 7, 7, 11, 9, 7, 8, 11, 8, 8, 10, 10, 9, 8, 9, 12, 6, 8,
7, 9, 11, 11, 9, 10, 9, 14, 9, 7, 8, 11, 7, 6, 12, 9, 8, 10,
13, 10, 13, 15, 8, 9, 10, 15, 11, 9, 9, 13, 14, 6, 6, 10, 10,
12, 14, 7, 11, 11, 13, 10, 7, 14, 10, 9, 9, 6, 14, 12, 10, 11,
8, 12, 9, 11, 8, 16, 7, 14, 12, 13, 12, 8, 10, 11, 16, 9, 12,
13, 10, 10, 11, 10, 10, 13, 9, 9, 14, 10, 9, 16, 9, 6, 11, 6,
11, 12, 14, 15, 11, 11, 12, 12, 9, 8, 8, 11, 6, 9, 7, 10, 12,
10, 7, 10, 8, 12, 9, 13, 12, 9, 8, 12, 11, 11, 8, 11, 11, 14,
9, 16, 9, 6, 10, 10, 12, 15, 11, 8, 15, 8, 9, 7, 9, 10, 9, 8,
10, 12, 7, 8, 11, 12, 10, 10, 8, 11, 8), fev = c(1.94, 3.785,
2.123, 2.993, 2.094, 2.187, 2.23, 2.14, 5.793, 2.069, 1.979,
1.931, 1.916, 1.547, 2.219, 3.135, 1.937, 2.665, 2.971, 2.677,
3.587, 2.569, 2.973, 1.603, 4.637, 4.273, 2.759, 2.725, 2.435,
1.624, 1.858, 3.411, 1.713, 1.895, 2.542, 3.428, 2.659, 2.581,
2.076, 2.633, 2.562, 2.606, 2.335, 3.004, 1.69, 2.348, 2.822,
2.928, 2.01, 2.42, 2.592, 2.866, 2.215, 2.318, 2.631, 1.703,
1.969, 2.236, 2.165, 2.391, 2.903, 4.225, 3.387, 3.111, 1.556,
2.332, 2.851, 3.681, 2.631, 2.531, 3.924, 1.726, 4.305, 2.871,
1.75, 2.09, 2.341, 2.371, 4.448, 3.208, 1.512, 2.175, 2.5, 2.795,
2.752, 2.352, 4.683, 2.964, 2.503, 2.55, 2.923, 2.735, 2.241,
4.336, 3.255, 2.642, 2.262, 3.06, 3, 1.905, 1.691, 2.476, 1.796,
3.255, 4.324, 1.458, 3.069, 2.717, 3.456, 2.715, 3.906, 2.568,
3.53, 1.624, 3.549, 3.089, 2.855, 3.847, 1.694, 1.657, 2.182,
2.65, 2.679, 1.698, 2.069, 4.279, 4.5, 2.927, 3.806, 2.691, 1.747,
2.358, 1.962, 1.415, 2.499, 2.993, 4.789, 2.485, 4.504, 2.864,
2.458, 1.292, 1.535, 3.171, 2.328, 3.056, 2.889, 2.689, 2.175,
2.015, 2.305, 3.183, 4.55, 2.094, 1.649, 1.953, 2.119, 3.341,
1.844, 1.609, 1.429, 2.639, 1.634, 3.845, 3.078, 2.388, 2.77,
3.343, 2.487, 2.665, 3.086, 1.697, 3.297, 2.356, 1.759, 2.304,
1.699, 3.114, 2.463, 2.646, 2.988, 4.506, 1.878, 3.515, 2.292,
3.086, 4.591, 1.37, 2.093, 2.605, 3.186, 2.688, 3.141, 2.387,
3.007, 2.673, 2.827, 3.251, 2.704, 1.754, 2.417, 2.417, 3.038,
2.732, 3.011, 2.498, 3.795, 3.984, 2.434, 2.091, 2.336, 3.247,
2.57, 2.084, 2.481, 2.812, 2.574, 3.842, 2.362, 4.271, 1.947,
2.22, 2.364, 2.564, 3.33, 2.276, 2.887, 2.09, 1.872, 1.253, 2.531,
2.449, 2.803, 1.912, 1.826, 4.593, 3.222, 3.674, 3.223, 2.278,
2.419, 3.403, 1.624, 1.338, 2.303, 4.831, 1.794, 4.763, 2.196,
2.164, 2.354, 2.264, 2.891, 2.751, 4.045, 3.596, 2.193, 2.346,
1.735, 3.058, 3.887, 2.681, 2.387, 2.069, 1.666, 3.329, 3.108,
2.25, 3.12, 2.301, 1.897, 3.058, 3.519, 3.082, 2.328, 3.004,
3.799, 3.692, 2.538, 3.957, 2.316, 1.933, 2.696, 2.976, 2.709,
3.147, 3.994, 2.352, 3.042, 1.758, 2.123, 1.855, 1.79, 2.046,
2.457, 3.681, 2.259, 2.13, 1.682, 1.697, 2.893, 3.211, 2.608,
3.489, 1.719, 3.029, 3.231, 2.56, 2.481, 2.458, 2.382, 2.32,
4.073, 1.461, 3.727, 1.165, 4.065, 3.079, 1.344, 3.32, 3.395,
1.631, 1.431, 2.226, 1.64, 2.841, 3.022, 4.232, 2.635, 3.741,
3.835, 2.258, 2.081, 2.201, 2.501, 2.797, 2.578, 1.606, 1.953,
3.05, 1.92, 2.118, 2.198, 3.47, 3.102, 3.688, 3.297, 2.884, 2.135,
1.427, 2.798, 1.572, 3.169, 2.386, 2.957, 2.491, 2.135, 2.981,
2.563, 2.838, 2.673, 2.535, 2.785, 2.216, 2.639, 2.934, 1.65,
3.68, 3.11, 3.279, 1.715, 5.083, 2.604, 1.473, 2.894, 2.556,
3.203, 1.348, 2.042, 2.545, 4.073, 3.745, 2.144, 1.658, 2.384,
3.774, 1.675, 3.206, 1.672, 3.236, 4.72, 2.095, 2.599, 1.728,
3.436, 1.917, 2.1, 3.501, 3.35, 1.536, 2.166, 2.833, 1.708, 2.935,
2.016, 2.85, 1.481, 3.035, 1.612, 3.354, 2.442, 3.305, 3.425,
3.078, 1.742, 3.073, 1.829, 2.901, 2.561, 4.27, 1.718, 1.523,
1.602, 3.498, 4.309, 3.529, 1.72, 2.246, 3.577, 2.762, 2.46,
2.366, 1.796, 1.415, 3.104, 1.942, 1.495, 2.071, 2.953, 2.135,
2.341, 1.873, 2.862, 2.455, 2.358, 2.529, 4.08, 2.104, 1.78,
1.789, 1.751, 3.28, 2.524, 2.04, 2.287, 2.048, 3.78, 2.988, 1.611,
1.698, 2.463, 1.827, 1.527, 2.868, 2.076, 2.145, 2.132, 3.331,
2.758, 2.216, 4.284, 1.744, 2.659, 1.858, 2.887, 3.977, 3.016,
1.591, 4.877, 3.169, 1.343, 2.102, 2.592, 2.72, 3.222, 3.585,
1.935, 3.023, 4.13, 2.819, 3.132, 2.002, 4.842, 2.365, 1.886,
3.239, 1.423, 2.997, 4.411, 2.504, 3.49, 2.98, 4.393, 1.716,
4.007, 1.987, 4.872, 2.111, 3.074, 3.751, 3.193, 2.913, 1.999,
1.823, 3.258, 4.07, 2.457, 5.224, 3.816, 2.25, 3.127, 2.354,
1.665, 2.975, 4.756, 2.246, 2.42, 3.381, 3.2, 1.869, 3.645, 1.558,
1.338, 2.578, 1.826, 2.17, 3.001, 4.111, 3.985, 3.583, 2.974,
3.791, 2.752, 2.1, 2.333, 1.335, 3.369, 1.919, 2.588, 2.056,
2.813, 4.203, 3.09, 2.158, 3.413, 1.991, 2.579, 2.126, 3.152,
2.347, 2.631, 1.523, 2.714, 3.654, 3.515, 1.562, 3.339, 3.223,
2.891, 1.773, 4.299, 2.571, 1.695, 3.048, 2.646, 3.082, 3.122,
2.465, 2.293, 3.731, 2.288, 2.056, 1.877, 2.688, 2.52, 3.556,
2.004, 3.166, 2.822, 1.932, 1.724, 3.111, 2.866, 1.811, 2.608,
2.211, 2.754, 2.435), gender = structure(c(2L, 1L, 2L, 2L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 2L,
2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L,
1L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 2L,
1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L,
1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 2L,
2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L,
2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 1L,
2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L,
1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L,
1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L,
1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L,
1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
1L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L,
2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 2L,
1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L,
2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L,
1L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L,
2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L,
2L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L,
2L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L,
1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L,
2L), .Label = c("f", "m"), class = "factor"), smoking = structure(c(1L,
2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L,
1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L,
1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L,
2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L), .Label = c("ns", "s"), class = "factor")), class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -598L))

Body:
In dplyr, you can refer to values in each row by inserting single or range position values in []. For example, the first value of mean column can be obtained by mean[1], the second by mean[2], both by mean[1:2] or mean[c(1, 2)], etc.

If you only have two rows, you can also access the second one by last(mean), the first by first(mean).

When you have a group_by statement before, these indices refer to row indices per each group. In your case you don't need to worry, since summarize automatically drops one grouping level per call - so you essentially end up with a tibble without groups.

However, the best way of doing this would be with just basic vectorized operations. For example, you can calculate the exponents and sum them up for se, while you can just use the diff function for mean.

See below:

group_stats <- fev %>%
  group_by(smoking) %>%
  summarize(mean = mean(fev), n = n(), sd = sd(fev), se = sd / sqrt(n)) %>%
  mutate(se_sum = sum(se ^ 2),
         se_idx = se[1] ^ 2 + se[2] ^ 2,
         mean_diff = diff(mean),
         mean_idx = mean[2] - mean[1],
         mean_diffLast = last(mean) - first(mean))

Output:

group_stats

# A tibble: 2 x 10
  smoking  mean     n    sd     se se_sum se_idx mean_diff mean_idx mean_diffLast
  <fct>   <dbl> <int> <dbl>  <dbl>  <dbl>  <dbl>     <dbl>    <dbl>         <dbl>
1 ns       2.61   539 0.788 0.0339 0.0111 0.0111     0.628    0.628         0.628
2 s        3.24    59 0.764 0.0995 0.0111 0.0111     0.628    0.628         0.628


问:
Access JS object with a key
I can access a value like driver.my_friends["793659690"].name but now I am using it in a loop where key will hold the key.

driver.my_friends[key].name doesn't work. Says undefined, and driver.my_friends["key"].name will look for a key named key. So how do I use it so that the variable of the variable is evaluated too.

答:
when you're iterating over an object's properties, some "garbage" may get into "key" variable. I would suggest the following:

```<code>for (var key in driver.my_friends) {
  if (key && driver.my_friends[key] && driver.my_friends[key].name) {
    // Do what you need here
  }
}
</code>```

Also, make sure that when the value of driver.my_friends[key] gets set, the key is the same as the one used for reading it

ContentLicense: CC BY-SA 3.0

Title: Access JS object with a key

Body:
when you're iterating over an object's properties, some "garbage" may get into "key" variable. I would suggest the following:

for (var key in driver.my_friends) {
  if (key && driver.my_friends[key] && driver.my_friends[key].name) {
    // Do what you need here
  }
}

Also, make sure that when the value of driver.my_friends[key] gets set, the key is the same as the one used for reading it


问:
Amazon Product API error 429: how to optimize performance and reliability for batch requests?
I'm getting this annoying error 429 for too many requests while sending multiple requests. What's even more disgusting is it limits amount of product to 10 per request as it seems.

So I have a code that breaks down my asin array into groups of 10s and chains it into multiple requests however, when I set 1 second wait after start of every request before making a new one, it doesn't work reliably and still returns an error, increasing the number to 2 sec per request solves this but makes it too slow. (Because usually it takes 0.5 sec per request and waits the remaining 1.5 seconds).

Amazon doesn't have any documentation on how exactly those limits work so we can only guess.

Is there way to improve it further or make something different with the queuing?

```<code>$all_posts = get_posts(array(
    'posts_per_page'   => -1
));
$serialized = serialize($all_posts);
preg_match_all ( "/]([^\]]*?)\[\/asa\]/" , $serialized , $matches);
$amazon_items=$matches[1];  //here we get an array of asins

$time_end=microtime(true);
$time_start=0;

$out=array();
for ($i=0;$i<count($amazon_items);$i+=10){
    $arr=array();
    for ($j=0;$j<10&&$i+$j<count($amazon_items);$j++){
        $arr[]=$amazon_items[$i+$j];
    }
    if ($time_end-$time_start<2) {
        echo 'sleeping '.(2-($time_end-$time_start)). 'sec; ';
        sleep (2-($time_end-$time_start));
    }
    $time_start = microtime(true);
    $list = GetItems($arr);
    $time_end = microtime(true);
    echo $time_end-$time_start.' sec, ',PHP_EOL;

    $out = array_merge($out, $list);
}
</code>```

答:
I think I got the solution, it seems paapi 5 is especially sensitive to the very first #1 and #2 request. There a good pause should be maintained, after which the request speed can be increased up to the nominal 1 per sec.

So the loop should go something like this:
1st request,
pause to make total of 2 seconds since the start of request,
2nd request,
pause to make total of 1 seconds since the start of request,
3rd request,
pause to make total of 1 seconds since the start of request,
4th request,
...etc

I suspect it might also work with holding 1 whole second AFTER the end of the first request instead of 2 seconds total, before switching to 1 sec total wait loop counted from the beginning of the requests, but I am yet to try this out in order to verify. Obviously if the first request exceeds 1 second and it throws an error then I'll know this is the case.

Edit: it worked for an hour then stopped working again, I am going to change to 1 sec after every request just to be sure. This is really retarded because there is no way to tell what time exactly does it record on their server side, it is neither the starting time of the request nor the end time of the request. It seems as though it can arbitrary fluctuate between the two, and whenever 1 second rule is violated (which happens at random) it starts throwing countless 429 errors. Ok I'm going to simply wait 1 second and hope my requests are slightly faster than 1 sec themselves, which should give me some small advantage and reliability vs waiting full 2 seconds every time, like in my initially posted example.

Body:
I'm getting this annoying error 429 for too many requests while sending multiple requests. What's even more disgusting is it limits amount of product to 10 per request as it seems.

So I have a code that breaks down my asin array into groups of 10s and chains it into multiple requests however, when I set 1 second wait after start of every request before making a new one, it doesn't work reliably and still returns an error, increasing the number to 2 sec per request solves this but makes it too slow. (Because usually it takes 0.5 sec per request and waits the remaining 1.5 seconds).

Amazon doesn't have any documentation on how exactly those limits work so we can only guess.

Is there way to improve it further or make something different with the queuing?

$all_posts = get_posts(array(
    'posts_per_page'   => -1
));
$serialized = serialize($all_posts);
preg_match_all ( "/]([^\]]*?)\[\/asa\]/" , $serialized , $matches);
$amazon_items=$matches[1];  //here we get an array of asins

$time_end=microtime(true);
$time_start=0;

$out=array();
for ($i=0;$i<count($amazon_items);$i+=10){
    $arr=array();
    for ($j=0;$j<10&&$i+$j<count($amazon_items);$j++){
        $arr[]=$amazon_items[$i+$j];
    }
    if ($time_end-$time_start<2) {
        echo 'sleeping '.(2-($time_end-$time_start)). 'sec; ';
        sleep (2-($time_end-$time_start));
    }
    $time_start = microtime(true);
    $list = GetItems($arr);
    $time_end = microtime(true);
    echo $time_end-$time_start.' sec, ',PHP_EOL;

    $out = array_merge($out, $list);
}


问:
How do you do block comments in YAML?
How do I comment a block of lines in YAML?</p>

答:
In the Azure DevOps browser (pipeline YAML editor),

Ctrl + K + C Comment Block

Ctrl + K + U Uncomment Block

There also a 'Toggle Block Comment' option, but this did not work for me.

There are other 'weird' ways too: Right-click to see 'Command Palette' or F1

Then choose a cursor option.

Now it is just a matter of #.

Or even smarter [Ctrl + K] + [Ctrl + C]

Title: How do you do block comments in YAML?


问:
Replace elements in string using references from list with dictionary
I want replace parameters in SQL scrip in string format using references from list with dictionary inside. This is example SQL script:

```<code>sql = "SELECT DISTINCT id, channel AS value FROM ${source} WHERE channel IN (${channel});"
</code>```

All of the queries are in this structure:

```<code>{'name': 'example', 'description': 'example1', 'sql': 'SELECT DISTINCT id, channel AS value FROM ${source} WHERE channel IN (${channel});'}
</code>```

The dictionary looks like this:

```<code>my_dict = [{"source":"table_name","channel":["abc","abcd"]}]
</code>```

The desired output is:

```<code>SELECT DISTINCT pnr, channel AS value FROM table_name WHERE channel IN ("abc", "abcd");
</code>```

Note: It is possible the channel parameter to have single value: my_dict = [{"source":"table_name","channel":["abc"]}] This is very important to have in mind.

I was thinking to .split the query and to replace the parameters, but for some reason it is not working and the channels are without quotes. I need them in quotes, so the query can be executed later.

```<code>queries = sql.split()
final_string = ' '.join(str(my_dict.get(word, word)) for word in queries)
</code>```

Another solution I found, but could not implemented for my case : Replacing a value in string with a value in a dictionary in python

答:
What you have is not a dictionary, but a list. If you are interested in the dictionary at the first position of the list you could use an f-string and do:</p>

```<code>>>> sql = f"SELECT DISTINCT id, channel AS value FROM {my_dict[0]['source']} WHERE channel IN {tuple(my_dict[0]['channel'])};"
>>> sql
"SELECT DISTINCT id, channel AS value FROM table_name WHERE channel IN ('abc', 'abcd');"
</code>```

Body:
I want replace parameters in SQL scrip in string format using references from list with dictionary inside. This is example SQL script:

sql = "SELECT DISTINCT id, channel AS value FROM ${source} WHERE channel IN (${channel});"

All of the queries are in this structure:

{'name': 'example', 'description': 'example1', 'sql': 'SELECT DISTINCT id, channel AS value FROM ${source} WHERE channel IN (${channel});'}

The dictionary looks like this:

my_dict = [{"source":"table_name","channel":["abc","abcd"]}]

The desired output is:

SELECT DISTINCT pnr, channel AS value FROM table_name WHERE channel IN ("abc", "abcd");

Note: It is possible the channel parameter to have single value: my_dict = [{"source":"table_name","channel":["abc"]}] This is very important to have in mind.

I was thinking to .split the query and to replace the parameters, but for some reason it is not working and the channels are without quotes. I need them in quotes, so the query can be executed later.

queries = sql.split()
final_string = ' '.join(str(my_dict.get(word, word)) for word in queries)

Another solution I found, but could not implemented for my case : Replacing a value in string with a value in a dictionary in python

Body:
What you have is not a dictionary, but a list. If you are interested in the dictionary at the first position of the list you could use an f-string and do:

>>> sql = f"SELECT DISTINCT id, channel AS value FROM {my_dict[0]['source']} WHERE channel IN {tuple(my_dict[0]['channel'])};"
>>> sql
"SELECT DISTINCT id, channel AS value FROM table_name WHERE channel IN ('abc', 'abcd');"


问:
Unit Test inconsistent pass or fail result
One of my unit tests seems to randomly pass or fail when I run it. The only thing that makes sense to me for why this is happening is if the data in the database is getting into a different state each time the test is ran, but I use transactions to rollback the database in each test - unless it's not working right. Here's my base unit test class and the unit test class that's having the problem. Can you see anything I might be missing or what else I should look for?

This happens with TestDriven.Net and the Visual Studio Unit Test Framework.

```<code>Partial Public MustInherit Class TestBase

    Private _scope As Transactions.TransactionScope

    <DebuggerStepThrough()> _
    <TestInitialize()> _
    Public Sub Setup()

            //'Start the Distribution Transaction Coordinator, if it's not already running.
            Using dtcService As New System.ServiceProcess.ServiceController("Distributed Transaction Coordinator", My.Computer.Name)
                    If dtcService.Status = ServiceProcess.ServiceControllerStatus.Stopped Then
                            dtcService.Start()
                    End If
            End Using

            _scope = New TransactionScope(TransactionScopeOption.RequiresNew, New TimeSpan(0))
    End Sub

    <DebuggerStepThrough()> _
    <TestCleanup()>
    Public Sub Teardown()
        If _scope IsNot Nothing Then
            _scope.Dispose()
        End If
    End Sub

    <System.Diagnostics.DebuggerStepThrough()> _
    Public Shared Function ExecSql(ByVal sql As String) As System.Data.DataTable

        Dim connStr = GlobalSettings.GetConnectionString()
        Using conn As New System.Data.SqlClient.SqlConnection(connStr)
            conn.Open()

            Dim cmd As New System.Data.SqlClient.SqlCommand(sql.ToString, conn)
            Dim adapter As System.Data.SqlClient.SqlDataAdapter = New System.Data.SqlClient.SqlDataAdapter(cmd)
            Dim dt As System.Data.DataTable = New System.Data.DataTable
            adapter.Fill(dt)

            Return dt

            If conn.State <> System.Data.ConnectionState.Closed Then
                conn.Close()
            End If
            conn.Dispose()
        End Using
    End Function
End Class
</code>```

And here's my unit test:

```<code>Partial Public Class CampaignEmailSendLimitServiceTests
    Inherits TestBase

    Private _service = ServiceManager.Current.MyService

    <TestMethod()> _
    Public Sub MyTest()
        //' Set the pre-test condition.
        ExecSql("update base.dbo.tblTableA set someDate = '2010-06-28' where id = 56937 ")

        //' Run the service
        _service.Process()

       //' Verify the expected result
       Dim dt = ExecSql("select deliveryDate from tblTableB ")
       Assert.AreEqual(False, dt.Rows(0).IsNull("deliveryDate"))

    End Sub
End Class
</code>```

答:
Why are You using DataAdapter.Fill to execute updates? It is designed to fill DataTables with select statements.

My guess is that You didn't write anything to database using ExecSql in the first place.

And second thing. That assert is as unreadable as possible.
I would change

```<code>Assert.AreEqual(False, dt.Rows(0).IsNull("deliveryDate"));</code>```

to

```<code>Assert.IsFalse(dt.Rows(0).IsNull("deliveryDate"));</code>```

or

```<code>Assert.That(dt.Rows(0)("deliveryDate"), Is.Not.Null));</code>```

Unreadable tests are one of the reasons some people say Unit Testing is bad because it slows You down. You have to make Unit Tests as easy to read and understand as possible. So that they don't have arguments against unit testing ;)

There may be some typos as I don't use VB.NET. Assert examples are from NUnit.

Body:
One of my unit tests seems to randomly pass or fail when I run it. The only thing that makes sense to me for why this is happening is if the data in the database is getting into a different state each time the test is ran, but I use transactions to rollback the database in each test - unless it's not working right. Here's my base unit test class and the unit test class that's having the problem. Can you see anything I might be missing or what else I should look for?

This happens with TestDriven.Net and the Visual Studio Unit Test Framework.

Partial Public MustInherit Class TestBase

    Private _scope As Transactions.TransactionScope

    <DebuggerStepThrough()> _
    <TestInitialize()> _
    Public Sub Setup()

            //'Start the Distribution Transaction Coordinator, if it's not already running.
            Using dtcService As New System.ServiceProcess.ServiceController("Distributed Transaction Coordinator", My.Computer.Name)
                    If dtcService.Status = ServiceProcess.ServiceControllerStatus.Stopped Then
                            dtcService.Start()
                    End If
            End Using

            _scope = New TransactionScope(TransactionScopeOption.RequiresNew, New TimeSpan(0))
    End Sub

    <DebuggerStepThrough()> _
    <TestCleanup()>
    Public Sub Teardown()
        If _scope IsNot Nothing Then
            _scope.Dispose()
        End If
    End Sub

    <System.Diagnostics.DebuggerStepThrough()> _
    Public Shared Function ExecSql(ByVal sql As String) As System.Data.DataTable

        Dim connStr = GlobalSettings.GetConnectionString()
        Using conn As New System.Data.SqlClient.SqlConnection(connStr)
            conn.Open()

            Dim cmd As New System.Data.SqlClient.SqlCommand(sql.ToString, conn)
            Dim adapter As System.Data.SqlClient.SqlDataAdapter = New System.Data.SqlClient.SqlDataAdapter(cmd)
            Dim dt As System.Data.DataTable = New System.Data.DataTable
            adapter.Fill(dt)

            Return dt

            If conn.State <> System.Data.ConnectionState.Closed Then
                conn.Close()
            End If
            conn.Dispose()
        End Using
    End Function
End Class

And here's my unit test:

Partial Public Class CampaignEmailSendLimitServiceTests
    Inherits TestBase

    Private _service = ServiceManager.Current.MyService

    <TestMethod()> _
    Public Sub MyTest()
        //' Set the pre-test condition.
        ExecSql("update base.dbo.tblTableA set someDate = '2010-06-28' where id = 56937 ")

        //' Run the service
        _service.Process()

       //' Verify the expected result
       Dim dt = ExecSql("select deliveryDate from tblTableB ")
       Assert.AreEqual(False, dt.Rows(0).IsNull("deliveryDate"))

    End Sub
End Class

Body:
Why are You using DataAdapter.Fill to execute updates? It is designed to fill DataTables with select statements.

My guess is that You didn't write anything to database using ExecSql in the first place.

And second thing. That assert is as unreadable as possible.
I would change

Assert.AreEqual(False, dt.Rows(0).IsNull("deliveryDate"));

to

Assert.IsFalse(dt.Rows(0).IsNull("deliveryDate"));

or

Assert.That(dt.Rows(0)("deliveryDate"), Is.Not.Null));

Unreadable tests are one of the reasons some people say Unit Testing is bad because it slows You down. You have to make Unit Tests as easy to read and understand as possible. So that they don't have arguments against unit testing ;)

There may be some typos as I don't use VB.NET. Assert examples are from NUnit.


问:
Unable to run localhost in Spring Boot application (Tomcat server)
I've been learning Spring using the following tutorials: https://www.youtube.com/playlist?list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x

I have created a Maven project and tried to run the Spring Boot application while referring to these videos:

https://www.youtube.com/watch?v=E7_a-kB46LU&index=9&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x

I tried to run my Spring application on Tomcat server but the localhost isn't working. (Port 8080)

My pom.xml looks like this:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>io.javabrains.springbootquickstart</groupId>
  <artifactId>course-api-new</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Java Brains Course API</name>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.2.RELEASE</version>
  </parent>

  <dependencies>
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
  </dependencies>

  <properties>
        <java.version>1.8</java.version>
  </properties>

</project>
</code>```

CourseApiApp.java :

```<code>package io.javabrains.springbootstarter;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CourseApiApp {

    public static void main(String[] args) {
        SpringApplication.run(CourseApiApp.class, args);

    }

}
</code>```

According to the video localhost should display Whitelist error on running the application, but it doesn't run at all.

Any help would be appreciated, thanks!

答:
You need to tell springboot where do you have to scan your reference classes</p>

```<code>@SpringBootApplication
@ComponentScan(basePackages= {"com.testbean.controller", "com.testbean.model", "com.testbean.service"})
public class DemoApplication {
</code>```

Body:
I've been learning Spring using the following tutorials: https://www.youtube.com/playlist?list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x

I have created a Maven project and tried to run the Spring Boot application while referring to these videos:

https://www.youtube.com/watch?v=E7_a-kB46LU&index=9&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x

I tried to run my Spring application on Tomcat server but the localhost isn't working. (Port 8080)

My pom.xml looks like this:

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>io.javabrains.springbootquickstart</groupId>
  <artifactId>course-api-new</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Java Brains Course API</name>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.2.RELEASE</version>
  </parent>

  <dependencies>
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
  </dependencies>

  <properties>
        <java.version>1.8</java.version>
  </properties>

</project>

CourseApiApp.java :

package io.javabrains.springbootstarter;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CourseApiApp {

    public static void main(String[] args) {
        SpringApplication.run(CourseApiApp.class, args);

    }

}

According to the video localhost should display Whitelist error on running the application, but it doesn't run at all.

Any help would be appreciated, thanks!

Body:
You need to tell springboot where do you have to scan your reference classes

@SpringBootApplication
@ComponentScan(basePackages= {"com.testbean.controller", "com.testbean.model", "com.testbean.service"})
public class DemoApplication {


问:
How can I put chained conditions inside property binding in XML view?
I have the following code for one of my app views (InvioceList.view.xml).

Code that works fine:

numberState="{= ${invoice>ExtendedPrice} > 50 ? 'Error' : 'Success'}"
```

<p>The property <code>numberState</code> of control <code>ObjectListItem</code> allows me to change the color of the invoices amount depending on the rate.</p>

<p><img src="https://i.stack.imgur.com/RkMfp.png" alt="Hello-world app"></p>

<p>However, the code that works is only ruling two colors. I want to do it with three (<code>Success</code> for green, <code>Warning</code> for yellow and <code>Error</code> for red). So in order to do that, I tried with this: </p>

<pre class="lang-xml prettyprint-override"><code><ObjectListItem
  numberState="{= ${invoice>ExtendedPrice} > 20 ? 'Success' : ${invoice>ExtendedPrice} > 50 ? 'Error' : 'Warning'}"
/>`
</code>```

Code that doesn't work fine:

numberState="{= ${invoice>ExtendedPrice} < 20 ? 'Success' : ${invoice>ExtendedPrice} > 60 ? 'Error' : 'Warning'}"
```

So since I'm a beginner in this, I can only recognize for now that the conditional statement I'm using is a ternary operator or multiple conditional, but for some reason, it is not working fine when using more than two intervals (maybe syntax).

So I would like to understand what am I doing wrong or what other way can I take to do the same without using that property. I hope some of you can throw me some light on this.

答:
If I understand your question correctly:

Your intervals are defined wrong. Right now you have

If the price is higher than 20, show success. If it's higher than 50, show error. Else show warning.

These statements are checked in exactly this order.

Let's say you have a price of 80.

Is it higher than 20? Yes it is, so show success. No need to check the rest, since the first condition was already a match.

If you want three intervals, don't start with the middle one.

```<code><ObjectListItem numberState="{= ${invoice>ExtendedPrice} > 50 ? 'Error' : 20 >= ${invoice>ExtendedPrice} ? 'Warning' : 'Success' }" />
</code>```

If you do want to start with the middle one, make your condition more strict.

For example, "is it higher than 20 but lower than or equal to 50 then success".

```<code><ObjectListItem numberState="{= ${invoice>ExtendedPrice} > 20 && ${invoice>ExtendedPrice} <= 50 ? 'Success' : ${invoice>ExtendedPrice} > 50 ? 'Error' : 'Warning' }" />
</code>```

& and < are special chars in XML, so you have to escape them.

But you see, it's hard to debug and hard to read. I'd strongly recommend a formatter function.

You can debug it (since it's plain JavaScript) and write readable ternary or if/else statements.

Body:
I have the following code for one of my app views (InvioceList.view.xml).

Code that works fine:

numberState="{= ${invoice>ExtendedPrice} > 50 ? 'Error' : 'Success'}"

The property numberState of control ObjectListItem allows me to change the color of the invoices amount depending on the rate.

However, the code that works is only ruling two colors. I want to do it with three (Success for green, Warning for yellow and Error for red). So in order to do that, I tried with this:

<ObjectListItem
  numberState="{= ${invoice>ExtendedPrice} > 20 ? 'Success' : ${invoice>ExtendedPrice} > 50 ? 'Error' : 'Warning'}"
/>`

Code that doesn't work fine:

numberState="{= ${invoice>ExtendedPrice} < 20 ? 'Success' : ${invoice>ExtendedPrice} > 60 ? 'Error' : 'Warning'}"

So since I'm a beginner in this, I can only recognize for now that the conditional statement I'm using is a ternary operator or multiple conditional, but for some reason, it is not working fine when using more than two intervals (maybe syntax).

So I would like to understand what am I doing wrong or what other way can I take to do the same without using that property. I hope some of you can throw me some light on this.

Body:
If I understand your question correctly:

Your intervals are defined wrong. Right now you have

If the price is higher than 20, show success. If it's higher than 50, show error. Else show warning.

These statements are checked in exactly this order.

Let's say you have a price of 80.

Is it higher than 20? Yes it is, so show success. No need to check the rest, since the first condition was already a match.

If you want three intervals, don't start with the middle one.

<ObjectListItem numberState="{= ${invoice>ExtendedPrice} > 50 ? 'Error' : 20 >= ${invoice>ExtendedPrice} ? 'Warning' : 'Success' }" />

If you do want to start with the middle one, make your condition more strict.

For example, "is it higher than 20 but lower than or equal to 50 then success".

<ObjectListItem numberState="{= ${invoice>ExtendedPrice} > 20 &amp;&amp; ${invoice>ExtendedPrice} &lt;= 50 ? 'Success' : ${invoice>ExtendedPrice} > 50 ? 'Error' : 'Warning' }" />

& and < are special chars in XML, so you have to escape them.

But you see, it's hard to debug and hard to read. I'd strongly recommend a formatter function.

You can debug it (since it's plain JavaScript) and write readable ternary or if/else statements.


问:
How to save selected values from one table column to another table column
I am new to Rails, and trying to learn. In my simple form I have created a drop down select with generated data from a table called professions. This part is working fine, and I can select multiple values. I'm using a mysql database.

When I click the submit button, I need it to save the chosen values to a column called my_professions in another table called users. I can’t figure out how to do this.
I get this error

My form

```<code><%= simple_form_for @user, url: wizard_path, method: :put do |f| %>
<%= collection_select(:f, :professions_id, Profession.where.not(name: nil), :id, :name, {:multiple => true}, {:class=>'js-example-basic-multiple', :id=>'jsmultipleddd'}) %>
<%= f.submit "Save", :class => 'btn blue'  %>
<% end %>
</code>```

I have tried to add this to the user model

user.rb

```<code>class User < ApplicationRecord

has_many :professions
accepts_nested_attributes_for :professions

serialize :my_professions, Array
end
</code>```

And this to the profession model

profession.rb

```<code>class Profession < ApplicationRecord
belongs_to :user
end
</code>```

my params look like this

registration_steps_controller.rb

```<code>def user_params

  params.require(:user).permit(:gender,:practitioner_website, :public_health_insurance, clinic_images: [], professions: [])

end
</code>```

application_controller.rb

```<code>def configure_permitted_parameters
  devise_parameter_sanitizer.permit(:sign_up, keys: [:gender, :practitioner_website, :public_health_insurance, clinic_images: [], professions: []])
  devise_parameter_sanitizer.permit(:account_update, keys: [:gender, :practitioner_website, :public_health_insurance, clinic_images: [], professions: []])
end
</code>```

答:
Start by getting rid of accepts_nested_attributes_for :professions. You don't need nested attributes for this.

Then get rid of serialize :my_professions, Array. Serialize is a legacy hack to store complex data in string columns. You don't need or want this (ever), since associations should be stored in join tables in ActiveRecord - not array columns. That's how AR was designed to work and that's how relational databases where designed to work.

Instead what you want is a join model. Which you can generate with:

```<code>rails g model user_profession user:belongs_to profession:belongs_to
</code>```

Run the migration. You then setup the associations between users and professions:

```<code>class User < ApplicationRecord
  # ...
  has_many :user_professions
  has_many :professions, through: :user_professions
end

class Profession < ApplicationRecord
  # ...
  has_many :user_professions
  has_many :users, through: :user_professions
end
</code>```

Now this lets us associate users with professions by passing profession_ids.

In a normal Rails form you would create the input with:

```<code><%= f.collection_select :profession_ids, Profession.all, :id, :name, multiple: true ... %>
</code>```

In SimpleForm use the association helper:

```<code><%= f.association :professions, ... %>
</code>```

Then whitelist the correct param:

```<code>def user_params
  # don't jam this into one super long unreadable line
  params.require(:user)
        .permit(
          :gender, :practitioner_website, :public_health_insurance,
          clinic_images: [], profession_ids: []
        )
end
</code>```

Body:
I am new to Rails, and trying to learn. In my simple form I have created a drop down select with generated data from a table called professions. This part is working fine, and I can select multiple values. I'm using a mysql database.

When I click the submit button, I need it to save the chosen values to a column called my_professions in another table called users. I can’t figure out how to do this.
I get this error

My form

<%= simple_form_for @user, url: wizard_path, method: :put do |f| %>
<%= collection_select(:f, :professions_id, Profession.where.not(name: nil), :id, :name, {:multiple => true}, {:class=>'js-example-basic-multiple', :id=>'jsmultipleddd'}) %>
<%= f.submit "Save", :class => 'btn blue'  %>
<% end %>

I have tried to add this to the user model

user.rb

class User < ApplicationRecord

has_many :professions
accepts_nested_attributes_for :professions

serialize :my_professions, Array
end

And this to the profession model

profession.rb

class Profession < ApplicationRecord
belongs_to :user
end

my params look like this

registration_steps_controller.rb

def user_params

  params.require(:user).permit(:gender,:practitioner_website, :public_health_insurance, clinic_images: [], professions: [])

end

application_controller.rb

def configure_permitted_parameters
  devise_parameter_sanitizer.permit(:sign_up, keys: [:gender, :practitioner_website, :public_health_insurance, clinic_images: [], professions: []])
  devise_parameter_sanitizer.permit(:account_update, keys: [:gender, :practitioner_website, :public_health_insurance, clinic_images: [], professions: []])
end

Body:
Start by getting rid of accepts_nested_attributes_for :professions. You don't need nested attributes for this.

Then get rid of serialize :my_professions, Array. Serialize is a legacy hack to store complex data in string columns. You don't need or want this (ever), since associations should be stored in join tables in ActiveRecord - not array columns. That's how AR was designed to work and that's how relational databases where designed to work.

Instead what you want is a join model. Which you can generate with:

rails g model user_profession user:belongs_to profession:belongs_to

Run the migration. You then setup the associations between users and professions:

class User < ApplicationRecord
  # ...
  has_many :user_professions
  has_many :professions, through: :user_professions
end

class Profession < ApplicationRecord
  # ...
  has_many :user_professions
  has_many :users, through: :user_professions
end

Now this lets us associate users with professions by passing profession_ids.

In a normal Rails form you would create the input with:

<%= f.collection_select :profession_ids, Profession.all, :id, :name, multiple: true ... %>

In SimpleForm use the association helper:

<%= f.association :professions, ... %>

Then whitelist the correct param:

def user_params
  # don't jam this into one super long unreadable line
  params.require(:user)
        .permit(
          :gender, :practitioner_website, :public_health_insurance,
          clinic_images: [], profession_ids: []
        )
end


问:
Vue.js - Making helper functions globally available to single-file components
I have a Vue 2 project that has many (50+) single-file components. I use Vue-Router for routing and Vuex for state.

There is a file, called helpers.js, that contains a bunch of general-purpose functions, such as capitalizing the first letter of a string. This file looks like this:

export default {
  capitalizeFirstLetter(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }
}
```
<p>My <strong>main.js</strong> file initializes the app:</p>
<pre class="lang-js prettyprint-override"><code>import Vue from 'vue'
import VueResource from "vue-resource"
import store from "./store"
import Router from "./router"
import App from "./components/App.vue"

Vue.use(VueResource)

const app = new Vue({
  router: Router,
  store,
  template: '<app></app>',
  components: { App },
}).$mount('#app')
</code>```

My App.vue file contains the template:

<template>
  <navbar></navbar>

    <router-view></router-view>

</template>

```
<p>I then have a bunch of single-file components, which Vue-Router handles navigating to inside the <code><router-view></code> tag in the App.vue template.</p>
<p>Now let's say that I need to use the <code>capitalizeFirstLetter()</code> function inside a component that is defined in <strong>SomeComponent.vue</strong>. In order to do this, I first need to import it:</p>
<pre class="lang-html prettyprint-override"><code><template>Some Component</template>

<script>
import {capitalizeFirstLetter} from '../helpers.js'
export default {
  data() {
    return {
      myString = "test"
    }
  },
  created() {
    var newString = this.capitalizeFirstLetter(this.myString)
  }
}
</script>
</code>```

This becomes a problem quickly because I end up importing the function into many different components, if not all of them. This seems repetitive and also makes the project harder to maintain. For example if I want to rename helpers.js, or the functions inside it, I then need to go into every single component that imports it and modify the import statement.

Long story short: how do I make the functions inside helpers.js globally available so that I can call them inside any component without having to first import them and then prepend this to the function name? I basically want to be able to do this:

```

答:
Using Webpack v4

Create a separate file for readability (just dropped mine in plugins folder).
Reproduced from @CodinCat and @digout responses.

//resources/js/plugins/mixin.js
import Vue from 'vue';

Vue.mixin({
  methods: {
    capitalizeFirstLetter: str => str.charAt(0).toUpperCase() + str.slice(1),
    sampleFunction() {
      alert('Global Functions');
    },
  }
});
```
<p>Then, import in your main.js or app.js file.</p>
<pre class="lang-js prettyprint-override"><code>//app.js
import mixin from './plugins/mixin';
</code>```

USAGE:

Call this.sampleFunction() or this.capitalizeFirstLetter().

Body:
I have a Vue 2 project that has many (50+) single-file components. I use Vue-Router for routing and Vuex for state.

There is a file, called helpers.js, that contains a bunch of general-purpose functions, such as capitalizing the first letter of a string. This file looks like this:

export default {
  capitalizeFirstLetter(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }
}

My main.js file initializes the app:

import Vue from 'vue'
import VueResource from "vue-resource"
import store from "./store"
import Router from "./router"
import App from "./components/App.vue"

Vue.use(VueResource)

const app = new Vue({
  router: Router,
  store,
  template: '<app></app>',
  components: { App },
}).$mount('#app')

My App.vue file contains the template:

<template>
  <navbar></navbar>

    <router-view></router-view>

</template>

I then have a bunch of single-file components, which Vue-Router handles navigating to inside the <router-view> tag in the App.vue template.

Now let's say that I need to use the capitalizeFirstLetter() function inside a component that is defined in SomeComponent.vue. In order to do this, I first need to import it:

<template>Some Component</template>

This becomes a problem quickly because I end up importing the function into many different components, if not all of them. This seems repetitive and also makes the project harder to maintain. For example if I want to rename helpers.js, or the functions inside it, I then need to go into every single component that imports it and modify the import statement.

Long story short: how do I make the functions inside helpers.js globally available so that I can call them inside any component without having to first import them and then prepend this to the function name? I basically want to be able to do this:

Body:
Using Webpack v4

Create a separate file for readability (just dropped mine in plugins folder).
Reproduced from @CodinCat and @digout responses.

//resources/js/plugins/mixin.js
import Vue from 'vue';

Vue.mixin({
  methods: {
    capitalizeFirstLetter: str => str.charAt(0).toUpperCase() + str.slice(1),
    sampleFunction() {
      alert('Global Functions');
    },
  }
});

Then, import in your main.js or app.js file.

//app.js
import mixin from './plugins/mixin';

USAGE:

Call this.sampleFunction() or this.capitalizeFirstLetter().


问:
How to change the below to variable in powershell?
I want to make it so i can select the process and CPU for each of these processes and save them in a variable. For example selecting the first process and saving it as a variable $process1 and $process1CPU</p>

```<code>$Processes = Get-Counter -ErrorAction SilentlyContinue '\Process(*)\% Processor Time' | Select-Object -ExpandProperty countersamples| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} | Sort-Object -Property cookedvalue -Descending| Select-Object -First 5|  ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}}
</code>```

答:
Try this:

```<code>$i = 0
$process = @("Processes")
$processCpu = @("Process CPU")
Get-Process | ForEach {
  $i++
  $process[$i] = $_.ProcessName
  $processCpu[$i] = (Get-Counter '\Process(*)\% Processor Time').CounterSamples).CookedValue
}
</code>```

Now example if you want to get the Process name 3 use $Process[3] and for its CPU use $ProcessCpu[3]

Body:
I want to make it so i can select the process and CPU for each of these processes and save them in a variable. For example selecting the first process and saving it as a variable $process1 and $process1CPU

$Processes = Get-Counter -ErrorAction SilentlyContinue '\Process(*)\% Processor Time' | Select-Object -ExpandProperty countersamples| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} | Sort-Object -Property cookedvalue -Descending| Select-Object -First 5|  ft InstanceName,@{L='CPU';E={($_.Cookedvalue/100/$env:NUMBER_OF_PROCESSORS).toString('P')}}

Body:
Try this:

$i = 0
$process = @("Processes")
$processCpu = @("Process CPU")
Get-Process | ForEach {
  $i++
  $process[$i] = $_.ProcessName
  $processCpu[$i] = (Get-Counter '\Process(*)\% Processor Time').CounterSamples).CookedValue
}

Now example if you want to get the Process name 3 use $Process[3] and for its CPU use $ProcessCpu[3]


问:
Not same result in csv as in terminal. Linux
In terminal when I compare two list, in terminal I got 67 4 6 in a column and in csv just a 6.</p>

```<code>import csv

s1=[4,6,0,23,8,67,5]
s2=[2,3,9,6,7,67,4]
a=list(set(s1)&set(s2))

for q in a:
    print(q)
f = open('fm/state/csv/test', 'w')
f.write (str(q))
</code>```

答:
Working code, write to csv common numbers as list to csv file:</p>

```<code>import csv

s1=[4,6,0,23,8,67,5]
s2=[2,3,9,6,7,67,4,]
a=list(set(s1)&set(s2))

with open('/fm/state/csv/test', 'w') as f:
  f.write (str(a))
</code>```

Body:
In terminal when I compare two list, in terminal I got 67 4 6 in a column and in csv just a 6.

import csv

s1=[4,6,0,23,8,67,5]
s2=[2,3,9,6,7,67,4]
a=list(set(s1)&set(s2))

for q in a:
    print(q)
f = open('fm/state/csv/test', 'w')
f.write (str(q))

Body:
Working code, write to csv common numbers as list to csv file:

import csv

s1=[4,6,0,23,8,67,5]
s2=[2,3,9,6,7,67,4,]
a=list(set(s1)&set(s2))

with open('/fm/state/csv/test', 'w') as f:
  f.write (str(a))


问:
How can i change the itemLayout in Adapter class
I try to get a key from the main class but it is Always getting null

```<code> Bundle bundle =new Bundle();
 String type = bundle.getString("theType");

if (type =="Check"){

    view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_note_check, parent, false);

}else if (type =="photo"){
    view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_note_photo, parent, false);
}else {view = LayoutInflater.from(parent.getContext())
         .inflate(R.layout.item_note, parent, false);
}
</code>```

to get kType from

```<code>public void onRadioButtonTypeClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();
Bundle bundle = new Bundle();

   // Intent intent = new Intent();
    kType="photo";
    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.radioButtonSheet:
            if (checked)
                mImageNoteV.setImageResource(R.drawable.radio_button_note);
            kType= "note";
            bundle.putString("theType",kType);
         //   intent.putExtra("theType",kType);
            break;
        case R.id.radioButtonDone:
            if (checked)
                mImageNoteV.setImageResource(R.drawable.radio_button_check_box);
            kType="Check";
            bundle.putString("theType",kType);
        //   intent.putExtra("theType",kType);
            break;
        case R.id.radioButtonPicture:
            if (checked)
                mImageNoteV.setImageResource(R.drawable.radio_button_photo);
            kType = "photo";
            bundle.putString("theType",kType);
         //   intent.putExtra("theType",kType);
            break;
    }
</code>```

i try to set it in other class and get it again from it but does not work = null. is there good way to solve this

答:
Your question is already answered here.

In this case you can use just Intent for sending data between classes.

Here is a sample of using intent:

FirstActivity:

```<code>Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("theType", YOUR_TYPE_HERE);
startActivity(intent);
</code>```

SecondAcivity

```<code>String type = getIntent.getStringExtra("theType");
</code>```

But if you want to use Bundle instead, here is sample:

FirstActivity:

```<code>Bundle bundle = new Bundle();
bundle.putString("theType", YOUR_TYPE_HERE);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtras(bundle);
startActivity(intent);
</code>```

SecondActivity:

```<code>Bundle bundle = getIntent().getExtras();
String type = bundle.getString("theType");
</code>```

Body:
I try to get a key from the main class but it is Always getting null

 Bundle bundle =new Bundle();
 String type = bundle.getString("theType");

if (type =="Check"){

    view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_note_check, parent, false);

}else if (type =="photo"){
    view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_note_photo, parent, false);
}else {view = LayoutInflater.from(parent.getContext())
         .inflate(R.layout.item_note, parent, false);
}

to get kType from

public void onRadioButtonTypeClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();
Bundle bundle = new Bundle();

   // Intent intent = new Intent();
    kType="photo";
    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.radioButtonSheet:
            if (checked)
                mImageNoteV.setImageResource(R.drawable.radio_button_note);
            kType= "note";
            bundle.putString("theType",kType);
         //   intent.putExtra("theType",kType);
            break;
        case R.id.radioButtonDone:
            if (checked)
                mImageNoteV.setImageResource(R.drawable.radio_button_check_box);
            kType="Check";
            bundle.putString("theType",kType);
        //   intent.putExtra("theType",kType);
            break;
        case R.id.radioButtonPicture:
            if (checked)
                mImageNoteV.setImageResource(R.drawable.radio_button_photo);
            kType = "photo";
            bundle.putString("theType",kType);
         //   intent.putExtra("theType",kType);
            break;
    }

i try to set it in other class and get it again from it but does not work = null. is there good way to solve this

Body:
Your question is already answered here.

In this case you can use just Intent for sending data between classes.

Here is a sample of using intent:

FirstActivity:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("theType", YOUR_TYPE_HERE);
startActivity(intent);

SecondAcivity

String type = getIntent.getStringExtra("theType");

But if you want to use Bundle instead, here is sample:

FirstActivity:

Bundle bundle = new Bundle();
bundle.putString("theType", YOUR_TYPE_HERE);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtras(bundle);
startActivity(intent);

SecondActivity:

Bundle bundle = getIntent().getExtras();
String type = bundle.getString("theType");


问:
Can't get Indeterminate ProgressBar to display while ListView is Loading
I am loading a listview that lists all installed apps on the phone. I want the app to display an indeterminate progressbar (the spinning circular one) while the listview is loading.

```<code>     final PackageManager pm = this.getPackageManager();

    Intent intent = new Intent(Intent.ACTION_MAIN, null);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);

    final ArrayList<ResolveInfo> list =
            (ArrayList<ResolveInfo>) pm.queryIntentActivities(intent,
                    PackageManager.PERMISSION_GRANTED);
    for (ResolveInfo rInfo : list)
    {
        Log.i(TAG, ": Installed Applications " + rInfo.activityInfo.
                applicationInfo.loadLabel(pm).toString());
    }

    final ArrayAdapter<ResolveInfo> adapter =
        new ArrayAdapter<ResolveInfo>(this, R.layout.list_item, list)
        {
        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            if (convertView == null)
                convertView = LayoutInflater.from(parent.getContext()).
                    inflate(R.layout.list_item, parent, false);

            final String text = list.get(position).activityInfo.
                applicationInfo.loadLabel(pm).toString();
            ((TextView)convertView.findViewById(R.id.text)).setText(text);

            final Drawable drawable = list.get(position).activityInfo.applicationInfo.loadIcon(pm);
            ((ImageView)convertView.findViewById(R.id.image)).setImageDrawable(drawable);

            return convertView;
        }

        };
    setListAdapter(adapter);

    ListView lv = getListView();
    lv.setEmptyView(findViewById(R.id.empty));
    lv.setTextFilterEnabled(true);
</code>```

Heres the XML:

```<code><?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageView android:id="@+id/image"
        android:layout_width="50dp" android:layout_height="50dp" />
    <TextView android:id="@+id/text"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:padding="10dp" android:textSize="16sp" />

 <ScrollView
            android:id="@+id/empty" android:layout_width="fill_parent"
            android:layout_height="fill_parent">
            <ProgressBar android:id="@+id/progressBar1" android:layout_width="wrap_content"
            android:layout_height="wrap_content"></ProgressBar>

        </ScrollView>

 </LinearLayout>
</code>```

Nothing displays while the listview is loading.... what am I doing wrong???

答:
I think you need to load your data asynchronously:

When doing the initial setup only set the main ListView for the activity and set the empty view

Write an AsyncTask (link here) that loads your data asynchronously and populates your adapter when it completes

start your AsyncTask after initial setup

During the task execution your empty view (progress bar) should display and when the task completes, the ListView should be populated

Body:
I am loading a listview that lists all installed apps on the phone. I want the app to display an indeterminate progressbar (the spinning circular one) while the listview is loading.

     final PackageManager pm = this.getPackageManager();

    Intent intent = new Intent(Intent.ACTION_MAIN, null);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);

    final ArrayList<ResolveInfo> list =
            (ArrayList<ResolveInfo>) pm.queryIntentActivities(intent,
                    PackageManager.PERMISSION_GRANTED);
    for (ResolveInfo rInfo : list)
    {
        Log.i(TAG, ": Installed Applications " + rInfo.activityInfo.
                applicationInfo.loadLabel(pm).toString());
    }

    final ArrayAdapter<ResolveInfo> adapter =
        new ArrayAdapter<ResolveInfo>(this, R.layout.list_item, list)
        {
        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            if (convertView == null)
                convertView = LayoutInflater.from(parent.getContext()).
                    inflate(R.layout.list_item, parent, false);

            final String text = list.get(position).activityInfo.
                applicationInfo.loadLabel(pm).toString();
            ((TextView)convertView.findViewById(R.id.text)).setText(text);

            final Drawable drawable = list.get(position).activityInfo.applicationInfo.loadIcon(pm);
            ((ImageView)convertView.findViewById(R.id.image)).setImageDrawable(drawable);

            return convertView;
        }

        };
    setListAdapter(adapter);

    ListView lv = getListView();
    lv.setEmptyView(findViewById(R.id.empty));
    lv.setTextFilterEnabled(true);

Heres the XML:

<?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageView android:id="@+id/image"
        android:layout_width="50dp" android:layout_height="50dp" />
    <TextView android:id="@+id/text"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:padding="10dp" android:textSize="16sp" />

 <ScrollView
            android:id="@+id/empty" android:layout_width="fill_parent"
            android:layout_height="fill_parent">
            <ProgressBar android:id="@+id/progressBar1" android:layout_width="wrap_content"
            android:layout_height="wrap_content"></ProgressBar>

        </ScrollView>

 </LinearLayout>

Nothing displays while the listview is loading.... what am I doing wrong???


问:
many to many insert from one form/controller method to all three tables - author, book & author_book in laravel
Succesfully inserted to author and book table but unable to insert in pivot table. I need to insert from the same form in all the 3 tables. I have attached screenshot of all of my code. Pls help.

Book Model

```<code>class Book extends Model
{
  protected $guarded = [];

  public function authors(){
    return $this->belongsToMany('App\Models\Author');
  }
}
</code>```

Author Model

```<code>class Author extends Model
{
  public $guarded = [];

  public function books(){
    return $this->belongsToMany('App\Models\Book');
  }
 }
</code>```

Book Controller

```<code>public function store(Request $request)
{
    Book::create($this->validateBookInputs());
    Author::create($this->validateAuthorInputs());

    $book_id=Book::latest()->first()->id;
    // $author_id=Author::latest()->first()->id;

    // $book = new Book();
    // $book->authors()->attach($author_id);

    $author = new Author();
    $author->books()->attach($book_id);
    return back()->with('status', 'Insert Successful!');
}

public function validateBookInputs(){
    return request()->validate([
        'book_name' => 'required'
    ]);
}
public function validateAuthorInputs(){
    return request()->validate([
        'author_name' => 'required'
    ]);
}
</code>```

Book Create - View

```<code><form action="/books" method="POST">
<div class="form-group">
    <label>Enter Book Name</label>
    <input type="text" name="book_name" placeholder="Book Name" value="{{old('book_name')}}" class="form-control">
</div>
<div class="form-group">
    <label>Enter Author Name</label>
    <input type="text" name="author_name" placeholder="Author Name" value="{{old('author_name')}}"
        class="form-control">
</div>

<button type="submit" class="button-green">Submit</button>
@csrf
</code>```

create authors table

```<code>public function up()
{
    Schema::create('authors', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('author_name', '30');
        $table->timestamps();
    });
}
</code>```

create books table

```<code>public function up()
{
    Schema::create('books', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('book_name', '30');
        $table->timestamps();
    });
}
</code>```

create author_book table

```<code>public function up()
{
    Schema::create('author_book', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('author_id');
        $table->unsignedBigInteger('book_id');
        $table->timestamps();
    });
}
</code>```

The Error

```<code>Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'author_id' cannot be null (SQL: insert into `author_book` (`author_id`, `book_id`) values (?, 25))
</code>```

答:
You can avoid attaching step and go from 3 to two steps</p>

```<code>$book = Book::create($this->validateBookInputs());
$author = $book->authors()->create($this->validateAuthorInputs())
</code>```

Body:
Succesfully inserted to author and book table but unable to insert in pivot table. I need to insert from the same form in all the 3 tables. I have attached screenshot of all of my code. Pls help.

Book Model

class Book extends Model
{
  protected $guarded = [];

  public function authors(){
    return $this->belongsToMany('App\Models\Author');
  }
}

Author Model

class Author extends Model
{
  public $guarded = [];

  public function books(){
    return $this->belongsToMany('App\Models\Book');
  }
 }

Book Controller

public function store(Request $request)
{
    Book::create($this->validateBookInputs());
    Author::create($this->validateAuthorInputs());

    $book_id=Book::latest()->first()->id;
    // $author_id=Author::latest()->first()->id;

    // $book = new Book();
    // $book->authors()->attach($author_id);

    $author = new Author();
    $author->books()->attach($book_id);
    return back()->with('status', 'Insert Successful!');
}

public function validateBookInputs(){
    return request()->validate([
        'book_name' => 'required'
    ]);
}
public function validateAuthorInputs(){
    return request()->validate([
        'author_name' => 'required'
    ]);
}

Book Create - View

<form action="/books" method="POST">

    Enter Book Name
    <input type="text" name="book_name" placeholder="Book Name" value="{{old('book_name')}}" class="form-control">

    Enter Author Name
    <input type="text" name="author_name" placeholder="Author Name" value="{{old('author_name')}}"
        class="form-control">

<button type="submit" class="button-green">Submit</button>
@csrf

create authors table

public function up()
{
    Schema::create('authors', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('author_name', '30');
        $table->timestamps();
    });
}

create books table

public function up()
{
    Schema::create('books', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('book_name', '30');
        $table->timestamps();
    });
}

create author_book table

public function up()
{
    Schema::create('author_book', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('author_id');
        $table->unsignedBigInteger('book_id');
        $table->timestamps();
    });
}

The Error

Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'author_id' cannot be null (SQL: insert into `author_book` (`author_id`, `book_id`) values (?, 25))

Body:
You can avoid attaching step and go from 3 to two steps

$book = Book::create($this->validateBookInputs());
$author = $book->authors()->create($this->validateAuthorInputs())


问:
How to broadcast/share a variable/property from a slave to the others?
I have a JMeter script that is executed in distributed mode with 4 nodes. One of them is the controller and does not do any request and the other 3, as workers do the requests.

I can currently set one of the workers as a master worker, setting a property in the user.properties file for that specific worker. This "master" worker perform some requests that has to be done only once, so these requests can't be done by the other workers.

Now I have the need of extract some values from the response of these unique request and send this information to the other slaves.

Is it possible to do this?
How can data be sent form one worker to the other workers at run time?

答:
No it's not possible.

The communication between Controller and servers is very reduced:

Controller send start / stop / shutdown commands to servers

Servers send sample result to controller

That's it.

To communicate you'll need to use 3rd party tiers like Redis DB or similar means.


问:
filter show not the correct list after he did the filtering
I have edited my Adapter class and extended the filterable class. My search functionality works but i am unable to get the currect list.

here is my adapter class:

```<code>public class ListViewAdapter extends BaseAdapter implements Filterable{
Context context;
private List<Student> studentList;
private List<Student> orginStudentList;

public ListViewAdapter(Context context,List<Student> studentList)
{
    this.studentList = new ArrayList<>();
    this.studentList = studentList;
    this.orginStudentList = studentList;
    this.context = context;
}
@Override
public Filter getFilter() {
    if(nameFilter == null)
        nameFilter = new NameFilter();
    return nameFilter;
}
public void resetData() {
    studentList = orginStudentList;
}
private class NameFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        // We implement here the filter logic
        if ((constraint == null) || (constraint.length() == 0)) {
            // No filter implemented we return all the list
            results.values = orginStudentList;
            results.count = orginStudentList.size();
        }else if (Character.isDigit(constraint.charAt(constraint.length()-1))){
            results.values = studentList;
            results.count = studentList.size();
        }
        else {
            // We perform filtering operation
            List<Student> nStudentList = new ArrayList<Student>();
            for (Student stu : orginStudentList) {
                String name = stu.getName();
                if (name.contains(constraint))
                    nStudentList.add(stu);
            }
            results.values = nStudentList;
            results.count = nStudentList.size();
        }
        return results;
    }
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        studentList = (List<Student>)results.values;
        notifyDataSetChanged();
    }
}
</code>```

}
I do check if the results are zero or null and if so to return the currect list? What am I missing?

答:
```<code> private void filter(String text) {
        List<Model> filterdNames = new ArrayList<>();

        for (Model s : Models) {

            if (s.getName().contains(text)) {

                filterdNames.add(s);
            }
        }

        //calling a method of the adapter class and passing the filtered list
        recyclerAdapter.filterList(filterdNames);
    }
</code>```

Body:
I have edited my Adapter class and extended the filterable class. My search functionality works but i am unable to get the currect list.

here is my adapter class:

public class ListViewAdapter extends BaseAdapter implements Filterable{
Context context;
private List<Student> studentList;
private List<Student> orginStudentList;

public ListViewAdapter(Context context,List<Student> studentList)
{
    this.studentList = new ArrayList<>();
    this.studentList = studentList;
    this.orginStudentList = studentList;
    this.context = context;
}
@Override
public Filter getFilter() {
    if(nameFilter == null)
        nameFilter = new NameFilter();
    return nameFilter;
}
public void resetData() {
    studentList = orginStudentList;
}
private class NameFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        // We implement here the filter logic
        if ((constraint == null) || (constraint.length() == 0)) {
            // No filter implemented we return all the list
            results.values = orginStudentList;
            results.count = orginStudentList.size();
        }else if (Character.isDigit(constraint.charAt(constraint.length()-1))){
            results.values = studentList;
            results.count = studentList.size();
        }
        else {
            // We perform filtering operation
            List<Student> nStudentList = new ArrayList<Student>();
            for (Student stu : orginStudentList) {
                String name = stu.getName();
                if (name.contains(constraint))
                    nStudentList.add(stu);
            }
            results.values = nStudentList;
            results.count = nStudentList.size();
        }
        return results;
    }
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        studentList = (List<Student>)results.values;
        notifyDataSetChanged();
    }
}

}
I do check if the results are zero or null and if so to return the currect list? What am I missing?


问:
Making divs appear side by side while using a loop in wordpress
I want to mak 2 divs appear in one row and then display following two in the next row and so on. I am using a php while loop to render the divs on the screen so they are appearing one below the other. How do I make it display them side by side?

Right now it looks like this:
screenshot of the way it is displaying

my code looks like this at the moment:

```<code><?php $decadesFrontPage = new WP_Query(array(
          'posts_per_page' => 2,
          'post_type' => 'Decades',
      ));

      while($decadesFrontPage->have_posts()){
        $decadesFrontPage -> the_post(); ?>

        <div class="row">
          <div class="col-sm-6">
            <div class="card">
              <div class="card-body">
                <h5 class="card-title"><?php the_title() ?></h5>
                <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
                <a href="#" class="btn btn-primary">Go somewhere</a>
              </div>
            </div>
          </div>

        </div>

      <?php } ?>
</code>```

答:
1. Move the row and col outside the loop

2. Add display inline-block to card

3. Define width for the card

```<code>    <div class="row">
      <div class="col-sm-6">
<?php $decadesFrontPage = new WP_Query(array(
      'posts_per_page' => 2,
      'post_type' => 'Decades',
  ));

  while($decadesFrontPage->have_posts()){
    $decadesFrontPage -> the_post(); ?>

        <div class="card d-inline-block" style="width: 18rem;>
          <div class="card-body">
            <h5 class="card-title"><?php the_title() ?></h5>
            <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
            <a href="#" class="btn btn-primary">Go somewhere</a>
          </div>
        </div>

  <?php } ?>
      </div>

    </div>
</code>```

Body:
I want to mak 2 divs appear in one row and then display following two in the next row and so on. I am using a php while loop to render the divs on the screen so they are appearing one below the other. How do I make it display them side by side?

Right now it looks like this:
screenshot of the way it is displaying

my code looks like this at the moment:

<?php $decadesFrontPage = new WP_Query(array(
          'posts_per_page' => 2,
          'post_type' => 'Decades',
      ));

      while($decadesFrontPage->have_posts()){
        $decadesFrontPage -> the_post(); ?>

<?php the_title() ?>

With supporting text below as a natural lead-in to additional content.

                Go somewhere

      <?php } ?>

Body:
1. Move the row and col outside the loop

2. Add display inline-block to card

3. Define width for the card

    <div class="row">
      <div class="col-sm-6">
<?php $decadesFrontPage = new WP_Query(array(
      'posts_per_page' => 2,
      'post_type' => 'Decades',
  ));

  while($decadesFrontPage->have_posts()){
    $decadesFrontPage -> the_post(); ?>

        <div class="card d-inline-block" style="width: 18rem;>
          <div class="card-body">
            <h5 class="card-title"><?php the_title() ?></h5>
            <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
            <a href="#" class="btn btn-primary">Go somewhere</a>
          </div>
        </div>

  <?php } ?>
      </div>

    </div>


问:
Can´t get custom attribute on WooCommerce product
I try to save custom meta data after creating an order in WooCommerce. I try it with the woocommerce_new_order_item hook and in general it works. But I need to store a custom attribute from the ordered product..but I can´t get it.

What I tried:

```<code>add_action('woocommerce_new_order_item','add_basic_meta_for_new_quote',10,3); // add extra order metas

function add_basic_meta_for_new_quote($item_id, $values, $cart_item_key)
{
    $angebotstext = get_post_meta($item_id, 'angebotstext', false);
    wc_add_order_item_meta($item_id, 'angebotstext', $angebotstext);
}
</code>```

or

```<code>add_action('woocommerce_new_order_item','add_basic_meta_for_new_quote',10,3); // add extra order metas

function add_basic_meta_for_new_quote($item_id, $values, $cart_item_key)
{
    global $product;
    $angebotstext = $product->get_attribute( 'pa_angebotstext' );
    wc_add_order_item_meta($item_id, 'angebotstext', $angebotstext);
}
</code>```

The attribute is saved here:

... and the result for meta_value is always empty, NULL or a:0:{}

Do you have any idea?

-----EDIT----

It worked with this way:

```<code>    add_action('woocommerce_new_order_item','add_basic_meta_for_new_quote',10,3); // add extra order metas

function add_basic_meta_for_new_quote($item_id, $item, $order_id )
{

    if ($order_id) {
        $order = wc_get_order( $order_id );
  }

    # Iterating through each order items (WC_Order_Item_Product objects in WC 3+)
    if ($order) {
        foreach ( $order->get_items() as $item_id => $item_values ) {

            // Product_id
            $product_id = $item_values->get_product_id();

            $product = wc_get_product($product_id);
            $angebotstext = $product->get_attribute('Angebotstext');
            if ( !empty($angebotstext) && $angebotstext != NULL ) {
                wc_add_order_item_meta($item_id, 'Angebotstext' , $angebotstext);
      }
        }
  }
}
</code>```

BUT: This code adds my custom attribute two times as meta.... why that?

答:
The main issue here is if the order contains multiple products, so you're going to face the issue of multiple updates for the same order.

To avoid that or to choose to deal with it the right way, here are some ideas:

To make this works for multiple products:

Changed this part:

```<code>wc_add_order_item_meta($item_id, 'Angebotstext _'.$product_id , $angebotstext);
</code>```

This will add a new custom meta for each product by adding the product ID at the end of each meta_key and the meta_value will be the product unique value for that attribute.
so you're going to find this custom fields on the order page:

Angebotstext_123 = product attribute.

Angebotstext_485 = product

attribute. Angebotstext_951 = product attribute.

the '123', '485' are the product id and the meta value for that meta_key will be that product attribute.

To prevent it from updating multiple times:

```<code>if ($order) {
     $angebotstext ='';
        foreach ( $order->get_items() as $item_id => $item_values ) {

            // Product_id
            $product_id = $item_values->get_product_id();

            $product = wc_get_product($product_id);
            $angebotstext = $product->get_attribute('Angebotstext');
            $prev_angebotstext = $angebotstext;
            if ( !empty($angebotstext) && $angebotstext != NULL && $angebotstext != $prev_angebotstext ) {
                wc_add_order_item_meta($item_id, 'Angebotstext' , $angebotstext);
      }
        }
  }
</code>```

"$prev_angebotstext" is the previous item attribute.

```<code>if ( !empty($angebotstext) && $angebotstext != NULL && $angebotstext != $prev_angebotstext )
</code>```

This condition will check if the current product attribute is equal to the previous product attribute, if yes it will not update the order again.

Thank you!

Body:
I try to save custom meta data after creating an order in WooCommerce. I try it with the woocommerce_new_order_item hook and in general it works. But I need to store a custom attribute from the ordered product..but I can´t get it.

What I tried:

add_action('woocommerce_new_order_item','add_basic_meta_for_new_quote',10,3); // add extra order metas

function add_basic_meta_for_new_quote($item_id, $values, $cart_item_key)
{
    $angebotstext = get_post_meta($item_id, 'angebotstext', false);
    wc_add_order_item_meta($item_id, 'angebotstext', $angebotstext);
}

or

add_action('woocommerce_new_order_item','add_basic_meta_for_new_quote',10,3); // add extra order metas

function add_basic_meta_for_new_quote($item_id, $values, $cart_item_key)
{
    global $product;
    $angebotstext = $product->get_attribute( 'pa_angebotstext' );
    wc_add_order_item_meta($item_id, 'angebotstext', $angebotstext);
}

The attribute is saved here:

... and the result for meta_value is always empty, NULL or a:0:{}

Do you have any idea?

-----EDIT----

It worked with this way:

    add_action('woocommerce_new_order_item','add_basic_meta_for_new_quote',10,3); // add extra order metas

function add_basic_meta_for_new_quote($item_id, $item, $order_id )
{

    if ($order_id) {
        $order = wc_get_order( $order_id );
  }

    # Iterating through each order items (WC_Order_Item_Product objects in WC 3+)
    if ($order) {
        foreach ( $order->get_items() as $item_id => $item_values ) {

            // Product_id
            $product_id = $item_values->get_product_id();

            $product = wc_get_product($product_id);
            $angebotstext = $product->get_attribute('Angebotstext');
            if ( !empty($angebotstext) && $angebotstext != NULL ) {
                wc_add_order_item_meta($item_id, 'Angebotstext' , $angebotstext);
      }
        }
  }
}

BUT: This code adds my custom attribute two times as meta.... why that?

Body:
The main issue here is if the order contains multiple products, so you're going to face the issue of multiple updates for the same order.

To avoid that or to choose to deal with it the right way, here are some ideas:

To make this works for multiple products:

Changed this part:

wc_add_order_item_meta($item_id, 'Angebotstext _'.$product_id , $angebotstext);

This will add a new custom meta for each product by adding the product ID at the end of each meta_key and the meta_value will be the product unique value for that attribute.
so you're going to find this custom fields on the order page:

Angebotstext_123 = product attribute.

Angebotstext_485 = product

attribute. Angebotstext_951 = product attribute.

the '123', '485' are the product id and the meta value for that meta_key will be that product attribute.

To prevent it from updating multiple times:

if ($order) {
     $angebotstext ='';
        foreach ( $order->get_items() as $item_id => $item_values ) {

            // Product_id
            $product_id = $item_values->get_product_id();

            $product = wc_get_product($product_id);
            $angebotstext = $product->get_attribute('Angebotstext');
            $prev_angebotstext = $angebotstext;
            if ( !empty($angebotstext) && $angebotstext != NULL && $angebotstext != $prev_angebotstext ) {
                wc_add_order_item_meta($item_id, 'Angebotstext' , $angebotstext);
      }
        }
  }

"$prev_angebotstext" is the previous item attribute.

if ( !empty($angebotstext) && $angebotstext != NULL && $angebotstext != $prev_angebotstext )

This condition will check if the current product attribute is equal to the previous product attribute, if yes it will not update the order again.

Thank you!


问:
Can I traverse through an excel file using Indexes when working with Apache POI?
Please excuse me if I am not clear. English is not my first language.

I'm trying to write a code where I can traverse through the first row of an excel file until I find the column labeled 'Comments'. I want to run some action on the text in that column and then save the result in a new column at the end of the file. Can I traverse the xlsx file in a manner similar to indexes? And if so, how can I jump straight to a cell using that cell's coordinates?

```<code>public static void main(String[] args) throws IOException {

    File myFile = new File("temp.xlsx");
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(myFile);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    @SuppressWarnings("resource")
    XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
    XSSFSheet mySheet = myWorkBook.getSheetAt(0);
    Iterator<Row> rowIterator = mySheet.iterator();

    Row row = rowIterator.next();
    Iterator<Cell> cellIterator = row.cellIterator();

    while (cellIterator.hasNext()) {

        Cell cell = cellIterator.next();

        String comment = cell.toString();

        if (comment.equals("Comments"))
        {
            System.out.println("Hello");
        }

    }

}
</code>```

}

答:
```<code>FileInputStream file = new FileInputStream(new File(fileLocation));

Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);

Map<Integer, List<String>> data = new HashMap<>();
int i = 0;
for (Row row : sheet) {
    data.put(i, new ArrayList<String>());
    for (Cell cell : row) {
        switch (cell.getCellTypeEnum()) {
            case STRING: ... break;
            case NUMERIC: ... break;
            case BOOLEAN: ... break;
            case FORMULA: ... break;
            default: data.get(new Integer(i)).add(" ");
        }
    }
    i++;
}
</code>```

Body:
Please excuse me if I am not clear. English is not my first language.

I'm trying to write a code where I can traverse through the first row of an excel file until I find the column labeled 'Comments'. I want to run some action on the text in that column and then save the result in a new column at the end of the file. Can I traverse the xlsx file in a manner similar to indexes? And if so, how can I jump straight to a cell using that cell's coordinates?

public static void main(String[] args) throws IOException {

    File myFile = new File("temp.xlsx");
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(myFile);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    @SuppressWarnings("resource")
    XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
    XSSFSheet mySheet = myWorkBook.getSheetAt(0);
    Iterator<Row> rowIterator = mySheet.iterator();

    Row row = rowIterator.next();
    Iterator<Cell> cellIterator = row.cellIterator();

    while (cellIterator.hasNext()) {

        Cell cell = cellIterator.next();

        String comment = cell.toString();

        if (comment.equals("Comments"))
        {
            System.out.println("Hello");
        }

    }

}

}


问:
On click, targat not found
I have given below html and jQuery.

When click on link, that particular content to show. but it not works.

I can't find the problem, can someone help me?

HTML

```<code><div class="nav">
    <ul>
        <li id="about" data-targat=".about-info"><a href="#">about</a></li>
        <li><a id="work" data-targat=".work-info"><a href="#">work</a></li>
    </ul>
</div>

<div class="Content-wrapper">
    <div class="about-info content">
        <p>about info goes here</p>
    </div>
    <div class="work-info content">
        <p>work info goes here</p>
    </div>
</div>
</code>```

jQuery

```<code>var $main = $(".Content-wrapper");
var $section = $(".content").hide();
$('.nav ul li').click(function(e) {
    e.preventDefault();
    $section.hide();
    var target = $(this).data('target');
    if(target){
        $section.filter(target).show();
    }
});
</code>```

答:
You should listen to li event like $('.nav ul li').on("click", function(e)

In HTML data-targat while in jQuery you are getting $(this).data('target')

In second li
 is redundant a tag.

var $main = $(".Content-wrapper");
var $section = $(".content").hide();
$('.nav ul li').on("click", function(e) {
    $section.hide();
    var target = $(this).data('target');
    if(target){
        $section.filter(target).show();
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="nav">
    <ul>
        <li id="about" data-target=".about-info">about</li>
        <li id="work" data-target=".work-info">href="#">work</li>
    </ul>
</div>

<div class="Content-wrapper">
    <div class="about-info content">
        <p>about info goes here</p>
    </div>
    <div class="work-info content">
        <p>work info goes here</p>
    </div>
</div></code>```

Title: On click, targat not found

Body:
I have given below html and jQuery.

When click on link, that particular content to show. but it not works.

I can't find the problem, can someone help me?

HTML

about

work

about info goes here

work info goes here

jQuery

var $main = $(".Content-wrapper");
var $section = $(".content").hide();
$('.nav ul li').click(function(e) {
    e.preventDefault();
    $section.hide();
    var target = $(this).data('target');
    if(target){
        $section.filter(target).show();
    }
});

Body:
You should listen to li event like $('.nav ul li').on("click", function(e)

In HTML data-targat while in jQuery you are getting $(this).data('target')

In second li <li><a id="work" is redundant a tag.

var $main = $(".Content-wrapper");
var $section = $(".content").hide();
$('.nav ul li').on("click", function(e) {
    $section.hide();
    var target = $(this).data('target');
    if(target){
        $section.filter(target).show();
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="nav">
    <ul>
        <li id="about" data-target=".about-info"><a href="#">about</a></li>
        <li id="work" data-target=".work-info"><a href="#">work</a></li>
    </ul>
</div>

<div class="Content-wrapper">
    <div class="about-info content">
        <p>about info goes here</p>
    </div>
    <div class="work-info content">
        <p>work info goes here</p>
    </div>
</div>