问:
Knitting a large plot_ly file in HTML
I am working with a large reddit text dataset utilizing about 5 million comments to create frequency tables and sentiment analysis. The number of subreddits that I selected was 33, which is cluttery to render in a single facet wrapped ggplot, so I opted for an interactive table with a drop-down menu to modify the values per subreddit selected. However, when I try to knit the file into HTML, the process takes about an hour and a half (which I expected, since the plotly file is 154 MB), and then fails with this error.

```<code>"C:/Program Files/RStudio/bin/quarto/bin/tools/pandoc" +RTS -K512m -RTS FinalProjectHTML.knit.md --to html4 --from markdown+autolink_bare_uris+tex_math_single_backslash --output FinalProjectHTML.html --lua-filter "C:\Users\miche\AppData\Local\R\win-library\4.2\rmarkdown\rmarkdown\lua\pagebreak.lua" --lua-filter "C:\Users\miche\AppData\Local\R\win-library\4.2\rmarkdown\rmarkdown\lua\latex-div.lua" --self-contained --variable bs3=TRUE --section-divs --template "C:\Users\miche\AppData\Local\R\win-library\4.2\rmarkdown\rmd\h\default.html" --no-highlight --variable highlightjs=1 --variable theme=bootstrap --mathjax --variable "mathjax-url=https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" --include-in-header "C:\Users\miche\AppData\Local\Temp\RtmpshXgZe\rmarkdown-str63c86fd53d4b.html"

pandoc.exe: getMBlocks: VirtualAlloc MEM_COMMIT failed: The paging file is too small for this operation to complete.
Error: pandoc document conversion failed with error 251
Execution halted
</code>```

Looking around for solutions, it seems that my problem is a matter of overloading my RAM and running out of memory in the process. So, I was wondering if there was a way I could solve this without turning my laptop into a jet engine.

To provide some context, the plotly table code is:

```<code>FrequencySubreddit <- tidysub_filter %>%
  count(subreddit, word, label, sort = TRUE) %>%
  arrange(desc(subreddit)) %>%
  group_by(subreddit) %>%
  slice(1:10) %>%
  plot_ly(
  x = ~n,
  y = ~word,
  type = "bar",
  transforms = list(list(
    type = 'filter',
    target = ~subreddit,
    operation = '=',
    value = unique(tidysub_filter$subreddit[1])
  ))
) %>%
  layout(title = "Word Frequency by Subreddit",
    yaxis = list(title = "Term", categoryorder = "trace", categoryarray = tidysub_filter$subreddit),
         xaxis = list(title = "Frequency"),
    font = list(family = "Times New Roman"),
    updatemenus = list(
    list(
      type = 'dropdown',
      active = 0,
      xanchor = "center",
      yanchor = "top",
      x = 1.2,
      y = 0.5,
      buttons = apply(as.data.frame(unique(tidysub_filter$subreddit)), 1,
                      function(x) list(method = 'restyle',args = list('transforms[0].value',x),label = x)))))
</code>```

With tidysub_filter being a data.frame in the form of:

Subreddit
Word
Label
n

Addiction
Word 1
MentalHealth
1000

Addiction
Word 2
MentalHealth
900

Addiction
Word 3
MentalHealth
800

Addiction
Word 4
MentalHealth
700

Addiction
Word 5
MentalHealth
600

Addiction
Word 6
MentalHealth
500

Addiction
Word 7
MentalHealth
400

Addiction
Word 8
MentalHealth
300

Addiction
Word 9
MentalHealth
200

Addiction
Word 10
MentalHealth
100

neoliberal
Word 1
Political
1000

neoliberal
Word 2
Political
900

neoliberal
Word 3
Political
800

neoliberal
Word 4
Political
700

neoliberal
Word 5
Political
600

neoliberal
Word 6
Political
500

neoliberal
Word 7
Political
400

neoliberal
Word 8
Political
300

neoliberal
Word 9
Political
200

neoliberal
Word 10
Political
100

And so on.

Furthermore, I limited the amount of stress the knitting process would take by saving the object into a .RData file and loading it into the environment before I knitted everything.

```<code>
---
title: "title"
subtitle:
author: "me"
date: "`r Sys.Date()`"
output: html_document
---

knitr::opts_chunk$set(echo = TRUE)
library(tinytex)
setwd("E:/Rdata")
load("env.RData")

FrequencyIDF
</code>```

Note: this is not the only interactive plot I want to insert; there are two other, of which one is a copy of the first one I just mentioned (with different data), while the other is a simple conversion of an existing ggplot. This last one I still haven't attempted to knit, so I don't know if I will incur in the same error. For reference, the code for it below, but I treated it in the same way as the FrequencySubreddit plot by loading it as an object.

```<code>tidysub_nrc_percentage <- tidysub_nrc %>%
  count(sentiment, label, day, year, sort = TRUE) %>%
  pivot_wider(names_from = sentiment, values_from = n) %>%
  mutate(total = select(., anger:trust) %>% rowSums(na.rm = TRUE)) %>%
  mutate(across(anger:trust , ~./total * 100)) %>%
  pivot_longer(anger:trust, names_to = "sentiment") %>%
  filter(sentiment != "negative", sentiment != "positive") %>%
  ggplot(aes(as.numeric(day), value, color = sentiment)) +
  geom_point() +
  geom_line() +
  facet_grid(year ~ label) +
  labs(title = "Share of Emotion by Day", subtitle = "Percentage of total emotion categories by label and year") +
  ylab("Percentage (%)") +
  xlab("Day") +
  placeholder_theme +
  scale_color_brewer(type = "qual", palette = 3) +
  theme(legend.position = "right")

tidysub_nrc_percentage
plotlynrc <- ggplotly(tidysub_nrc_percentage)
</code>```

EDIT

I finished loading my data again and I can provide you with the actual structure of the tidysub_filter object after it passes through the initial processing before the plot_ly command. The actual tidysub_filter file is too big to dput.

Just inputting this as:

```<code>Top10 <- tidysub_filter %>%
  count(subreddit, word, label, sort = TRUE) %>%
  arrange(desc(subreddit)) %>%
  group_by(subreddit) %>%
  slice(1:10)

FrequencySubreddit <- Top10 %>%
  plot_ly()
</code>```
```<code>structure(list(subreddit = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 12L, 12L,
12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 13L,
13L, 13L, 13L, 13L, 13L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L,
14L, 14L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 16L,
16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 17L, 17L, 17L, 17L,
17L, 17L, 17L, 17L, 17L, 17L, 18L, 18L, 18L, 18L, 18L, 18L, 18L,
18L, 18L, 18L, 19L, 19L, 19L, 19L, 19L, 19L, 19L, 19L, 19L, 19L,
20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 21L, 21L, 21L,
21L, 21L, 21L, 21L, 21L, 21L, 21L, 22L, 22L, 22L, 22L, 22L, 22L,
22L, 22L, 22L, 22L, 23L, 23L, 23L, 23L, 23L, 23L, 23L, 23L, 23L,
23L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 25L, 25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 26L, 26L, 26L, 26L, 26L,
26L, 26L, 26L, 26L, 26L, 27L, 27L, 27L, 27L, 27L, 27L, 27L, 27L,
27L, 27L, 28L, 28L, 28L, 28L, 28L, 28L, 28L, 28L, 28L, 28L, 29L,
29L, 29L, 29L, 29L, 29L, 29L, 29L, 29L, 29L, 30L, 30L, 30L, 30L,
30L, 30L, 30L, 30L, 30L, 30L, 31L, 31L, 31L, 31L, 31L, 31L, 31L,
31L, 31L, 31L, 32L, 32L, 32L, 32L, 32L, 32L, 32L, 32L, 32L, 32L,
33L, 33L, 33L, 33L, 33L, 33L, 33L, 33L, 33L, 33L), levels = c("addiction",
"alcoholism", "anarchy", "CanadaPolitics", "centrist", "Conservative",
"CryptoCurrency", "domesticviolence", "Eyebleach", "feedthebeast",
"geopolitics", "Home", "LifeProTips", "lonely", "MadeMeSmile",
"meirl", "mentalhealth", "neoliberal", "NoStupidQuestions", "offmychest",
"pcmasterrace", "propaganda", "rape", "Republican", "schizophrenia",
"science", "selfharm", "Shitstatistssay", "socialism", "techsupport",
"Vent", "WatchPeopleDieInside", "YUROP"), class = "factor"),
    word = c("addiction", "sober", "drugs", "stop", "clean",
    "hard", "addict", "days", "recovery", "quit", "drinking",
    "alcohol", "drink", "sober", "aa", "stop", "alcoholic", "days",
    "quit", "luck", "capitalism", "anarchism", "property", "definition",
    "anarchist", "anarchy", "government", "anarchists", "lol",
    "society", "government", "canada", "party", "tax", "vote",
    "change", "system", "liberals", "ndp", "issue", "trump",
    "left", "party", "republicans", "democrats", "government",
    "political", "biden", "vote", "election", "trump", "left",
    "vote", "democrats", "government", "country", "conservative",
    "biden", "shit", "party", "crypto", "btc", "market", "buy",
    "bitcoin", "eth", "lol", "price", "moons", "reddit", "abuse",
    "leave", "relationship", "abuser", "family", "hard", "abusive",
    "situation", "love", "support", "dog", "cat", "cute", "love",
    "dogs", "cats", "lol", "animals", "baby", "happy", "mod",
    "mods", "pack", "game", "minecraft", "modpack", "server",
    "world", "blocks", "version", "china", "chinese", "russia",
    "war", "countries", "world", "power", "country", "india",
    "government", "house", "water", "door", "wall", "paint",
    "home", "wood", "tape", "fix", "clean", "job", "lpt", "pay",
    "home", "water", "car", "shit", "house", "school", "makes",
    "friends", "love", "talk", "hope", "happy", "lonely", "friend",
    "hard", "women", "birthday", "love", "happy", "lol", "kids",
    "guy", "hope", "nice", "kid", "shit", "beautiful", "lol",
    "shit", "women", "love", "fuck", "guy", "friends", "pretty",
    "house", "fucking", "mental", "therapy", "talk", "therapist",
    "health", "depression", "hope", "anxiety", "hard", "feeling",
    "pretty", "shit", "trump", "lol", "government", "war", "world",
    "country", "literally", "vote", "question", "pretty", "world",
    "reason", "makes", "live", "pay", "women", "water", "answer",
    "love", "hope", "friends", "relationship", "happy", "talk",
    "hard", "friend", "care", "family", "pc", "gpu", "games",
    "cpu", "card", "game", "buy", "power", "ti", "ram", "propaganda",
    "russia", "war", "lol", "russian", "media", "wing", "ukraine",
    "country", "trump", "rape", "happened", "sexual", "talk",
    "hope", "sex", "raped", "fault", "trauma", "consent", "trump",
    "democrats", "vote", "left", "republicans", "party", "republican",
    "country", "biden", "election", "schizophrenia", "symptoms",
    "meds", "voices", "hope", "psychosis", "delusions", "hard",
    "medication", "talk", "women", "study", "kids", "pretty",
    "science", "covid", "world", "research", "makes", "health",
    "cut", "harm", "hope", "sh", "scars", "talk", "clean", "stop",
    "cutting", "hard", "government", "free", "property", "market",
    "system", "pay", "private", "tax", "capitalism", "shit",
    "socialism", "socialist", "capitalism", "class", "world",
    "government", "party", "system", "capitalist", "left", "windows",
    "drive", "issue", "pc", "computer", "power", "check", "usb",
    "laptop", "cpu", "hope", "love", "friends", "talk", "shit",
    "hard", "care", "women", "friend", "understand", "guy", "shit",
    "lol", "fuck", "video", "fucking", "dude", "wrong", "pretty",
    "literally", "eu", "germany", "russia", "europe", "country",
    "uk", "war", "countries", "european", "german"), label = structure(c(1L,
    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, 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, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 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, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 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, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), levels = c("MentalHealth",
    "Political", "Random"), class = "factor"), n = c(1330L, 708L,
    706L, 612L, 602L, 554L, 542L, 538L, 502L, 494L, 3176L, 2403L,
    2050L, 1481L, 1112L, 916L, 796L, 796L, 716L, 564L, 131L,
    111L, 108L, 105L, 99L, 99L, 95L, 92L, 82L, 80L, 6497L, 5591L,
    4097L, 3410L, 2839L, 2579L, 2526L, 2513L, 2464L, 2444L, 2353L,
    1778L, 1651L, 1480L, 1382L, 1351L, 1306L, 1143L, 1099L, 1094L,
    9412L, 8564L, 6930L, 5737L, 5478L, 5182L, 4816L, 4789L, 4781L,
    4557L, 37790L, 17442L, 17339L, 15421L, 15397L, 13328L, 11266L,
    9997L, 9057L, 8943L, 647L, 444L, 316L, 312L, 306L, 302L,
    301L, 299L, 298L, 271L, 3930L, 3500L, 2160L, 2103L, 1801L,
    1680L, 1162L, 1018L, 931L, 908L, 5288L, 4419L, 3125L, 1757L,
    1584L, 1558L, 1526L, 1468L, 1438L, 1423L, 5171L, 2163L, 2008L,
    1920L, 1819L, 1650L, 1469L, 1398L, 1257L, 1171L, 579L, 487L,
    378L, 350L, 297L, 260L, 204L, 201L, 174L, 172L, 5785L, 4686L,
    4601L, 4453L, 4352L, 4297L, 4046L, 4041L, 3631L, 3624L, 4047L,
    2955L, 2677L, 2396L, 2364L, 1896L, 1849L, 1778L, 1636L, 1474L,
    14586L, 10645L, 9343L, 7269L, 7246L, 6910L, 6737L, 6373L,
    6009L, 5894L, 10566L, 9240L, 8970L, 7954L, 7801L, 6860L,
    5720L, 5636L, 5597L, 5436L, 3632L, 3402L, 2944L, 2687L, 2645L,
    2564L, 2536L, 2532L, 2272L, 2204L, 9228L, 8445L, 8245L, 8018L,
    7737L, 7437L, 7187L, 7119L, 6971L, 6744L, 31799L, 20101L,
    19067L, 18863L, 18524L, 18502L, 17496L, 16726L, 16549L, 16437L,
    10765L, 8908L, 7383L, 6913L, 6515L, 6310L, 6080L, 5893L,
    5799L, 5586L, 34405L, 29401L, 25535L, 25124L, 22366L, 19316L,
    18495L, 17629L, 17564L, 17340L, 162L, 127L, 94L, 63L, 60L,
    54L, 49L, 48L, 42L, 41L, 607L, 499L, 325L, 309L, 303L, 257L,
    238L, 227L, 226L, 224L, 553L, 455L, 373L, 367L, 354L, 321L,
    308L, 291L, 284L, 213L, 1796L, 1509L, 1373L, 1115L, 927L,
    926L, 785L, 730L, 729L, 727L, 11067L, 10612L, 7666L, 5476L,
    5427L, 5340L, 5171L, 5167L, 5101L, 5088L, 2098L, 1862L, 1685L,
    1516L, 1369L, 1308L, 1247L, 1140L, 1103L, 1095L, 1683L, 805L,
    614L, 566L, 565L, 563L, 524L, 482L, 443L, 434L, 2069L, 1846L,
    1616L, 1217L, 1203L, 1039L, 1003L, 973L, 958L, 956L, 10469L,
    7359L, 5776L, 5362L, 4843L, 4621L, 4365L, 4132L, 3953L, 3852L,
    1601L, 1580L, 1567L, 1408L, 1278L, 1190L, 1096L, 1062L, 1008L,
    974L, 4722L, 3860L, 3554L, 2820L, 2418L, 2415L, 2175L, 2104L,
    2054L, 1672L, 1100L, 877L, 868L, 842L, 806L, 646L, 619L,
    600L, 506L, 490L)), class = c("grouped_df", "tbl_df", "tbl",
"data.frame"), row.names = c(NA, -330L), groups = structure(list(
    subreddit = structure(1:33, levels = c("addiction", "alcoholism",
    "anarchy", "CanadaPolitics", "centrist", "Conservative",
    "CryptoCurrency", "domesticviolence", "Eyebleach", "feedthebeast",
    "geopolitics", "Home", "LifeProTips", "lonely", "MadeMeSmile",
    "meirl", "mentalhealth", "neoliberal", "NoStupidQuestions",
    "offmychest", "pcmasterrace", "propaganda", "rape", "Republican",
    "schizophrenia", "science", "selfharm", "Shitstatistssay",
    "socialism", "techsupport", "Vent", "WatchPeopleDieInside",
    "YUROP"), class = "factor"), .rows = structure(list(1:10,
        11:20, 21:30, 31:40, 41:50, 51:60, 61:70, 71:80, 81:90,
        91:100, 101:110, 111:120, 121:130, 131:140, 141:150,
        151:160, 161:170, 171:180, 181:190, 191:200, 201:210,
        211:220, 221:230, 231:240, 241:250, 251:260, 261:270,
        271:280, 281:290, 291:300, 301:310, 311:320, 321:330), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), row.names = c(NA, -33L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE))
</code>```

