问:
showing estimate value in the forest plot from ZINB model
This question is a follow up question to Overlay of forest plot from ZINB model. I need help in displaying the estimated value in the forest plot from ZINB model indicated in the picture below

library(sjPlot)
library(sjlabelled)
library(sjmisc)
library(ggplot2)
library(MASS)
library(pscl)
library(boot)

library(broom)
library(poissonreg)
library(tidyverse) ## purrr::map_dfr, ggplot ...
theme_set(theme_bw())
library(colorspace)

zinb_all_uni <- zeroinfl(ivdays~age,
                         link="logit",
                         dist = "negbin",
                         data=caterpillor)

summary(zinb_all_uni)
plot_model(zinb_all_uni, type="est")

zinb_full_adj <- zeroinfl(ivdays~age+sex+edu,
                          link="logit",
                          dist = "negbin",
                          data=caterpillor)

summary(zinb_full_adj)
plot_model(zinb_full_adj, type="est", terms = c("count_ageb", "count_agec", "zero_ageb", "zero_agec"))

############ second model#######

Zinb_uni_sub <- zeroinfl(ivdays~age,
                         link="logit",
                         dist = "negbin",
                         data=subset(caterpillor, country=="eng"))

summary(Zinb_uni_sub)
plot_model(Zinb_uni_sub, type="est")

zinb_adj_sub <- zeroinfl(ivdays~age+sex+edu,
                         link="logit",
                         dist = "negbin",
                         data=subset(caterpillor, country=="eng"))

summary(zinb_adj_sub)

plot_model(zinb_adj_sub, type="est", terms = c("count_ageb", "count_agec", "zero_ageb", "zero_agec"))

mod_list <- list(all_uni = zinb_all_uni, uni_sub = Zinb_uni_sub)

tidy(zinb_all_uni, type = "all")

coefs <- (mod_list
          |> map_dfr(tidy, type = "all",
                     .id = "model")
          ## construct CIs
          |> mutate(conf.low  = qnorm(0.025, estimate, std.error),
                    conf.high = qnorm(0.975, estimate, std.error))
          |> filter(term != "(Intercept)")  ## usually don't want this
          ## cosmetic (strip results down to the components we actually need)
          |> dplyr::select(model, term, type, estimate, conf.low, conf.high)
          ## back-transform
          |> mutate(across(c(estimate, conf.low, conf.high), exp))
          |> filter(stringr::str_detect(term, "^age"))
)

ggplot(coefs, aes(x = estimate, y = term, colour = model)) +
  geom_pointrange(aes(xmin = conf.low, xmax = conf.high),
                  position = position_dodge(width = 0.5)) +
  ## separate count-ratio and odds-ratio (conditional/zero) plots
  facet_wrap(~type, scale = "free") +
  scale_color_discrete_qualitative()+ ## cosmetic
  geom_vline(xintercept = 1, lty = 1, color = "yellow", size = 1.5)+
  labs(x = "Incidence rate ratio: #IV days", y= "age")

```
<p>Here is the plots. I would like to display the estimated values circled below:
<img src="https://i.stack.imgur.com/Evlej.png" alt="enter image description here" /></p>
<p><img src="https://i.stack.imgur.com/9EFic.png" alt="enter image description here" /></p>
<p>The following is the data:</p>
```caterpillor=structure(list(id = 1:100,
                           age = structure(c(1L, 1L, 2L, 1L,
                                             2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L, 3L, 3L,
                                             1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 2L, 1L, 2L, 2L,
                                             2L, 3L, 3L, 3L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L,
                                             2L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L,
                                             3L, 3L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 2L, 1L,
                                             2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L, 3L, 3L),
                                           .Label = c("a", "b", "c"), class = "factor"),
                           sex = structure(c(2L,
                                             1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L,
                                             1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L,
                                             1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L,
                                             2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L,
                                             2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L,
                                             2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L,
                                             2L, 1L, 1L),
                                           .Label = c("F", "M"), class = "factor"),
                           country = structure(c(1L,
                                                 1L, 1L, 1L, 3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 3L, 3L, 3L,
                                                 2L, 2L, 2L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L,
                                                 1L, 3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 2L, 2L,
                                                 2L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 3L,
                                                 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 2L, 2L, 2L, 1L,
                                                 1L, 1L, 1L, 3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 3L, 3L, 3L,
                                                 2L, 2L, 2L),
                                               .Label = c("eng", "scot", "wale"), class = "factor"),
                           edu = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L,
                                             1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L,
                                             2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L,
                                             1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L,
                                             2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L,
                                             1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L,
                                             2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L),
                                           .Label = c("x", "y", "z"), class = "factor"),
                           lungfunction = c(45L,
                                            23L, 25L, 45L, 70L, 69L, 90L, 50L, 62L, 45L, 23L, 25L, 45L,
                                            70L, 69L, 90L, 50L, 62L, 45L, 23L, 25L, 45L, 70L, 69L, 90L,
                                            50L, 62L, 45L, 23L, 25L, 45L, 70L, 69L, 90L, 50L, 62L, 45L,
                                            23L, 25L, 45L, 70L, 69L, 90L, 50L, 62L, 45L, 23L, 25L, 45L,
                                            70L, 69L, 90L, 50L, 62L, 45L, 23L, 25L, 45L, 70L, 69L, 90L,
                                            50L, 62L, 45L, 23L, 25L, 45L, 70L, 69L, 90L, 50L, 62L, 45L,
                                            23L, 25L, 45L, 70L, 69L, 90L, 50L, 62L, 25L, 45L, 70L, 69L,
                                            90L, 50L, 62L, 25L, 45L, 70L, 69L, 90L, 50L, 62L, 25L, 45L,
                                            70L, 69L, 90L),
                           ivdays = c(15L, 26L, 36L, 34L, 2L, 4L, 5L,
                                      8L, 9L, 15L, 26L, 36L, 34L, 2L, 4L, 5L, 8L, 9L, 15L, 26L,
                                      0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
                                      0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
                                      0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
                                      0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
                                      0L, 0L, 0L, 0L, 0L, 5L, 8L, 9L, 36L, 34L, 2L, 4L, 5L, 8L,
                                      9L, 36L, 34L, 2L, 4L, 5L),
                           no2_quintile = structure(c(1L,
                                                      1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                                      1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
                                                      2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
                                                      3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
                                                      3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L,
                                                      4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L,
                                                      5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L),
                                                    .Label = c("q1", "q2",
                                                               "q3", "q4", "q5"), class = "factor")),
                      class = "data.frame", row.names = c(NA,
                                                          -100L))

