答:
Below, I walk through suggestions for (1) preparing your data, (2) specifying the model, and (3) examining model results.

In addition to tidyverse packages and lme4, I'll use broom.mixed::glance() and tidy() to inspect model parameters, and ggeffects::ggpredict() to generate model predictions for plotting.

library(tidyverse)
library(lme4)
library(broom.mixed)
library(ggeffects)
```
<h3>Data Prep & Variable Selection</h3>
<p><code>Timepoint</code> is a character, and will be treated as as an unordered category in the model, which likely isn't what you want. It's often better to use the actual time elapsed since baseline rather than a generic "timepoint," especially if distance between timepoints is variable. For this answer, I computed an alternate <code>Timepoint_yrs</code> based on each subject's change in age from baseline; but if you have a more precise record of time, you may want to use that instead.</p>
<p>Also, <code>outcome</code> consists of a small range of values, on the order of 1e-4 - 1e-3; this can cause lmer to misbehave, so I scaled this.</p>
<pre class="lang-r prettyprint-override"><code>DF <- DF %>%
  group_by(ID) %>%
  mutate(Timepoint_yrs = Age - min(Age)) %>%
  ungroup() %>%
  mutate(outcome_scaled = as.numeric(scale(outcome)))
</code>```

Including both Age and Age_group in the model will cause issues with multicollinearity, as one is a function of the other. Given the extreme bimodal distribution of Age, I just used Age_group. And as above, change in age is now accounted for by Timepoint_yrs.

Model Specification

"I am trying to estimate if there is a significant difference in slope of the outcome variable between Young and Older adults across the 3 Timepoints" -- i.e., an Age_group by Timepoint_yrs interaction. You also wrote that "sex is used as an interaction variable." So putting this together, you're looking at a 3-way Age_group by Sex by Timepoint_yrs interaction. Because Age_group and Sex only vary between subjects, we'll specify this at the level of fixed effects:

outcome_scaled ~ Age_group * Sex * Timepoint_yrs
```
<p>Because you have multiple measurements per person (<code>ID</code>), we'll include random intercepts for <code>ID</code>:</p>
<pre class="lang-r prettyprint-override"><code>outcome_scaled ~ Age_group * Sex * Timepoint_yrs + (1 | ID)
</code>```

We can also allow the slope of Timepoint_yrs to vary within individuals. From your post, I don't see a strong theoretical reason for whether or not to include random slopes -- so we'll do both and see which model fits best.

# model 1 - random intercepts
rnd_intercept <- lmer(outcome_scaled ~ Age_group * Sex * Timepoint_yrs + (1 | ID), data = DF)

# model 2 - random intercepts and slopes
rnd_int_slope <- lmer(outcome_scaled ~ Age_group * Sex * Timepoint_yrs + (Timepoint_yrs | ID), data = DF)
```
<h3>Model Results</h3>
<pre class="lang-r prettyprint-override"><code>glance(rnd_intercept)
# # A tibble: 1 x 6
# sigma logLik   AIC   BIC REMLcrit df.residual
#   <dbl>  <dbl> <dbl> <dbl>    <dbl>       <int>
# 1 0.510  -575. 1170. 1212.    1150.         494

glance(rnd_int_slopes)
# A tibble: 1 x 6
#   sigma logLik   AIC   BIC REMLcrit df.residual
#   <dbl>  <dbl> <dbl> <dbl>    <dbl>       <int>
# 1 0.487  -575. 1173. 1224.    1149.         492
</code>```

Looking at AIC and BIC, the random intercepts model seems a better / more parsimonious fit; absent any theoretical reason to prefer the random slopes model, we'll stick with that one.

tidy(rnd_intercept, conf.int = TRUE)
# # A tibble: 10 x 8
#    effect   group    term               estimate std.error statistic conf.low conf.high
#    <chr>    <chr>    <chr>                 <dbl>     <dbl>     <dbl>    <dbl>     <dbl>
#  1 fixed    NA       (Intercept)         -0.123     0.122    -1.01    -0.361     0.116
#  2 fixed    NA       Age_groupYoung      -0.0142    0.221    -0.0643  -0.448     0.419
#  3 fixed    NA       SexMale              0.248     0.214     1.16    -0.171     0.667
#  4 fixed    NA       Timepoint_yrs        0.131     0.0407    3.21     0.0509    0.210
#  5 fixed    NA       Age_groupYoung:Se~  -0.0704    0.317    -0.222   -0.692     0.551
#  6 fixed    NA       Age_groupYoung:Ti~  -0.152     0.0654   -2.32    -0.280    -0.0234
#  7 fixed    NA       SexMale:Timepoint~  -0.0547    0.0771   -0.709   -0.206     0.0964
#  8 fixed    NA       Age_groupYoung:Se~   0.0192    0.101     0.190   -0.178     0.217
#  9 ran_pars ID       sd__(Intercept)      0.862    NA        NA       NA        NA
# 10 ran_pars Residual sd__Observation      0.510    NA        NA       NA        NA
```
<p>Finally, we can plot predicted values from the model. Your original code predicted a datapoint for every row in your original data, then basically traced a line between each of these, which as you noted isn't very informative. Instead, we want to base the plot on just one predicted outcome value (+/- error) for each unique combination of your predictors. <code>ggeffects::ggpredict()</code> is a nice shortcut for this; <code>emmeans::emmeans()</code> would be another option.</p>
<pre class="lang-r prettyprint-override"><code>plot_data <- ggpredict(rnd_intercept, terms = c("Timepoint_yrs", "Age_group", "Sex"))
# col names: x = Timepoint_yrs, group = Age_group, facet = Sex, predicted = observed_scaled

ggplot(plot_data, aes(x, predicted)) +
  geom_line(aes(color = group)) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high, fill = group), alpha = .1) +
  facet_wrap(vars(facet)) +
  labs(x = "Years Since Baseline", y = "Outcome\n(scaled, model-predicted)") +
  theme_classic()
</code>```

Based on your model coefficients, you may also want to look at just Age_group across Timepoint_yrs, as well as the main effect of Timepoint_yrs collapsed across other variables. You can do this by changing the terms argument to ggpredict() and modifying the ggplot spec accordingly.

Title: lmer longitudinal analyses in R for variance within subjects and between timepoints

Body:
I have the following longitudinal (3 Timepoints) data set:

# A tibble: 504 x 6
      ID   Age Age_group Sex    Timepoint  outcome
   <int> <int> <fct>     <chr>  <chr>        <dbl>
 1 33714    15 Young     Male   bl        0.00103
 2 35377    15 Young     Female bl        0.00106
 3 38623    45 Older     Female bl        0.00103
 4 38806    66 Older     Female bl        0.00114
 5 39593    69 Older     Female bl        0.00113
 6 39820    60 Older     Female bl        0.00113
 7 39951    46 Older     Male   bl        0.000986
 8 40286    68 Older     Female bl        0.00107
 9 40556     9 Young     Male   bl        0.00114
10 40798    11 Young     Male   bl        0.00111
# ... with 494 more rows

data:

39820L, 39951L, 40286L, 40556L, 40798L, 40800L, 40815L, 43762L,
50848L, 52183L, 52461L, 52577L, 53320L, 53873L, 54153L, 54206L,
54581L, 55122L, 55267L, 55462L, 55612L, 55920L, 56022L, 56307L,
56420L, 56679L, 57405L, 57445L, 57480L, 57725L, 57809L, 58004L,
58215L, 58229L, 58503L, 59326L, 59327L, 59344L, 59361L, 59865L,
60099L, 60100L, 60280L, 60384L, 60429L, 60493L, 60503L, 60575L,
60603L, 60664L, 60846L, 61415L, 61656L, 61749L, 61883L, 62081L,
62210L, 62285L, 62937L, 62983L, 63327L, 63329L, 64081L, 64328L,
64418L, 64507L, 64596L, 65178L, 65250L, 65302L, 65478L, 65480L,
65487L, 65572L, 65802L, 65935L, 65974L, 65975L, 65978L, 65991L,
65995L, 66013L, 66154L, 66237L, 66245L, 66389L, 66396L, 66460L,
66572L, 66589L, 67174L, 73230L, 73525L, 73539L, 73677L, 73942L,
73953L, 74034L, 74113L, 74114L, 74427L, 74439L, 74607L, 74641L,
74657L, 74794L, 74800L, 74836L, 74942L, 74952L, 74962L, 74969L,
74977L, 74985L, 74989L, 75220L, 75229L, 75407L, 75653L, 75732L,
75735L, 75757L, 75895L, 75898L, 76381L, 76559L, 76574L, 76594L,
76595L, 76746L, 76751L, 76755L, 76759L, 76775L, 77088L, 77091L,
77099L, 77134L, 77188L, 77203L, 77252L, 77304L, 77413L, 77453L,
77528L, 77556L, 77585L, 77668L, 78262L, 79724L, 79730L, 79850L,
79977L, 80052L, 80819L, 80901L, 80932L, 81064L, 81065L, 81071L,
81098L, 81142L, 81175L, 33714L, 35377L, 38623L, 38806L, 39593L,
39820L, 39951L, 40286L, 40556L, 40798L, 40800L, 40815L, 43762L,
50848L, 52183L, 52461L, 52577L, 53320L, 53873L, 54153L, 54206L,
54581L, 55122L, 55267L, 55462L, 55612L, 55920L, 56022L, 56307L,
56420L, 56679L, 57405L, 57445L, 57480L, 57725L, 57809L, 58004L,
58215L, 58229L, 58503L, 59326L, 59327L, 59344L, 59361L, 59865L,
60099L, 60100L, 60280L, 60384L, 60429L, 60493L, 60503L, 60575L,
60603L, 60664L, 60846L, 61415L, 61656L, 61749L, 61883L, 62081L,
62210L, 62285L, 62937L, 62983L, 63327L, 63329L, 64081L, 64328L,
64418L, 64507L, 64596L, 65178L, 65250L, 65302L, 65478L, 65480L,
65487L, 65572L, 65802L, 65935L, 65974L, 65975L, 65978L, 65991L,
65995L, 66013L, 66154L, 66237L, 66245L, 66389L, 66396L, 66460L,
66572L, 66589L, 67174L, 73230L, 73525L, 73539L, 73677L, 73942L,
73953L, 74034L, 74113L, 74114L, 74427L, 74439L, 74607L, 74641L,
74657L, 74794L, 74800L, 74836L, 74942L, 74952L, 74962L, 74969L,
74977L, 74985L, 74989L, 75220L, 75229L, 75407L, 75653L, 75732L,
75735L, 75757L, 75895L, 75898L, 76381L, 76559L, 76574L, 76594L,
76595L, 76746L, 76751L, 76755L, 76759L, 76775L, 77088L, 77091L,
77099L, 77134L, 77188L, 77203L, 77252L, 77304L, 77413L, 77453L,
77528L, 77556L, 77585L, 77668L, 78262L, 79724L, 79730L, 79850L,
79977L, 80052L, 80819L, 80901L, 80932L, 81064L, 81065L, 81071L,
81098L, 81142L, 81175L, 33714L, 35377L, 38623L, 38806L, 39593L,
39820L, 39951L, 40286L, 40556L, 40798L, 40800L, 40815L, 43762L,
50848L, 52183L, 52461L, 52577L, 53320L, 53873L, 54153L, 54206L,
54581L, 55122L, 55267L, 55462L, 55612L, 55920L, 56022L, 56307L,
56420L, 56679L, 57405L, 57445L, 57480L, 57725L, 57809L, 58004L,
58215L, 58229L, 58503L, 59326L, 59327L, 59344L, 59361L, 59865L,
60099L, 60100L, 60280L, 60384L, 60429L, 60493L, 60503L, 60575L,
60603L, 60664L, 60846L, 61415L, 61656L, 61749L, 61883L, 62081L,
62210L, 62285L, 62937L, 62983L, 63327L, 63329L, 64081L, 64328L,
64418L, 64507L, 64596L, 65178L, 65250L, 65302L, 65478L, 65480L,
65487L, 65572L, 65802L, 65935L, 65974L, 65975L, 65978L, 65991L,
65995L, 66013L, 66154L, 66237L, 66245L, 66389L, 66396L, 66460L,
66572L, 66589L, 67174L, 73230L, 73525L, 73539L, 73677L, 73942L,
73953L, 74034L, 74113L, 74114L, 74427L, 74439L, 74607L, 74641L,
74657L, 74794L, 74800L, 74836L, 74942L, 74952L, 74962L, 74969L,
74977L, 74985L, 74989L, 75220L, 75229L, 75407L, 75653L, 75732L,
75735L, 75757L, 75895L, 75898L, 76381L, 76559L, 76574L, 76594L,
76595L, 76746L, 76751L, 76755L, 76759L, 76775L, 77088L, 77091L,
77099L, 77134L, 77188L, 77203L, 77252L, 77304L, 77413L, 77453L,
77528L, 77556L, 77585L, 77668L, 78262L, 79724L, 79730L, 79850L,
79977L, 80052L, 80819L, 80901L, 80932L, 81064L, 81065L, 81071L,
81098L, 81142L, 81175L), Age = c(15L, 15L, 45L, 66L, 69L, 60L,
46L, 68L, 9L, 11L, 16L, 9L, 56L, 16L, 16L, 14L, 53L, 8L, 6L,
63L, 14L, 10L, 15L, 13L, 15L, 8L, 9L, 9L, 8L, 9L, 9L, 13L, 58L,
10L, 7L, 8L, 8L, 6L, 15L, 43L, 8L, 11L, 44L, 70L, 14L, 12L, 10L,
16L, 12L, 10L, 6L, 13L, 67L, 11L, 12L, 13L, 10L, 66L, 13L, 14L,
12L, 45L, 52L, 64L, 17L, 9L, 12L, 44L, 69L, 11L, 10L, 12L, 10L,
10L, 70L, 54L, 45L, 43L, 54L, 14L, 42L, 44L, 16L, 15L, 43L, 45L,
50L, 53L, 53L, 49L, 69L, 14L, 65L, 14L, 13L, 67L, 59L, 52L, 54L,
44L, 62L, 69L, 10L, 63L, 57L, 12L, 62L, 9L, 53L, 54L, 66L, 49L,
63L, 51L, 9L, 45L, 49L, 49L, 61L, 62L, 57L, 67L, 65L, 45L, 16L,
55L, 64L, 67L, 56L, 52L, 63L, 10L, 62L, 14L, 66L, 68L, 15L, 13L,
43L, 47L, 55L, 69L, 67L, 52L, 15L, 64L, 55L, 44L, 13L, 48L, 71L,
64L, 13L, 50L, 61L, 70L, 57L, 51L, 46L, 57L, 69L, 46L, 8L, 11L,
46L, 71L, 38L, 56L, 16L, 16L, 46L, 67L, 70L, 61L, 47L, 69L, 11L,
13L, 18L, 10L, 57L, 18L, 18L, 15L, 54L, 10L, 8L, 64L, 15L, 12L,
16L, 14L, 16L, 9L, 11L, 11L, 10L, 10L, 11L, 14L, 59L, 12L, 8L,
9L, 9L, 8L, 16L, 44L, 9L, 13L, 45L, 71L, 16L, 13L, 12L, 18L,
13L, 11L, 8L, 14L, 68L, 12L, 13L, 14L, 11L, 67L, 14L, 15L, 14L,
46L, 53L, 65L, 18L, 11L, 14L, 46L, 70L, 12L, 12L, 13L, 11L, 11L,
71L, 55L, 46L, 44L, 55L, 15L, 43L, 45L, 17L, 16L, 44L, 46L, 51L,
55L, 54L, 50L, 70L, 15L, 66L, 15L, 14L, 68L, 60L, 53L, 55L, 46L,
63L, 70L, 11L, 64L, 58L, 13L, 63L, 10L, 54L, 55L, 67L, 50L, 64L,
52L, 11L, 46L, 50L, 50L, 62L, 63L, 58L, 68L, 66L, 46L, 18L, 56L,
65L, 68L, 57L, 53L, 64L, 11L, 63L, 15L, 67L, 69L, 16L, 14L, 44L,
48L, 56L, 70L, 68L, 53L, 17L, 65L, 56L, 45L, 14L, 49L, 73L, 65L,
14L, 50L, 62L, 71L, 58L, 52L, 47L, 58L, 70L, 47L, 9L, 12L, 47L,
72L, 39L, 57L, 18L, 18L, 47L, 68L, 71L, 62L, 48L, 70L, 12L, 14L,
19L, 11L, 58L, 19L, 19L, 16L, 55L, 11L, 9L, 65L, 17L, 13L, 18L,
16L, 18L, 11L, 12L, 12L, 11L, 11L, 12L, 16L, 60L, 13L, 9L, 11L,
10L, 9L, 17L, 45L, 11L, 14L, 46L, 72L, 17L, 14L, 13L, 19L, 15L,
12L, 9L, 15L, 69L, 14L, 14L, 15L, 12L, 68L, 16L, 17L, 15L, 47L,
54L, 66L, 20L, 12L, 15L, 47L, 71L, 13L, 13L, 14L, 12L, 12L, 72L,
56L, 47L, 45L, 56L, 16L, 44L, 46L, 19L, 18L, 44L, 47L, 52L, 56L,
55L, 51L, 71L, 16L, 67L, 16L, 15L, 69L, 60L, 54L, 56L, 46L, 64L,
71L, 12L, 65L, 59L, 14L, 64L, 11L, 55L, 57L, 68L, 51L, 65L, 53L,
11L, 47L, 51L, 51L, 63L, 64L, 59L, 69L, 67L, 48L, 19L, 57L, 66L,
69L, 59L, 54L, 65L, 12L, 64L, 16L, 68L, 70L, 17L, 15L, 45L, 48L,
57L, 71L, 69L, 54L, 18L, 66L, 57L, 50L, 15L, 50L, 74L, 66L, 15L,
51L, 63L, 72L, 59L, 53L, 48L, 59L, 71L, 48L, 10L, 13L, 48L, 73L,
40L, 58L), Age_group = structure(c(1L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L,
1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L,
2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L,
2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L,
2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L,
2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L,
1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L,
2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L,
1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L,
2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L,
2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L,
2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L,
2L), .Label = c("Young", "Older"), class = "factor"), Sex = c("Male",
"Female", "Female", "Female", "Female", "Female", "Male", "Female",
"Male", "Male", "Male", "Male", "Female", "Male", "Male", "Male",
"Female", "Male", "Male", "Male", "Male", "Male", "Male", "Male",
"Male", "Female", "Female", "Male", "Female", "Male", "Female",
"Female", "Female", "Male", "Female", "Female", "Male", "Female",
"Male", "Female", "Male", "Female", "Male", "Male", "Female",
"Male", "Male", "Male", "Female", "Female", "Female", "Male",
"Female", "Male", "Female", "Female", "Male", "Male", "Female",
"Male", "Male", "Female", "Female", "Male", "Male", "Female",
"Female", "Female", "Female", "Female", "Male", "Male", "Male",
"Male", "Female", "Female", "Female", "Female", "Female", "Male",
"Female", "Female", "Male", "Male", "Female", "Male", "Female",
"Female", "Female", "Female", "Female", "Male", "Male", "Female",
"Female", "Male", "Female", "Female", "Female", "Female", "Female",
"Female", "Female", "Female", "Female", "Female", "Female", "Female",
"Female", "Female", "Male", "Female", "Male", "Female", "Male",
"Female", "Female", "Female", "Female", "Female", "Male", "Male",
"Female", "Female", "Male", "Female", "Male", "Female", "Female",
"Male", "Female", "Female", "Female", "Male", "Female", "Male",
"Male", "Male", "Female", "Female", "Male", "Male", "Male", "Female",
"Female", "Male", "Female", "Female", "Male", "Female", "Female",
"Male", "Female", "Male", "Male", "Male", "Male", "Female", "Male",
"Male", "Female", "Male", "Male", "Male", "Male", "Male", "Male",
"Female", "Male", "Female", "Female", "Female", "Female", "Female",
"Male", "Female", "Male", "Male", "Male", "Male", "Female", "Male",
"Male", "Male", "Female", "Male", "Male", "Male", "Male", "Male",
"Male", "Male", "Male", "Female", "Female", "Male", "Female",
"Male", "Female", "Female", "Female", "Male", "Female", "Female",
"Male", "Female", "Male", "Female", "Male", "Female", "Male",
"Male", "Female", "Male", "Male", "Male", "Female", "Female",
"Female", "Male", "Female", "Male", "Female", "Female", "Male",
"Male", "Female", "Male", "Male", "Female", "Female", "Male",
"Male", "Female", "Female", "Female", "Female", "Female", "Male",
"Male", "Male", "Male", "Female", "Female", "Female", "Female",
"Female", "Male", "Female", "Female", "Male", "Male", "Female",
"Male", "Female", "Female", "Female", "Female", "Female", "Male",
"Male", "Female", "Female", "Male", "Female", "Female", "Female",
"Female", "Female", "Female", "Female", "Female", "Female", "Female",
"Female", "Female", "Female", "Female", "Male", "Female", "Male",
"Female", "Male", "Female", "Female", "Female", "Female", "Female",
"Male", "Male", "Female", "Female", "Male", "Female", "Male",
"Female", "Female", "Male", "Female", "Female", "Female", "Male",
"Female", "Male", "Male", "Male", "Female", "Female", "Male",
"Male", "Male", "Female", "Female", "Male", "Female", "Female",
"Male", "Female", "Female", "Male", "Female", "Male", "Male",
"Male", "Male", "Female", "Male", "Male", "Female", "Male", "Male",
"Male", "Male", "Male", "Male", "Female", "Male", "Female", "Female",
"Female", "Female", "Female", "Male", "Female", "Male", "Male",
"Male", "Male", "Female", "Male", "Male", "Male", "Female", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Male", "Female",
"Female", "Male", "Female", "Male", "Female", "Female", "Female",
"Male", "Female", "Female", "Male", "Female", "Male", "Female",
"Male", "Female", "Male", "Male", "Female", "Male", "Male", "Male",
"Female", "Female", "Female", "Male", "Female", "Male", "Female",
"Female", "Male", "Male", "Female", "Male", "Male", "Female",
"Female", "Male", "Male", "Female", "Female", "Female", "Female",
"Female", "Male", "Male", "Male", "Male", "Female", "Female",
"Female", "Female", "Female", "Male", "Female", "Female", "Male",
"Male", "Female", "Male", "Female", "Female", "Female", "Female",
"Female", "Male", "Male", "Female", "Female", "Male", "Female",
"Female", "Female", "Female", "Female", "Female", "Female", "Female",
"Female", "Female", "Female", "Female", "Female", "Female", "Male",
"Female", "Male", "Female", "Male", "Female", "Female", "Female",
"Female", "Female", "Male", "Male", "Female", "Female", "Male",
"Female", "Male", "Female", "Female", "Male", "Female", "Female",
"Female", "Male", "Female", "Male", "Male", "Male", "Female",
"Female", "Male", "Male", "Male", "Female", "Female", "Male",
"Female", "Female", "Male", "Female", "Female", "Male", "Female",
"Male", "Male", "Male", "Male", "Female", "Male", "Male", "Female",
"Male", "Male", "Male", "Male", "Male", "Male", "Female"), Timepoint = c("bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
"bl", "bl", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
"flu1", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
"flu2"), outcome = c(0.0010333, 0.00105981, 0.00103209, 0.001136335,
0.001130695, 0.00113139, 0.000986063, 0.0010712, 0.00113736,
0.001108715, 0.00104864, 0.00110772, 0.00110197, 0.00109096,
0.00109855, 0.00104169, 0.001090875, 0.00112465, 0.001096525,
0.001030151, 0.000985059, 0.001098955, 0.001069465, 0.00105376,
0.00106878, 0.00110388, 0.00108702, 0.001162835, 0.001070955,
0.0010971, 0.00111695, 0.001060525, 0.001035065, 0.00108797,
0.00103262, 0.001117605, 0.001061707, 0.001156365, 0.00104431,
0.001056565, 0.00109114, 0.001053765, 0.001064622, 0.001114025,
0.001045395, 0.00106441, 0.00108481, 0.0011145, 0.001095115,
0.001099075, 0.001057, 0.001096125, 0.001087175, 0.00109696,
0.001064795, 0.00108024, 0.00102137, 0.001087645, 0.001103185,
0.00111948, 0.001110965, 0.0010694, 0.001089425, 0.001129075,
0.00103784, 0.00104419, 0.00101302, 0.00110335, 0.00111867, 0.00108785,
0.001098765, 0.001052415, 0.0010976, 0.001064385, 0.00108407,
0.001076165, 0.00112799, 0.00106542, 0.00105824, 0.001129705,
0.001051684, 0.001073525, 0.001076575, 0.001049785, 0.00102377,
0.0011, 0.001039055, 0.00105945, 0.001083505, 0.0010723, 0.001123395,
0.00103181, 0.00110417, 0.001078155, 0.001129015, 0.00114891,
0.001115405, 0.00110057, 0.001054205, 0.00105165, 0.001095601,
0.001112195, 0.001024814, 0.001061645, 0.001081505, 0.00109171,
0.00112992, 0.001007862, 0.001069345, 0.00108842, 0.001066665,
0.00106081, 0.001065165, 0.00108621, 0.001099885, 0.00103779,
0.00103329, 0.00107046, 0.001094945, 0.001063225, 0.001077665,
0.0011242, 0.001161425, 0.001092915, 0.00109162, 0.001120835,
0.001060845, 0.001072238, 0.00109486, 0.00111587, 0.001166475,
0.001060665, 0.00107877, 0.00106572, 0.00103524, 0.001112615,
0.00106803, 0.00113409, 0.000992363, 0.001057025, 0.001055855,
0.001165165, 0.001046216, 0.001015101, 0.001052505, 0.001094015,
0.00104152, 0.00104361, 0.001138575, 0.001056924, 0.0011807,
0.001090905, 0.00108723, 0.00106178, 0.00113283, 0.001154635,
0.00110195, 0.001115265, 0.001102255, 0.00106396, 0.001073585,
0.001047345, 0.001046765, 0.001090765, 0.001022798, 0.001187635,
0.001033095, 0.00112301, 0.001060205, 0.0010143, 0.00102627,
0.00110609, 0.001158665, 0.00112353, 0.00097819, 0.001078495,
0.001106365, 0.00113328, 0.001045545, 0.001081185, 0.00109504,
0.001102495, 0.00108775, 0.001055425, 0.001056945, 0.001130705,
0.00115777, 0.001034427, 0.00105974, 0.001089395, 0.001069105,
0.001054605, 0.00107229, 0.001128765, 0.001111455, 0.001111155,
0.001095955, 0.001108905, 0.001077275, 0.00104525, 0.00105191,
0.00111458, 0.001110655, 0.001114555, 0.00110557, 0.001167755,
0.0010552, 0.001014149, 0.00110002, 0.00104991, 0.001018892,
0.00112666, 0.001069695, 0.001101185, 0.001066815, 0.00109388,
0.001079455, 0.001097655, 0.001106855, 0.00108804, 0.001024891,
0.001102495, 0.001077445, 0.00104224, 0.001064015, 0.001071736,
0.00110557, 0.00112483, 0.001093865, 0.001075945, 0.001031211,
0.001122935, 0.00105965, 0.001048305, 0.0010719, 0.00107988,
0.001161715, 0.001098505, 0.001073105, 0.001049325, 0.001097175,
0.00111584, 0.00112603, 0.00107674, 0.001147125, 0.00104971,
0.00108423, 0.001122035, 0.00103364, 0.001071835, 0.001036422,
0.001016249, 0.00101976, 0.00107818, 0.001067145, 0.001062425,
0.00110346, 0.00108456, 0.00113592, 0.001015195, 0.001110565,
0.00110143, 0.001121325, 0.00110386, 0.00112389, 0.001091155,
0.00105652, 0.001030636, 0.001106515, 0.00109062, 0.001047755,
0.001030305, 0.00108161, 0.001063235, 0.00112294, 0.001079355,
0.001052327, 0.00107416, 0.001091, 0.001057725, 0.00107489, 0.0010597,
0.001086495, 0.001047792, 0.000995212, 0.001092055, 0.00106338,
0.001078475, 0.00110247, 0.00111765, 0.00113914, 0.001073185,
0.001074005, 0.001091145, 0.001040767, 0.00106448, 0.00105502,
0.00108874, 0.00117407, 0.00109106, 0.001044455, 0.00103907,
0.00104921, 0.001136435, 0.0010907, 0.001101685, 0.001009874,
0.00106717, 0.001055338, 0.001157375, 0.001061175, 0.000983892,
0.001017475, 0.001094945, 0.001018795, 0.00107304, 0.00113138,
0.0010772, 0.00114321, 0.00111869, 0.001086615, 0.0010709, 0.00116752,
0.001175765, 0.001113535, 0.001123455, 0.001081295, 0.001084425,
0.00107189, 0.001030513, 0.001076375, 0.001088265, 0.001043751,
0.001157355, 0.001039899, 0.00116496, 0.00106309, 0.00106822,
0.001076605, 0.001113025, 0.00115085, 0.00115274, 0.001005614,
0.00111759, 0.001052205, 0.001106125, 0.001060125, 0.00106945,
0.00107761, 0.001092695, 0.00107696, 0.001063425, 0.00111791,
0.001116725, 0.00105891, 0.001033532, 0.001054205, 0.00109295,
0.00109387, 0.00101807, 0.001066195, 0.001120295, 0.001111565,
0.001088595, 0.00102183, 0.0010934, 0.00111935, 0.00105371, 0.001038104,
0.00108314, 0.0011006, 0.001079585, 0.001127775, 0.001140825,
0.00106203, 0.001059563, 0.001118035, 0.00103535, 0.001027819,
0.001120055, 0.00099512, 0.001078955, 0.00108867, 0.0010789,
0.001030445, 0.00106243, 0.001028545, 0.00108679, 0.00108158,
0.00105624, 0.001110145, 0.00107318, 0.00106523, 0.001099325,
0.001103515, 0.00112404, 0.001064455, 0.001086375, 0.001109065,
0.001077765, 0.001040425, 0.001059305, 0.00106362, 0.00109264,
0.00116222, 0.001079395, 0.00107183, 0.0010652, 0.00106983, 0.00111722,
0.00112626, 0.001091765, 0.00113837, 0.00104618, 0.00109727,
0.00114111, 0.001055565, 0.001115175, 0.001059649, 0.001029902,
0.000986792, 0.00107968, 0.00106097, 0.001067105, 0.001083625,
0.00109082, 0.00114355, 0.001062825, 0.001099115, 0.001102155,
0.001122135, 0.001125253, 0.001131355, 0.001104175, 0.001104315,
0.00103858, 0.001072123, 0.00109497, 0.00103623, 0.00107783,
0.00107379, 0.00108648, 0.00114186, 0.001081035, 0.00110761,
0.001102845, 0.001090495, 0.00105551, 0.00108908, 0.001082845,
0.001110075, 0.0010599, 0.001042808, 0.00108644, 0.00106482,
0.00111119, 0.001077005, 0.001183845, 0.001134605, 0.00107317,
0.001039397, 0.00112268, 0.00108716, 0.00108437, 0.0010827, 0.00111043,
0.001177305, 0.001057715, 0.00110218, 0.0010338, 0.00103996,
0.00111301, 0.001071455, 0.001072065, 0.00100762, 0.00106678,
0.001030939, 0.001161045, 0.001080915, 0.001053775, 0.001032233,
0.001072078, 0.00103878, 0.00112049, 0.00111996, 0.001085025,
0.001165745, 0.00114263, 0.00106407, 0.00109784, 0.001187105,
0.001194925, 0.001139195, 0.0011009, 0.00110112, 0.00107563,
0.001055985, 0.00100656, 0.0010693, 0.001104395, 0.001022506,
0.00114974, 0.00105716, 0.00113243)), row.names = c(NA, -504L
), class = c("tbl_df", "tbl", "data.frame"))