Title: Knitting a large plot_ly file in HTML

Body:
I am working with a large reddit text dataset utilizing about 5 million comments to create frequency tables and sentiment analysis. The number of subreddits that I selected was 33, which is cluttery to render in a single facet wrapped ggplot, so I opted for an interactive table with a drop-down menu to modify the values per subreddit selected. However, when I try to knit the file into HTML, the process takes about an hour and a half (which I expected, since the plotly file is 154 MB), and then fails with this error.

"C:/Program Files/RStudio/bin/quarto/bin/tools/pandoc" +RTS -K512m -RTS FinalProjectHTML.knit.md --to html4 --from markdown+autolink_bare_uris+tex_math_single_backslash --output FinalProjectHTML.html --lua-filter "C:\Users\miche\AppData\Local\R\win-library\4.2\rmarkdown\rmarkdown\lua\pagebreak.lua" --lua-filter "C:\Users\miche\AppData\Local\R\win-library\4.2\rmarkdown\rmarkdown\lua\latex-div.lua" --self-contained --variable bs3=TRUE --section-divs --template "C:\Users\miche\AppData\Local\R\win-library\4.2\rmarkdown\rmd\h\default.html" --no-highlight --variable highlightjs=1 --variable theme=bootstrap --mathjax --variable "mathjax-url=https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" --include-in-header "C:\Users\miche\AppData\Local\Temp\RtmpshXgZe\rmarkdown-str63c86fd53d4b.html"

pandoc.exe: getMBlocks: VirtualAlloc MEM_COMMIT failed: The paging file is too small for this operation to complete.
Error: pandoc document conversion failed with error 251
Execution halted

Looking around for solutions, it seems that my problem is a matter of overloading my RAM and running out of memory in the process. So, I was wondering if there was a way I could solve this without turning my laptop into a jet engine.

To provide some context, the plotly table code is:

FrequencySubreddit <- tidysub_filter %>%
  count(subreddit, word, label, sort = TRUE) %>%
  arrange(desc(subreddit)) %>%
  group_by(subreddit) %>%
  slice(1:10) %>%
  plot_ly(
  x = ~n,
  y = ~word,
  type = "bar",
  transforms = list(list(
    type = 'filter',
    target = ~subreddit,
    operation = '=',
    value = unique(tidysub_filter$subreddit[1])
  ))
) %>%
  layout(title = "Word Frequency by Subreddit",
    yaxis = list(title = "Term", categoryorder = "trace", categoryarray = tidysub_filter$subreddit),
         xaxis = list(title = "Frequency"),
    font = list(family = "Times New Roman"),
    updatemenus = list(
    list(
      type = 'dropdown',
      active = 0,
      xanchor = "center",
      yanchor = "top",
      x = 1.2,
      y = 0.5,
      buttons = apply(as.data.frame(unique(tidysub_filter$subreddit)), 1,
                      function(x) list(method = 'restyle',args = list('transforms[0].value',x),label = x)))))

With tidysub_filter being a data.frame in the form of:

Subreddit
Word
Label
n

Addiction
Word 1
MentalHealth
1000

Addiction
Word 2
MentalHealth
900

Addiction
Word 3
MentalHealth
800

Addiction
Word 4
MentalHealth
700

Addiction
Word 5
MentalHealth
600

Addiction
Word 6
MentalHealth
500

Addiction
Word 7
MentalHealth
400

Addiction
Word 8
MentalHealth
300

Addiction
Word 9
MentalHealth
200

Addiction
Word 10
MentalHealth
100

neoliberal
Word 1
Political
1000

neoliberal
Word 2
Political
900

neoliberal
Word 3
Political
800

neoliberal
Word 4
Political
700

neoliberal
Word 5
Political
600

neoliberal
Word 6
Political
500

neoliberal
Word 7
Political
400

neoliberal
Word 8
Political
300

neoliberal
Word 9
Political
200

neoliberal
Word 10
Political
100

And so on.

Furthermore, I limited the amount of stress the knitting process would take by saving the object into a .RData file and loading it into the environment before I knitted everything.

---
title: "title"
subtitle:
author: "me"
date: "`r Sys.Date()`"
output: html_document
---

knitr::opts_chunk$set(echo = TRUE)
library(tinytex)
setwd("E:/Rdata")
load("env.RData")

FrequencyIDF

Note: this is not the only interactive plot I want to insert; there are two other, of which one is a copy of the first one I just mentioned (with different data), while the other is a simple conversion of an existing ggplot. This last one I still haven't attempted to knit, so I don't know if I will incur in the same error. For reference, the code for it below, but I treated it in the same way as the FrequencySubreddit plot by loading it as an object.

tidysub_nrc_percentage <- tidysub_nrc %>%
  count(sentiment, label, day, year, sort = TRUE) %>%
  pivot_wider(names_from = sentiment, values_from = n) %>%
  mutate(total = select(., anger:trust) %>% rowSums(na.rm = TRUE)) %>%
  mutate(across(anger:trust , ~./total * 100)) %>%
  pivot_longer(anger:trust, names_to = "sentiment") %>%
  filter(sentiment != "negative", sentiment != "positive") %>%
  ggplot(aes(as.numeric(day), value, color = sentiment)) +
  geom_point() +
  geom_line() +
  facet_grid(year ~ label) +
  labs(title = "Share of Emotion by Day", subtitle = "Percentage of total emotion categories by label and year") +
  ylab("Percentage (%)") +
  xlab("Day") +
  placeholder_theme +
  scale_color_brewer(type = "qual", palette = 3) +
  theme(legend.position = "right")

tidysub_nrc_percentage
plotlynrc <- ggplotly(tidysub_nrc_percentage)

EDIT

I finished loading my data again and I can provide you with the actual structure of the tidysub_filter object after it passes through the initial processing before the plot_ly command. The actual tidysub_filter file is too big to dput.

Just inputting this as:

Top10 <- tidysub_filter %>%
  count(subreddit, word, label, sort = TRUE) %>%
  arrange(desc(subreddit)) %>%
  group_by(subreddit) %>%
  slice(1:10)

FrequencySubreddit <- Top10 %>%
  plot_ly()