```

Any help is appreciated!

Body:
This question is a follow up question to Overlay of forest plot from ZINB model. I need help in displaying the estimated value in the forest plot from ZINB model indicated in the picture below

library(sjPlot)
library(sjlabelled)
library(sjmisc)
library(ggplot2)
library(MASS)
library(pscl)
library(boot)

library(broom)
library(poissonreg)
library(tidyverse) ## purrr::map_dfr, ggplot ...
theme_set(theme_bw())
library(colorspace)

zinb_all_uni <- zeroinfl(ivdays~age,
                         link="logit",
                         dist = "negbin",
                         data=caterpillor)

summary(zinb_all_uni)
plot_model(zinb_all_uni, type="est")

zinb_full_adj <- zeroinfl(ivdays~age+sex+edu,
                          link="logit",
                          dist = "negbin",
                          data=caterpillor)

summary(zinb_full_adj)
plot_model(zinb_full_adj, type="est", terms = c("count_ageb", "count_agec", "zero_ageb", "zero_agec"))

############ second model#######

Zinb_uni_sub <- zeroinfl(ivdays~age,
                         link="logit",
                         dist = "negbin",
                         data=subset(caterpillor, country=="eng"))

summary(Zinb_uni_sub)
plot_model(Zinb_uni_sub, type="est")

zinb_adj_sub <- zeroinfl(ivdays~age+sex+edu,
                         link="logit",
                         dist = "negbin",
                         data=subset(caterpillor, country=="eng"))

summary(zinb_adj_sub)

plot_model(zinb_adj_sub, type="est", terms = c("count_ageb", "count_agec", "zero_ageb", "zero_agec"))

mod_list <- list(all_uni = zinb_all_uni, uni_sub = Zinb_uni_sub)

tidy(zinb_all_uni, type = "all")

coefs <- (mod_list
          |> map_dfr(tidy, type = "all",
                     .id = "model")
          ## construct CIs
          |> mutate(conf.low  = qnorm(0.025, estimate, std.error),
                    conf.high = qnorm(0.975, estimate, std.error))
          |> filter(term != "(Intercept)")  ## usually don't want this
          ## cosmetic (strip results down to the components we actually need)
          |> dplyr::select(model, term, type, estimate, conf.low, conf.high)
          ## back-transform
          |> mutate(across(c(estimate, conf.low, conf.high), exp))
          |> filter(stringr::str_detect(term, "^age"))
)

ggplot(coefs, aes(x = estimate, y = term, colour = model)) +
  geom_pointrange(aes(xmin = conf.low, xmax = conf.high),
                  position = position_dodge(width = 0.5)) +
  ## separate count-ratio and odds-ratio (conditional/zero) plots
  facet_wrap(~type, scale = "free") +
  scale_color_discrete_qualitative()+ ## cosmetic
  geom_vline(xintercept = 1, lty = 1, color = "yellow", size = 1.5)+
  labs(x = "Incidence rate ratio: #IV days", y= "age")

Here is the plots. I would like to display the estimated values circled below:

The following is the data:

caterpillor=structure(list(id = 1:100,
                           age = structure(c(1L, 1L, 2L, 1L,
                                             2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L, 3L, 3L,
                                             1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 2L, 1L, 2L, 2L,
                                             2L, 3L, 3L, 3L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L,
                                             2L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L,
                                             3L, 3L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 2L, 1L,
                                             2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 3L, 3L, 3L),
                                           .Label = c("a", "b", "c"), class = "factor"),
                           sex = structure(c(2L,
                                             1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L,
                                             1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L,
                                             1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L,
                                             2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L,
                                             2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L,
                                             2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L,
                                             2L, 1L, 1L),
                                           .Label = c("F", "M"), class = "factor"),
                           country = structure(c(1L,
                                                 1L, 1L, 1L, 3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 3L, 3L, 3L,
                                                 2L, 2L, 2L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L,
                                                 1L, 3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 2L, 2L,
                                                 2L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 3L,
                                                 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 2L, 2L, 2L, 1L,
                                                 1L, 1L, 1L, 3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 3L, 3L, 3L,
                                                 2L, 2L, 2L),
                                               .Label = c("eng", "scot", "wale"), class = "factor"),
                           edu = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L,
                                             1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L,
                                             2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L,
                                             1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L,
                                             2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L,
                                             1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L,
                                             2L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L),
                                           .Label = c("x", "y", "z"), class = "factor"),
                           lungfunction = c(45L,
                                            23L, 25L, 45L, 70L, 69L, 90L, 50L, 62L, 45L, 23L, 25L, 45L,
                                            70L, 69L, 90L, 50L, 62L, 45L, 23L, 25L, 45L, 70L, 69L, 90L,
                                            50L, 62L, 45L, 23L, 25L, 45L, 70L, 69L, 90L, 50L, 62L, 45L,
                                            23L, 25L, 45L, 70L, 69L, 90L, 50L, 62L, 45L, 23L, 25L, 45L,
                                            70L, 69L, 90L, 50L, 62L, 45L, 23L, 25L, 45L, 70L, 69L, 90L,
                                            50L, 62L, 45L, 23L, 25L, 45L, 70L, 69L, 90L, 50L, 62L, 45L,
                                            23L, 25L, 45L, 70L, 69L, 90L, 50L, 62L, 25L, 45L, 70L, 69L,
                                            90L, 50L, 62L, 25L, 45L, 70L, 69L, 90L, 50L, 62L, 25L, 45L,
                                            70L, 69L, 90L),
                           ivdays = c(15L, 26L, 36L, 34L, 2L, 4L, 5L,
                                      8L, 9L, 15L, 26L, 36L, 34L, 2L, 4L, 5L, 8L, 9L, 15L, 26L,
                                      0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
                                      0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
                                      0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
                                      0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
                                      0L, 0L, 0L, 0L, 0L, 5L, 8L, 9L, 36L, 34L, 2L, 4L, 5L, 8L,
                                      9L, 36L, 34L, 2L, 4L, 5L),
                           no2_quintile = structure(c(1L,
                                                      1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                                                      1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
                                                      2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
                                                      3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
                                                      3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L,
                                                      4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L,
                                                      5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L),
                                                    .Label = c("q1", "q2",
                                                               "q3", "q4", "q5"), class = "factor")),
                      class = "data.frame", row.names = c(NA,
                                                          -100L))

Any help is appreciated!


来源: stackexchange

问:
ORDER BY sort by then from smallest to largest in medoo
How to write this query with medoo?

```<code>query="SELECT DISTINCT id FROM items WHERE name='Mag' AND var='Bl' ORDER BY atrow +0 ASC"
</code>```

In the query results above, they are sorted according to the atrow values from the smallest to the largest

Can anyone help?

```<code>$item= $database->select("items", "@id", [ "var[=]" => "Bl", "name[=]" => "Mag","ORDER" => [ " atrow" => "ASC" ] ]);
</code>```

But

Every time I refresh, the order is messed up

ContentLicense: CC BY-SA 4.0

Body:
How to write this query with medoo?

query="SELECT DISTINCT id FROM items WHERE name='Mag' AND var='Bl' ORDER BY atrow +0 ASC"

In the query results above, they are sorted according to the atrow values from the smallest to the largest

Can anyone help?

$item= $database->select("items", "@id", [ "var[=]" => "Bl", "name[=]" => "Mag","ORDER" => [ " atrow" => "ASC" ] ]);

But

Every time I refresh, the order is messed up


问:
Detecting Semantic Difference between Two Images
I am seeking to determine if an edited version of an image has been edited so as to change semantic meaning.

To this end, I compute the cosine similarity between the two images under the embedding of openAI's CLIP. The problem: images edited in valid ways (eg simple brightness changes) show similar similarity scored (approx 0.9) to images with true semantic change (eg changing a frown to a smile), so this is clearly not enough. Wondering if anyone has ideas on how to leverage CLIP to detect "invalid" differences?


问:
Overcome memory leakage of 3rd party C-library called in while loop with multiprocessing?
I have a memory leakage identified in a 3rd party C-library, that I cannot correct.
This leaky stuff needs to be executed forever in a while loop (see code below), leading to consistent memory increase over time.

```<code>import psutil
import os

class LeakyClass():

    def __init__():
        self.Dict = {}
        # do stuff with leaky C-library to fill the Dict

if __name__ == '__main__':
    while True:
        my_dict = LeakyClass().Dict
        # do stuff with my_dict
        proc = psutil.Process(os.getpid())
        print(proc.memory_info().rss / 1024**2)
        sleep(8)
</code>```

To try to avoid the leak, I have moved the problematic leaky part into another Process, thinking this way when the process will end, I'll get rid of the leakage. I have added a manager to get my Dict available in the main process. Below is the new code:

```<code>import multiprocessing
import psutil
import os

class LeakyClass():

    def __init__():
        self.Dict = {}
        # do stuff with leaky C-library to fill the Dict

def task(shared_dict):
    shared_dict.clear()
    my_dict = LeakyClass().Dict
    for key in my_dict:
        shared_dict[key] = my_dict[key]

if __name__ == '__main__':
    manager = multiprocessing.Manager()
    shared_dict = manager.dict()

    while True:
        process = multiprocessing.Process(target=task, args=(shared_dict,))
        process.start()
        process.join()
        # do stuff with shared_dict
        proc = psutil.Process(os.getpid())
        print(proc.memory_info().rss / 1024**2)
        sleep(8)
</code>```

Besides the new code works as intended, memory still increases at the same rate as in the original code. I expected that as only the shared_dict was shared, I would get rid of the leak.

I am totally new to multiprocessing, so I have probably miss something. Does the memory still being shared between the 2 processes ?
I work with Linux, so process start is set to fork.

I'm totally open also to other solutions not using multiprocessing, I only need a way to get rid of the leak.

Body:
I have a memory leakage identified in a 3rd party C-library, that I cannot correct.
This leaky stuff needs to be executed forever in a while loop (see code below), leading to consistent memory increase over time.

import psutil
import os

class LeakyClass():

    def __init__():
        self.Dict = {}
        # do stuff with leaky C-library to fill the Dict

if __name__ == '__main__':
    while True:
        my_dict = LeakyClass().Dict
        # do stuff with my_dict
        proc = psutil.Process(os.getpid())
        print(proc.memory_info().rss / 1024**2)
        sleep(8)

To try to avoid the leak, I have moved the problematic leaky part into another Process, thinking this way when the process will end, I'll get rid of the leakage. I have added a manager to get my Dict available in the main process. Below is the new code:

import multiprocessing
import psutil
import os

class LeakyClass():

    def __init__():
        self.Dict = {}
        # do stuff with leaky C-library to fill the Dict

def task(shared_dict):
    shared_dict.clear()
    my_dict = LeakyClass().Dict
    for key in my_dict:
        shared_dict[key] = my_dict[key]

if __name__ == '__main__':
    manager = multiprocessing.Manager()
    shared_dict = manager.dict()

    while True:
        process = multiprocessing.Process(target=task, args=(shared_dict,))
        process.start()
        process.join()
        # do stuff with shared_dict
        proc = psutil.Process(os.getpid())
        print(proc.memory_info().rss / 1024**2)
        sleep(8)

Besides the new code works as intended, memory still increases at the same rate as in the original code. I expected that as only the shared_dict was shared, I would get rid of the leak.

I am totally new to multiprocessing, so I have probably miss something. Does the memory still being shared between the 2 processes ?
I work with Linux, so process start is set to fork.

I'm totally open also to other solutions not using multiprocessing, I only need a way to get rid of the leak.


问:
How to get rid of blank lines generated by Python 3 CSV writer on Linux
I'm trying to write a CSV file with data generated from the analysis of video frames. First I collect the metadata of each video in an array (vid_data), which is then appended to a bigger list of all the videos' metadata (data_list). After that, I need to write two more columns: contractions and time intervals at which they happen.

def writing_to_cvs():

    # open the file in 'writing' mode
    with open("output.csv", 'w', newline='', encoding='utf-8') as csv_file:

        # create a writer object
        writer = csv.writer(csv_file, lineterminator='\n')

        # write out the headers for the columns of the CSV file
        writer.writerow(["Video filename","Duration","FrameRate","NumFrames","Height","Width","Contractions","TimeIntervals"])

        # using a two-dimensional list where
        # every sublist represents a row in the CSV
        #print("the row:", data_list)

        for vid_data in data_list:
            writer.writerow(vid_data)

        for contra in contractions_list:
            for c in contra:
                writer.writerow([''] * 6 + [c])

        for inter in time_intervals:
            #print('time:', inter)
            writer.writerow([''] * 7 + [inter])
```

My issue is that each time writerow is called, it leaves blank rows between that and the last time it was called. The resulting CSV file is this:

Any idea on how to get rid of those blank lines?

I've already tried using the newline='' and the lineterminator='\n' but it didn't change anything. I've read in other similar posts that it could be related to the OS (I'm using Linux), but haven't found specific advice addressing that other than adding newline='' for Windows users.

Also, for info I'm using Python 3.10.

Body:
I'm trying to write a CSV file with data generated from the analysis of video frames. First I collect the metadata of each video in an array (vid_data), which is then appended to a bigger list of all the videos' metadata (data_list). After that, I need to write two more columns: contractions and time intervals at which they happen.

def writing_to_cvs():

    # open the file in 'writing' mode
    with open("output.csv", 'w', newline='', encoding='utf-8') as csv_file:

        # create a writer object
        writer = csv.writer(csv_file, lineterminator='\n')

        # write out the headers for the columns of the CSV file
        writer.writerow(["Video filename","Duration","FrameRate","NumFrames","Height","Width","Contractions","TimeIntervals"])

        # using a two-dimensional list where
        # every sublist represents a row in the CSV
        #print("the row:", data_list)

        for vid_data in data_list:
            writer.writerow(vid_data)

        for contra in contractions_list:
            for c in contra:
                writer.writerow([''] * 6 + [c])

        for inter in time_intervals:
            #print('time:', inter)
            writer.writerow([''] * 7 + [inter])

My issue is that each time writerow is called, it leaves blank rows between that and the last time it was called. The resulting CSV file is this:

Any idea on how to get rid of those blank lines?

I've already tried using the newline='' and the lineterminator='\n' but it didn't change anything. I've read in other similar posts that it could be related to the OS (I'm using Linux), but haven't found specific advice addressing that other than adding newline='' for Windows users.

Also, for info I'm using Python 3.10.