outcome is a physiological measure that was sampled per subject (ID) at timepoint-bl (1), timepoint-flu1 (2) and timepoint-flu2 (3). Each subject age, age_group and sex are recorded as well. Age is a predictor of outcome and sex is used as an interaction variable.

Aims:

I am trying to estimate if there is a significant difference in slope of the outcome variable between Young and Older adults across the 3 Timepoints.

I am trying to estimate the individual (ID) variance of outcome between timepoints and age_group.

Is this the correct way to model for my aims? The plot doesn't look accurate to me. I am new to linear mixed models so any advice is appreciated.

#mixed
DF_mixed <- lmer(outcome ~ Age* Sex + (1 + Age| Age_group:Timepoint) + (1|ID), data = DF)
# identify age*sex interactions to predict outcome value between timepoints, nested in age_group that have random slope and intercepts

#plot
ggplot(DF, aes(x = Age, y = outcome, color = Timepoint)) +
      geom_point(alpha = 0.7) +
      theme_classic() +
      geom_line(data = cbind(DF, pred = predict(DF_mixed)), aes(y = pred), size = 1)   # adding predicted line from mixed model

Body:
Below, I walk through suggestions for (1) preparing your data, (2) specifying the model, and (3) examining model results.

In addition to tidyverse packages and lme4, I'll use broom.mixed::glance() and tidy() to inspect model parameters, and ggeffects::ggpredict() to generate model predictions for plotting.

library(tidyverse)
library(lme4)
library(broom.mixed)
library(ggeffects)

Data Prep & Variable Selection

Timepoint is a character, and will be treated as as an unordered category in the model, which likely isn't what you want. It's often better to use the actual time elapsed since baseline rather than a generic "timepoint," especially if distance between timepoints is variable. For this answer, I computed an alternate Timepoint_yrs based on each subject's change in age from baseline; but if you have a more precise record of time, you may want to use that instead.

Also, outcome consists of a small range of values, on the order of 1e-4 - 1e-3; this can cause lmer to misbehave, so I scaled this.

DF <- DF %>%
  group_by(ID) %>%
  mutate(Timepoint_yrs = Age - min(Age)) %>%
  ungroup() %>%
  mutate(outcome_scaled = as.numeric(scale(outcome)))