structure(list(subreddit = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 12L, 12L,
12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 13L,
13L, 13L, 13L, 13L, 13L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L,
14L, 14L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 16L,
16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 17L, 17L, 17L, 17L,
17L, 17L, 17L, 17L, 17L, 17L, 18L, 18L, 18L, 18L, 18L, 18L, 18L,
18L, 18L, 18L, 19L, 19L, 19L, 19L, 19L, 19L, 19L, 19L, 19L, 19L,
20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 21L, 21L, 21L,
21L, 21L, 21L, 21L, 21L, 21L, 21L, 22L, 22L, 22L, 22L, 22L, 22L,
22L, 22L, 22L, 22L, 23L, 23L, 23L, 23L, 23L, 23L, 23L, 23L, 23L,
23L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 24L, 25L, 25L,
25L, 25L, 25L, 25L, 25L, 25L, 25L, 25L, 26L, 26L, 26L, 26L, 26L,
26L, 26L, 26L, 26L, 26L, 27L, 27L, 27L, 27L, 27L, 27L, 27L, 27L,
27L, 27L, 28L, 28L, 28L, 28L, 28L, 28L, 28L, 28L, 28L, 28L, 29L,
29L, 29L, 29L, 29L, 29L, 29L, 29L, 29L, 29L, 30L, 30L, 30L, 30L,
30L, 30L, 30L, 30L, 30L, 30L, 31L, 31L, 31L, 31L, 31L, 31L, 31L,
31L, 31L, 31L, 32L, 32L, 32L, 32L, 32L, 32L, 32L, 32L, 32L, 32L,
33L, 33L, 33L, 33L, 33L, 33L, 33L, 33L, 33L, 33L), levels = c("addiction",
"alcoholism", "anarchy", "CanadaPolitics", "centrist", "Conservative",
"CryptoCurrency", "domesticviolence", "Eyebleach", "feedthebeast",
"geopolitics", "Home", "LifeProTips", "lonely", "MadeMeSmile",
"meirl", "mentalhealth", "neoliberal", "NoStupidQuestions", "offmychest",
"pcmasterrace", "propaganda", "rape", "Republican", "schizophrenia",
"science", "selfharm", "Shitstatistssay", "socialism", "techsupport",
"Vent", "WatchPeopleDieInside", "YUROP"), class = "factor"),
    word = c("addiction", "sober", "drugs", "stop", "clean",
    "hard", "addict", "days", "recovery", "quit", "drinking",
    "alcohol", "drink", "sober", "aa", "stop", "alcoholic", "days",
    "quit", "luck", "capitalism", "anarchism", "property", "definition",
    "anarchist", "anarchy", "government", "anarchists", "lol",
    "society", "government", "canada", "party", "tax", "vote",
    "change", "system", "liberals", "ndp", "issue", "trump",
    "left", "party", "republicans", "democrats", "government",
    "political", "biden", "vote", "election", "trump", "left",
    "vote", "democrats", "government", "country", "conservative",
    "biden", "shit", "party", "crypto", "btc", "market", "buy",
    "bitcoin", "eth", "lol", "price", "moons", "reddit", "abuse",
    "leave", "relationship", "abuser", "family", "hard", "abusive",
    "situation", "love", "support", "dog", "cat", "cute", "love",
    "dogs", "cats", "lol", "animals", "baby", "happy", "mod",
    "mods", "pack", "game", "minecraft", "modpack", "server",
    "world", "blocks", "version", "china", "chinese", "russia",
    "war", "countries", "world", "power", "country", "india",
    "government", "house", "water", "door", "wall", "paint",
    "home", "wood", "tape", "fix", "clean", "job", "lpt", "pay",
    "home", "water", "car", "shit", "house", "school", "makes",
    "friends", "love", "talk", "hope", "happy", "lonely", "friend",
    "hard", "women", "birthday", "love", "happy", "lol", "kids",
    "guy", "hope", "nice", "kid", "shit", "beautiful", "lol",
    "shit", "women", "love", "fuck", "guy", "friends", "pretty",
    "house", "fucking", "mental", "therapy", "talk", "therapist",
    "health", "depression", "hope", "anxiety", "hard", "feeling",
    "pretty", "shit", "trump", "lol", "government", "war", "world",
    "country", "literally", "vote", "question", "pretty", "world",
    "reason", "makes", "live", "pay", "women", "water", "answer",
    "love", "hope", "friends", "relationship", "happy", "talk",
    "hard", "friend", "care", "family", "pc", "gpu", "games",
    "cpu", "card", "game", "buy", "power", "ti", "ram", "propaganda",
    "russia", "war", "lol", "russian", "media", "wing", "ukraine",
    "country", "trump", "rape", "happened", "sexual", "talk",
    "hope", "sex", "raped", "fault", "trauma", "consent", "trump",
    "democrats", "vote", "left", "republicans", "party", "republican",
    "country", "biden", "election", "schizophrenia", "symptoms",
    "meds", "voices", "hope", "psychosis", "delusions", "hard",
    "medication", "talk", "women", "study", "kids", "pretty",
    "science", "covid", "world", "research", "makes", "health",
    "cut", "harm", "hope", "sh", "scars", "talk", "clean", "stop",
    "cutting", "hard", "government", "free", "property", "market",
    "system", "pay", "private", "tax", "capitalism", "shit",
    "socialism", "socialist", "capitalism", "class", "world",
    "government", "party", "system", "capitalist", "left", "windows",
    "drive", "issue", "pc", "computer", "power", "check", "usb",
    "laptop", "cpu", "hope", "love", "friends", "talk", "shit",
    "hard", "care", "women", "friend", "understand", "guy", "shit",
    "lol", "fuck", "video", "fucking", "dude", "wrong", "pretty",
    "literally", "eu", "germany", "russia", "europe", "country",
    "uk", "war", "countries", "european", "german"), label = structure(c(1L,
    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, 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, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 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, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 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, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), levels = c("MentalHealth",
    "Political", "Random"), class = "factor"), n = c(1330L, 708L,
    706L, 612L, 602L, 554L, 542L, 538L, 502L, 494L, 3176L, 2403L,
    2050L, 1481L, 1112L, 916L, 796L, 796L, 716L, 564L, 131L,
    111L, 108L, 105L, 99L, 99L, 95L, 92L, 82L, 80L, 6497L, 5591L,
    4097L, 3410L, 2839L, 2579L, 2526L, 2513L, 2464L, 2444L, 2353L,
    1778L, 1651L, 1480L, 1382L, 1351L, 1306L, 1143L, 1099L, 1094L,
    9412L, 8564L, 6930L, 5737L, 5478L, 5182L, 4816L, 4789L, 4781L,
    4557L, 37790L, 17442L, 17339L, 15421L, 15397L, 13328L, 11266L,
    9997L, 9057L, 8943L, 647L, 444L, 316L, 312L, 306L, 302L,
    301L, 299L, 298L, 271L, 3930L, 3500L, 2160L, 2103L, 1801L,
    1680L, 1162L, 1018L, 931L, 908L, 5288L, 4419L, 3125L, 1757L,
    1584L, 1558L, 1526L, 1468L, 1438L, 1423L, 5171L, 2163L, 2008L,
    1920L, 1819L, 1650L, 1469L, 1398L, 1257L, 1171L, 579L, 487L,
    378L, 350L, 297L, 260L, 204L, 201L, 174L, 172L, 5785L, 4686L,
    4601L, 4453L, 4352L, 4297L, 4046L, 4041L, 3631L, 3624L, 4047L,
    2955L, 2677L, 2396L, 2364L, 1896L, 1849L, 1778L, 1636L, 1474L,
    14586L, 10645L, 9343L, 7269L, 7246L, 6910L, 6737L, 6373L,
    6009L, 5894L, 10566L, 9240L, 8970L, 7954L, 7801L, 6860L,
    5720L, 5636L, 5597L, 5436L, 3632L, 3402L, 2944L, 2687L, 2645L,
    2564L, 2536L, 2532L, 2272L, 2204L, 9228L, 8445L, 8245L, 8018L,
    7737L, 7437L, 7187L, 7119L, 6971L, 6744L, 31799L, 20101L,
    19067L, 18863L, 18524L, 18502L, 17496L, 16726L, 16549L, 16437L,
    10765L, 8908L, 7383L, 6913L, 6515L, 6310L, 6080L, 5893L,
    5799L, 5586L, 34405L, 29401L, 25535L, 25124L, 22366L, 19316L,
    18495L, 17629L, 17564L, 17340L, 162L, 127L, 94L, 63L, 60L,
    54L, 49L, 48L, 42L, 41L, 607L, 499L, 325L, 309L, 303L, 257L,
    238L, 227L, 226L, 224L, 553L, 455L, 373L, 367L, 354L, 321L,
    308L, 291L, 284L, 213L, 1796L, 1509L, 1373L, 1115L, 927L,
    926L, 785L, 730L, 729L, 727L, 11067L, 10612L, 7666L, 5476L,
    5427L, 5340L, 5171L, 5167L, 5101L, 5088L, 2098L, 1862L, 1685L,
    1516L, 1369L, 1308L, 1247L, 1140L, 1103L, 1095L, 1683L, 805L,
    614L, 566L, 565L, 563L, 524L, 482L, 443L, 434L, 2069L, 1846L,
    1616L, 1217L, 1203L, 1039L, 1003L, 973L, 958L, 956L, 10469L,
    7359L, 5776L, 5362L, 4843L, 4621L, 4365L, 4132L, 3953L, 3852L,
    1601L, 1580L, 1567L, 1408L, 1278L, 1190L, 1096L, 1062L, 1008L,
    974L, 4722L, 3860L, 3554L, 2820L, 2418L, 2415L, 2175L, 2104L,
    2054L, 1672L, 1100L, 877L, 868L, 842L, 806L, 646L, 619L,
    600L, 506L, 490L)), class = c("grouped_df", "tbl_df", "tbl",
"data.frame"), row.names = c(NA, -330L), groups = structure(list(
    subreddit = structure(1:33, levels = c("addiction", "alcoholism",
    "anarchy", "CanadaPolitics", "centrist", "Conservative",
    "CryptoCurrency", "domesticviolence", "Eyebleach", "feedthebeast",
    "geopolitics", "Home", "LifeProTips", "lonely", "MadeMeSmile",
    "meirl", "mentalhealth", "neoliberal", "NoStupidQuestions",
    "offmychest", "pcmasterrace", "propaganda", "rape", "Republican",
    "schizophrenia", "science", "selfharm", "Shitstatistssay",
    "socialism", "techsupport", "Vent", "WatchPeopleDieInside",
    "YUROP"), class = "factor"), .rows = structure(list(1:10,
        11:20, 21:30, 31:40, 41:50, 51:60, 61:70, 71:80, 81:90,
        91:100, 101:110, 111:120, 121:130, 131:140, 141:150,
        151:160, 161:170, 171:180, 181:190, 191:200, 201:210,
        211:220, 221:230, 231:240, 241:250, 251:260, 261:270,
        271:280, 281:290, 291:300, 301:310, 311:320, 321:330), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), row.names = c(NA, -33L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE))


来源: stackexchange

问:
Using python schema pypi package to validate for type function
I'm trying to use the schema pypi package to validate a data-structure in python

How to validate structure (or schema) of dictionary in Python?

I would like to use it to try and validate for type function in my dictionary.

Reading through the docs there is no obvious way to do this.

Has anyone used schema to do this?

ContentLicense: CC BY-SA 4.0


问:
img2pdf key error when trying to convert to pdf
When trying to convert a list of .tif/.tiff files I run into a key error that is thrown from PIL package. I'm running the Anaconda diet on a Mac. I haven't been able to find many answers on why this happens. I can see that the list of images is 6 but it appears it is trying to continue to iterate on this list when it is at the end of the list.

I also was trying to only look for tif files but the commented out part doesn't seem to work.

Here's the code block in question.

```<code>imgs = []
for fname in os.listdir(storePath):
    #if not fname.endswith(".tif") or fname.endswith(".tiff"):
        #continue
    path = os.path.join(storePath, fname)
    if os.path.isdir(path):
        continue
    print(path)
    imgs.append(path)
    with open("name.pdf","wb") as f:
        f.write(img2pdf.convert(imgs))
</code>```

Here's the error stack:

```<code>setting <module 'PIL.TiffImagePlugin' from '/Users/userName/opt/anaconda3/lib/python3.9/site-packages/PIL/TiffImagePlugin.py'>.STRIP_SIZE = 5625
</code>```
```<code>KeyError                                  Traceback (most recent call last)
/var/folders/22/86x9q83n67j39t2kwfy970w40000gn/T/ipykernel_61196/4104548731.py in <module>
      9     imgs.append(path)
     10     with open("name.pdf","wb") as f:
---> 11         f.write(img2pdf.convert(imgs))

~/opt/anaconda3/lib/python3.9/site-packages/img2pdf.py in convert(*images, **kwargs)
   2358             rotation,
   2359             iccp,
-> 2360         ) in read_images(
   2361             rawdata,
   2362             kwargs["colorspace"],

~/opt/anaconda3/lib/python3.9/site-packages/img2pdf.py in read_images(rawdata, colorspace, first_frame_only, rot)
   1728     while True:
   1729         try:
-> 1730             imgdata.seek(img_page_count)
   1731         except EOFError:
   1732             break

~/opt/anaconda3/lib/python3.9/site-packages/PIL/TiffImagePlugin.py in seek(self, frame)
   1099         if not self._seek_check(frame):
   1100             return
-> 1101         self._seek(frame)
   1102         # Create a new core image object on second and
   1103         # subsequent frames in the image. Image may be

~/opt/anaconda3/lib/python3.9/site-packages/PIL/TiffImagePlugin.py in _seek(self, frame)
   1141         self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)
   1142         self.__frame = frame
-> 1143         self._setup()
   1144
   1145     def tell(self):

~/opt/anaconda3/lib/python3.9/site-packages/PIL/TiffImagePlugin.py in _setup(self)
   1311
   1312         # extract relevant tags
-> 1313         self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]
   1314         self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)
   1315

KeyError: 34712
</code>```

Body:
When trying to convert a list of .tif/.tiff files I run into a key error that is thrown from PIL package. I'm running the Anaconda diet on a Mac. I haven't been able to find many answers on why this happens. I can see that the list of images is 6 but it appears it is trying to continue to iterate on this list when it is at the end of the list.

I also was trying to only look for tif files but the commented out part doesn't seem to work.

Here's the code block in question.

imgs = []
for fname in os.listdir(storePath):
    #if not fname.endswith(".tif") or fname.endswith(".tiff"):
        #continue
    path = os.path.join(storePath, fname)
    if os.path.isdir(path):
        continue
    print(path)
    imgs.append(path)
    with open("name.pdf","wb") as f:
        f.write(img2pdf.convert(imgs))

Here's the error stack:

setting <module 'PIL.TiffImagePlugin' from '/Users/userName/opt/anaconda3/lib/python3.9/site-packages/PIL/TiffImagePlugin.py'>.STRIP_SIZE = 5625

KeyError                                  Traceback (most recent call last)
/var/folders/22/86x9q83n67j39t2kwfy970w40000gn/T/ipykernel_61196/4104548731.py in <module>
      9     imgs.append(path)
     10     with open("name.pdf","wb") as f:
---> 11         f.write(img2pdf.convert(imgs))

~/opt/anaconda3/lib/python3.9/site-packages/img2pdf.py in convert(*images, **kwargs)
   2358             rotation,
   2359             iccp,
-> 2360         ) in read_images(
   2361             rawdata,
   2362             kwargs["colorspace"],

~/opt/anaconda3/lib/python3.9/site-packages/img2pdf.py in read_images(rawdata, colorspace, first_frame_only, rot)
   1728     while True:
   1729         try:
-> 1730             imgdata.seek(img_page_count)
   1731         except EOFError:
   1732             break

~/opt/anaconda3/lib/python3.9/site-packages/PIL/TiffImagePlugin.py in seek(self, frame)
   1099         if not self._seek_check(frame):
   1100             return
-> 1101         self._seek(frame)
   1102         # Create a new core image object on second and
   1103         # subsequent frames in the image. Image may be

~/opt/anaconda3/lib/python3.9/site-packages/PIL/TiffImagePlugin.py in _seek(self, frame)
   1141         self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)
   1142         self.__frame = frame