问:
Why would a built-in Wordpress function be undefined in a plugin?
I'm troubleshooting a custom plugin from one of my predecessors.

The plugin is on a Multisite installation and it creates some default posts and pages when a new site is added.

It uses the built-in WP function get_page_by_title() and I just got
PHP Fatal error: Uncaught Error: Call to undefined function get_page_by_title()

The code in question is

```<code>function addPostOverview() {
    $title = 'Project Overview';
    $page = get_page_by_title($title, null, 'post');

    if (!empty($page)) {
        return;
    }

$post = array(
        'post_content' => 'Overview Example. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum mauris lorem, tempor a erat a, vehicula ultricies diam. Suspendisse in leo aliquet, ornare sapien vitae, commodo mi. Nullam ornare, mi et volutpat accumsan, enim tellus aliquam quam, vitae molestie sapien magna quis est. Praesent et magna efficitur, ornare nunc eget, commodo nunc. Donec et erat ac urna pharetra luctus et sed mauris.', // The full text of the post.
        'post_name' => 'project-overview', // The name (slug) for your post
        'post_title' => $title, // The title of your post.
        'post_status' => 'publish', //[ 'draft' | 'publish' | 'pending'| 'future' | 'private' | custom registered status ] // Default 'draft'.
        'post_type' => 'post', // [ 'post' | 'page' | 'link' | 'nav_menu_item' | custom post type ] // Default 'post'.
        'comment_status' => 'closed', // Default is the option 'default_comment_status', or 'closed'.
        'post_category' => array(get_cat_ID('Project Page'))  // Default empty.
    );

    $postID = wp_insert_post($post, $wp_error);
}
addPostOverview();
</code>```

In what circumstances would a built-in WP function be undefined? I'm in WP 6.1.1 (latest) and just updated to PHP 8.1.

Body:
I'm troubleshooting a custom plugin from one of my predecessors.

The plugin is on a Multisite installation and it creates some default posts and pages when a new site is added.

It uses the built-in WP function get_page_by_title() and I just got
PHP Fatal error: Uncaught Error: Call to undefined function get_page_by_title()

The code in question is

function addPostOverview() {
    $title = 'Project Overview';
    $page = get_page_by_title($title, null, 'post');

    if (!empty($page)) {
        return;
    }

$post = array(
        'post_content' => 'Overview Example. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum mauris lorem, tempor a erat a, vehicula ultricies diam. Suspendisse in leo aliquet, ornare sapien vitae, commodo mi. Nullam ornare, mi et volutpat accumsan, enim tellus aliquam quam, vitae molestie sapien magna quis est. Praesent et magna efficitur, ornare nunc eget, commodo nunc. Donec et erat ac urna pharetra luctus et sed mauris.', // The full text of the post.
        'post_name' => 'project-overview', // The name (slug) for your post
        'post_title' => $title, // The title of your post.
        'post_status' => 'publish', //[ 'draft' | 'publish' | 'pending'| 'future' | 'private' | custom registered status ] // Default 'draft'.
        'post_type' => 'post', // [ 'post' | 'page' | 'link' | 'nav_menu_item' | custom post type ] // Default 'post'.
        'comment_status' => 'closed', // Default is the option 'default_comment_status', or 'closed'.
        'post_category' => array(get_cat_ID('Project Page'))  // Default empty.
    );

    $postID = wp_insert_post($post, $wp_error);
}
addPostOverview();

In what circumstances would a built-in WP function be undefined? I'm in WP 6.1.1 (latest) and just updated to PHP 8.1.


问:
Hyphenation Turn Off in Each Text Shapes MS Publisher
I would like to turn of hyphenation (MS Publisher) in every shape containing a text.

I wrote a small code to highlight the text in each shape on each page one after the other:

```<code>Sub TurnOffHyphenation()

Dim pg As Long
Dim sp As Long
Dim shpAll As ShapeRange

pg = ActiveDocument.Pages.Count

For pg = 1 To pg

    sp = ActiveDocument.Pages(pg).Shapes.Count
     ActiveDocument.ActiveView.ActivePage = ActiveDocument.Pages(pg)

  For sp = 1 To sp

    ActiveDocument.Pages(pg).Shapes(sp).Select
     Set shpAll = Application.ActiveDocument.Selection.ShapeRange
        If shpAll.HasTextFrame = msoFalse Then
          'do nothing
        Else
            Selection.ShapeRange.TextFrame.TextRange.Select
       '<Action> => Hyphenation Turn Off
        End If

  Next sp
Next pg

End Sub
</code>```

 is probably a one line which have to be completed.

Manual steps which have to be done in MS Publisher:

Click the Text Box Tools Format tab, and then click Hyphenation

In the Hyphenation dialog box, clear the Automatically hyphenate this story check box

This two steps I would like to transform into a macro code.  :)

Body:
I would like to turn of hyphenation (MS Publisher) in every shape containing a text.

I wrote a small code to highlight the text in each shape on each page one after the other:

Sub TurnOffHyphenation()

Dim pg As Long
Dim sp As Long
Dim shpAll As ShapeRange

pg = ActiveDocument.Pages.Count

For pg = 1 To pg

    sp = ActiveDocument.Pages(pg).Shapes.Count
     ActiveDocument.ActiveView.ActivePage = ActiveDocument.Pages(pg)

  For sp = 1 To sp

    ActiveDocument.Pages(pg).Shapes(sp).Select
     Set shpAll = Application.ActiveDocument.Selection.ShapeRange
        If shpAll.HasTextFrame = msoFalse Then
          'do nothing
        Else
            Selection.ShapeRange.TextFrame.TextRange.Select
       '<Action> => Hyphenation Turn Off
        End If

  Next sp
Next pg

End Sub

 is probably a one line which have to be completed.

Manual steps which have to be done in MS Publisher:

Click the Text Box Tools Format tab, and then click Hyphenation

In the Hyphenation dialog box, clear the Automatically hyphenate this story check box

This two steps I would like to transform into a macro code.  :)


问:
How to remove error __init__() got an unexpected keyword argument 'estimator__n_neighbors'
I have this task:

Implement knn data classification method in combination with PCA feature space dimension reduction technique and then test their effectiveness and select optimal parameters. Implementation should be done in python + jupyter notebook environment. Dedicated numerical libraries can be used. The classifiers are to use the database available at: http://archive.ics.uci.edu/ml/datasets/Letter+Recognition. From the database, 10 letters were selected for system testing: B, C, F, G, I, L, R, U, Z, W. The accuracy of the classifier's performance is to be verified and the result is to be estimated as a percentage for different parameter values: number k, distance function (metric), decision strategy (OvO, OvA/OvR). After determining the optimal values of the classifier's parameters, perform a dimension reduction operation of the feature space using the PCA method and estimate what is the smallest dimension of the feature space that achieves results no worse than the previously determined optimal classifier.
After testing, measure how much faster the classifier performs on the reduced feature space compared to the classifier on the full data.

This is the code I created:

```<code>import pandas as pd
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.multiclass import OneVsOneClassifier, OneVsRestClassifier
from sklearn.metrics import accuracy_score

url = "https://archive.ics.uci.edu/ml/machine-learning-databases/letter-recognition/letter-recognition.data"
data = pd.read_csv(url, header=None)

X = data.iloc[:, 1:]
y = data.iloc[:, 0]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

knn = KNeighborsClassifier()
params = {
    "estimator__n_neighbors": [3, 5, 7, 9],
    "estimator__metric": ["euclidean", "manhattan", "minkowski"],
}

ovo = OneVsOneClassifier(knn)
grid_search = GridSearchCV(ovo, params, cv=5)
grid_search.fit(X_train_scaled, y_train)
print(f"Best (OvO): {grid_search.best_params_}")
y_pred = grid_search.predict(X_test_scaled)
acc = accuracy_score(y_test, y_pred)
print(f"accuracy_score(OvO): {acc:.2f}")

knn = KNeighborsClassifier()
params = {
    "estimator__n_neighbors": [3, 5, 7, 9],
    "estimator__metric": ["euclidean", "manhattan", "minkowski"],
}
ovr = OneVsRestClassifier(knn)
grid_search_ovr = GridSearchCV(ovr, params, cv=5)
grid_search_ovr.fit(X_train_scaled, y_train)
print(f"Best (OvR): {grid_search_ovr.best_params_}")
y_pred = grid_search_ovr.predict(X_test_scaled)
acc = accuracy_score(y_test, y_pred)
print(f"accuracy_score(OvR): {acc:.2f}")

#PCA

best_params_ovo = grid_search_ovo.best_params_
best_params_ovr = grid_search_ovr.best_params_

knn_clf_ovo = KNeighborsClassifier(**best_params_ovo)
knn_clf_ovr = KNeighborsClassifier(**best_params_ovr)

accuracies = np.zeros((2, len(X_train[0])))

for n_components in range(1, len(X_train[0])+1):

    pca = PCA(n_components=n_components)

    X_train_reduced = pca.fit_transform(X_train)
    X_test_reduced = pca.transform(X_test)

    knn_clf_ovo.fit(X_train_reduced, y_train)
    accuracy_ovo = knn_clf_ovo.score(X_test_reduced, y_test)

    accuracies[0, n_components-1] = accuracy_ovo

    knn_clf_ovr.fit(X_train_reduced, y_train)
    accuracy_ovr = knn_clf_ovr.score(X_test_reduced, y_test)

    accuracies[1, n_components-1] = accuracy_ovr

    print(f"Accuracy of KNN classifier for OvO strategy: {accuracy_ovo:.2f}")
    print(f"Accuracy of KNN classifier for OvR strategy: {accuracy_ovr:.2f}")

for i in range(n_components):
  if accuracies[0, i] >= best_accuracy_ovo and accuracies[1, i] >= best_accuracy_ovr:
    min_dim = i+1
    break

print(f"The smallest dimension to achieve results no worse than the optimal classifier:  {min_dim}")

#time:
X_train_full = X_train.values
X_test_full = X_test.values

%timeit knn_clf_ovo.predict(X_test_full)
%timeit knn_clf_ovo.predict(X_test_reduced)
%timeit knn_clf_ovr.predict(X_test_full)
%timeit knn_clf_ovr.predict(X_test_reduced)

</code>```

In line: best_params_ovo = grid_search_ovo.best_params_ i have an error:
init() got an unexpected keyword argument 'estimator__n_neighbors'

In the code, I use the ovo object as an argument to GridSearchCV, and ovo is an instance of OneVsOneClassifier that has an estimator property. This means that in order to set the n_neighbors parameters for KNeighborsClassifier within OneVsOneClassifier, I need to use the estimator__n_neighbors notation. But later in this error requires me to use n_neighbors itself.