Including both Age and Age_group in the model will cause issues with multicollinearity, as one is a function of the other. Given the extreme bimodal distribution of Age, I just used Age_group. And as above, change in age is now accounted for by Timepoint_yrs.

Model Specification

"I am trying to estimate if there is a significant difference in slope of the outcome variable between Young and Older adults across the 3 Timepoints" -- i.e., an Age_group by Timepoint_yrs interaction. You also wrote that "sex is used as an interaction variable." So putting this together, you're looking at a 3-way Age_group by Sex by Timepoint_yrs interaction. Because Age_group and Sex only vary between subjects, we'll specify this at the level of fixed effects:

outcome_scaled ~ Age_group * Sex * Timepoint_yrs

Because you have multiple measurements per person (ID), we'll include random intercepts for ID:

outcome_scaled ~ Age_group * Sex * Timepoint_yrs + (1 | ID)

We can also allow the slope of Timepoint_yrs to vary within individuals. From your post, I don't see a strong theoretical reason for whether or not to include random slopes -- so we'll do both and see which model fits best.

# model 1 - random intercepts
rnd_intercept <- lmer(outcome_scaled ~ Age_group * Sex * Timepoint_yrs + (1 | ID), data = DF)

# model 2 - random intercepts and slopes
rnd_int_slope <- lmer(outcome_scaled ~ Age_group * Sex * Timepoint_yrs + (Timepoint_yrs | ID), data = DF)

Model Results

glance(rnd_intercept)
# # A tibble: 1 x 6
# sigma logLik   AIC   BIC REMLcrit df.residual
#   <dbl>  <dbl> <dbl> <dbl>    <dbl>       <int>
# 1 0.510  -575. 1170. 1212.    1150.         494

glance(rnd_int_slopes)
# A tibble: 1 x 6
#   sigma logLik   AIC   BIC REMLcrit df.residual
#   <dbl>  <dbl> <dbl> <dbl>    <dbl>       <int>
# 1 0.487  -575. 1173. 1224.    1149.         492

Looking at AIC and BIC, the random intercepts model seems a better / more parsimonious fit; absent any theoretical reason to prefer the random slopes model, we'll stick with that one.

tidy(rnd_intercept, conf.int = TRUE)
# # A tibble: 10 x 8
#    effect   group    term               estimate std.error statistic conf.low conf.high
#    <chr>    <chr>    <chr>                 <dbl>     <dbl>     <dbl>    <dbl>     <dbl>
#  1 fixed    NA       (Intercept)         -0.123     0.122    -1.01    -0.361     0.116
#  2 fixed    NA       Age_groupYoung      -0.0142    0.221    -0.0643  -0.448     0.419
#  3 fixed    NA       SexMale              0.248     0.214     1.16    -0.171     0.667
#  4 fixed    NA       Timepoint_yrs        0.131     0.0407    3.21     0.0509    0.210
#  5 fixed    NA       Age_groupYoung:Se~  -0.0704    0.317    -0.222   -0.692     0.551
#  6 fixed    NA       Age_groupYoung:Ti~  -0.152     0.0654   -2.32    -0.280    -0.0234
#  7 fixed    NA       SexMale:Timepoint~  -0.0547    0.0771   -0.709   -0.206     0.0964
#  8 fixed    NA       Age_groupYoung:Se~   0.0192    0.101     0.190   -0.178     0.217
#  9 ran_pars ID       sd__(Intercept)      0.862    NA        NA       NA        NA
# 10 ran_pars Residual sd__Observation      0.510    NA        NA       NA        NA

Finally, we can plot predicted values from the model. Your original code predicted a datapoint for every row in your original data, then basically traced a line between each of these, which as you noted isn't very informative. Instead, we want to base the plot on just one predicted outcome value (+/- error) for each unique combination of your predictors. ggeffects::ggpredict() is a nice shortcut for this; emmeans::emmeans() would be another option.

plot_data <- ggpredict(rnd_intercept, terms = c("Timepoint_yrs", "Age_group", "Sex"))
# col names: x = Timepoint_yrs, group = Age_group, facet = Sex, predicted = observed_scaled

ggplot(plot_data, aes(x, predicted)) +
  geom_line(aes(color = group)) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high, fill = group), alpha = .1) +
  facet_wrap(vars(facet)) +
  labs(x = "Years Since Baseline", y = "Outcome\n(scaled, model-predicted)") +
  theme_classic()

Based on your model coefficients, you may also want to look at just Age_group across Timepoint_yrs, as well as the main effect of Timepoint_yrs collapsed across other variables. You can do this by changing the terms argument to ggpredict() and modifying the ggplot spec accordingly.


来源: stackexchange

问:
A href pointed to nowhere added # to url
I have a href which pointed to #

```<code><a href="#" id="bla" >Bla<a>
</code>```

I have onclick function which displaying popup on click on that a href.

```<code>function doingClick()
{
   //display popup
   return false;
}
</code>```

But after click symbol # every time added to the url in browser.

So for example if url was like that before I click on my link http://mywebsite.com

But after click on a href the url looking like that: http://mywebsite.com#

Is there any way to avoid such behavior?

答:
If you don't get better answer, you could make nasty ugly workaround by placing script tag very early on page (on the beginning of body or in head) with following javascript:

```<code>if(document.location.href[document.location.href.length-1]=='#'){
    document.location.href = document.location.href.substring(0, document.location.href.length-2)
}
</code>```

I DO NOT RECOMMEND you to do this as will cause double requests to server when # is in url, but it is here if you have to.

ContentLicense: CC BY-SA 3.0

Body:
I have a href which pointed to #

Bla

I have onclick function which displaying popup on click on that a href.

function doingClick()
{
   //display popup
   return false;
}

But after click symbol # every time added to the url in browser.

So for example if url was like that before I click on my link http://mywebsite.com

But after click on a href the url looking like that: http://mywebsite.com#

Is there any way to avoid such behavior?

Body:
If you don't get better answer, you could make nasty ugly workaround by placing script tag very early on page (on the beginning of body or in head) with following javascript:

if(document.location.href[document.location.href.length-1]=='#'){
    document.location.href = document.location.href.substring(0, document.location.href.length-2)
}

I DO NOT RECOMMEND you to do this as will cause double requests to server when # is in url, but it is here if you have to.


问:
convert int to date in redshift
I have column named datenum which is int type. For ex. 20220208
Need to convert datenum column type to date with YYYY/MM/DD format.
Tried to_date("datenum", 'YYYY/MM/DD') but isn't working.</p>

答:
Dates in Redshift (or any SQL database) do not really have any internal format.  To convert your input text dates to bona fide Redshift dates, use TO_DATE with the appropriate date mask:

SELECT TO_DATE(datenum, 'YYYYMMDD')
FROM yourTable;
```
<p>If you really want to <em>view</em> your input dates in some other text format, then do a full roundtrip back to string, using <code>TO_CHAR</code>:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT TO_CHAR(TO_DATE(datenum, 'YYYYMMDD'), 'YYYY/MM/DD')
FROM yourTable;
</code>```

ContentLicense: CC BY-SA 4.0

Title: convert int to date in redshift

Body:
Dates in Redshift (or any SQL database) do not really have any internal format.  To convert your input text dates to bona fide Redshift dates, use TO_DATE with the appropriate date mask:

SELECT TO_DATE(datenum, 'YYYYMMDD')
FROM yourTable;

If you really want to view your input dates in some other text format, then do a full roundtrip back to string, using TO_CHAR:

SELECT TO_CHAR(TO_DATE(datenum, 'YYYYMMDD'), 'YYYY/MM/DD')
FROM yourTable;


问:
What is the type for a vector of async functions that return "impl Responder"?
```<code>use actix_web::{delete, get, post, put, HttpResponse, Responder};

#[get("/user")]
async fn get_user() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

#[post("/user")]
async fn add_user() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

#[delete("/user")]
async fn delete_user() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

#[put("/user")]
async fn update_user() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

pub const my_functions: Vec<fn() -> impl Responder> = vec![get_user, add_user, delete_user, apdate_user].iter();
</code>```

Trying to create web app with actix.rs. I want to split all API handlers to controllers and than map it as the services like App::new().service(func1).service(func2).

I can't understand how to add correct type for vector.

答:
The type .body() returns is HttpResponse. But you cannot put your functions together in a vector, for two reasons: a) The underlying type of impl Trait is supposed to be opaque. The compiler won't let you use it, even if you know it, to not leak encapsulation. From the compiler point of view, you have different functions that returns different types. b) even if you would specify the type directly (and not rely on impl Trait), like @StefanZobel said they're async functions, and thus returns an impl Future<...>. The returned future is a different type for each function.

You can use a closure to wrap the futures into Pin<Box<dyn Future<...>>> (you can use dyn Responder too, or specify the concrete type. I wrote like if you specified the concrete type):

let my_functions: Vec<fn() -> Pin<Box<dyn Future<Output = HttpResponse>>>> = vec![|| Box::pin(get_user()), || Box::pin(add_user), || Box::pin(delete_user), || Box::pin(update_user)].iter();
```

Also note that you cannot create a Vec (nor a Box) inside const or static.

But all of that doesn't matter because you wrapped your functions with actix's macros (#[get("...")] etc.). They transform the function into an anonymous struct that implements HttpServiceFactory. So you can't just call them or whatever. What you need to do depends on what you want to do with your functions, but you can e.g. wrap them into Box<dyn HttpServiceFactory>

Body:
use actix_web::{delete, get, post, put, HttpResponse, Responder};

#[get("/user")]
async fn get_user() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

#[post("/user")]
async fn add_user() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

#[delete("/user")]
async fn delete_user() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

#[put("/user")]
async fn update_user() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

pub const my_functions: Vec<fn() -> impl Responder> = vec![get_user, add_user, delete_user, apdate_user].iter();

Trying to create web app with actix.rs. I want to split all API handlers to controllers and than map it as the services like App::new().service(func1).service(func2).

I can't understand how to add correct type for vector.

Body:
The type .body() returns is HttpResponse. But you cannot put your functions together in a vector, for two reasons: a) The underlying type of impl Trait is supposed to be opaque. The compiler won't let you use it, even if you know it, to not leak encapsulation. From the compiler point of view, you have different functions that returns different types. b) even if you would specify the type directly (and not rely on impl Trait), like @StefanZobel said they're async functions, and thus returns an impl Future<...>. The returned future is a different type for each function.

You can use a closure to wrap the futures into Pin<Box<dyn Future<...>>> (you can use dyn Responder too, or specify the concrete type. I wrote like if you specified the concrete type):

let my_functions: Vec<fn() -> Pin<Box<dyn Future<Output = HttpResponse>>>> = vec![|| Box::pin(get_user()), || Box::pin(add_user), || Box::pin(delete_user), || Box::pin(update_user)].iter();

Also note that you cannot create a Vec (nor a Box) inside const or static.

But all of that doesn't matter because you wrapped your functions with actix's macros (#[get("...")] etc.). They transform the function into an anonymous struct that implements HttpServiceFactory. So you can't just call them or whatever. What you need to do depends on what you want to do with your functions, but you can e.g. wrap them into Box<dyn HttpServiceFactory>


问:
How to end peer connection in react-native
how can i end peer connection when using react-native-peerjs..The connection is successful& the call works. but at the point of ending the call, i haven't found a disconnect function, so the call still goes on in background till i restart the app.

my connection is like this

```<code> const peerServer = new Peer(undefined, {
    host: 'mvmarketserver.herokuapp.com',
    config: {
        iceServers: [
            {url:'stun:eu-turn3.xirsys.com'},
            {
                username: "",
                credential: "",
                credentialType: 'password',
                urls: [
                    "turn:eu-turn3.xirsys.com:80?transport=udp",
                    "turn:eu-turn3.xirsys.com:3478?transport=udp",
                    "turn:eu-turn3.xirsys.com:80?transport=tcp",
                    "turn:eu-turn3.xirsys.com:3478?transport=tcp",
                    "turns:eu-turn3.xirsys.com:443?transport=tcp",
                    "turns:eu-turn3.xirsys.com:5349?transport=tcp",
                ]
            }
        ]
    },
    secure: true,
    port: 443,
    path: '/mypeer'
})