-> 1143         self._setup()
   1144
   1145     def tell(self):

~/opt/anaconda3/lib/python3.9/site-packages/PIL/TiffImagePlugin.py in _setup(self)
   1311
   1312         # extract relevant tags
-> 1313         self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]
   1314         self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)
   1315

KeyError: 34712


问:
Uncaught ReferenceError: Alpine is not defined
Using Alpine with Laravel Vite is not working as expected. I'm getting the error: Uncaught ReferenceError: Alpine is not defined

My app.js file:

import Alpine from 'alpinejs';

Alpine.start();

window.Alpine = Alpine; // this should make Alpine globally accessible, right?
```
<p>Including the app.js file in the head with: <code>@vite('resources/js/app.js')</code></p>
<p>Then, when trying to use Alpine I placed the following script on the page:</p>
<pre class="lang-html prettyprint-override"><code><script type="text/javascript">
    document.addEventListener('alpine:init', () => {
        console.log('alpine loaded') // this works so the event listener is called
        console.log(Alpine) // Uncaught ReferenceError: Alpine is not defined
    });
</script>
</code>```

When opening the developer console and typing Alpine the object does actually exist. Any ideas on why Alpine isn't available in the global scope?

Body:
Using Alpine with Laravel Vite is not working as expected. I'm getting the error: Uncaught ReferenceError: Alpine is not defined

My app.js file:

import Alpine from 'alpinejs';

Alpine.start();

window.Alpine = Alpine; // this should make Alpine globally accessible, right?

Including the app.js file in the head with: @vite('resources/js/app.js')

Then, when trying to use Alpine I placed the following script on the page:

When opening the developer console and typing Alpine the object does actually exist. Any ideas on why Alpine isn't available in the global scope?


问:
What's the syntax mean retf $12 in GAS?
In a syscall_handler, I found the code

```<code>syscall_handler:
    push %ds
    pusha

    mov $KERNEL_DATA_SEGMENT, %ax
    mov %ax,%ds
    mov %esp, %ebp

    push 13*4(%ebp)
    push 12*4(%ebp)
    push 11*4(%ebp)

    call do_syscall

    mov %ebp, %esp

    popa
    pop %ds

    retf $12
</code>```

I don't konw retf $12 mean, what is the use of it? I've only seen retf with no immediate number

Title: What's the syntax mean retf $12 in GAS?

Body:
In a syscall_handler, I found the code

syscall_handler:
    push %ds
    pusha

    mov $KERNEL_DATA_SEGMENT, %ax
    mov %ax,%ds
    mov %esp, %ebp

    push 13*4(%ebp)
    push 12*4(%ebp)
    push 11*4(%ebp)

    call do_syscall

    mov %ebp, %esp

    popa
    pop %ds

    retf $12

I don't konw retf $12 mean, what is the use of it? I've only seen retf with no immediate number


问:
TYPO3 official introduction package unused css classes. Is this a bug?
We are evaluating TYPO3 so we have installed it on a Rocky linux 9.1 using composer. So far, so good. TYPO3 is working as expected, no errors.

I installed the introduction package and attempted to analyse how the css styles work, as I wanted to change the style of the default header, and wasn't having much success. On the home page, we have the following html code for the header:

```<code><header id="page-header" class="bp-page-header navbar navbar-mainnavigation navbar-default-transition navbar-has-image navbar-top navbar-fixed-top">
</code>```

The problem is, the definition for the class "bp-page-header" is nowhere to be found. Is this a bug in the TYPO3 package? I was expecting to find the definitions for all css classes used, and I can find the definitions of all the other classes.

I want to make sure it is a real issue before reporting it. Any hints are welcome.

Body:
We are evaluating TYPO3 so we have installed it on a Rocky linux 9.1 using composer. So far, so good. TYPO3 is working as expected, no errors.

I installed the introduction package and attempted to analyse how the css styles work, as I wanted to change the style of the default header, and wasn't having much success. On the home page, we have the following html code for the header:

The problem is, the definition for the class "bp-page-header" is nowhere to be found. Is this a bug in the TYPO3 package? I was expecting to find the definitions for all css classes used, and I can find the definitions of all the other classes.

I want to make sure it is a real issue before reporting it. Any hints are welcome.


问:
Ran the two commands in Pyspark- spark.read.table("df1").collect() and spark.table("df1").collect() , both gave same output. What is the difference?
Ran the two commands in Pyspark- spark.read.table("df1").collect()  and spark.table("df1").collect()  , both gave same output. What is the difference?</p>


问:
Consuming external API request from kubernetes pod
I'm learning Kubernetes and i developed a simple spring-boot project that expose a simple API /getHomeSpace. When invoked, this API making a request to an external API that is the following: https://api.nasa.gov/planetary/apod. When i start-up my app with docker-compose it works perfectly. But when i set up kubernetes pod and service i receive the following error:

```<code>Error during callApod: I/O error on GET request for "https://api.nasa.gov/planetary/apod": No subject alternative DNS name matching api.nasa.gov found.; nested exception is javax.net.ssl.SSLHandshakeException: No subject alternative DNS name matching api.nasa.gov found.

</code>```

My kubernetes config files:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      component: server
  template:
    metadata:
      labels:
        component: server
    spec:
      containers:
        - name: server
          image: antonio94c/view_api:11
          ports:
          - containerPort: 8080
</code>```
```<code>apiVersion: v1
kind: Service
metadata:
  name: api-service
spec:
  type: ClusterIP
  ports:
    - port: 8080
      targetPort: 8080
      #nodePort: 30000
  selector:
    component: server