Is it possible to correct this in my code somehow? Is it at all well done and consistent with the content of the task, or am I doing it in all the wrong ways?

Body:
I have this task:

Implement knn data classification method in combination with PCA feature space dimension reduction technique and then test their effectiveness and select optimal parameters. Implementation should be done in python + jupyter notebook environment. Dedicated numerical libraries can be used. The classifiers are to use the database available at: http://archive.ics.uci.edu/ml/datasets/Letter+Recognition. From the database, 10 letters were selected for system testing: B, C, F, G, I, L, R, U, Z, W. The accuracy of the classifier's performance is to be verified and the result is to be estimated as a percentage for different parameter values: number k, distance function (metric), decision strategy (OvO, OvA/OvR). After determining the optimal values of the classifier's parameters, perform a dimension reduction operation of the feature space using the PCA method and estimate what is the smallest dimension of the feature space that achieves results no worse than the previously determined optimal classifier.
After testing, measure how much faster the classifier performs on the reduced feature space compared to the classifier on the full data.

This is the code I created:

import pandas as pd
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.multiclass import OneVsOneClassifier, OneVsRestClassifier
from sklearn.metrics import accuracy_score

url = "https://archive.ics.uci.edu/ml/machine-learning-databases/letter-recognition/letter-recognition.data"
data = pd.read_csv(url, header=None)

X = data.iloc[:, 1:]
y = data.iloc[:, 0]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

knn = KNeighborsClassifier()
params = {
    "estimator__n_neighbors": [3, 5, 7, 9],
    "estimator__metric": ["euclidean", "manhattan", "minkowski"],
}

ovo = OneVsOneClassifier(knn)
grid_search = GridSearchCV(ovo, params, cv=5)
grid_search.fit(X_train_scaled, y_train)
print(f"Best (OvO): {grid_search.best_params_}")
y_pred = grid_search.predict(X_test_scaled)
acc = accuracy_score(y_test, y_pred)
print(f"accuracy_score(OvO): {acc:.2f}")

knn = KNeighborsClassifier()
params = {
    "estimator__n_neighbors": [3, 5, 7, 9],
    "estimator__metric": ["euclidean", "manhattan", "minkowski"],
}
ovr = OneVsRestClassifier(knn)
grid_search_ovr = GridSearchCV(ovr, params, cv=5)
grid_search_ovr.fit(X_train_scaled, y_train)
print(f"Best (OvR): {grid_search_ovr.best_params_}")
y_pred = grid_search_ovr.predict(X_test_scaled)
acc = accuracy_score(y_test, y_pred)
print(f"accuracy_score(OvR): {acc:.2f}")

#PCA

best_params_ovo = grid_search_ovo.best_params_
best_params_ovr = grid_search_ovr.best_params_

knn_clf_ovo = KNeighborsClassifier(**best_params_ovo)
knn_clf_ovr = KNeighborsClassifier(**best_params_ovr)

accuracies = np.zeros((2, len(X_train[0])))

for n_components in range(1, len(X_train[0])+1):

    pca = PCA(n_components=n_components)

    X_train_reduced = pca.fit_transform(X_train)
    X_test_reduced = pca.transform(X_test)

    knn_clf_ovo.fit(X_train_reduced, y_train)
    accuracy_ovo = knn_clf_ovo.score(X_test_reduced, y_test)

    accuracies[0, n_components-1] = accuracy_ovo

    knn_clf_ovr.fit(X_train_reduced, y_train)
    accuracy_ovr = knn_clf_ovr.score(X_test_reduced, y_test)

    accuracies[1, n_components-1] = accuracy_ovr

    print(f"Accuracy of KNN classifier for OvO strategy: {accuracy_ovo:.2f}")
    print(f"Accuracy of KNN classifier for OvR strategy: {accuracy_ovr:.2f}")

for i in range(n_components):
  if accuracies[0, i] >= best_accuracy_ovo and accuracies[1, i] >= best_accuracy_ovr:
    min_dim = i+1
    break

print(f"The smallest dimension to achieve results no worse than the optimal classifier:  {min_dim}")

#time:
X_train_full = X_train.values
X_test_full = X_test.values

%timeit knn_clf_ovo.predict(X_test_full)
%timeit knn_clf_ovo.predict(X_test_reduced)
%timeit knn_clf_ovr.predict(X_test_full)
%timeit knn_clf_ovr.predict(X_test_reduced)

In line: best_params_ovo = grid_search_ovo.best_params_ i have an error:
init() got an unexpected keyword argument 'estimator__n_neighbors'

In the code, I use the ovo object as an argument to GridSearchCV, and ovo is an instance of OneVsOneClassifier that has an estimator property. This means that in order to set the n_neighbors parameters for KNeighborsClassifier within OneVsOneClassifier, I need to use the estimator__n_neighbors notation. But later in this error requires me to use n_neighbors itself.

Is it possible to correct this in my code somehow? Is it at all well done and consistent with the content of the task, or am I doing it in all the wrong ways?


问:
"HELP" Command in REPLIT in PYTHON
I don't know why whenever I use replit in terminal of manjaro linux I got stuck on one thing.
Whenever I try help command in replit. yeah it gives me output but it get stuck by giving message END.

And I don't know how to quit it so I just terminate the process or cut the terminal.

So have to know if there is any way I can escape from python rather exiting from Terminal?

I was trying HELP command and was thinking to get output though I got but wasn't able to go back.

Title: "HELP" Command in REPLIT in PYTHON


问:
Animate marker coordinate update
I am using swift to integrate mapbox in an application. I need a mapbox marker to move from point A to point B with animation.
I am adding marker using pointannotation as follows

```<code>     let deviceCoordinate = CLLocationCoordinate2D(latitude: device.latitude, longitude: device.longitude)
     var pointAnnotation = PointAnnotation(id: device.id, coordinate: deviceCoordinate)
     let markerImage = AppImages.otherMarker?.tinted(with: UIColor(hex: device.color ?? "#8E793D"), text: device.displayNumber)
     pointAnnotation.image = .init(image: markerImage!, name: "\(device.displayNumber!)")
     pointAnnotation.iconAnchor = .bottom
     let pointAnnotationManager = mapView.annotations.makePointAnnotationManager(id: "annotationLayer", layerPosition: LayerPosition.at(100))
     pointAnnotationManager.annotations = [pointAnnotation]
</code>```

Then to update coordinate of the marker I am using

```<code>marker.point.coordinates = CLLocationCoordinate2D(latitude: lat, longitude: lng)
</code>```

Here marker is one specific marker and lat and lng are new coordinates for the existing marker.

As far as I know mapbox does not provide animation options and am willing to explore ways to animate the transition as the abrupt changes in the marker position is not nice.

I am thinking of gradually updating the marker to its new position by interpolating positions between start and end but am not aware of the means to achieve that. Any suggestions?

Title: Animate marker coordinate update

Body:
I am using swift to integrate mapbox in an application. I need a mapbox marker to move from point A to point B with animation.
I am adding marker using pointannotation as follows

     let deviceCoordinate = CLLocationCoordinate2D(latitude: device.latitude, longitude: device.longitude)
     var pointAnnotation = PointAnnotation(id: device.id, coordinate: deviceCoordinate)
     let markerImage = AppImages.otherMarker?.tinted(with: UIColor(hex: device.color ?? "#8E793D"), text: device.displayNumber)
     pointAnnotation.image = .init(image: markerImage!, name: "\(device.displayNumber!)")
     pointAnnotation.iconAnchor = .bottom
     let pointAnnotationManager = mapView.annotations.makePointAnnotationManager(id: "annotationLayer", layerPosition: LayerPosition.at(100))
     pointAnnotationManager.annotations = [pointAnnotation]

Then to update coordinate of the marker I am using

marker.point.coordinates = CLLocationCoordinate2D(latitude: lat, longitude: lng)

Here marker is one specific marker and lat and lng are new coordinates for the existing marker.

As far as I know mapbox does not provide animation options and am willing to explore ways to animate the transition as the abrupt changes in the marker position is not nice.

I am thinking of gradually updating the marker to its new position by interpolating positions between start and end but am not aware of the means to achieve that. Any suggestions?


问:
eas build run fastlane error: Provisioning profile doesn't match the entitlements file's value for the com.apple.developer.networking.wifi-info
I'm getting error with  eas build --platform ios

error: Provisioning profile doesn't match the entitlements file's value for the com.apple.developer.networking.wifi-info entitlement.

When I am running expo build:ios  then getting no error.

I've checked the identifier and licenses on Apple Developer and the Access Wifi Information is enabled


问:
Error: RWI 00313 Error: INF When Assigning Reference
I have created a column in business objects that gives the count of information a column in which I used Concatenate to merge two numbers to create a unique number. When I assign reference to this column, so that I can then edit the formula for the NAMEOF the column, I get the following error:  An error occurred while retrieving the document from the storage token. (Error:  RWI 00313) (Error: INF). How can I resolve this so that I can assign a reference and name the column?

Thanks.

Allow me to assign a reference


问:
DMS setting current_timestamp as default value in target when no default set in source database
We're migrating a fairly hefty MariaDB database from an external server to RDS in preparation for a hosting move later this year. The migration task is currently running with ongoing replication. As part of our validation checks, I've written a script to pull random rows from some tables and compare them between our current production database and the imported version in RDS.

The script is showing that some timestamp columns that are default null in the source database have had the default set to current_timestamp in the target database. We have no transformations set on the migration task as we want a 1:1 replacement.

I can't find an explanation in the DMS documentation, nor anything that looks like a likely culprit in the task settings. I also can't find any mention of others having this problem, so I assume something in the task is misconfigured.


问:
Lazy load modal module in angular
I'm working with angular version 11 and I have a module MyModalModule that declares modal components and the components they use.
Since the user won't open them 90% of the time, I implemented lazy loading for this module using the import function of webpack to dynamic import the module. I decided not to use the built in lazy loading of angular since my entry points are non routable (they are opened in a modal clicking a button).

Here are the files I use (not the real code, just same architecture and functions so you get the idea) :

```<code>@NgModule({
    declarations: [
        ModalComponentA,
        ModalComponentB,
        ComponentA,
        ComponentB,
        ComponentC,
        ComponentD,
    ],
    imports: [CommonModule, SharedModule, NgbModule, PipesModule],
    exports: [],
})
export class MyModalModule{
    static getModalComponentA(): typeof ModalComponentA {
        return ModalComponentA;
    }
    static getModalComponentB(): typeof ModalComponentB {
        return ModalComponentB;
    }
}
</code>```