peerServer.on('error', console.log)
</code>```

Currently my disconnect is like this, i try to use new Peer() to see if creating a new one, ends the previous one.Please help

```<code>dispatch({type: DELETE_STREAM, payload: []})
    dispatch({type: DELETE_MY_STREAM, payload: null})
    dispatch({type: DELETE_REMOTE_STREAM, payload: []})
KeepAwake.deactivate()
            SoundPlayer.stop()
            const roomID = this.state.room;
            console.log('leave ' + roomID);
            socket.emit('end-call', {roomID});
            const peer = new Peer();
            console.log('disconnected')
            InCallManager.stop({ busytone: '_DTMF_'})
            this.props.leaveRoom()
            const {goBack} = this.props.navigation;
            goBack(null);
</code>```

答:
Here I use native peerConnection but maybe you can try this way.

```<code>peerServer.on('connection', conn => {
    conn.on('close', () => {
        console.log("Close PeerConnection");
        conn.close();
    });
})
</code>```

But if this does't work, maybe conn.on('close') not trigered.
https://github.com/peers/peerjs/issues/636

if you are using SocketIo you can add suck event as

```<code>socket.broadcast.emit("user-disconnected", {SOME_DATA_WHAT_YOU_WANT_TO_SEND});
</code>```

and you can on event in client

```<code>socket.on("user-disconnected", (userId)=>{
    // Close peer connection or remove all video or audio stream
    closePeer()
});
</code>```

create closePeer function

```<code>function closePeer() {
    for (let conns in peerServer.connections) {
      peerServer.connections[conns].forEach((conn, index, array) => {
        conn.peerConnection.close();
        if (conn.close)
          conn.close();
      });
    }
  }
</code>```

hope it helps little

Body:
how can i end peer connection when using react-native-peerjs..The connection is successful& the call works. but at the point of ending the call, i haven't found a disconnect function, so the call still goes on in background till i restart the app.

my connection is like this

 const peerServer = new Peer(undefined, {
    host: 'mvmarketserver.herokuapp.com',
    config: {
        iceServers: [
            {url:'stun:eu-turn3.xirsys.com'},
            {
                username: "",
                credential: "",
                credentialType: 'password',
                urls: [
                    "turn:eu-turn3.xirsys.com:80?transport=udp",
                    "turn:eu-turn3.xirsys.com:3478?transport=udp",
                    "turn:eu-turn3.xirsys.com:80?transport=tcp",
                    "turn:eu-turn3.xirsys.com:3478?transport=tcp",
                    "turns:eu-turn3.xirsys.com:443?transport=tcp",
                    "turns:eu-turn3.xirsys.com:5349?transport=tcp",
                ]
            }
        ]
    },
    secure: true,
    port: 443,
    path: '/mypeer'
})

peerServer.on('error', console.log)

Currently my disconnect is like this, i try to use new Peer() to see if creating a new one, ends the previous one.Please help

dispatch({type: DELETE_STREAM, payload: []})
    dispatch({type: DELETE_MY_STREAM, payload: null})
    dispatch({type: DELETE_REMOTE_STREAM, payload: []})
KeepAwake.deactivate()
            SoundPlayer.stop()
            const roomID = this.state.room;
            console.log('leave ' + roomID);
            socket.emit('end-call', {roomID});
            const peer = new Peer();
            console.log('disconnected')
            InCallManager.stop({ busytone: '_DTMF_'})
            this.props.leaveRoom()
            const {goBack} = this.props.navigation;
            goBack(null);

Body:
Here I use native peerConnection but maybe you can try this way.

peerServer.on('connection', conn => {
    conn.on('close', () => {
        console.log("Close PeerConnection");
        conn.close();
    });
})

But if this does't work, maybe conn.on('close') not trigered.
https://github.com/peers/peerjs/issues/636

if you are using SocketIo you can add suck event as

socket.broadcast.emit("user-disconnected", {SOME_DATA_WHAT_YOU_WANT_TO_SEND});

and you can on event in client

socket.on("user-disconnected", (userId)=>{
    // Close peer connection or remove all video or audio stream
    closePeer()
});

create closePeer function

function closePeer() {
    for (let conns in peerServer.connections) {
      peerServer.connections[conns].forEach((conn, index, array) => {
        conn.peerConnection.close();
        if (conn.close)
          conn.close();
      });
    }
  }

hope it helps little


问:
Collecting multiple unknown inputs
Alright so this problem has been grinding me for a good hour. I am taking a zybooks course and I'm presented with the prompt,

Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max.

Ex: If the input is:

15 20 0 5
the output is:

10 20
currently I have it 'working' with my code but the issue is I cannot figure out how to keep the input open for more or less inputs as zybooks runs through multiple different tests. i'm sure its something simple im overlooking. anything helps!

```<code>nums = []
for i in range(0, 4):
    number = int(input('Enter number'))
    nums.append(number)
avg = sum(nums) / len(nums)
print(max(nums), avg)
</code>```

答:
This code continually asks the user to enter values until they enter a blank (just press enter without typing).

This is the code:

```<code>nums = []

# initialse
number = 0
# loop until there isn't an input
while number != "":
    # ask for user input
    number = input('Enter number:')
    # validate the input isn't blank
    # prevents errors
    if number != "":
        # make input integer and add it to list
        nums.append(int(number))

avg = sum(nums) / len(nums)
print(max(nums), avg)
</code>```

Alternatively, if you have the list of numbers:

```<code>def maxAndAvg(nums):
    avg = sum(nums) / len(nums)
    return max(nums), avg
</code>```

Title: Collecting multiple unknown inputs

Body:
Alright so this problem has been grinding me for a good hour. I am taking a zybooks course and I'm presented with the prompt,

Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max.

Ex: If the input is:

15 20 0 5
the output is:

10 20
currently I have it 'working' with my code but the issue is I cannot figure out how to keep the input open for more or less inputs as zybooks runs through multiple different tests. i'm sure its something simple im overlooking. anything helps!

nums = []
for i in range(0, 4):
    number = int(input('Enter number'))
    nums.append(number)
avg = sum(nums) / len(nums)
print(max(nums), avg)

Body:
This code continually asks the user to enter values until they enter a blank (just press enter without typing).

This is the code:

nums = []

# initialse
number = 0
# loop until there isn't an input
while number != "":
    # ask for user input
    number = input('Enter number:')
    # validate the input isn't blank
    # prevents errors
    if number != "":
        # make input integer and add it to list
        nums.append(int(number))

avg = sum(nums) / len(nums)
print(max(nums), avg)

Alternatively, if you have the list of numbers:

def maxAndAvg(nums):
    avg = sum(nums) / len(nums)
    return max(nums), avg


问:
Best method for a Java app to access a windows process, and send commands
Basically I am attempting to control a win32 app (press a button, add stuff to a text field) etc from a java app.

Whats the best method of attempting this (i.e are there any toolkits, DDE?) or will I have to attempt to do some sort of FindWindowEx, then send a WM_LBUTTONDOWN or something?

Cheers

答:
Use the Java Robot.  Class is java.awt.robot.   It works great for controlling other applications. See here:

http://java.sun.com/javase/6/docs/api/java/awt/Robot.html

I actually used this to automate logins to World of Warcraft back when I played a lot.  The server I played on almost always had a login queue that took about 30 minutes to get through.  So I had the Windows scheduler kick off my Robot program about 4:45pm.  It would send a shortcut combination to Windows to launch WoW.  Then it would pause for a time then send keystrokes to enter my password and log me in.  By the time I got home from work I would be ready to play without having to wait in the queue.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: DMKing

LastEditorDisplayName: DMKing


问:
Dspace 6.x - Modifying/Showing the metadata displayed on Item page
After migrating from the Dspace 5.x version to the Dspace 6.x version, I'm having problems to show the metadata in the item-view screen with the XMLUI-Mirage2 theme.

In version 5.x and using JSPUI, the configuration was performed in dspace.cfg, using the property:

webui.itemdisplay.default = dc.title, dc.title.alternative, dc.contributor.author, dc.subject, dc.date.issued, dc.publisher, dc.identifier.citation, dc.relation.ispartofseries, dc.description.abstract, dc.description, dc.identifier.uri, dc.language.iso, dc.citation, dc.identifier

How to make this same change (show more metadata, in item view page) in Dspace 6.x version with XMLUI - Mirage2 theme?

答:
You have to create an XSL template first for each metadata that you would like to display in the simple item record. The file to edit is item-view.xsl found in [dspace]/webapps/xmlui/themes/Mirage2/xsl/aspect/artifactbrowser/.

For example, you like to display the ISBN if it is available, create an XSL template for ISBN:

```<code>    <xsl:template name="itemSummaryView-DIM-ISBN">
        <xsl:if test="dim:field[@element='identifier' and @qualifier='isbn' and descendant::text()]">
            <div class="col-sm-6 col-print-4">
                <div class="simple-item-view-isbn item-page-field-wrapper table">
                    <h5><i18n:text>xmlui.dri2xhtml.METS-1.0.item-isbn</i18n:text></h5>
                    <span>
                        <xsl:for-each select="dim:field[@element='identifier' and @qualifier='isbn']">
                            <xsl:copy-of select="./node()"/>
                            <xsl:if test="count(following-sibling::dim:field[@element='identifier' and @qualifier='isbn']) != 0">
                                <xsl:text>; </xsl:text>
                            </xsl:if>
                        </xsl:for-each>
                    </span>
                </div>
            </div>
        </xsl:if>
    </xsl:template>
</code>```

Then call this template in the portion that you would like to appear, in the example below I would like it to display under the Abstract field:

```<code><div class="col-sm-8">
    <xsl:call-template name="itemSummaryView-DIM-abstract"/>
    <xsl:call-template name="itemSummaryView-DIM-ISSBN"/>