</code>```

What i'm missing??

I tried to read Kubernetes doc and stackoverflow related topics, but i didn't found a solution.

Body:
I'm learning Kubernetes and i developed a simple spring-boot project that expose a simple API /getHomeSpace. When invoked, this API making a request to an external API that is the following: https://api.nasa.gov/planetary/apod. When i start-up my app with docker-compose it works perfectly. But when i set up kubernetes pod and service i receive the following error:

Error during callApod: I/O error on GET request for "https://api.nasa.gov/planetary/apod": No subject alternative DNS name matching api.nasa.gov found.; nested exception is javax.net.ssl.SSLHandshakeException: No subject alternative DNS name matching api.nasa.gov found.

My kubernetes config files:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      component: server
  template:
    metadata:
      labels:
        component: server
    spec:
      containers:
        - name: server
          image: antonio94c/view_api:11
          ports:
          - containerPort: 8080

apiVersion: v1
kind: Service
metadata:
  name: api-service
spec:
  type: ClusterIP
  ports:
    - port: 8080
      targetPort: 8080
      #nodePort: 30000
  selector:
    component: server

What i'm missing??

I tried to read Kubernetes doc and stackoverflow related topics, but i didn't found a solution.


问:
How do I compile an existing C++ ibrary using sockets to WASM?
I have some existing server code written in C++, Node.js and Python that I would like to port to WASM. This code makes heavy use of UDP/TCP sockets. Ideally with little to no modification of the code.

I know this type of question has been asked a number of times, and the answer is to convert them to websockets and use a bridge. However, this adds another moving part that I'd like to avoid if at all possible.

The code runs as a service on desktop, not in the browser. I know that there's a WASI proposal for sockets that is implemented by WasmEdge.

I'm quite new to WASM and still a little hazy on how it all fits together. Any advice on how to solve this would be greatly appreciated.

Thanks in advance!

I've tried two approaches and am unsure how best to proceed:

#1 Use WasmEdge - but I don't quite understand how to compile to WASM in a way that will take advantage of WasmEdge's socket support. For example, using emscripten will always convert the sockets to websocket.

#2 Create a Node.js wrapper that handles the sockets directly and passes the contents of the buffers back and forth with the embedded WASM module. This isn't ideal as I'd have to modify the source code or at the least create a shim of some kind to replace  networking.


问:
Superset: How can I edit value labels in chart legend?
I have a Superset chart and would like to edit the value labels displayed in chart legend. Can I do this without editing the data? I can edit the axis name via Data / Customize, but there seems to be no option to replace the values.</p>


问:
Flutter workmanager with home_widget working in debug and profile, but not in Android build APK
I have a todo app built in Flutter and intended only for Android. I built a home screen widget for it (using the home_widget package in Flutter) to allow users to see a list of tasks and check them off directly from the widget.

At midnight, the tasks should reset with the new tasks for the day (I used the workmanager package to accomplish this, although I also tried the android_alarm_manager_plus package, with the same results). All of this functionality is working perfectly in debug mode, and even in profile mode (I can't test it in release mode because, according to my understanding, that would remove services and thus the home_widget would not work; however, when I do the build, that doesn't seem to be the problem because the home widget still shows up). BUT! When I build the release APK and submit it to Google Play for internal testing, then download it onto my Pixel 7 (with no power saving modes on, as far as I'm aware), the midnight function does not run. :(

Here's the relevant code:

main_prod.dart

```<code>void main() async {
  return mainGeneric('Prod Name', ProdFirebaseOptions.currentPlatform, Environment.prod);
}
</code>```

main_generic.dart

```<code>
/// Used for Background Updates using Workmanager Plugin
@pragma('vm:entry-point')
void workmanagerCallbackDispatcher() {
  Workmanager().executeTask((taskName, inputData) {
    if (taskName == 'widgetBackgroundUpdate') {
      try {
        return Future.wait<void>([
          // This is a static Future<void> function from a helper class that resets
          // the tasks; it seems to be working when I test it by itself, as well as
          // in debug or profile mode.
          MidnightService.resetTasks(),
        ]).then((value) {
          return Future.value(true);
        });
      } catch(err) {
        print(err.toString());
        throw Exception(err);
      }
    }
    return Future.value(true);
  });
}

void _startBackgroundUpdate() async {
  if (await MidnightService.shouldUpdateWorkManagerTasks()) {
    (await SharedPreferences.getInstance()).setInt('midnight_tasks_update_version', Constants.MIDNIGHT_TASKS_UPDATE_VERSION);

    await Workmanager().cancelAll();
    DateTime now = DateTime.now();
    int nowMillis = now.millisecondsSinceEpoch;
    int midnightTonightMillis = DateTime(now?.year ?? 0, now?.month ?? 0, (now?.day ?? 0) + 1).millisecondsSinceEpoch;
    int millisUntilMidnight = midnightTonightMillis - nowMillis;
    await Workmanager().registerPeriodicTask('midnightUpdate', 'widgetBackgroundUpdate', initialDelay: Duration(milliseconds: millisUntilMidnight), frequency: Duration(days: 1));
  }
}

void mainGeneric(String appName, FirebaseOptions firebaseOptions, Environment environment) async {
  // Avoid errors caused by flutter upgrade.
  WidgetsFlutterBinding.ensureInitialized();
  Workmanager().initialize(workmanagerCallbackDispatcher, isInDebugMode: kDebugMode).then((_) => _startBackgroundUpdate());
  ...
  // If this is the first time opening the app with widget functionality.
  HomeWidget.getWidgetData<String>('todays_tasks_string', defaultValue: '').then((todaysTasksString) async {
    if (todaysTasksString == '') {
      List<Task> todaysTasks = await Repositories().taskRepository.getFocusedTasks();
      await HomeWidgetUtils.setTodaysTasks(todaysTasks);
      return true;
    }
    return false;
  });

  Firebase.initializeApp(
    name: appName,
    options: firebaseOptions,
  ).then((_) async {
    ...
  });

  HomeWidget.registerBackgroundCallback(homeWidgetBackgroundCallback);
  runApp(AppConfig(
    child: MyApp(),
    environment: environment,
    appTitle: appName,
  ));
}

// Called when doing background work initiated from home screen widget
@pragma('vm:entry-point')
Future<void> homeWidgetBackgroundCallback(Uri uri) async {
  if (uri.host.startsWith('completetask_')) {
    String todaysTasksString = await HomeWidgetUtils.updateTaskById(uri.host.split('_')[1], true);
    await HomeWidget.saveWidgetData<String>('todays_tasks_string', todaysTasksString);
    await HomeWidget.updateWidget(androidName: 'TodaysTasksWidgetProvider');
  }
}
</code>```

midnight_service.dart

```<code>class MidnightService {
  ...
  static Future<bool> shouldUpdateWorkManagerTasks() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      int midnightTasksUpdateVersion = prefs.getInt('midnight_tasks_update_version');
      return Constants.MIDNIGHT_TASKS_UPDATE_VERSION > midnightTasksUpdateVersion;
    }
    catch (e) { print(e); }
    return true;
  }
}
</code>```

It might also be valuable to note that, when a user checks off a task from the home screen widget, sometimes the task takes a while to actually be checked off  (and sometimes requires the app to be opened before it will execute). However, I figured this is just a slowness issue or something controlled by the OS that I can't do much about.

With all of that, my question is then, why is the workmanager not executing its midnight task?

I've been smashing my head against this for days, so any help and/or advice is greatly appreciated!!

Body:
I have a todo app built in Flutter and intended only for Android. I built a home screen widget for it (using the home_widget package in Flutter) to allow users to see a list of tasks and check them off directly from the widget.

At midnight, the tasks should reset with the new tasks for the day (I used the workmanager package to accomplish this, although I also tried the android_alarm_manager_plus package, with the same results). All of this functionality is working perfectly in debug mode, and even in profile mode (I can't test it in release mode because, according to my understanding, that would remove services and thus the home_widget would not work; however, when I do the build, that doesn't seem to be the problem because the home widget still shows up). BUT! When I build the release APK and submit it to Google Play for internal testing, then download it onto my Pixel 7 (with no power saving modes on, as far as I'm aware), the midnight function does not run. :(

Here's the relevant code:

main_prod.dart

void main() async {
  return mainGeneric('Prod Name', ProdFirebaseOptions.currentPlatform, Environment.prod);
}

main_generic.dart

/// Used for Background Updates using Workmanager Plugin
@pragma('vm:entry-point')
void workmanagerCallbackDispatcher() {
  Workmanager().executeTask((taskName, inputData) {
    if (taskName == 'widgetBackgroundUpdate') {
      try {
        return Future.wait<void>([
          // This is a static Future<void> function from a helper class that resets
          // the tasks; it seems to be working when I test it by itself, as well as
          // in debug or profile mode.
          MidnightService.resetTasks(),
        ]).then((value) {
          return Future.value(true);
        });
      } catch(err) {
        print(err.toString());
        throw Exception(err);
      }
    }
    return Future.value(true);
  });
}

void _startBackgroundUpdate() async {
  if (await MidnightService.shouldUpdateWorkManagerTasks()) {
    (await SharedPreferences.getInstance()).setInt('midnight_tasks_update_version', Constants.MIDNIGHT_TASKS_UPDATE_VERSION);

    await Workmanager().cancelAll();
    DateTime now = DateTime.now();
    int nowMillis = now.millisecondsSinceEpoch;
    int midnightTonightMillis = DateTime(now?.year ?? 0, now?.month ?? 0, (now?.day ?? 0) + 1).millisecondsSinceEpoch;
    int millisUntilMidnight = midnightTonightMillis - nowMillis;
    await Workmanager().registerPeriodicTask('midnightUpdate', 'widgetBackgroundUpdate', initialDelay: Duration(milliseconds: millisUntilMidnight), frequency: Duration(days: 1));
  }
}

void mainGeneric(String appName, FirebaseOptions firebaseOptions, Environment environment) async {
  // Avoid errors caused by flutter upgrade.
  WidgetsFlutterBinding.ensureInitialized();
  Workmanager().initialize(workmanagerCallbackDispatcher, isInDebugMode: kDebugMode).then((_) => _startBackgroundUpdate());
  ...
  // If this is the first time opening the app with widget functionality.
  HomeWidget.getWidgetData<String>('todays_tasks_string', defaultValue: '').then((todaysTasksString) async {
    if (todaysTasksString == '') {
      List<Task> todaysTasks = await Repositories().taskRepository.getFocusedTasks();
      await HomeWidgetUtils.setTodaysTasks(todaysTasks);
      return true;
    }
    return false;
  });

  Firebase.initializeApp(
    name: appName,
    options: firebaseOptions,
  ).then((_) async {
    ...
  });

  HomeWidget.registerBackgroundCallback(homeWidgetBackgroundCallback);
  runApp(AppConfig(
    child: MyApp(),
    environment: environment,
    appTitle: appName,
  ));
}

// Called when doing background work initiated from home screen widget
@pragma('vm:entry-point')
Future<void> homeWidgetBackgroundCallback(Uri uri) async {
  if (uri.host.startsWith('completetask_')) {
    String todaysTasksString = await HomeWidgetUtils.updateTaskById(uri.host.split('_')[1], true);
    await HomeWidget.saveWidgetData<String>('todays_tasks_string', todaysTasksString);
    await HomeWidget.updateWidget(androidName: 'TodaysTasksWidgetProvider');
  }
}

midnight_service.dart

class MidnightService {
  ...
  static Future<bool> shouldUpdateWorkManagerTasks() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      int midnightTasksUpdateVersion = prefs.getInt('midnight_tasks_update_version');
      return Constants.MIDNIGHT_TASKS_UPDATE_VERSION > midnightTasksUpdateVersion;
    }
    catch (e) { print(e); }
    return true;
  }
}

It might also be valuable to note that, when a user checks off a task from the home screen widget, sometimes the task takes a while to actually be checked off  (and sometimes requires the app to be opened before it will execute). However, I figured this is just a slowness issue or something controlled by the OS that I can't do much about.

With all of that, my question is then, why is the workmanager not executing its midnight task?

I've been smashing my head against this for days, so any help and/or advice is greatly appreciated!!


问:
SQL DATEDIFF between multiple entries with same id
I want to calculate the days between 2 dates on multiple entries but I have this error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

I'm trying to use a LAG() but I can't find a solution.

[Data to read]
(https://i.stack.imgur.com/L7X35.png)

```<code>SELECT DATEDIFF(
DAY,
(SELECT DATEFROMPARTS(dat.year, dat.month, dat.day)
FROM FactReport
JOIN DimDate AS dat ON dat.id = factReport.updatedDateId
WHERE bugId IN (
SELECT bugid FROM FactReport
GROUP BY bugid HAVING count(*) > 1)),

LAG(
(SELECT DATEFROMPARTS(dat.year, dat.month, dat.day)
FROM FactReport
JOIN DimDate AS dat ON dat.id = factReport.updatedDateId
WHERE bugId IN (
SELECT bugid FROM FactReport
GROUP BY bugid HAVING count(*) > 1)
))
OVER (ORDER BY FactReport.bugid))