my-modal.module.ts

```<code>@Injectable({
    providedIn: 'root',
})
export class LazyLoaderService{
    modalService = inject(NgbModal);

    async loadModalA(options?: NgbModalOptions): Promise<NgbModalRef> {
        const myModule = await import('../path-to-my-module');
        return this.modalService.open(myModule.MyModalModule.getModalComponentA(), options);
    }

    async loadModalB(options?: NgbModalOptions): Promise<NgbModalRef> {
        const myModule  = await import('../path-to-my-module');
        return this.modalService.open(myModule.MyModalModule.getModalComponentB(), options);
    }
}
</code>```

lazy-loader.service.ts

Everything is working fine with this simple solution.
Otherwise, imagine I have 20 modals, I would have to define 20 functions doing the exact same thing...

So instead of giving the responsability to the service to provide a function for each component that can be  an entry point, I'd like to have one generic function that loads the module and open the component passed in parameter of the function in a new modal.

I tried something that looks like :

```<code> async loadModal(componentName: string, options?: NgbModalOptions): Promise<NgbModalRef> {
        const myModule = await import('../path-to-my-module');
        return this.modalService.open(myModule.MyModalModule[componentName], options);
    }
</code>```

Otherwise, myModule.MyModalModule[componentName] is undefined.
So I guess you cannot get a component like that in angular, and when I checked the myModule.MyModalModule object, I didn't find anything useful.

(PS : sorry for my english, did my best..)

Title: Lazy load modal module in angular

Body:
I'm working with angular version 11 and I have a module MyModalModule that declares modal components and the components they use.
Since the user won't open them 90% of the time, I implemented lazy loading for this module using the import function of webpack to dynamic import the module. I decided not to use the built in lazy loading of angular since my entry points are non routable (they are opened in a modal clicking a button).

Here are the files I use (not the real code, just same architecture and functions so you get the idea) :

@NgModule({
    declarations: [
        ModalComponentA,
        ModalComponentB,
        ComponentA,
        ComponentB,
        ComponentC,
        ComponentD,
    ],
    imports: [CommonModule, SharedModule, NgbModule, PipesModule],
    exports: [],
})
export class MyModalModule{
    static getModalComponentA(): typeof ModalComponentA {
        return ModalComponentA;
    }
    static getModalComponentB(): typeof ModalComponentB {
        return ModalComponentB;
    }
}

my-modal.module.ts

@Injectable({
    providedIn: 'root',
})
export class LazyLoaderService{
    modalService = inject(NgbModal);

    async loadModalA(options?: NgbModalOptions): Promise<NgbModalRef> {
        const myModule = await import('../path-to-my-module');
        return this.modalService.open(myModule.MyModalModule.getModalComponentA(), options);
    }

    async loadModalB(options?: NgbModalOptions): Promise<NgbModalRef> {
        const myModule  = await import('../path-to-my-module');
        return this.modalService.open(myModule.MyModalModule.getModalComponentB(), options);
    }
}

lazy-loader.service.ts

Everything is working fine with this simple solution.
Otherwise, imagine I have 20 modals, I would have to define 20 functions doing the exact same thing...

So instead of giving the responsability to the service to provide a function for each component that can be  an entry point, I'd like to have one generic function that loads the module and open the component passed in parameter of the function in a new modal.

I tried something that looks like :

 async loadModal(componentName: string, options?: NgbModalOptions): Promise<NgbModalRef> {
        const myModule = await import('../path-to-my-module');
        return this.modalService.open(myModule.MyModalModule[componentName], options);
    }

Otherwise, myModule.MyModalModule[componentName] is undefined.
So I guess you cannot get a component like that in angular, and when I checked the myModule.MyModalModule object, I didn't find anything useful.

(PS : sorry for my english, did my best..)


问:
Python, cant use mechanize - No module named 'mechanize'
hope u can help me.

i have the problem that i cant use mechanize in Python. i really dont know why.

My python version is: Python 3.10.9

i just wrote this in a python file:

```<code>import mechanize

browser = mechanize.Browser()
</code>```

and the Error is:

Traceback (most recent call last):
File "C:\Users\Daniel\Desktop\stackoverflow.py", line 1, in
import mechanize
ModuleNotFoundError: No module named 'mechanize'

thanks guys!

before you ask, yes i installed the last version of mechanize on my windows computer like this:

```<code>C:\Users\Daniel>pip3 install mechanize
Requirement already satisfied: mechanize in c:\users\daniel\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (0.4.8)
Requirement already satisfied: html5lib>=0.999999999 in c:\users\daniel\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from mechanize) (1.1)
Requirement already satisfied: webencodings in c:\users\daniel\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from html5lib>=0.999999999->mechanize) (0.5.1)
Requirement already satisfied: six>=1.9 in c:\users\daniel\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from html5lib>=0.999999999->mechanize) (1.16.0)
</code>```

Body:
hope u can help me.

i have the problem that i cant use mechanize in Python. i really dont know why.

My python version is: Python 3.10.9

i just wrote this in a python file:

import mechanize

browser = mechanize.Browser()

and the Error is:

Traceback (most recent call last):
File "C:\Users\Daniel\Desktop\stackoverflow.py", line 1, in
import mechanize
ModuleNotFoundError: No module named 'mechanize'

thanks guys!

before you ask, yes i installed the last version of mechanize on my windows computer like this:

C:\Users\Daniel>pip3 install mechanize
Requirement already satisfied: mechanize in c:\users\daniel\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (0.4.8)
Requirement already satisfied: html5lib>=0.999999999 in c:\users\daniel\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from mechanize) (1.1)
Requirement already satisfied: webencodings in c:\users\daniel\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from html5lib>=0.999999999->mechanize) (0.5.1)
Requirement already satisfied: six>=1.9 in c:\users\daniel\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\python310\site-packages (from html5lib>=0.999999999->mechanize) (1.16.0)


问:
Unity Mars: Error Running unity AR foundation and unity mars in different scenes
I have an existing app with one scene runs ARF for image tracking and plane detection. recently added another scene with unity mars and using it for facetracking. When i switch from scene1(ARF scene) to scene2(MARS scene) it works fine.. However switch from Scene 2 to Scene 1 is breaking. it just shows black screen.

from scene 1 --> scene 2

if(message.key == "SWITCH_MARS") { SceneManager.LoadScene("Mars", LoadSceneMode.Single); }

from scene 2 --> scene 1

if(message.key == "SWITCH_AR"){ SceneManager.LoadScene("UXManagerScene", LoadSceneMode.Single); }

Also, I am seeing this error on xcode

Loading plugin UnityARKit for subsystem ARKit-Input... [Subsystems] UnityARKit successfully registered Provider for ARKit-Input [Subsystems] Loading plugin UnityARKit for subsystem ARKit-Meshing... [Subsystems] Failed to initialize subsystem ARKit-Meshing [error: 1] NotSupportedException: Update requires a configuration.   at UnityEngine.XR.ARKit.ARKitSessionSubsystem+ARKitProvider.Update (UnityEngine.XR.ARSubsystems.XRSessionUpdateParams updateParams) [0x00000] in <00000000000000000000000000000000>:0   at UnityEngine.XR.ARSubsystems.XRSessionSubsystem.Update (UnityEngine.XR.ARSubsystems.XRSessionUpdateParams updateParams) [0x00000] in <00000000000000000000000000000000>:0   at UnityEngine.XR.ARFoundation.ARSession.Update () [0x00000] in <00000000000000000000000000000000>:0

[B]NotSupportedException: Update requires a configuration.[/B] [B]  at UnityEngine.XR.ARKit.ARKitSessionSubsystem+ARKitProvider.Update (UnityEngine.XR.ARSubsystems.XRSessionUpdateParams updateParams) [0x00000] in <00000000000000000000000000000000>:0 [/B] [B]  at UnityEngine.XR.ARSubsystems.XRSessionSubsystem.Update (UnityEngine.XR.ARSubsystems.XRSessionUpdateParams updateParams) [0x00000] in <00000000000000000000000000000000>:0 [/B] [B]  at UnityEngine.XR.ARFoundation.ARSession.Update () [0x00000] in <00000000000000000000000000000000>:0 [/B]


问:
I need to extract tracking number from _wc_shipment_tracking_items field in wordpress woocommerce order
I need to extract tracking_number from _wc_shipment_tracking_items field in wordpress woocommerce order.

I retrieve the data like this:

```<code>return get_post_meta($order->id)['_wc_shipment_tracking_items'][0];
</code>```

and in response I get JSON format list of data:

```<code>[
{"tracking_provider": "australia-post",
"custom_tracking_provider":",
"custom_tracking_link":"",
"tracking_number":"WZGZ10000709",
"tracking_product_code":",
"date_shipped":"1672963200",
"products_list":",
"status_shipped": "1",
"tracking_id":"f98fb8c0fe94b25688d15db12fd73"}
]
</code>```

How do I get just the tracking number WZGZ10000709?

Body:
I need to extract tracking_number from _wc_shipment_tracking_items field in wordpress woocommerce order.

I retrieve the data like this:

return get_post_meta($order->id)['_wc_shipment_tracking_items'][0];

and in response I get JSON format list of data:

[
{"tracking_provider": "australia-post",
"custom_tracking_provider":",
"custom_tracking_link":"",
"tracking_number":"WZGZ10000709",
"tracking_product_code":",
"date_shipped":"1672963200",
"products_list":",
"status_shipped": "1",
"tracking_id":"f98fb8c0fe94b25688d15db12fd73"}
]

How do I get just the tracking number WZGZ10000709?


问:
ServiceLoader not loading classes in Bukkit plugin
So I started working on a new Bukkit plugin and did some research on possible ways of automating listener registration. I came across the ServiceLoader class and read its JavaDocs. Basically I'm trying to load all the classes that implement the Listener interface, looping through them and registering them with this method:

private static void registerListeners() {
    ServiceLoader<Listener> loader = ServiceLoader.load(Listener.class);
    for (Listener listener : loader) {
        Bukkit.getPluginManager().registerEvents(listener, get());
    }
}
```
<p>The <code>get()</code> method here returns the <code>instance</code> variable (<code>private static Posc instance;</code> "Posc" being the name of the main class and the plugin) which is declared in the <code>onEnable()</code> method.
I would then call this method in the <code>onEnable()</code> method like so:</p>
```@Override
public void onEnable() {
    instance = this;
    registerListeners();
}
```
<p>As stated in the documentation, I created the <code>META-INF\services</code> directory in the <code>resources</code> directory and added a text file called <code>org.bukkit.event.Listener</code>, in this text file I added the full names of my listener classes, one per line, like so:</p>
```me.lord.posc.listeners.PlayerJoinListener
me.lord.posc.listeners.PlayerQuitListener
```
<p>My IDE (JetBrain IntelliJ IDEA Community Edition 2022.3.1) does not give any errors or warnings in any of my classes or the <code>org.bukkit.event.Listener</code> file. No errors or warnings were given in the console when I started the server with the plugin. In game I ran the <code>/plugins</code> Bukkit command which showed my plugin in green, which means it has loaded successfully, which means the <code>onEnable()</code> method was called. This was also confirmed when I added this line into the <code>registerListeners()</code> method:</p>
<pre class="lang-java prettyprint-override"><code>get().getLogger().info("test");
</code>```

"test" was written into the console by my plugin.

The PlayerJoinListener class looks like this:

package me.lord.posc.listeners;

import me.lord.posc.Posc;
import me.lord.posc.utilities.TextUtil;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

public class PlayerJoinListener implements Listener {
    // TODO: Replace Bukkit.getOfflinePlayers().length with a player counting system to increase performance
    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        event.joinMessage(TextUtil.c("&7[&a+&7] &f" + event.getPlayer().getName() + (event.getPlayer().hasPlayedBefore() ? "" : " &8| &6" + TextUtil.ordinal(Bukkit.getOfflinePlayers().length) + " join")));
        Posc.get().getLogger().info("test");
    }
}
```
<p>And the <code>PlayerQuitListener</code> class looks like this:</p>
<pre class="lang-java prettyprint-override"><code>package me.lord.posc.listeners;

import me.lord.posc.Posc;
import me.lord.posc.utilities.TextUtil;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;

public class PlayerQuitListener implements Listener {
    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        event.quitMessage(TextUtil.c("&7[&c-&7] &f" + event.getPlayer().getName()));
        Posc.get().getLogger().info("test");
    }
}
</code>```

These classes, if they worked properly, would change the join and leave messages, and print "test" whenever a player joins or leaves. This is however not the case as none of these things happen when anyone leaves or joins the server which indicates that these listeners have not been registered properly or at all.

I've tried many things to get it work but with no success. I tried...

changing the location of the META-INF directory to src, src\main and src\main\java but none of these did anything.

making a new interface that extended org.bukkit.event.Listener, making the listener classes implement that and switching Listener with my interface in the META-INF\services directory and in the registerListeners() method

using different methods in place of the for, like streams, Iterator and foreach()

getClass().newInstance()

I tried loader.stream().findFirst().isEmpty() to see if it actually loaded the classes, and the method returned true which means the loader doesn't for some reason load the classes.

Body:
So I started working on a new Bukkit plugin and did some research on possible ways of automating listener registration. I came across the ServiceLoader class and read its JavaDocs. Basically I'm trying to load all the classes that implement the Listener interface, looping through them and registering them with this method:

private static void registerListeners() {
    ServiceLoader<Listener> loader = ServiceLoader.load(Listener.class);
    for (Listener listener : loader) {
        Bukkit.getPluginManager().registerEvents(listener, get());
    }
}

The get() method here returns the instance variable (private static Posc instance; "Posc" being the name of the main class and the plugin) which is declared in the onEnable() method.
I would then call this method in the onEnable() method like so:

@Override
public void onEnable() {
    instance = this;
    registerListeners();
}

As stated in the documentation, I created the META-INF\services directory in the resources directory and added a text file called org.bukkit.event.Listener, in this text file I added the full names of my listener classes, one per line, like so:

me.lord.posc.listeners.PlayerJoinListener
me.lord.posc.listeners.PlayerQuitListener

My IDE (JetBrain IntelliJ IDEA Community Edition 2022.3.1) does not give any errors or warnings in any of my classes or the org.bukkit.event.Listener file. No errors or warnings were given in the console when I started the server with the plugin. In game I ran the /plugins Bukkit command which showed my plugin in green, which means it has loaded successfully, which means the onEnable() method was called. This was also confirmed when I added this line into the registerListeners() method:

get().getLogger().info("test");

"test" was written into the console by my plugin.

The PlayerJoinListener class looks like this:

package me.lord.posc.listeners;

import me.lord.posc.Posc;
import me.lord.posc.utilities.TextUtil;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

public class PlayerJoinListener implements Listener {
    // TODO: Replace Bukkit.getOfflinePlayers().length with a player counting system to increase performance
    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        event.joinMessage(TextUtil.c("&7[&a+&7] &f" + event.getPlayer().getName() + (event.getPlayer().hasPlayedBefore() ? "" : " &8| &6" + TextUtil.ordinal(Bukkit.getOfflinePlayers().length) + " join")));
        Posc.get().getLogger().info("test");
    }
}

And the PlayerQuitListener class looks like this:

package me.lord.posc.listeners;

import me.lord.posc.Posc;
import me.lord.posc.utilities.TextUtil;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;

public class PlayerQuitListener implements Listener {
    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        event.quitMessage(TextUtil.c("&7[&c-&7] &f" + event.getPlayer().getName()));
        Posc.get().getLogger().info("test");
    }
}

These classes, if they worked properly, would change the join and leave messages, and print "test" whenever a player joins or leaves. This is however not the case as none of these things happen when anyone leaves or joins the server which indicates that these listeners have not been registered properly or at all.

I've tried many things to get it work but with no success. I tried...

changing the location of the META-INF directory to src, src\main and src\main\java but none of these did anything.

making a new interface that extended org.bukkit.event.Listener, making the listener classes implement that and switching Listener with my interface in the META-INF\services directory and in the registerListeners() method

using different methods in place of the for, like streams, Iterator and foreach()

getClass().newInstance()

I tried loader.stream().findFirst().isEmpty() to see if it actually loaded the classes, and the method returned true which means the loader doesn't for some reason load the classes.


问:
Not able to fetch title inside chrome.tabs.query() method
I am developing a chrome extension which lets the user input a title and saves the url of the current active window in a link (anchor tag) with the title as the text of the link. But somehow I am not able to fetch the title input by the user.

```<code>//utility function which saves the element
/*this function comes under a react component which receives props*/
function saveUtil(e) {
    const hero = e.currentTarget.parentElement.parentElement; //selects the hero section (where input tag resides)
    const prblmTitleInput = hero.querySelector("#prblm-title-input");

    //get link to current tab, create new item object and call handleSave() function
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      const tabURL = tabs[0].url;
      const newItem = {
        id: Math.random(),
        title: prblmTitleInput.value,
        link: tabURL,
      };
      props.handleSave(newItem); //calls another function which updates localStorage and does other stuff
    });
    prblmTitleInput.value = ""; //set the value of input tag again to empty string
  }
</code>```

The anchor tag which is generated consists of no title at all. I am stuck with this issue. If I do not use the chrome.tabs.query() method and set newItem.link = "some dummy link", then the anchor tag is generated perfectly well with the desired title. What am I doing wrong? (Note that all other functions are working perfectly well)

Body:
I am developing a chrome extension which lets the user input a title and saves the url of the current active window in a link (anchor tag) with the title as the text of the link. But somehow I am not able to fetch the title input by the user.

//utility function which saves the element
/*this function comes under a react component which receives props*/
function saveUtil(e) {
    const hero = e.currentTarget.parentElement.parentElement; //selects the hero section (where input tag resides)
    const prblmTitleInput = hero.querySelector("#prblm-title-input");

    //get link to current tab, create new item object and call handleSave() function
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      const tabURL = tabs[0].url;
      const newItem = {
        id: Math.random(),
        title: prblmTitleInput.value,
        link: tabURL,
      };
      props.handleSave(newItem); //calls another function which updates localStorage and does other stuff
    });
    prblmTitleInput.value = ""; //set the value of input tag again to empty string
  }

The anchor tag which is generated consists of no title at all. I am stuck with this issue. If I do not use the chrome.tabs.query() method and set newItem.link = "some dummy link", then the anchor tag is generated perfectly well with the desired title. What am I doing wrong? (Note that all other functions are working perfectly well)


问:
How do you make a cell span multiple columns in mui DataGrid?
I am fairly new to the MUI DataGrid. I am using datagrid premium.

Using rowGrouping I would like the cell that represents the grouped row to span multiple columns.

I've tried "colSpan", but it appears to have no effect.

```<code>  const _columns = [
    {
      field: "fileName",
      headerName: "File Name",
      colSpan:3,
    },
  ];
</code>```

Body:
I am fairly new to the MUI DataGrid. I am using datagrid premium.

Using rowGrouping I would like the cell that represents the grouped row to span multiple columns.

I've tried "colSpan", but it appears to have no effect.

  const _columns = [
    {
      field: "fileName",
      headerName: "File Name",
      colSpan:3,
    },
  ];


问:
npm config rebuild-bundle set to false producing unexpected behavior
As defined in the npm package.json docs, in npm 8 and above, I can set bundleDependencies to the boolean value true, which will bundle all of my dependencies. However, every time I install a new package, npm automatically enumerates a list of bundleDependencies, replacing my boolean value. I went searching for a configuration setting to prevent this behavior on installation of a new package, and I found rebuild-bundle. Based on the description in the documentation, I would expect that if this setting were set to false, an npm installation would not modified bundleDependencies in my package. However, I set the the rebuild-bundle configuration value to false in .npmrc, and upon package installation, bundleDependencies is still overridden by npm.

Am I understanding rebuild-bundle correctly?

I may not have configured my npmrc properly, but I configured this option on the global configuration:
npm config --global set rebuild-bundle=false
and added a .npmrc file in my repository and set the same setting.


问:
How to transform (scale, rotate) contents of a TexturePaint in java without transforming its root shape and then use it in Batik
There is a simple modified version of TexturePaint that support internal transforms. This one works well, affine transforms inside contents, without altering graphics objects, only internal contents. It is being used in multi path fills.
But in order use it in Batik there must be a an extension handler that is able to reform this, I do not have the knowledge to do so, and I am looking for an alternative to just use a vanilla texturePatnt and transforms that can be recognized by Batik svg generator.

Is there an alternative way to use affine transform (scale, rotate) in texturePaint contents without using the transform to the graphics2D object itself?  I mean just transform the internal fill (image, pattern etc), without applying the transform to its root shape.

references:
Apply AffineTransform to TexturePaint