... Rest of other templates ...
</code>```

Please note that if you don't have the i18n message for ISBN, you can just write
ISBN
 instead of <i18n:text>xmlui.dri2xhtml.METS-1.0.item-isbn</i18n:text> but I suggest to update the i18n messages for non-existing labels.

Body:
You have to create an XSL template first for each metadata that you would like to display in the simple item record. The file to edit is item-view.xsl found in [dspace]/webapps/xmlui/themes/Mirage2/xsl/aspect/artifactbrowser/.

For example, you like to display the ISBN if it is available, create an XSL template for ISBN:

    <xsl:template name="itemSummaryView-DIM-ISBN">
        <xsl:if test="dim:field[@element='identifier' and @qualifier='isbn' and descendant::text()]">
            <div class="col-sm-6 col-print-4">
                <div class="simple-item-view-isbn item-page-field-wrapper table">
                    <h5><i18n:text>xmlui.dri2xhtml.METS-1.0.item-isbn</i18n:text></h5>
                    <span>
                        <xsl:for-each select="dim:field[@element='identifier' and @qualifier='isbn']">
                            <xsl:copy-of select="./node()"/>
                            <xsl:if test="count(following-sibling::dim:field[@element='identifier' and @qualifier='isbn']) != 0">
                                <xsl:text>; </xsl:text>
                            </xsl:if>
                        </xsl:for-each>
                    </span>
                </div>
            </div>
        </xsl:if>
    </xsl:template>

Then call this template in the portion that you would like to appear, in the example below I would like it to display under the Abstract field:

<div class="col-sm-8">
    <xsl:call-template name="itemSummaryView-DIM-abstract"/>
    <xsl:call-template name="itemSummaryView-DIM-ISSBN"/>
... Rest of other templates ...

Please note that if you don't have the i18n message for ISBN, you can just write <h5>ISBN</h5> instead of <i18n:text>xmlui.dri2xhtml.METS-1.0.item-isbn</i18n:text> but I suggest to update the i18n messages for non-existing labels.


问:
(Javascript) i want to reduce every duplicate values in 2 Dimensional Array but i don't know how
my English is not good but i really need your help.

I want to reduce all same values in this 2 Dimensional Array but it doesn't work.

```<code>let edge = [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]];

 function removeDup(edge) {
      for (let i = 0; i < edge.length; i++) {
        if (edge.some((item) => item > 1)) {
          edge.splice(i, 1);
        }
      }
      return edge;
    }
</code>```

i want to change array like this.

```<code> [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]]

to

[[0,1,4],[1,2,4],[2,3,4],[3,0,4]]
</code>```

答:
This is the solution by using the reduce() method.

let edge = [
  [0, 1, 4],
  [1, 2, 4],
  [0, 2, 4],
  [2, 3, 4],
  [3, 0, 4],
  [0, 2, 4],
];

function removeDuplicate(edge) {
  return edge.reduce((acc, cur) => {
    !acc.some((elm) => elm.every((e, i) => cur[i] === e)) && acc.push(cur);
    return acc;
  }, []);
}

console.log(removeDuplicate(edge));```

Body:
my English is not good but i really need your help.

I want to reduce all same values in this 2 Dimensional Array but it doesn't work.

let edge = [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]];

 function removeDup(edge) {
      for (let i = 0; i < edge.length; i++) {
        if (edge.some((item) => item > 1)) {
          edge.splice(i, 1);
        }
      }
      return edge;
    }

i want to change array like this.

 [[0,1,4],[1,2,4],[0,2,4],[2,3,4],[3,0,4],[0,2,4]]

to

[[0,1,4],[1,2,4],[2,3,4],[3,0,4]]


问:
How to plot a box plot with two summary statistics using Matplotlib?
I have summary statistics for my data:

Summary 1: min = 0, 1st quarter = 5, median = 200, mean = 455, 3rd
quarter = 674, max = 980

Summary 2: min = 1, 1st quarter = 7.5, median = 254, mean = 586, 3rd
quarter = 851, max = 1021

I want to plot box plot using matplotlib from these statistics by plotting Summary 1 and 2 side by side.

I can plot the graph (box plot) for each of the summary separately (two graph) but couldn't do it in single plot.

I am using below code for separate box plot:

```<code>import matplotlib.pyplot as plt

stats = [{
    "label": 'Summary 1',  # not required
    "mean":  455,  # not required
    "med": 200,
    "q1": 5,
    "q3": 674,
    "whislo": 0,  # required (min)
    "whishi": 980,  # required (max)
    "fliers": []  # required if showfliers=True
    }]

fs = 10  # fontsize

fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(6, 6), sharey=True)
axes.bxp(stats)
axes.set_title('Boxplot for Summary 1', fontsize=fs)
plt.show()
</code>```

Can anyone tell me how can I do it?

答:
Looking at the value of stats in the source code of the example on the matplotlib docs, you need to put them both into the same list.

```<code>import matplotlib.pyplot as plt

stats = [{
    "label": 'Summary 1',  # not required
    "mean":  455,  # not required
    "med": 200,
    "q1": 5,
    "q3": 674,
    "whislo": 0,  # required (min)
    "whishi": 980,  # required (max)
    "fliers": []  # required if showfliers=True
    },
         {
    "label": 'Summary 2',  # not required
    "mean":586,  # not required
    "med": 254,
    "q1": 7.5,
    "q3": 851,
    "whislo": 1,  # required (min)
    "whishi": 1021,  # required (max)
    "fliers": []  # required if showfliers=True
    }]

fs = 10  # fontsize

fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(6, 6), sharey=True)
axes.bxp(stats)
axes.bxp(stats)
axes.set_title('Boxplot for Summary 1', fontsize=fs)
plt.show()
</code>```

Body:
I have summary statistics for my data:

Summary 1: min = 0, 1st quarter = 5, median = 200, mean = 455, 3rd
quarter = 674, max = 980

Summary 2: min = 1, 1st quarter = 7.5, median = 254, mean = 586, 3rd
quarter = 851, max = 1021

I want to plot box plot using matplotlib from these statistics by plotting Summary 1 and 2 side by side.

I can plot the graph (box plot) for each of the summary separately (two graph) but couldn't do it in single plot.

I am using below code for separate box plot:

import matplotlib.pyplot as plt

stats = [{
    "label": 'Summary 1',  # not required
    "mean":  455,  # not required
    "med": 200,
    "q1": 5,
    "q3": 674,
    "whislo": 0,  # required (min)
    "whishi": 980,  # required (max)
    "fliers": []  # required if showfliers=True
    }]

fs = 10  # fontsize

fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(6, 6), sharey=True)
axes.bxp(stats)
axes.set_title('Boxplot for Summary 1', fontsize=fs)
plt.show()

Can anyone tell me how can I do it?

Body:
Looking at the value of stats in the source code of the example on the matplotlib docs, you need to put them both into the same list.

import matplotlib.pyplot as plt

stats = [{
    "label": 'Summary 1',  # not required
    "mean":  455,  # not required
    "med": 200,
    "q1": 5,
    "q3": 674,
    "whislo": 0,  # required (min)
    "whishi": 980,  # required (max)
    "fliers": []  # required if showfliers=True
    },
         {
    "label": 'Summary 2',  # not required
    "mean":586,  # not required
    "med": 254,
    "q1": 7.5,
    "q3": 851,
    "whislo": 1,  # required (min)
    "whishi": 1021,  # required (max)
    "fliers": []  # required if showfliers=True
    }]

fs = 10  # fontsize

fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(6, 6), sharey=True)
axes.bxp(stats)
axes.bxp(stats)
axes.set_title('Boxplot for Summary 1', fontsize=fs)
plt.show()


问:
Sending HTML Email in php?
Here is the code.

```<code>$to = 'youraddress@example.com';

$subject = 'Test HTML email';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

--PHP-alt-<?php echo $random_hash; ?>--
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
</code>```

I don't follow it well. expect someone can do me a favor.

Why should I generate a random hash?

Why I must add boundary string and mime type specification to header?

Why use ob_start();?

4.

```<code>--PHP-alt-<?php echo $random_hash; ?>
 Content-Type: text/html; charset="iso-8859-1"
 Content-Transfer-Encoding: 7bit
</code>```

What are those lines meaning? Could I delete them? Thank you.

答:
I am not certain why the random hash is used here, but I think it is just additional safety to ensure a unique boundary string, preventing name collisions between parts.

As to the content-type: you need  to specify that to tell the mail client that it should render HTML, and to indicate that your message is multipart. Multipart means there's more than one part, in your case a text-based part and a HTML part.

The boundary part is used to separate the contents of one part form the contents of another part, and from the header.

Using the PHP Output Buffer (ob_start and ob_end_clean) is not necessary at all, you can also just enter strings using quotes or using HEREDOC. An advantage of using the output buffer is that you can end the PHP (using ?>) and have your IDE help you writing HTML. Make sure to add ob_end_clean(); though, it is not yet in your code.

Title: Sending HTML Email in php?

Body:
Here is the code.

$to = 'youraddress@example.com';

$subject = 'Test HTML email';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!

This is something with HTML formatting.

--PHP-alt-<?php echo $random_hash; ?>--
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>

I don't follow it well. expect someone can do me a favor.

Why should I generate a random hash?

Why I must add boundary string and mime type specification to header?

Why use ob_start();?

4.

--PHP-alt-<?php echo $random_hash; ?>
 Content-Type: text/html; charset="iso-8859-1"
 Content-Transfer-Encoding: 7bit

What are those lines meaning? Could I delete them? Thank you.


问:
How to solve "Property muws_disruptive_ads_minor.POLICY_NAME not found"
App Status: Rejected
Your app has been rejected and wasn't published due to the policy issue(s) listed below. If you submitted an update, the previous version of your app is still available on Google Play.
Issue found: Property muws_disruptive_ads_minor.TITLE not found
Property muws_disruptive_ads_minor.SHORT_DESCRIPTION not found
Issue details
We found an issue in the following area(s):
•   SPLIT_BUNDLE 1:
About the Property muws_disruptive_ads_minor.POLICY_NAME is not found Policy
Property muws_disruptive_ads_minor.POLICY_DESCRIPTION not found
About the Property muws_disruptive_ads_minor.POLICY_NAME2 not found Policy
Property muws_disruptive_ads_minor.POLICY_DESCRIPTION2 not found
Action required: Submit an updated app for review
Here's what to do to help get your app on Google Play:
1.  Make sure to read the applicable policies or requirements:
o   Property muws_disruptive_ads_minor.POLICY_NAME not found
o   Property muws_disruptive_ads_minor.POLICY_NAME2 not found
2.  Visit Google Play’s Academy for App Success to get contextual learning on this Google Play policy.
3.  Make appropriate changes to your app (if possible), and be sure to address the issue described above. You may also want to check your app's store listing for compliance, if applicable.
4.  Additionally, follow these steps to bring your app into compliance
Property muws_disruptive_ads_minor.NEXT_STEPS not found
5.  Double check that your app is compliant with all other Developer Program Policies.
6.  If you made changes to your app bundle, store listing, or APK, please sign in to your Play Console and submit the update(s).

What can I do?

答:
Looks like the email was not properly formatted. From the text, it is clear, your app was rejected due to Disruptive Ads.

Are you showing Interstitial ads too frequently or while opening/closing the app?

Make sure Interstitial ads are not blocking the easy navigation and are shown only at appropriate times.


问:
Trying to use playwright with electron, but getting an error
I'm using the react electron boilerplate and after installing playwright by using "npm install -D playwright" I'm getting 23 errors like these when trying to package it, development is fine. Thanks</p>
```<code>[0] ERROR in ./node_modules/playwright-core/bin/README.md 1:4
[0] Module parse failed: Unexpected token (1:4)
[0] You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
[0] > See building instructions at [`//browser_patches/winldd/README.md`](../browser_patches/winldd/README.md)
[0] |
[0] |
[0]  @ ./node_modules/playwright-core/bin/ sync ^\.\/.*$ ./README.md
[0]  @ ./node_modules/playwright-core/lib/server/android/android.js 169:134-173
[0]  @ ./node_modules/playwright-core/lib/server/playwright.js 9:15-43
[0]  @ ./node_modules/playwright-core/lib/inProcessFactory.js 10:18-48
[0]  @ ./node_modules/playwright-core/lib/inprocess.js 3:24-53
[0]  @ ./node_modules/playwright-core/index.js 18:0-43
[0]  @ ./node_modules/playwright/index.js 17:0-43
[0]  @ ./src/main/main.ts 21:19-40
[0]
[0] ERROR in ./node_modules/playwright-core/bin/android-driver-target.apk 1:2
[0] Module parse failed: Unexpected character '' (1:2)
[0] You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
[0] (Source code omitted for this binary file)
[0]  @ ./node_modules/playwright-core/bin/ sync ^\.\/.*$ ./android-driver-target.apk
[0]  @ ./node_modules/playwright-core/lib/server/android/android.js 169:134-173
[0]  @ ./node_modules/playwright-core/lib/server/playwright.js 9:15-43
[0]  @ ./node_modules/playwright-core/lib/inProcessFactory.js 10:18-48
[0]  @ ./node_modules/playwright-core/lib/inprocess.js 3:24-53
[0]  @ ./node_modules/playwright-core/index.js 18:0-43
[0]  @ ./node_modules/playwright/index.js 17:0-43
[0]  @ ./src/main/main.ts 21:19-40