as TimeToUpdate
FROM FactReport
</code>```

Body:
I want to calculate the days between 2 dates on multiple entries but I have this error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

I'm trying to use a LAG() but I can't find a solution.

[Data to read]
(https://i.stack.imgur.com/L7X35.png)

SELECT DATEDIFF(
DAY,
(SELECT DATEFROMPARTS(dat.year, dat.month, dat.day)
FROM FactReport
JOIN DimDate AS dat ON dat.id = factReport.updatedDateId
WHERE bugId IN (
SELECT bugid FROM FactReport
GROUP BY bugid HAVING count(*) > 1)),

LAG(
(SELECT DATEFROMPARTS(dat.year, dat.month, dat.day)
FROM FactReport
JOIN DimDate AS dat ON dat.id = factReport.updatedDateId
WHERE bugId IN (
SELECT bugid FROM FactReport
GROUP BY bugid HAVING count(*) > 1)
))
OVER (ORDER BY FactReport.bugid))

as TimeToUpdate
FROM FactReport


问:
Button didn't response for clicks after swipe(Jetpack compose)
This is simplified version of my view. Button, that can change its orientation.

```<code>@OptIn(ExperimentalMaterialApi::class)
@Composable
fun SwipeableButton() {
    val state = rememberSwipeableState(0)
    val anchors = mapOf(0f to 0, -400f to 1)

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .swipeable(
                state = state,
                anchors = anchors,
                orientation = Orientation.Horizontal
            )
    ) {
        Button(
            onClick = {},
            content = { Text("Button text") },
            modifier = Modifier
                .offset { IntOffset(state.offset.value.roundToInt(), 0) }
                .align(Alignment.CenterEnd)
        )
    }
}
</code>```

The problems is that button isn't response for click for ~1 sec after swipe. Why is that happened? And how can I fix that?

Body:
This is simplified version of my view. Button, that can change its orientation.

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun SwipeableButton() {
    val state = rememberSwipeableState(0)
    val anchors = mapOf(0f to 0, -400f to 1)

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .swipeable(
                state = state,
                anchors = anchors,
                orientation = Orientation.Horizontal
            )
    ) {
        Button(
            onClick = {},
            content = { Text("Button text") },
            modifier = Modifier
                .offset { IntOffset(state.offset.value.roundToInt(), 0) }
                .align(Alignment.CenterEnd)
        )
    }
}

The problems is that button isn't response for click for ~1 sec after swipe. Why is that happened? And how can I fix that?


问:
Is it possible for Jupyter to automatically insert new lines?
In Kumar's answer to "How to wrap code/text in Jupyter notebooks" he provides a screenshot of Jupyter's word-wrapping options. These options are documented in the pull request Add wordWrapColumn and bounded line wrapping modes by AlbertHilb · jupyterlab/jupyterlab. Unfortunately all these settings don't seem to automatically add new lines, they just determine where the wrapping happens visually.

For now my workaround is to add a ruler (see python 3.x - ipython3 notebook vertical margin/marker line at 80 characters - Stack Overflow) and manually wrap.

I'm saving my content in the the MyST format, which makes version control much easier. Hence the question (users saving to JSON wouldn't need this).


问:
Function that creates a pyramid of stars without None when called with a print statement
Want to write a function that outputs a pyramid of stars.

This function must be called with a print statement.

My solution results in None displayed.

```<code>def tree(n):
    for i in range(n):
        for j in range(n-i-1):
            print(" ", end="")
        for j in range(2*i+1):
            print('*', end="")
        print('\r')

print(tree(5))
</code>```
```<code>    *
   ***
  *****
 *******
*********
None
</code>```

How do I get rid of the None?

I tried using a return statement with no success:

```<code>def tree(n):
    for i in range(n):
        a=((n - (i + 1)) * " " + ((2*i)+1) * '*')

    return a

print(tree(5))
</code>```

returns

*********

Is the return statement the right approach?

Calling the function without the print statement is not an option :)

Thanks.

Body:
Want to write a function that outputs a pyramid of stars.

This function must be called with a print statement.

My solution results in None displayed.

def tree(n):
    for i in range(n):
        for j in range(n-i-1):
            print(" ", end="")
        for j in range(2*i+1):
            print('*', end="")
        print('\r')

print(tree(5))

    *
   ***
  *****
 *******
*********
None

How do I get rid of the None?

I tried using a return statement with no success:

def tree(n):
    for i in range(n):
        a=((n - (i + 1)) * " " + ((2*i)+1) * '*')

    return a

print(tree(5))

returns

*********

Is the return statement the right approach?

Calling the function without the print statement is not an option :)

Thanks.


问:
Sound not correctly detected with KY-037 and Rasberry Pi Zero
I have the KY-037 sound sensor with three jumpers going to the Ras Pi.

Ground - going to PIN 6

Out - going to PIN 7

VCC - going to PIN 2 (5v) I tried it on 3.3v (PIN 1) as well

I am running a program using Python on the Pi Zero. I want to send a text to my Twilio number but right now I am just trying to print the PIN and fire off a "sound detected" print statement when sound occurs.

HERE IS MY CODE:

```<code>import time
import RPi.GPIO as GPIO
from twilio.rest import Client

# Twilio account information
account_sid = "123123123"
auth_token = "123123123"
twilio_number = "5551351234"
destination_number = "1121231122"

# Sound sensor configuration
sensor_pin = 4

# Set the pin numbering mode so the pin will be 4 instead of 7
GPIO.setmode(GPIO.BCM)

# Set the sensor pin as an input
GPIO.setup(sensor_pin, GPIO.IN)

# Initialize the Twilio client
client = Client(account_sid, auth_token)

while True:

 # Read the sound sensor value
    value = GPIO.input(sensor_pin)

    # Use the value to determine whether a sound has occurred
    if value == 1:
        # A sound has occurred, so send a text message using Twilio
        print ("Sound Detected")

       #this will send a message to my Twilio account
        #message = client.messages.create(to=destination_number, from_=twilio_number, body="Sound detected!")

    # Wait a little bit before checking again
    time.sleep(0.1) ```
```

Body:
I have the KY-037 sound sensor with three jumpers going to the Ras Pi.

Ground - going to PIN 6

Out - going to PIN 7

VCC - going to PIN 2 (5v) I tried it on 3.3v (PIN 1) as well

I am running a program using Python on the Pi Zero. I want to send a text to my Twilio number but right now I am just trying to print the PIN and fire off a "sound detected" print statement when sound occurs.

HERE IS MY CODE:

import time
import RPi.GPIO as GPIO
from twilio.rest import Client

# Twilio account information
account_sid = "123123123"
auth_token = "123123123"
twilio_number = "5551351234"
destination_number = "1121231122"

# Sound sensor configuration
sensor_pin = 4

# Set the pin numbering mode so the pin will be 4 instead of 7
GPIO.setmode(GPIO.BCM)

# Set the sensor pin as an input
GPIO.setup(sensor_pin, GPIO.IN)

# Initialize the Twilio client
client = Client(account_sid, auth_token)

while True:

 # Read the sound sensor value
    value = GPIO.input(sensor_pin)

    # Use the value to determine whether a sound has occurred
    if value == 1:
        # A sound has occurred, so send a text message using Twilio
        print ("Sound Detected")

       #this will send a message to my Twilio account
        #message = client.messages.create(to=destination_number, from_=twilio_number, body="Sound detected!")

    # Wait a little bit before checking again
    time.sleep(0.1) ```


问:
Why do I need to register my repository class inside my ASP.NET Web API project?
My solution has a ASP.NET Web API project and a Core project that contains the entity framework core DbContext, repository (SeriesRepository : ISeriesRepository), and service that calls the repository (SeriesService : ISeriesService). The API should call the service using dependency injection by adding Builder.Services.AddScoped<ISeriesService, SeriesService>(); in Program.cs. The controller should use the SeriesService via an injected dependency:

private readonly ISeriesService _seriesService;

public SeriesController(ISeriesService seriesService)
{
    _seriesService = seriesService;
}
```

But when I try and run it, I get this exception:

System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: Project.Core.Services.ISeriesService Lifetime: Scoped ImplementationType: Project.Core.Services.SeriesService': Unable to resolve service for type 'Project.Core.Repositories.ISeriesRepository' while attempting to activate 'Project.Core.Services.SeriesService'.

If I add the repository Builder.Services.AddScoped<ISeriesRepository, SeriesRepository>(); in Program.cs, it runs successfully. But this seems like it defeats the purpose of using the SeriesService to abstract away the repository/DbContext. If this isn't the correct way, how do I correctly implement this using services/repositories and dependency injection?

Body:
My solution has a ASP.NET Web API project and a Core project that contains the entity framework core DbContext, repository (SeriesRepository : ISeriesRepository), and service that calls the repository (SeriesService : ISeriesService). The API should call the service using dependency injection by adding Builder.Services.AddScoped<ISeriesService, SeriesService>(); in Program.cs. The controller should use the SeriesService via an injected dependency:

private readonly ISeriesService _seriesService;

public SeriesController(ISeriesService seriesService)
{
    _seriesService = seriesService;
}

But when I try and run it, I get this exception:

System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: Project.Core.Services.ISeriesService Lifetime: Scoped ImplementationType: Project.Core.Services.SeriesService': Unable to resolve service for type 'Project.Core.Repositories.ISeriesRepository' while attempting to activate 'Project.Core.Services.SeriesService'.

If I add the repository Builder.Services.AddScoped<ISeriesRepository, SeriesRepository>(); in Program.cs, it runs successfully. But this seems like it defeats the purpose of using the SeriesService to abstract away the repository/DbContext. If this isn't the correct way, how do I correctly implement this using services/repositories and dependency injection?


问:
command button (Active X control) in VBA is not stable in one location
I'm facing a new problem in vba. I have create a active X button in excel vba, named "transfer". It contains the below code

```<code>
Option Explicit

Dim msg, clear_content As String

Private Sub Transfer_data_Click()

    If Sheets("Print").Range("B8") = "" Then

        Sheets("final").Range("B8:D39").Copy Destination:=Sheets("Print").Range("B8")

    ElseIf Sheets("Print").Range("B59") = "" Then

        Sheets("final").Range("B8:D39").Copy Destination:=Sheets("Print").Range("B59")

    Else

     msg = MsgBox("Print page is full,Do you need to clear the page", vbQuestion + vbYesNo, "User Repsonse")

        If msg = vbYes Then

            clear_content = MsgBox("Warning! Print data will be erased completly", vbQuestion + vbYesNo, "user response")

            If clear_content = vbYes Then

                Sheets("Print").Range("B8:J39").ClearContents
                Sheets("Print").Range("C44:J50").ClearContents

                Sheets("Print").Range("B59:J90").ClearContents
                Sheets("Print").Range("c95:J101").ClearContents

            End If

        End If

    End If

End Sub

</code>```

There are total 6 sheets, where 4 sheets contains data and in 5th sheet this "transfer" button is there. When i run the main program ,which will paste the result in this 5th page, this transfer button is placing randomly when my main code runs.
before code run](https://i.stack.imgur.com/mqarC.png)

Aftercode run]

Body:
I'm facing a new problem in vba. I have create a active X button in excel vba, named "transfer". It contains the below code

Option Explicit

Dim msg, clear_content As String