```<code>/*
 * @(#)TransformedTexturePaint.java
 *
 * $Date: 2011-05-02 16:01:45 -0500 (Mon, 02 May 2011) $
 *
 * Copyright (c) 2011 by Jeremy Wood.
 * All rights reserved.
 *
 * The copyright of this software is owned by Jeremy Wood.
 * You may not use, copy or modify this software, except in
 * accordance with the license agreement you entered into with
 * Jeremy Wood. For details see accompanying license terms.
 *
 * This software is probably, but not necessarily, discussed here:
 * http://javagraphics.java.net/
 *
 * That site should also contain the most recent official version
 * of this software.  (See the SVN repository for more details.)
 */
package com.bric.halftone;

import java.awt.Paint;
import java.awt.PaintContext;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.TexturePaint;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;

/** This effectively extends <code>TexturePaint</code> to support
 * arbitrary <code>AffineTransforms</code> inside this paint object.
 * <P>This does not technically extend the <code>TexturePaint</code>
 * class, although it does relay most calls to an internal
 * <code>TexturePaint</code>.  This is because some graphics pipelines
 * (notably Java 1.4 on Mac) will fail to work the paint context
 * correctly if this class officially extends <code>TexturePaint</code>.
 *
 */
public class TransformedTexturePaint implements Paint {
    TexturePaint texturePaint;
    AffineTransform transform;

    public TransformedTexturePaint(BufferedImage txtr, Rectangle2D anchor,AffineTransform transform) {
        texturePaint = new TexturePaint(txtr, anchor);
        if(transform==null) transform = new AffineTransform();

        this.transform = new AffineTransform(transform);
    }

    public AffineTransform getTransform() {
        return transform;
    }

    public PaintContext createContext(ColorModel cm, Rectangle deviceBounds,
            Rectangle2D userBounds, AffineTransform xform, RenderingHints hints) {
        AffineTransform newTransform = new AffineTransform(xform);
        newTransform.concatenate(transform);
        //this is necessary on Java 1.4 toa void a NullPointerException
        //from: java.awt.TexturePaintContext.getContext(TexturePaintContext.java:57)
        if(hints==null)
            hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_DEFAULT);
        return texturePaint.createContext(cm, deviceBounds, userBounds, newTransform, hints);
    }

    public Rectangle2D getAnchorRect() {
        return texturePaint.getAnchorRect();
    }

    public BufferedImage getImage() {
        return texturePaint.getImage();
    }

    public int getTransparency() {
        return texturePaint.getTransparency();
    }
}
</code>```

Body:
There is a simple modified version of TexturePaint that support internal transforms. This one works well, affine transforms inside contents, without altering graphics objects, only internal contents. It is being used in multi path fills.
But in order use it in Batik there must be a an extension handler that is able to reform this, I do not have the knowledge to do so, and I am looking for an alternative to just use a vanilla texturePatnt and transforms that can be recognized by Batik svg generator.

Is there an alternative way to use affine transform (scale, rotate) in texturePaint contents without using the transform to the graphics2D object itself?  I mean just transform the internal fill (image, pattern etc), without applying the transform to its root shape.

references:
Apply AffineTransform to TexturePaint

/*
 * @(#)TransformedTexturePaint.java
 *
 * $Date: 2011-05-02 16:01:45 -0500 (Mon, 02 May 2011) $
 *
 * Copyright (c) 2011 by Jeremy Wood.
 * All rights reserved.
 *
 * The copyright of this software is owned by Jeremy Wood.
 * You may not use, copy or modify this software, except in
 * accordance with the license agreement you entered into with
 * Jeremy Wood. For details see accompanying license terms.
 *
 * This software is probably, but not necessarily, discussed here:
 * http://javagraphics.java.net/
 *
 * That site should also contain the most recent official version
 * of this software.  (See the SVN repository for more details.)
 */
package com.bric.halftone;

import java.awt.Paint;
import java.awt.PaintContext;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.TexturePaint;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;

/** This effectively extends TexturePaint to support
 * arbitrary AffineTransforms inside this paint object.
 *
This does not technically extend the TexturePaint
 * class, although it does relay most calls to an internal
 * TexturePaint.  This is because some graphics pipelines
 * (notably Java 1.4 on Mac) will fail to work the paint context
 * correctly if this class officially extends TexturePaint.
 *
 */
public class TransformedTexturePaint implements Paint {
    TexturePaint texturePaint;
    AffineTransform transform;

    public TransformedTexturePaint(BufferedImage txtr, Rectangle2D anchor,AffineTransform transform) {
        texturePaint = new TexturePaint(txtr, anchor);
        if(transform==null) transform = new AffineTransform();

        this.transform = new AffineTransform(transform);
    }

    public AffineTransform getTransform() {
        return transform;
    }

    public PaintContext createContext(ColorModel cm, Rectangle deviceBounds,
            Rectangle2D userBounds, AffineTransform xform, RenderingHints hints) {
        AffineTransform newTransform = new AffineTransform(xform);
        newTransform.concatenate(transform);
        //this is necessary on Java 1.4 toa void a NullPointerException
        //from: java.awt.TexturePaintContext.getContext(TexturePaintContext.java:57)
        if(hints==null)
            hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_DEFAULT);
        return texturePaint.createContext(cm, deviceBounds, userBounds, newTransform, hints);
    }

    public Rectangle2D getAnchorRect() {
        return texturePaint.getAnchorRect();
    }

    public BufferedImage getImage() {
        return texturePaint.getImage();
    }

    public int getTransparency() {
        return texturePaint.getTransparency();
    }
}


问:
Python matplotlib graphics crash due to missing radeonsi and swrast plugins
After installing Linux on my personal computer to work from home, I realized compiling my script that my hardware configuration makes the matplotlib graphics crash, and therefore unable to print any figure. I have an AMD Radeon RX 6500 XT graphic card and Ubuntu 22.04.1 installed. I get the following error when I compile and try to output some graphics :

```<code>libGL error: MESA-LOADER: failed to open radeonsi: /usr/lib/dri/radeonsi_dri.so: Ne peut ouvrir le fichier d'objet partagé: Aucun fichier ou dossier de ce type (search paths /usr/lib/x86_64-linux-gnu/dri:\$${ORIGIN}/dri:/usr/lib/dri, suffix _dri)
libGL error: failed to load driver: radeonsi
libGL error: MESA-LOADER: failed to open radeonsi: /usr/lib/dri/radeonsi_dri.so: Ne peut ouvrir le fichier d'objet partagé: Aucun fichier ou dossier de ce type (search paths /usr/lib/x86_64-linux-gnu/dri:\$${ORIGIN}/dri:/usr/lib/dri, suffix _dri)
libGL error: failed to load driver: radeonsi
libGL error: MESA-LOADER: failed to open swrast: /usr/lib/dri/swrast_dri.so: Ne peut ouvrir le fichier d'objet partagé: Aucun fichier ou dossier de ce type (search paths /usr/lib/x86_64-linux-gnu/dri:\$${ORIGIN}/dri:/usr/lib/dri, suffix _dri)
libGL error: failed to load driver: swrast
</code>```

After some research on the internet, I didn't manage to find out how to get those working.

Body:
After installing Linux on my personal computer to work from home, I realized compiling my script that my hardware configuration makes the matplotlib graphics crash, and therefore unable to print any figure. I have an AMD Radeon RX 6500 XT graphic card and Ubuntu 22.04.1 installed. I get the following error when I compile and try to output some graphics :

libGL error: MESA-LOADER: failed to open radeonsi: /usr/lib/dri/radeonsi_dri.so: Ne peut ouvrir le fichier d'objet partagé: Aucun fichier ou dossier de ce type (search paths /usr/lib/x86_64-linux-gnu/dri:\$${ORIGIN}/dri:/usr/lib/dri, suffix _dri)
libGL error: failed to load driver: radeonsi
libGL error: MESA-LOADER: failed to open radeonsi: /usr/lib/dri/radeonsi_dri.so: Ne peut ouvrir le fichier d'objet partagé: Aucun fichier ou dossier de ce type (search paths /usr/lib/x86_64-linux-gnu/dri:\$${ORIGIN}/dri:/usr/lib/dri, suffix _dri)
libGL error: failed to load driver: radeonsi
libGL error: MESA-LOADER: failed to open swrast: /usr/lib/dri/swrast_dri.so: Ne peut ouvrir le fichier d'objet partagé: Aucun fichier ou dossier de ce type (search paths /usr/lib/x86_64-linux-gnu/dri:\$${ORIGIN}/dri:/usr/lib/dri, suffix _dri)
libGL error: failed to load driver: swrast

After some research on the internet, I didn't manage to find out how to get those working.


问:
Get Heroku SIGTERM signal in pycord Discord bot
My Discord bot is hosted on Heroku. I'm trying to get the "SIGTERM" signal that heroku sends before restarting the dyno in my Discord bot so i can save some stuff to my database before the dyno gets terminated after 30seconds. How would i do that?</p>


问:
It never working watchPosition function on Android
Only getCurrentPosition function works on Android devices but its not working watchPosition function. I run the getCurrentPosition function in setInterval when I want to track location. It just gives me that fixed location and i can't do instant location tracking. Although I tried many methods, I could not get it to work. I want to follow the vehicle instantly. Thanks in advance for your help. With michalchudziak/react-native-geolocation</p>
```<code>const interval = setInterval(async () => {Geolocation.getCurrentPosition(info => {setCurrentLatitude(info.coords.latitude);
</code>```
```<code>setCurrentLongitude(info.coords.longitude);
</code>```
```<code>try {
  const watchID = Geolocation.watchPosition(
    position => {
      console.warn(JSON.stringify(position));
    });
  setSubscriptionId(watchID);
} catch (error) {
  console.error('WatchPosition Error', JSON.stringify(error));
}
try {
const watchID = Geolocation.watchPosition(
  position => {
  console.warn(JSON.stringify(position));
 });
 setSubscriptionId(watchID);
 } catch (error) {
console.error('WatchPosition Error', JSON.stringify(error));
}
};
</code>```
```<code></code>```

Body:
Only getCurrentPosition function works on Android devices but its not working watchPosition function. I run the getCurrentPosition function in setInterval when I want to track location. It just gives me that fixed location and i can't do instant location tracking. Although I tried many methods, I could not get it to work. I want to follow the vehicle instantly. Thanks in advance for your help. With michalchudziak/react-native-geolocation