[0] webpack compiled with 23 errors
[0] npm run build:main exited with code 1
</code>```

答:
Manually add to ./release/app/package.json.

Example:

```<code>  "dependencies": {
    "playwright": "^1.17.2"
  },
</code>```

From https://electron-react-boilerplate.js.org/docs/adding-dependencies/

If the module is native to a platform (like node-postgres), it should be listed under dependencies in ./release/app/package.json

Body:
I'm using the react electron boilerplate and after installing playwright by using "npm install -D playwright" I'm getting 23 errors like these when trying to package it, development is fine. Thanks

[0] ERROR in ./node_modules/playwright-core/bin/README.md 1:4
[0] Module parse failed: Unexpected token (1:4)
[0] You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
[0] > See building instructions at [`//browser_patches/winldd/README.md`](../browser_patches/winldd/README.md)
[0] |
[0] |
[0]  @ ./node_modules/playwright-core/bin/ sync ^\.\/.*$ ./README.md
[0]  @ ./node_modules/playwright-core/lib/server/android/android.js 169:134-173
[0]  @ ./node_modules/playwright-core/lib/server/playwright.js 9:15-43
[0]  @ ./node_modules/playwright-core/lib/inProcessFactory.js 10:18-48
[0]  @ ./node_modules/playwright-core/lib/inprocess.js 3:24-53
[0]  @ ./node_modules/playwright-core/index.js 18:0-43
[0]  @ ./node_modules/playwright/index.js 17:0-43
[0]  @ ./src/main/main.ts 21:19-40
[0]
[0] ERROR in ./node_modules/playwright-core/bin/android-driver-target.apk 1:2
[0] Module parse failed: Unexpected character '' (1:2)
[0] You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
[0] (Source code omitted for this binary file)
[0]  @ ./node_modules/playwright-core/bin/ sync ^\.\/.*$ ./android-driver-target.apk
[0]  @ ./node_modules/playwright-core/lib/server/android/android.js 169:134-173
[0]  @ ./node_modules/playwright-core/lib/server/playwright.js 9:15-43
[0]  @ ./node_modules/playwright-core/lib/inProcessFactory.js 10:18-48
[0]  @ ./node_modules/playwright-core/lib/inprocess.js 3:24-53
[0]  @ ./node_modules/playwright-core/index.js 18:0-43
[0]  @ ./node_modules/playwright/index.js 17:0-43
[0]  @ ./src/main/main.ts 21:19-40

[0] webpack compiled with 23 errors
[0] npm run build:main exited with code 1

Body:
Manually add to ./release/app/package.json.

Example:

  "dependencies": {
    "playwright": "^1.17.2"
  },

From https://electron-react-boilerplate.js.org/docs/adding-dependencies/

If the module is native to a platform (like node-postgres), it should be listed under dependencies in ./release/app/package.json


问:
What does '&' do in C/C++ and what is its equivalent operator in perl?
I'm writing a perl implementation of a protocol whose specification is given for C/C++ but I don't know much C.

What does the condition if ((flags & 0x400) != 0) mean? How do I do that in perl?

Is if ($flags == "\x400") correct?

答:
& is a bitwise AND. See Bitwise operators.

So flags is being treated as a series of bits, and then you AND it with something which has exactly the bit set that you want to check. If the result is non-zero, then the bit is set, otherwise the bit you were looking at isn't set. In particular, in your example 0x400 = 0100 0000 0000 is being used to check if the 11th bit is set (to 1) in flags.

Typically, you wouldn't use 0x400 but a named constant, so it is clear what that bit represents.

So if ($flags == "\x400") isn't correct. See Working with bits in Perl.

A common example of bit-masking can be seen in Linux file permissions.


问:
Finding x numbers in list greater than 0 with potential duplicates and assigning index of original list
I have lists of floats which will have some zeros in it. Eg.

```<code>numbers = [1.2, 0.0, 0.0, 1.2, 2.0, 2.5, 17, 1.3, 1.8, 1.3, 1.2]
</code>```

I am trying to assign these values to n numbers (assuming it will be the first 5) for the lowest 5 values that are greater than 0.

I can get the first by using:

```<code>first = min(o for o in numbers if o > 0)
</code>```

But as there are duplicates in the smallest value (1.2), I cannot easily assign second, third, fourth and fifth.

I need to assign these and allow me to keep the index of their values in the original list and assign these too. Eg.

```<code>first_pos = numbers.index(first)
</code>```

I cannot use the above for second as it will assign it the first index value.

Is there any efficient way using a for loop or list comprehension or even a small function to assigning the other numbers so that:

```<code>second = 1.2
second_pos = 4
third = 1.2
third_pos = 10
fourth = 1.3
fourth_pos = 7
fifth = 1.3
fifth_pos = 9
</code>```

I cannot do this with any list comprehension I know of for second as it will not pick up a duplicate. Eg.:

```<code>sec = min(o for o in numbers if o > first)
</code>```

The lists vary in length of values (at least 5, though) and may or may not have duplicates and zeros but many will.

答:
Ok, to badly answer my own question, I have been able to do this by copying and removing the zeros, enumerating over the list for the index values and removing each number once assigned:

```<code>number = [n for n in numbers if n > 0]
numbs = [n for n, x in enumerate(numbers) if x > 0]
for n in number:
  first = min(number)
  first_pos = number.index(first)
  first_ind = numbs[first_pos]
number.remove(first)
numbs.remove(first_ind)
for n in number:
  second = min(number)
  sec_pos = number.index(second)
  sec_ind = numbs[sec_pos]
number.remove(second)
numbs.remove(sec_ind)
</code>```

This will keep and assign the values and indexes of each minimum value greater than zero.

Is there any way to add this into a function to assign all values greater than zero in the list to its own variables?

Body:
I have lists of floats which will have some zeros in it. Eg.

numbers = [1.2, 0.0, 0.0, 1.2, 2.0, 2.5, 17, 1.3, 1.8, 1.3, 1.2]

I am trying to assign these values to n numbers (assuming it will be the first 5) for the lowest 5 values that are greater than 0.

I can get the first by using:

first = min(o for o in numbers if o > 0)

But as there are duplicates in the smallest value (1.2), I cannot easily assign second, third, fourth and fifth.

I need to assign these and allow me to keep the index of their values in the original list and assign these too. Eg.

first_pos = numbers.index(first)

I cannot use the above for second as it will assign it the first index value.

Is there any efficient way using a for loop or list comprehension or even a small function to assigning the other numbers so that:

second = 1.2
second_pos = 4
third = 1.2
third_pos = 10
fourth = 1.3
fourth_pos = 7
fifth = 1.3
fifth_pos = 9

I cannot do this with any list comprehension I know of for second as it will not pick up a duplicate. Eg.:

sec = min(o for o in numbers if o > first)

The lists vary in length of values (at least 5, though) and may or may not have duplicates and zeros but many will.

Body:
Ok, to badly answer my own question, I have been able to do this by copying and removing the zeros, enumerating over the list for the index values and removing each number once assigned:

number = [n for n in numbers if n > 0]
numbs = [n for n, x in enumerate(numbers) if x > 0]
for n in number:
  first = min(number)
  first_pos = number.index(first)
  first_ind = numbs[first_pos]
number.remove(first)
numbs.remove(first_ind)
for n in number:
  second = min(number)
  sec_pos = number.index(second)
  sec_ind = numbs[sec_pos]
number.remove(second)
numbs.remove(sec_ind)

This will keep and assign the values and indexes of each minimum value greater than zero.

Is there any way to add this into a function to assign all values greater than zero in the list to its own variables?


问:
What's the best way to store a phone number in Django models?
I am storing a phone number in model like this:

```<code>phone_number = models.CharField(max_length=12)
</code>```

The user would enter a phone number and I would use the phone number for SMS authentication. This application would be used globally. So I would also need a country code. Is CharField a good way to store a phone number? And, how do I validate the phone number?

答:
First of all, you need to install the phone number Django package.

pip install django-phonenumber-field[phonenumbers]
```
<p>Then next is to add it to the installed applications:</p>
```INSTALLED_APPS = [
    ...
    'phonenumber_field',
    ...
]
```
<p>This is how to use it in your model:</p>
```from phonenumber_field.modelfields import PhoneNumberField

class Artist(models.Model):

    phone_number = PhoneNumberField()
```

Body:
I am storing a phone number in model like this:

phone_number = models.CharField(max_length=12)

The user would enter a phone number and I would use the phone number for SMS authentication. This application would be used globally. So I would also need a country code. Is CharField a good way to store a phone number? And, how do I validate the phone number?

Body:
First of all, you need to install the phone number Django package.

pip install django-phonenumber-field[phonenumbers]

Then next is to add it to the installed applications:

INSTALLED_APPS = [
    ...
    'phonenumber_field',
    ...
]

This is how to use it in your model:

from phonenumber_field.modelfields import PhoneNumberField

class Artist(models.Model):

    phone_number = PhoneNumberField()


问:
Handling the "IndexError: string index out of range" error
I have the following string my_string:

```<code>my_string = 'A15B27C32D72A7B14C9D31'
</code>```

I split this string into chunks by the character A:

```<code>chunks = ['A' + elem for elem in my_string.split('A') if elem != '']

chunks
['A15B27C32D72', 'A7B14C9D31']
</code>```

I'd like to be able to check whether there is a number associated with the "D" character of each chunk.  To do this, I use:

```<code>for elem in chunks:
    if elem[elem.find('D') + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])
</code>```

(Technically, this isn't correct since it won't catch cases whereby the number isn't a single digit.)

Now, let's change my_string to:

```<code>my_string = 'A15B27C32DA7B14C9D31'

chunks = ['A' + elem for elem in my_string.split('A') if elem != '']
chunks
['A15B27C32D', 'A7B14C9D31']
</code>```

(notice that D in the first chunk doesn't have an associated number)

If I run the following:

```<code>for elem in chunks:
    if elem[elem.find('D') + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])
</code>```

I get:

```<code>IndexError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_8844/1838165888.py in <module>
      1 for elem in chunks:
----> 2     if elem[elem.find('D') + 1].isdigit() is False:
      3         print('no number associated with D')
      4     else:
      5         print('the number associated with D is', elem[elem.find('D') +1])

IndexError: string index out of range
</code>```

To fix this, I can use try/except.

I can also use the following:

```<code>for elem in chunks:
    if elem[-1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])