Private Sub Transfer_data_Click()

    If Sheets("Print").Range("B8") = "" Then

        Sheets("final").Range("B8:D39").Copy Destination:=Sheets("Print").Range("B8")

    ElseIf Sheets("Print").Range("B59") = "" Then

        Sheets("final").Range("B8:D39").Copy Destination:=Sheets("Print").Range("B59")

    Else

     msg = MsgBox("Print page is full,Do you need to clear the page", vbQuestion + vbYesNo, "User Repsonse")

        If msg = vbYes Then

            clear_content = MsgBox("Warning! Print data will be erased completly", vbQuestion + vbYesNo, "user response")

            If clear_content = vbYes Then

                Sheets("Print").Range("B8:J39").ClearContents
                Sheets("Print").Range("C44:J50").ClearContents

                Sheets("Print").Range("B59:J90").ClearContents
                Sheets("Print").Range("c95:J101").ClearContents

            End If

        End If

    End If

End Sub

There are total 6 sheets, where 4 sheets contains data and in 5th sheet this "transfer" button is there. When i run the main program ,which will paste the result in this 5th page, this transfer button is placing randomly when my main code runs.
before code run](https://i.stack.imgur.com/mqarC.png)

Aftercode run]


问:
Trend SDK for Python Runtime 3.9
We are using deepsecurity package for reporting purpose, it was working in older versions (until 3.7) however it fails for 3.9 with below error

```<code>{
"errorMessage": "[Errno 38] Function not implemented",
"errorType": "OSError",
"requestId": "b628e51a-1f8e-480e-b9ba-25712b296927",
</code>```

code where it fails: api_instance = deepsecurity.ReportTemplatesApi(deepsecurity.ApiClient(configuration))

Tried changing versions of python run time, it works until 3.7

Title: Trend SDK for Python Runtime 3.9

Body:
We are using deepsecurity package for reporting purpose, it was working in older versions (until 3.7) however it fails for 3.9 with below error