const interval = setInterval(async () => {Geolocation.getCurrentPosition(info => {setCurrentLatitude(info.coords.latitude);

setCurrentLongitude(info.coords.longitude);

try {
  const watchID = Geolocation.watchPosition(
    position => {
      console.warn(JSON.stringify(position));
    });
  setSubscriptionId(watchID);
} catch (error) {
  console.error('WatchPosition Error', JSON.stringify(error));
}
try {
const watchID = Geolocation.watchPosition(
  position => {
  console.warn(JSON.stringify(position));
 });
 setSubscriptionId(watchID);
 } catch (error) {
console.error('WatchPosition Error', JSON.stringify(error));
}
};


问:
how to register new DarkRPVar?
i'm beginner developer.

i'm trying to develop my own gmod server ( darkrp )

i just connected my server with mysql, but i don't know how to get data from mysql to my server.

local qs2 = [[ INSERT IGNORE INTO darkrp_ruby` (steamid, ruby, rpname)
VALUES ('%s', '%s', '%s')
]]

```<code>qs2 = string.format(qs2, ply:SteamID(), 0, ply:Name())
local q2 = databaseObject:query(qs2)

q2:start()
</code>```

`
anyone help me

connect my server with mysql

Title: how to register new DarkRPVar?

Body:
i'm beginner developer.

i'm trying to develop my own gmod server ( darkrp )

i just connected my server with mysql, but i don't know how to get data from mysql to my server.

local qs2 = [[ INSERT IGNORE INTO darkrp_ruby` (steamid, ruby, rpname)
VALUES ('%s', '%s', '%s')
]]

qs2 = string.format(qs2, ply:SteamID(), 0, ply:Name())
local q2 = databaseObject:query(qs2)

q2:start()

`
anyone help me

connect my server with mysql


问:
gt table conditional styling also subtotals
I'm trying to generate a table with the gt package in R. So far so good... But I would like also that my conditional styling also applies to the summary (subtotal per group).
Is there any way to make it with the gt package.

Edit:

```<code>data <- structure(list(Type = c("A", "A"), Region = c("Bbbb", "Cccc"),
    `Ytd Supply` = c(11867.67, 1557.87), `Ytd Budget` = c(11364.25,
    1352.97), `Ytd Dif` = c(-503.42, -204.9), `Ytg Supply` = c(8432.97,
    10313.95), `Ytg Budget` = c(8945.33, 10777.04), `Ytg Dif` = c(-512.360000000001,
    -463.089999999998)), class = c("grouped_df", "tbl_df", "tbl",
"data.frame"), row.names = c(NA, -2L), groups = structure(list(
    Type = "A", .rows = structure(list(1:2), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -1L), .drop = TRUE))

gt(data) %>%
  tab_header(
  title = "my tytle") %>%
tab_spanner(
  label = "YTD",
  columns = contains("YTD")) %>%
tab_spanner(
  label = "YTG",
  columns = contains("YTG")) %>%
summary_rows(
  groups = TRUE,
  columns = where(is.numeric),
    fns = list(
       Total = ~sum(., na.rm = TRUE))) %>%
 tab_style(
    style = list(
    cell_fill(color = "#F08080")),
    locations = cells_body(
      columns = `Ytd Dif`,
      rows =  `Ytd Dif` < 0))
</code>```

Thanks

Body:
I'm trying to generate a table with the gt package in R. So far so good... But I would like also that my conditional styling also applies to the summary (subtotal per group).
Is there any way to make it with the gt package.

Edit:

data <- structure(list(Type = c("A", "A"), Region = c("Bbbb", "Cccc"),
    `Ytd Supply` = c(11867.67, 1557.87), `Ytd Budget` = c(11364.25,
    1352.97), `Ytd Dif` = c(-503.42, -204.9), `Ytg Supply` = c(8432.97,
    10313.95), `Ytg Budget` = c(8945.33, 10777.04), `Ytg Dif` = c(-512.360000000001,
    -463.089999999998)), class = c("grouped_df", "tbl_df", "tbl",
"data.frame"), row.names = c(NA, -2L), groups = structure(list(
    Type = "A", .rows = structure(list(1:2), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -1L), .drop = TRUE))

gt(data) %>%
  tab_header(
  title = "my tytle") %>%
tab_spanner(
  label = "YTD",
  columns = contains("YTD")) %>%
tab_spanner(
  label = "YTG",
  columns = contains("YTG")) %>%
summary_rows(
  groups = TRUE,
  columns = where(is.numeric),
    fns = list(
       Total = ~sum(., na.rm = TRUE))) %>%
 tab_style(
    style = list(
    cell_fill(color = "#F08080")),
    locations = cells_body(
      columns = `Ytd Dif`,
      rows =  `Ytd Dif` < 0))

Thanks


问:
How do I make a property readonly in Monaco Editor JSON language?
Is there a way to make a property readonly in Monaco Editor JSON language?  For example, make "p1" property in the Monaco Editor playground (https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-configure-json-defaults) readonly, so that it cannot be modified.

I tried adding "readonly: true" to the property itself (in https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-configure-json-defaults), and I also tried adding "readonly": ["p1"] as a sibling to the properties.

I have downloaded and experimenting with the Monaco Editor JSON language.  I had a similar need for making a property "required".  I added "required": ["a-property-name"] as sibling to the properties in the schema and that worked fine.  Like this:

```<code>                "schema": {
                    "type": 'object',
                    "properties": {
                        "px": {"type": "string"},
                    },
                    "required": ["px"]
                 }
</code>```

I figured that surely there must be a "readonly" allowed as sibling to "properties", but not so.

Am I missing something?

Body:
Is there a way to make a property readonly in Monaco Editor JSON language?  For example, make "p1" property in the Monaco Editor playground (https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-configure-json-defaults) readonly, so that it cannot be modified.

I tried adding "readonly: true" to the property itself (in https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-configure-json-defaults), and I also tried adding "readonly": ["p1"] as a sibling to the properties.

I have downloaded and experimenting with the Monaco Editor JSON language.  I had a similar need for making a property "required".  I added "required": ["a-property-name"] as sibling to the properties in the schema and that worked fine.  Like this:

                "schema": {
                    "type": 'object',
                    "properties": {
                        "px": {"type": "string"},
                    },
                    "required": ["px"]
                 }

I figured that surely there must be a "readonly" allowed as sibling to "properties", but not so.

Am I missing something?


问:
Why the Script component inside the Head component of a Nextjs application blocks the dynamic insertion of css rules by the sweetalert library?
Below snippet is taken from _app.tsx file. I know that having Script component inside the Head component is wrong but this buggy code is blocking the sweetalert library (which I am using in another page to render pop up) from dynamically inserting the CSS rules.

import Head from "next/head";
import Script from "next/script";
import type { AppProps } from "next/app";

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>


问:
Using subquery in insert statement(Oracle Forms Builder)
I'm new to database and form builder .

I'm getting:

Error 103 at line 10, column 2

Encountered the symbol "SELECT"...

Whats the correct syntax for that please?

```<code>INSERT INTO vehicle (
                     vehicleid, reg_no, year, fuel,
                     engine_capacity, transmission, seat_capacity, rice_per_day,
                     modelid, policy_id, type_name, color
                    )
VALUES (:vehicle_block.id,
        :vehicle_block.reg_no,
        :vehicle_block.year,
        :vehicle_block.fuel,
        :vehicle_block.cc,
        :vehicle_block.transm,
        :vehicle_block.seat,
        :vehicle_block.price_p_day,
        (SELECT modelid
           FROM model m
          WHERE m.make = :vehicle_block.make
            AND m.mode_name = :vehicle_block.model),
        :vehicle_block.policy,
        :vehicle_block.type,
        :vehicle_block.color);
COMMIT;
</code>```

Body:
I'm new to database and form builder .

I'm getting:

Error 103 at line 10, column 2

Encountered the symbol "SELECT"...

Whats the correct syntax for that please?

INSERT INTO vehicle (
                     vehicleid, reg_no, year, fuel,
                     engine_capacity, transmission, seat_capacity, rice_per_day,
                     modelid, policy_id, type_name, color
                    )
VALUES (:vehicle_block.id,
        :vehicle_block.reg_no,
        :vehicle_block.year,
        :vehicle_block.fuel,
        :vehicle_block.cc,
        :vehicle_block.transm,
        :vehicle_block.seat,
        :vehicle_block.price_p_day,
        (SELECT modelid
           FROM model m
          WHERE m.make = :vehicle_block.make
            AND m.mode_name = :vehicle_block.model),
        :vehicle_block.policy,
        :vehicle_block.type,
        :vehicle_block.color);
COMMIT;


问:
How to change initial Talkback focus when code Android View in Jetpack Compose
Basically, I am looking for a equivalent in Jetpack Compose of the sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED) used in xml.

Currently, my page looks in this structure:

```<code>Surface {
   TopToolbarBar() {
     Row() {
       NavigationIcon()
       Title()
       ....
     }
   }
   Card1{
     Row1()
     Column() {
       RowA()
       RowB()
       Button()
     }
   }
   Card2{
     ...
   }
}
</code>```

I would like to place the accessibility focus on the Button() instead of NavigationIcon() when this page is open. Not sure if there is any workaround to achieve this? I don't think there is an official way to do so.

I know there is a requestFocus() method together with a FocusManager concept. However, I don't think they are useful when it comes to the accessibility focus

I tried to set a focusRequester and call requestFocus() inside a LaunchedEffect() block. But it won't work. The inital Talkback focus will stay at the navigation icon, which is the left and top most item of my Compose page.

Any hints? I also found there is a SemanticsPropertyReceiver.requestFocus but there is barely a sample that I can use to understand how it works.

Body:
Basically, I am looking for a equivalent in Jetpack Compose of the sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED) used in xml.

Currently, my page looks in this structure:

Surface {
   TopToolbarBar() {
     Row() {
       NavigationIcon()
       Title()
       ....
     }
   }
   Card1{
     Row1()
     Column() {
       RowA()
       RowB()
       Button()
     }
   }
   Card2{
     ...
   }
}

I would like to place the accessibility focus on the Button() instead of NavigationIcon() when this page is open. Not sure if there is any workaround to achieve this? I don't think there is an official way to do so.

I know there is a requestFocus() method together with a FocusManager concept. However, I don't think they are useful when it comes to the accessibility focus

I tried to set a focusRequester and call requestFocus() inside a LaunchedEffect() block. But it won't work. The inital Talkback focus will stay at the navigation icon, which is the left and top most item of my Compose page.

Any hints? I also found there is a SemanticsPropertyReceiver.requestFocus but there is barely a sample that I can use to understand how it works.