no number associated with D
the number associated with D is 3
</code>```

But, both of these approaches feel somewhat hacky.

Is there a more elegant and idiomatic way to handle the string index out of range error?

Thanks!

答:
Here is 4 problems in your code:

If string is '1234' → '1234'.find('D') will return -1 and '1234'[-1+1] will return 1. And that is not correct

If string is '123D' → '123D'.find('D') will return 3 and that is last element of list, so '123D'[3+1] raises index out of range error

if string is '' → ''.find('D') will return -1 → ''[-1+1] → see ②

If string is 'D12D34' → only first D will be found. But as I can understand only one D should be present in chunk by design

Most closer solution will be:

```<code>d_index = elem.find('D') + 1
if d_index > 0 and len(elem) > d_index and elem[d_index].isdigit() is True:
    print('the number associated with D is', elem[elem.find('D') +1])
else:
    print('no number associated with D')
</code>```

Body:
I have the following string my_string:

my_string = 'A15B27C32D72A7B14C9D31'

I split this string into chunks by the character A:

chunks = ['A' + elem for elem in my_string.split('A') if elem != '']

chunks
['A15B27C32D72', 'A7B14C9D31']

I'd like to be able to check whether there is a number associated with the "D" character of each chunk.  To do this, I use:

for elem in chunks:
    if elem[elem.find('D') + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])

(Technically, this isn't correct since it won't catch cases whereby the number isn't a single digit.)

Now, let's change my_string to:

my_string = 'A15B27C32DA7B14C9D31'

chunks = ['A' + elem for elem in my_string.split('A') if elem != '']
chunks
['A15B27C32D', 'A7B14C9D31']

(notice that D in the first chunk doesn't have an associated number)

If I run the following:

for elem in chunks:
    if elem[elem.find('D') + 1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])

I get:

IndexError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_8844/1838165888.py in <module>
      1 for elem in chunks:
----> 2     if elem[elem.find('D') + 1].isdigit() is False:
      3         print('no number associated with D')
      4     else:
      5         print('the number associated with D is', elem[elem.find('D') +1])

IndexError: string index out of range

To fix this, I can use try/except.

I can also use the following:

for elem in chunks:
    if elem[-1].isdigit() is False:
        print('no number associated with D')
    else:
        print('the number associated with D is', elem[elem.find('D') +1])

no number associated with D
the number associated with D is 3

But, both of these approaches feel somewhat hacky.

Is there a more elegant and idiomatic way to handle the string index out of range error?

Thanks!

Body:
Here is 4 problems in your code:

If string is '1234' → '1234'.find('D') will return -1 and '1234'[-1+1] will return 1. And that is not correct

If string is '123D' → '123D'.find('D') will return 3 and that is last element of list, so '123D'[3+1] raises index out of range error

if string is '' → ''.find('D') will return -1 → ''[-1+1] → see ②

If string is 'D12D34' → only first D will be found. But as I can understand only one D should be present in chunk by design

Most closer solution will be:

d_index = elem.find('D') + 1
if d_index > 0 and len(elem) > d_index and elem[d_index].isdigit() is True:
    print('the number associated with D is', elem[elem.find('D') +1])
else:
    print('no number associated with D')


问:
Intellisense not working for .vue files
I am working with Vue and Typescript in Visual Studio Code and the Vetur extension. The problem: when I update any code, intellisense won't recognise the changes when working in a .vue file. In .ts files, intellisense IS working!

I use this definition file so that typescript recognises the .vue file extension:

```<code>declare module "*.vue" {
    import Vue from "vue";
    export default Vue;
}
</code>```

Example

test.ts just changed

```<code>export default class Test {
    // testFunction() {}    // just removed this
    dummyFunction() {}      // added this
}
</code>```

app.vue intellisense not working

In any .vue file, intellisense keeps suggesting testFunction and doesn't recognise dummyFunction:

```<code>import Test from "./test"
export default class App extends Vue {
    created() {
        const t = new Test()
        t.testFunction()        // allowed - but it doesn't exist
        t.dummyFunction()       // not allowed - but it does exist
    }
}
</code>```

somefile.ts intellisense is working

In regular old .ts files, intellisense works.

```<code>import Test from "./test"
const t = new Test()
t.testFunction()        // here it works - this is not allowed
t.dummyFunction()       // here it works - this is allowed
</code>```

If I close VS Code and reopen, then the new changes are updated. Is this a Vetur glitch? Do I need to alter my tsconfig or definition files?

答:
I believe you need to add something like this to your tsconfig:

```<code>{
  "include": ["src/**/*.vue"]
}
</code>```

From the docs: "If a glob pattern doesn’t include a file extension, then only files with supported extensions are included (e.g. .ts, .tsx, and .d.ts by default, with .js and .jsx if allowJs is set to true)."

I'm not sure how Vetur is behaving, but from a TS perspective, this should do the trick.

Title: Intellisense not working for .vue files

Body:
I am working with Vue and Typescript in Visual Studio Code and the Vetur extension. The problem: when I update any code, intellisense won't recognise the changes when working in a .vue file. In .ts files, intellisense IS working!

I use this definition file so that typescript recognises the .vue file extension:

declare module "*.vue" {
    import Vue from "vue";
    export default Vue;
}

Example

test.ts just changed

export default class Test {
    // testFunction() {}    // just removed this
    dummyFunction() {}      // added this
}

app.vue intellisense not working

In any .vue file, intellisense keeps suggesting testFunction and doesn't recognise dummyFunction:

import Test from "./test"
export default class App extends Vue {
    created() {
        const t = new Test()
        t.testFunction()        // allowed - but it doesn't exist
        t.dummyFunction()       // not allowed - but it does exist
    }
}

somefile.ts intellisense is working

In regular old .ts files, intellisense works.

import Test from "./test"
const t = new Test()
t.testFunction()        // here it works - this is not allowed
t.dummyFunction()       // here it works - this is allowed

If I close VS Code and reopen, then the new changes are updated. Is this a Vetur glitch? Do I need to alter my tsconfig or definition files?

Body:
I believe you need to add something like this to your tsconfig:

{
  "include": ["src/**/*.vue"]
}

From the docs: "If a glob pattern doesn’t include a file extension, then only files with supported extensions are included (e.g. .ts, .tsx, and .d.ts by default, with .js and .jsx if allowJs is set to true)."

I'm not sure how Vetur is behaving, but from a TS perspective, this should do the trick.


问:
MapKit: coordinates from Sqlite database
I have a sqlite database with about 100 000 rows containing longitudes and latitudes of ATMs. I want to display this ATMs by pins on MKMapView. But I think that it is not good for memory and not o fast if I will load all coordinates from DB at once. What is the best way to do it?</p>

答:
You're absolutely right, don't load them all at once!

Use a bounding box to only get coordinates that are within the map your want to display. Check out the answer to this question : Core Data and Core Location

Use the same concept of a upper and lower limit to your lat and lng to only return rows from sqlite that are currently visible. Your query would look something like

```<code>SELECT * FROM atms WHERE lat > 51.4 and lat < 51.6 and lng > -0.165 and lng < -0.175
</code>```

This query only returns ATMs that are near central London (51.5, -0.17).

Body:
You're absolutely right, don't load them all at once!

Use a bounding box to only get coordinates that are within the map your want to display. Check out the answer to this question : Core Data and Core Location

Use the same concept of a upper and lower limit to your lat and lng to only return rows from sqlite that are currently visible. Your query would look something like

SELECT * FROM atms WHERE lat > 51.4 and lat < 51.6 and lng > -0.165 and lng < -0.175

This query only returns ATMs that are near central London (51.5, -0.17).


问:
Using Go to make a POST request using a JSON file
I am very new to Go and searched around for this question but did not find anything, so I apologize if this is a duplicate that I missed.

I need to send a POST request using Go and have the body come from a JSON file. Below is a modified version of the code from https://golangtutorial.dev/tips/http-post-json-go/ that I am using as a starting point.

I am thinking that I can just substitute the jsonData var with a JSON file that I pull in but I just wanted to know if this is the correct approach and how to best go about doing this. Thanks!

```<code>package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    httpposturl := "https://reqres.in/api/users"

    // I think this is the block I need to alter?:
    var jsonData = []byte(`{
        "name": "morpheus",
        "job": "leader"
    }`)

    request, error := http.NewRequest("POST", httpposturl, bytes.NewBuffer(jsonData))
    request.Header.Set("Content-Type", "application/json; charset=UTF-8")

    client := &http.Client{}
    response, error := client.Do(request)
    if error != nil {
        panic(error)
    }
    defer response.Body.Close()

    fmt.Println("response Status:", response.Status)
}
</code>```

答:
Note: whatever(words, file, image, or even video, etc..) you want to post by the http protocol, you post bytes stream in fact. That means you should treat anything you want to post as an array of binary bytes.

In your case, you should first open the file you want to post, and creates an instance of type io.Reader which pointes to your file. the simple code as belows:

```<code>f, _ := os.Open("./my-file")

http.Post("https://example.com/api","application/json",f)
</code>```

Body:
I am very new to Go and searched around for this question but did not find anything, so I apologize if this is a duplicate that I missed.

I need to send a POST request using Go and have the body come from a JSON file. Below is a modified version of the code from https://golangtutorial.dev/tips/http-post-json-go/ that I am using as a starting point.

I am thinking that I can just substitute the jsonData var with a JSON file that I pull in but I just wanted to know if this is the correct approach and how to best go about doing this. Thanks!

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    httpposturl := "https://reqres.in/api/users"

    // I think this is the block I need to alter?:
    var jsonData = []byte(`{
        "name": "morpheus",
        "job": "leader"
    }`)

    request, error := http.NewRequest("POST", httpposturl, bytes.NewBuffer(jsonData))
    request.Header.Set("Content-Type", "application/json; charset=UTF-8")

    client := &http.Client{}
    response, error := client.Do(request)
    if error != nil {
        panic(error)
    }
    defer response.Body.Close()

    fmt.Println("response Status:", response.Status)
}

Body:
Note: whatever(words, file, image, or even video, etc..) you want to post by the http protocol, you post bytes stream in fact. That means you should treat anything you want to post as an array of binary bytes.

In your case, you should first open the file you want to post, and creates an instance of type io.Reader which pointes to your file. the simple code as belows:

f, _ := os.Open("./my-file")

http.Post("https://example.com/api","application/json",f)


问:
Please help me to understand the use of "->" in Arrays.sort()
I was solving problems in GeeksforGeeks and suddenly got this. I understand the use of "Integer.compare", but could not get the use of "->" in the sortBySetBitCount method.</p>
```<code>static void sortBySetBitCount(Integer arr[], int n)
{
    Arrays.sort(arr, (a, b) -> Integer.compare(countSetBit(b), countSetBit(a)));
         //I mean here the "->" operator
}

static int countSetBit(int n) {
    int count = 0;
    while (n>0) {
        n = n & (n - 1);
        count += 1;
    }
    return count;
}
</code>```

答:
This is a part of the syntax of the new lambda expression introduced in Java 8. There are a couple of online tutorials to get the hang of it, Lambda Expression Document API link.

It is basically
The symbol -> separates the parameters ( i.e left-side) from the implementation (i.e right side)

The general syntax for using lambda expressions is

(Parameters) -> { Body } where the -> separates parameters and lambda expression body.

The parameters are enclosed in parentheses which is the same way as for methods and the lambda expression body is a block of code enclosed in braces.

Body:
I was solving problems in GeeksforGeeks and suddenly got this. I understand the use of "Integer.compare", but could not get the use of "->" in the sortBySetBitCount method.

static void sortBySetBitCount(Integer arr[], int n)
{
    Arrays.sort(arr, (a, b) -> Integer.compare(countSetBit(b), countSetBit(a)));
         //I mean here the "->" operator
}

static int countSetBit(int n) {
    int count = 0;
    while (n>0) {
        n = n & (n - 1);
        count += 1;
    }
    return count;
}