{
"errorMessage": "[Errno 38] Function not implemented",
"errorType": "OSError",
"requestId": "b628e51a-1f8e-480e-b9ba-25712b296927",

code where it fails: api_instance = deepsecurity.ReportTemplatesApi(deepsecurity.ApiClient(configuration))

Tried changing versions of python run time, it works until 3.7


问:
Python manage.py dumpdata killed prematurely
I'm migrating a database from MySQL to Postgres. This question has been very helpful. When running the python manage.py dumpdata --exclude contenttypes --indent=4 --natural-foreign > everything_else.json to create a json fixture the connection is aborted by the database server. All other steps have been successful.

The MySQL database is hosted on RDS and the connection is aborted at the same point in the file each time I try to run this (file size is always 12288 bytes). Logs from the RDS instance state the problem as follows (db, user and host changed to dummy values):

```<code>[Note] Aborted connection 600000 to db: 'mydb' user: 'myUsername' host: '127.0.0.1' (Got an error writing communication packets)
</code>```

In the terminal the message is simply killed.

Why would this error be happening and how can I create this json fixture?

Update

To test for timeout issues I've followed the advice in this post to change default timeout values. This has no effect on the problem.

I've also tried modifying the DB instance to one with more memory etc. This had no effect.

Further update

I didn't get to the bottom of this but instead took a different route and used AWS database migration service (DMS). There's a good walkthrough for this here. For my small ~5GB database the migration process took 5 minutes with negligible costs on the smallest DMS instance.

Body:
I'm migrating a database from MySQL to Postgres. This question has been very helpful. When running the python manage.py dumpdata --exclude contenttypes --indent=4 --natural-foreign > everything_else.json to create a json fixture the connection is aborted by the database server. All other steps have been successful.

The MySQL database is hosted on RDS and the connection is aborted at the same point in the file each time I try to run this (file size is always 12288 bytes). Logs from the RDS instance state the problem as follows (db, user and host changed to dummy values):

[Note] Aborted connection 600000 to db: 'mydb' user: 'myUsername' host: '127.0.0.1' (Got an error writing communication packets)

In the terminal the message is simply killed.

Why would this error be happening and how can I create this json fixture?

Update

To test for timeout issues I've followed the advice in this post to change default timeout values. This has no effect on the problem.

I've also tried modifying the DB instance to one with more memory etc. This had no effect.

Further update

I didn't get to the bottom of this but instead took a different route and used AWS database migration service (DMS). There's a good walkthrough for this here. For my small ~5GB database the migration process took 5 minutes with negligible costs on the smallest DMS instance.


问:
why does Svelte warn me about needed props that I pass to component?
I get this warning from svelte:

Modal.svelte:38 <Modal> was created with unknown prop 'setIsOpen'

it's true that I don't include an export statement for this prop, intentionally.
but this is an essential prop, that I pass to a composed component, using $$restProps, like so:

```<code><ModalInner on:close
        {lastSuccess}
        {errorLocation}
        {...$$restProps}
>
    <slot></slot>
</ModalInner>

</code>```

I think this warning is erroneous. any way to prevent it?

Body:
I get this warning from svelte:

Modal.svelte:38 <Modal> was created with unknown prop 'setIsOpen'

it's true that I don't include an export statement for this prop, intentionally.
but this is an essential prop, that I pass to a composed component, using $$restProps, like so:

<ModalInner on:close
        {lastSuccess}
        {errorLocation}
        {...$$restProps}
>
    <slot></slot>
</ModalInner>

I think this warning is erroneous. any way to prevent it?


问:
How to use ALLEXCEPT filter correctly in a measure calculation without affecting the visual?
In PowerBI, with DAX, I am using the following code to count attendance of campaign members across ALL historical campaigns (stored in a Campaigns table), but I want to only show the attendance in a table visual for campaigns pertaining to a specific campaign I choose using a report page slicer:

```<code>Member Attendance =
var AttendanceCount = calculate(countrows('Campaign Member'), ALLEXCEPT(Campain, Campaign[Id]),'Campaign Member'[Status]="Attended")
return AttendanceCount
</code>```

While the calculation is correct, the table I've constructed to visualize the results now ALSO ignores the Campaign ID filter (which would be activated by a slicer on my report page). This means the visual lists all campaign members, even those that aren't in the specific campaign I've filtered using a slicer on the report page

My visual with Campaign B filter on in report page. This result is not desired because I have a slicer that should filter the visual so that only Campaign B, Orange newsletter members should show up. But the calculation results are correct. Bob only attended one event; so did Amy:

My visual as desired. The filter 'B campaign filter' on my Campaign slicer means that only Bob and Amy show up in the table visual. AND the Member Attendance measure still counts attendance as if the Campaign ID filter is ignored:

Solutions using DAX or otherwise Power BI visual or page filters?

Body:
In PowerBI, with DAX, I am using the following code to count attendance of campaign members across ALL historical campaigns (stored in a Campaigns table), but I want to only show the attendance in a table visual for campaigns pertaining to a specific campaign I choose using a report page slicer:

Member Attendance =
var AttendanceCount = calculate(countrows('Campaign Member'), ALLEXCEPT(Campain, Campaign[Id]),'Campaign Member'[Status]="Attended")
return AttendanceCount

While the calculation is correct, the table I've constructed to visualize the results now ALSO ignores the Campaign ID filter (which would be activated by a slicer on my report page). This means the visual lists all campaign members, even those that aren't in the specific campaign I've filtered using a slicer on the report page

My visual with Campaign B filter on in report page. This result is not desired because I have a slicer that should filter the visual so that only Campaign B, Orange newsletter members should show up. But the calculation results are correct. Bob only attended one event; so did Amy:

My visual as desired. The filter 'B campaign filter' on my Campaign slicer means that only Bob and Amy show up in the table visual. AND the Member Attendance measure still counts attendance as if the Campaign ID filter is ignored:

Solutions using DAX or otherwise Power BI visual or page filters?


问:
influxdb v2 startup error when replication is enabled and files inside replicationq folder deleted
I am not able to start influxdb on windows after moving the data directory, which seems to have deleted replicationq files. Now when I try to start influxd it gives following error

```<code>2022-12-09T15:40:58.383788Z     error   failed to open replication stream durable queue {"log_id": "0eetaSmW000", "service": "replications", "error": "open data\replicationq\0a689fa6d6e8c000: The system cannot find the file specified.", "id": "0a689fa6d6e8c000"}
2022-12-09T15:40:58.383788Z     error   Failed to open replications service     {"log_id": "0eetaSmW000", "error": "startup tasks for replications durable queue management failed, see server logs for details"}Error: startup tasks for replications durable queue management failed, see server logs for details
</code>```

I have tried to see if there is any config option is available where I can ignore this startup error

Body:
I am not able to start influxdb on windows after moving the data directory, which seems to have deleted replicationq files. Now when I try to start influxd it gives following error

2022-12-09T15:40:58.383788Z     error   failed to open replication stream durable queue {"log_id": "0eetaSmW000", "service": "replications", "error": "open data\replicationq\0a689fa6d6e8c000: The system cannot find the file specified.", "id": "0a689fa6d6e8c000"}
2022-12-09T15:40:58.383788Z     error   Failed to open replications service     {"log_id": "0eetaSmW000", "error": "startup tasks for replications durable queue management failed, see server logs for details"}Error: startup tasks for replications durable queue management failed, see server logs for details

I have tried to see if there is any config option is available where I can ignore this startup error


问:
how to access specific item from multiple entity room database, if chilld entity is empty then hide this item

hello, I have three entity, 1.noteEntity 2.timeEntity 3.favouriteEntity

If any item is added to favourite entity then show only these item in recyclerView.

this is my note apps. if any note item is added to favourite. and I want to access only item which item is added favourite. please help me.

Dao object

```<code>
@Transaction
@Query("SELECT * from note_new ORDER BY mID DESC")
fun getNoteAndTimeDESC(): Flow<List<NtityAndTime>>

@Transaction
@Query("SELECT * from note_new ORDER BY title ASC")
fun getNoteAndTimeASC(): Flow<List<NtityAndTime>>

@Query("SELECT * FROM note_new WHERE title LIKE ( :searchQuery) ORDER BY mID DESC")
fun getSearchDatabase(searchQuery: String?): Flow<List<NtityAndTime>>
</code>```

    here my all entity relations

```<code>class NtityAndTime(
@Embedded
var nTity: NTity? = null,
@Relation(
parentColumn = "mID",
entityColumn = "timeID",
)
val timeEntity: TimeEntity? = null,

    @Relation(
        parentColumn = "mID",
        entityColumn = "alarmID"
    )
    val alarmBox: AlarmBox? = null,

    @Relation(
        parentColumn = "mID",
        entityColumn = "fabId"
    )
    val favourite: Favourite? = null
</code>```

this is my note apps, if any note item is added to favourite.
then, favourite activity will show only favourite note item. not all item.

Body:
hello, I have three entity, 1.noteEntity 2.timeEntity 3.favouriteEntity

If any item is added to favourite entity then show only these item in recyclerView.

this is my note apps. if any note item is added to favourite. and I want to access only item which item is added favourite. please help me.

Dao object

@Transaction
@Query("SELECT * from note_new ORDER BY mID DESC")
fun getNoteAndTimeDESC(): Flow<List<NtityAndTime>>

@Transaction
@Query("SELECT * from note_new ORDER BY title ASC")
fun getNoteAndTimeASC(): Flow<List<NtityAndTime>>

@Query("SELECT * FROM note_new WHERE title LIKE ( :searchQuery) ORDER BY mID DESC")
fun getSearchDatabase(searchQuery: String?): Flow<List<NtityAndTime>>

    here my all entity relations

class NtityAndTime(
@Embedded
var nTity: NTity? = null,
@Relation(
parentColumn = "mID",
entityColumn = "timeID",
)
val timeEntity: TimeEntity? = null,

    @Relation(
        parentColumn = "mID",
        entityColumn = "alarmID"
    )
    val alarmBox: AlarmBox? = null,

    @Relation(
        parentColumn = "mID",
        entityColumn = "fabId"
    )
    val favourite: Favourite? = null

this is my note apps, if any note item is added to favourite.
then, favourite activity will show only favourite note item. not all item.


问:
Js Heap out of memory error for packing source images into a texture atlas pixel by pixel
I have this pack function that packs a lot of source images into one texture atlas:

```<code>  pack() {
    let { padding } = this

    let sources = this.entries

    let { w, h } = potpack(sources.map(_ => _.packed))

    let page = {
      width: w,
      height: h,
      pixels: []
    }

    this.pages.push(new ImageSave(page))

    for (let i = 0; i < sources.length; i++) {
      let dst = sources[i].packed,
        src = sources[i].pixels

      let sw = sources[i].frame.w,
        sh = sources[i].frame.h

      for (let x = 0; x < sw; x++) {
        for (let y = 0; y < sh; y++) {
          let sx = x + padding
          let sy = y + padding

          page.pixels[(dst.x + sx + (dst.y + sy) * page.width) * 4 + 0] =
            src[(x + y * sw) * 4 + 0]

          page.pixels[(dst.x + sx + (dst.y + sy) * page.width) * 4 + 1] =
            src[(x + y * sw) * 4 + 1]

          page.pixels[(dst.x + sx + (dst.y + sy) * page.width) * 4 + 2] =
            src[(x + y * sw) * 4 + 2]

          page.pixels[(dst.x + sx + (dst.y + sy) * page.width) * 4 + 3] =
            src[(x + y * sw) * 4 + 3]
        }
      }

    }

  }
</code>```

The problem is the nested for loops that copies the source image pixels into destination image. It throws Heap Out of Memory error.

I don't understand how JS allocates a lot of memory to execute this. Because source images doesn't exceed 100mb in file size.

I reckon this is because I treat one pixel data as a number which takes four bytes which is four times more than what it should be, I am not sure.

Can someone explain what is going on, and how can I fix this issue.

Body:
I have this pack function that packs a lot of source images into one texture atlas:

  pack() {
    let { padding } = this

    let sources = this.entries

    let { w, h } = potpack(sources.map(_ => _.packed))

    let page = {
      width: w,
      height: h,
      pixels: []
    }

    this.pages.push(new ImageSave(page))

    for (let i = 0; i < sources.length; i++) {
      let dst = sources[i].packed,
        src = sources[i].pixels

      let sw = sources[i].frame.w,
        sh = sources[i].frame.h

      for (let x = 0; x < sw; x++) {
        for (let y = 0; y < sh; y++) {
          let sx = x + padding
          let sy = y + padding

          page.pixels[(dst.x + sx + (dst.y + sy) * page.width) * 4 + 0] =
            src[(x + y * sw) * 4 + 0]

          page.pixels[(dst.x + sx + (dst.y + sy) * page.width) * 4 + 1] =
            src[(x + y * sw) * 4 + 1]

          page.pixels[(dst.x + sx + (dst.y + sy) * page.width) * 4 + 2] =
            src[(x + y * sw) * 4 + 2]

          page.pixels[(dst.x + sx + (dst.y + sy) * page.width) * 4 + 3] =
            src[(x + y * sw) * 4 + 3]
        }
      }

    }

  }

The problem is the nested for loops that copies the source image pixels into destination image. It throws Heap Out of Memory error.

I don't understand how JS allocates a lot of memory to execute this. Because source images doesn't exceed 100mb in file size.

I reckon this is because I treat one pixel data as a number which takes four bytes which is four times more than what it should be, I am not sure.

Can someone explain what is going on, and how can I fix this issue.


问:
Read excel file function, code freezes ( Python, pandas)
The following line reads a specific excel file from a series of enumerated files, and saves a subset of a column from such a file into a vector. The actual reading is done as a function, so that the vectors corresponding to different Excel files can be compared easily

```<code>import pandas as pd
import numpy as np

def fetch_excel(x):
    df_x = pd.read_excel(f"D00{x}_balance.xlsx")
    return df_x

T = np.zeros(3000)

for i in range(0, 3000):
    T[i] = fetch_excel(1).iloc[i+18, 0]
</code>```

But when I try to do something simple, like print the first element of T the code just freezes and does not execute. I think the problem lies in the for loop. I can call on the function just fine if I comment it out.

Body:
The following line reads a specific excel file from a series of enumerated files, and saves a subset of a column from such a file into a vector. The actual reading is done as a function, so that the vectors corresponding to different Excel files can be compared easily

import pandas as pd
import numpy as np

def fetch_excel(x):
    df_x = pd.read_excel(f"D00{x}_balance.xlsx")
    return df_x

T = np.zeros(3000)

for i in range(0, 3000):
    T[i] = fetch_excel(1).iloc[i+18, 0]

But when I try to do something simple, like print the first element of T the code just freezes and does not execute. I think the problem lies in the for loop. I can call on the function just fine if I comment it out.


问:
Unable to save reports to PowerBI Report Server - Create with Recent Version
I have been struggling to upload reports created with PowerBI Desktop to our PowerBi Report server.

It continually tells me:

"We're not able to upload this report. The report was created with a recent version of Power BI Desktop that is not yet supported by this server."

I have researched online and the most common advice I find is to make sure that the PowerBI Report Server is the most recent version and to be sure you are using the proper version of PowerBI desktop for this. I have done that, to no avail.

PowerBI Report Server:

PowerBI Desktop:

I have tried both the 32-bit and 64-bit versions of the desktop client.

I am using a version of Power BI Desktop that is optimized for use with PowerBI Report Server.

I am not sure what else to try.  I cannot save from the client, nor can I upload via the browser. I do have one report that I have been able to upload via the browser. It was an old report (from 2020) that I found on my computer. It uploaded and seems to work fine, but I have no idea what version of PowerBI Desktop it was created in, and when I try to open it and save it in the new version of PowerBI Desktop, it fails.


问:
How can i add paginator and filter to django
Hai I am trying to add a paginator to the Django filter But when i am trying to add if the filter containing category is zero Django still shows the data

This is my views.py file

```<code>class blogview(ListView):
    model = wallpapers
    template_name = 'blogs/blogs.html'
    context_object_name = 'blogs'
    ordering = '-created_on', '-time'
    paginate_by = 2

    def get(self, request, *args, **kwargs):
        try:
            ba = blog.objects.all().order_by('-created_on', '-time')
            p = Paginator(ba, 2)
            page_number = request.GET.get('page')
            page_obj = p.get_page(page_number)
            filter = BlogFilter(self.request.GET, queryset=blog.objects.all())
        except blog.DoesNotExist:
            return render(request, 'blogs/blogs.html')
        context = {
            'page_obj':page_obj,
            'filter': filter
        }
        return render(request, 'blogs/blogs.html', context)
</code>```

This is my template file

```<code><ul>
  {% for w in page_obj %}
  <li>
    <a href="{% url 'blogdetails' w.slug %}" data-fancybox data-fancybox="gallery" data-caption="{{w.title}}">
      <img src="{{w.image.url}}" alt="{{w.title}}" loading="lazy">
    </a>
  </li>
  {% endfor %}
  <li></li>
</ul>
</code>```

How can I add pagination and filter to this view and display contents according to that? Now pagination works but if the filter category contains zero elements data will be shown

Body:
Hai I am trying to add a paginator to the Django filter But when i am trying to add if the filter containing category is zero Django still shows the data

This is my views.py file

class blogview(ListView):
    model = wallpapers
    template_name = 'blogs/blogs.html'
    context_object_name = 'blogs'
    ordering = '-created_on', '-time'
    paginate_by = 2

    def get(self, request, *args, **kwargs):
        try:
            ba = blog.objects.all().order_by('-created_on', '-time')
            p = Paginator(ba, 2)
            page_number = request.GET.get('page')
            page_obj = p.get_page(page_number)
            filter = BlogFilter(self.request.GET, queryset=blog.objects.all())
        except blog.DoesNotExist:
            return render(request, 'blogs/blogs.html')
        context = {
            'page_obj':page_obj,
            'filter': filter
        }
        return render(request, 'blogs/blogs.html', context)

This is my template file

  {% for w in page_obj %}

  {% endfor %}

How can I add pagination and filter to this view and display contents according to that? Now pagination works but if the filter category contains zero elements data will be shown


问:
Get Access to Controller Render Models in OpenXR
I am developing with OpenXR (using the C API) and using mainly a Quest 2 headset for testing (but also other systems), and need to be able to load and render controller models (and preferrably be able to animate button presses etc.). I have previously used OpenVR, where controller models for different vendors are available through a common interface (although only static models). With OpenXR, I am having a hard time understanding how to get access to controller models, at least on the test system. I have found the "XR_MSFT_controller_model" extension, which seems to have the functionality that I am looking for. However, the Oculus runtime does not report this as a supported extension (maybe vendors do not implement each others interfaces? That's one of the things that I am trying to understand). My other test systems are HTC Vive and Valve Index, but I haven't come to testing this problem with those yes. The Oculus runtime is version 1.79.0, and I am using the 1.0.25 version of the OpenXR API.

So my questions then are:

Is there a common interface for loading controller models/meshes in OpenXR, and if so, which interface is that?

If not, are there separate interfaces for all vendors, and what are they, e.g. for Quest 2?


问:
Validate that EF can understand expression tree
I wonder if there is any way to validate a Expression towards EF core without using a real database.

We could of course do the validation in a integration tests, but It would be very helpful if we could ensure that the expression is valid already in a unit test.

To me, a novice, it feels like pretty basic functionality. Despite this I have yet to find any solution when looking around on the internet.

Any insight would be appreciated.

Edit:
To summarize, I do not need to validate the sql ( does it find table X etc ) rather I only want to know that EF can generate a query string from the expression tree.


问:
How can I connect a DLL file with a browser based softphone?
we use CXOne within our Service Now system using the SiX agent. It is a phone system completely within the Service Now webpage.

I have been requested to try and see if I can implement Blynclights by having them make noise, change color etc. when a call comes in or our call agents are on the phone. I've been researching for a few weeks now to try and figure out the best way to do this. The SDK is a DLL file and I've been able to manipulate it through PowerShell and C# fine, but I am having trouble figuring out a way connecting this to try and read when a call comes in and end.

I tried creating a PowerShell script originally to read if the browser was using the microphone. I tried doing it through C# and the SDK of the headsets we use (Jabra). I tried creating a Chrome Extension but I'm running into a roadblock of accessing the DLL file.


问:
scrollIntoView({behavior: "smooth}) doesn't work with React in Google Chrome
I'm working in a React Project and I want to trigger a scroll down when changing a state. I tried in firefox and it works perfectly but in Chrome it just doesn't work at all.

this is the code :

```<code>  const chartDiv = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (chartScenarioId) chartDiv.current?.scrollIntoView();
  }, [chartDiv.current, chartScenarioId]);

</code>```
```<code><div ref={ref}>
      {chartScenarioId && (
        <div className="mt-16" style={{ height: "800px" }}>
          {isFetching ? <Spinner centered /> : <Bar options={{}} data={{ datasets, labels }} plugins={[]} />}
        </div>
      )}
    </div>
</code>```

I have googled some solutions but nothing seems to work.

Body:
I'm working in a React Project and I want to trigger a scroll down when changing a state. I tried in firefox and it works perfectly but in Chrome it just doesn't work at all.

this is the code :

  const chartDiv = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (chartScenarioId) chartDiv.current?.scrollIntoView();
  }, [chartDiv.current, chartScenarioId]);

      {chartScenarioId && (

          {isFetching ? <Spinner centered /> : <Bar options={{}} data={{ datasets, labels }} plugins={[]} />}

      )}

I have googled some solutions but nothing seems to work.