问:
How to detect pattern and frequency in a column of characters, using R?
I have a df which shows an "activity chain" of people, which looks like this (snipet at the bottom of question):

```<code>head(agents)
   id                                                                                leg_activity
1   9                                                                                home, adpt, shop, car_passenger, home, adpt, work, adpt, home, work, outside, pt, home
2  10 home, pt, outside, pt, home, car, leisure, car, other, car, leisure, car, leisure, car, other, car, leisure, car, other, car, leisure, car, home, adpt, leisure, adpt, home
3  11                                                                                home, work, adpt, home
4  96                                                                                home, car, work, car, home, work, adpt, home
5  97                              home, adpt, work, car_passenger, leisure, car_passenger, work, adpt, home, car_passenger, outside, car_passenger, outside, car_passenger, home
6 101                                       home, bike, outside, car_passenger, outside, car_passenger, outside, bike, home, adpt, leisure, adpt, home, bike, leisure, bike, home
</code>```

What I'm interested in is to detect a pattern of the occurrences of adpt. The simplest way is to use the count() function, which gives me a frequency table as an output.  Unfortunately, this result will be misleading.

This is how that looks:

```<code>x                                 freq
home, adpt, work, adpt, home      2071
home, adpt, shop, adpt, home      653
home, adpt, education, adpt, home 545
home, pt, work, adpt, home        492
home, adpt, work, pt, home        468
home, adpt, work, home            283
</code>```

The problem with this approach is that I can't detect patterns in longer activity chains; for example:

```<code> home, adpt, education, adpt, education, adpt, home, car, work, car, home, shop, adpt, home
</code>```

This case has at the beginning an activity chain, which is very frequent, but as further activities are followed, it does not count with the count function.

Is there a way to use a count function that also takes into consideration what happens inside the cell?
So it would be interesting to have a table which shows all combinations possible and their frequency, like this:

```<code>x                                freq
home, adpt, home                 10
home, adpt, home, pt, work, home 4
home, pt, work, home             2
</code>```

Thank you a lot for the help!

the data:

```<code>structure(list(id = c(9L, 10L, 11L, 96L, 97L, 101L, 103L, 248L,
499L, 1044L, 1215L, 1238L, 1458L, 1569L, 1615L, 1626L, 1734L,
1735L, 1790L, 1912L, 9040L, 14858L, 14859L, 14967L, 15011L, 15012L,
15015L, 15045L, 15050L, 15058L, 15060L, 15086L, 15088L, 15094L,
15109L, 15113L, 15152L, 15157L, 15192L, 15193L, 15222L, 15230L,
15231L, 15234L, 15235L, 15237L, 15256L, 15257L, 15258L, 15269L,
15270L, 15318L, 15319L, 15338L, 15369L, 15371L, 15396L, 15397L,
15399L, 15404L, 15505L, 15506L, 15515L, 15516L, 15525L, 15542L,
15593L, 15602L, 15608L, 15643L, 15667L, 15727L, 15728L, 15729L,
15752L, 15775L, 15808L, 15851L, 15869L, 15881L, 15882L, 15960L,
15962L, 15966L, 16058L, 16107L, 16174L, 16229L, 16237L, 16238L,
16291L, 16333L, 16416L, 16418L, 16449L, 16450L, 16451L, 16491L,
16506L, 16508L), leg_activity = c("home, adpt, shop, car_passenger, home, adpt, work, adpt, home, work, outside, pt, home",
"home, pt, outside, pt, home, car, leisure, car, other, car, leisure, car, leisure, car, other, car, leisure, car, other, car, leisure, car, home, adpt, leisure, adpt, home",
"home, work, adpt, home", "home, car, work, car, home, work, adpt, home",
"home, adpt, work, car_passenger, leisure, car_passenger, work, adpt, home, car_passenger, outside, car_passenger, outside, car_passenger, home",
"home, bike, outside, car_passenger, outside, car_passenger, outside, bike, home, adpt, leisure, adpt, home, bike, leisure, bike, home",
"home, adpt, work, adpt, home, walk, other, pt, home", "home, adpt, work, walk, home, adpt, work, walk, home",
"home, adpt, leisure, adpt, home, bike, outside, bike, home",
"home, pt, work, adpt, home, adpt, work, adpt, home", "home, adpt, work, adpt, home, car, outside, car, work, car, work, car, home",
"home, work, leisure, adpt, home", "home, outside, pt, home, adpt, leisure, adpt, home",
"home, car_passenger, leisure, walk, work, walk, leisure, walk, work, adpt, home, walk, home",
"home, adpt, work, walk, work, walk, work, pt, home", "home, car, work, pt, leisure, adpt, work, car, home, car, home",
"home, adpt, other, adpt, home, car, home", "home, adpt, other, adpt, home",
"home, education, walk, shop, walk, education, pt, outside, home, adpt, leisure, adpt, home",
"home, adpt, work, adpt, home, walk, home", "home, adpt, work, pt, leisure, adpt, work, adpt, work, adpt, home, adpt, other, walk, home",
"home, adpt, work, adpt, home, adpt, work, adpt, home, walk, leisure, walk, home",
"home, adpt, work, adpt, home, work, adpt, home, walk, leisure, walk, home",
"home, adpt, work, adpt, home, car_passenger, outside, car_passenger, leisure, car_passenger, home, car_passenger, home",
"home, adpt, other, adpt, home, car, work, car, home", "home, adpt, education, adpt, leisure, adpt, home, walk, leisure, walk, home",
"home, car_passenger, other, pt, home, walk, other, walk, home, car_passenger, other, walk, home, adpt, other, adpt, home",
"home, work, pt, work, adpt, work, adpt, home", "home, adpt, leisure, adpt, home, car, shop, car, other, car, home",
"home, adpt, work, adpt, home, walk, other, adpt, home", "home, adpt, work, adpt, home, car_passenger, leisure, car_passenger, home",
"home, car, other, car, home, adpt, shop, adpt, home", "home, pt, work, adpt, home",
"home, adpt, work, adpt, home", "home, adpt, work, adpt, home",
"home, walk, education, adpt, home, walk, education, walk, home, bike, leisure, bike, home",
"home, adpt, shop, adpt, home, car, home", "home, adpt, leisure, walk, leisure, walk, leisure, adpt, home",
"home, adpt, shop, pt, home, adpt, other, adpt, home", "home, adpt, other, adpt, home, car_passenger, leisure, walk, home",
"home, adpt, work, adpt, home, car_passenger, shop, car_passenger, home",
"home, adpt, other, adpt, work, adpt, home", "home, adpt, work, adpt, home, adpt, other, walk, shop, walk, home, car, outside, car, outside, car, outside, car, home",
"home, adpt, other, adpt, home", "home, adpt, education, adpt, home, adpt, education, adpt, home",
"home, pt, work, adpt, work, adpt, work, adpt, work, adpt, home, adpt, work, adpt, home",
"home, walk, other, car_passenger, education, walk, home, car_passenger, education, adpt, home",
"home, walk, shop, walk, home, walk, leisure, adpt, leisure, adpt, home",
"home, adpt, work, adpt, home, walk, shop, walk, home, walk, leisure, walk, home, walk, home",
"home, adpt, leisure, adpt, home", "home, walk, leisure, walk, home, adpt, other, adpt, shop, walk, leisure, walk, home",
"home, pt, leisure, adpt, home, pt, outside, pt, home, bike, leisure, bike, home",
"home, pt, outside, pt, home, walk, home, walk, other, adpt, shop, pt, home, car_passenger, leisure, adpt, home",
"home, adpt, work, adpt, home, adpt, shop, adpt, work, adpt, home",
"home, adpt, shop, adpt, other, walk, home", "home, walk, other, walk, home, walk, home, adpt, other, adpt, home, adpt, shop, adpt, home, car, other, car, home, adpt, other, adpt, home",
"home, adpt, leisure, pt, home", "home, leisure, adpt, home",
"home, adpt, leisure, pt, shop, walk, home, walk, shop, walk, home",
"home, car, outside, car, outside, leisure, car, outside, car, outside, car, home, adpt, other, adpt, home",
"home, adpt, work, adpt, shop, walk, home", "home, adpt, other, walk, work, adpt, home, adpt, other, adpt, work, adpt, home, adpt, leisure, adpt, home",
"home, adpt, leisure, adpt, home, car, shop, car, home", "home, walk, shop, adpt, home, car, other, car, home, adpt, other, adpt, home",
"home, walk, leisure, walk, home, adpt, work, adpt, home", "home, adpt, work, adpt, home",
"home, adpt, leisure, pt, shop, adpt, home, adpt, leisure, walk, home",
"home, walk, other, walk, leisure, walk, home, car, leisure, car, home, walk, leisure, adpt, home",
"home, adpt, work, adpt, home", "home, walk, leisure, walk, home, adpt, leisure, adpt, home, adpt, leisure, walk, home",
"home, walk, home, walk, shop, walk, home, walk, leisure, walk, home, adpt, other, adpt, home",
"home, car_passenger, outside, car_passenger, outside, car_passenger, home, adpt, other, adpt, home",
"home, walk, education, adpt, home", "home, adpt, education, walk, home, bike, education, bike, home",
"home, adpt, other, adpt, home, adpt, shop, pt, home", "home, adpt, other, adpt, shop, walk, home, adpt, leisure, car_passenger, home",
"home, adpt, work, adpt, other, adpt, home", "home, adpt, work, adpt, home",
"home, adpt, work, adpt, home, walk, home", "home, car, work, adpt, leisure, adpt, work, car, home",
"home, adpt, shop, adpt, home, car, other, car, home, car_passenger, outside, car_passenger, home",
"home, adpt, work, pt, home, car, shop, car, home", "home, walk, other, adpt, work, adpt, shop, adpt, shop, adpt, home",
"home, adpt, leisure, adpt, shop, adpt, leisure, pt, home", "home, adpt, leisure, adpt, shop, adpt, home",
"home, car, outside, car, outside, car, outside, car, outside, car, home, adpt, education, pt, home",
"home, adpt, work, adpt, home", "home, adpt, shop, adpt, home",
"home, adpt, education, adpt, home, adpt, education, adpt, home",
"home, adpt, other, adpt, other, walk, leisure, adpt, other, adpt, home",
"home, adpt, work, adpt, home", "home, adpt, work, adpt, home, car, other, car, home",
"home, car, work, car, shop, car, home, adpt, work, adpt, home, car, home",
"home, walk, other, walk, education, adpt, home, adpt, education, walk, home, walk, home",
"home, adpt, shop, walk, leisure, adpt, home", "home, adpt, shop, walk, home, adpt, work, adpt, home",
"home, adpt, leisure, adpt, shop, walk, home", "home, walk, other, adpt, shop, walk, home, walk, other, walk, home, walk, other, walk, other, adpt, home",
"home, adpt, education, walk, home, walk, education, walk, home, walk, home",
"home, bike, education, bike, home, adpt, education, adpt, home, walk, home"
)), row.names = c(NA, 100L), class = "data.frame")
</code>```

答:
I'm not quite sure what exactly it is you want to do, but I understand that you are interested in detecting a pattern of the occurrences of the activity adpt. This is often done in NLP, below is a solution using the tidytext package. I split up the leg_activity column in what is called n-grams, i.e. I break up the text in consecutive sequence of words. A sequence of two consequtive words is called bi-gram, three consecutive words tri-gram etc. When we then count these n-grams we learn which activities most often preceed adpt and which most often come after adpt.

Here is how to do it forbi-grams:

```<code>df %>%
  unnest_tokens(bigram, leg_activity, token = "ngrams", n = 2) %>%
  filter(str_detect(bigram, "adpt")) %>%
  count(bigram, sort = TRUE)

           bigram   n
1       home adpt 100
2       adpt home  97
3       work adpt  51
4       adpt work  48
5    leisure adpt  27
6      adpt other  26
7      other adpt  26
8    adpt leisure  24
9       adpt shop  22
10      shop adpt  13
11 adpt education  10
12 education adpt  10
</code>```

So adpt is most often preceeded by "home" and "home" is also what comes directly after "adpt" most often. If we were interested in the three activities cosecutively occuring together and including "adpt" we can do the same for tri-grams:

```<code>df %>%
  unnest_tokens(bigram, leg_activity, token = "ngrams", n = 3) %>%  #n is the only thing that changed
  filter(str_detect(bigram, "adpt")) %>%
  count(bigram, sort = TRUE)

                    bigram  n
1                work adpt home 42
2                adpt work adpt 40
3                home adpt work 36
4               home adpt other 22
5               adpt other adpt 21
6             home adpt leisure 20
7             leisure adpt home 19
8               other adpt home 18
9             adpt leisure adpt 16
10               adpt home adpt 15
11               home adpt shop 12
12                adpt home car 11
13               adpt home walk 11
14               adpt shop adpt 11
15          home adpt education 10
16          education adpt home  9
[list continues]
</code>```

This list is considerably longer, since now there are more possible combinations. Here a link to a good tutorial on n-grams if you want to learn more. Is this what you wanted to do?

Body:
I have a df which shows an "activity chain" of people, which looks like this (snipet at the bottom of question):

head(agents)
   id                                                                                leg_activity
1   9                                                                                home, adpt, shop, car_passenger, home, adpt, work, adpt, home, work, outside, pt, home
2  10 home, pt, outside, pt, home, car, leisure, car, other, car, leisure, car, leisure, car, other, car, leisure, car, other, car, leisure, car, home, adpt, leisure, adpt, home
3  11                                                                                home, work, adpt, home
4  96                                                                                home, car, work, car, home, work, adpt, home
5  97                              home, adpt, work, car_passenger, leisure, car_passenger, work, adpt, home, car_passenger, outside, car_passenger, outside, car_passenger, home
6 101                                       home, bike, outside, car_passenger, outside, car_passenger, outside, bike, home, adpt, leisure, adpt, home, bike, leisure, bike, home

What I'm interested in is to detect a pattern of the occurrences of adpt. The simplest way is to use the count() function, which gives me a frequency table as an output.  Unfortunately, this result will be misleading.

This is how that looks:

x                                 freq
home, adpt, work, adpt, home      2071
home, adpt, shop, adpt, home      653
home, adpt, education, adpt, home 545
home, pt, work, adpt, home        492
home, adpt, work, pt, home        468
home, adpt, work, home            283

The problem with this approach is that I can't detect patterns in longer activity chains; for example:

 home, adpt, education, adpt, education, adpt, home, car, work, car, home, shop, adpt, home

This case has at the beginning an activity chain, which is very frequent, but as further activities are followed, it does not count with the count function.

Is there a way to use a count function that also takes into consideration what happens inside the cell?
So it would be interesting to have a table which shows all combinations possible and their frequency, like this:

x                                freq
home, adpt, home                 10
home, adpt, home, pt, work, home 4
home, pt, work, home             2

Thank you a lot for the help!

the data:

structure(list(id = c(9L, 10L, 11L, 96L, 97L, 101L, 103L, 248L,
499L, 1044L, 1215L, 1238L, 1458L, 1569L, 1615L, 1626L, 1734L,
1735L, 1790L, 1912L, 9040L, 14858L, 14859L, 14967L, 15011L, 15012L,
15015L, 15045L, 15050L, 15058L, 15060L, 15086L, 15088L, 15094L,
15109L, 15113L, 15152L, 15157L, 15192L, 15193L, 15222L, 15230L,
15231L, 15234L, 15235L, 15237L, 15256L, 15257L, 15258L, 15269L,
15270L, 15318L, 15319L, 15338L, 15369L, 15371L, 15396L, 15397L,
15399L, 15404L, 15505L, 15506L, 15515L, 15516L, 15525L, 15542L,
15593L, 15602L, 15608L, 15643L, 15667L, 15727L, 15728L, 15729L,
15752L, 15775L, 15808L, 15851L, 15869L, 15881L, 15882L, 15960L,
15962L, 15966L, 16058L, 16107L, 16174L, 16229L, 16237L, 16238L,
16291L, 16333L, 16416L, 16418L, 16449L, 16450L, 16451L, 16491L,
16506L, 16508L), leg_activity = c("home, adpt, shop, car_passenger, home, adpt, work, adpt, home, work, outside, pt, home",
"home, pt, outside, pt, home, car, leisure, car, other, car, leisure, car, leisure, car, other, car, leisure, car, other, car, leisure, car, home, adpt, leisure, adpt, home",
"home, work, adpt, home", "home, car, work, car, home, work, adpt, home",
"home, adpt, work, car_passenger, leisure, car_passenger, work, adpt, home, car_passenger, outside, car_passenger, outside, car_passenger, home",
"home, bike, outside, car_passenger, outside, car_passenger, outside, bike, home, adpt, leisure, adpt, home, bike, leisure, bike, home",
"home, adpt, work, adpt, home, walk, other, pt, home", "home, adpt, work, walk, home, adpt, work, walk, home",
"home, adpt, leisure, adpt, home, bike, outside, bike, home",
"home, pt, work, adpt, home, adpt, work, adpt, home", "home, adpt, work, adpt, home, car, outside, car, work, car, work, car, home",
"home, work, leisure, adpt, home", "home, outside, pt, home, adpt, leisure, adpt, home",
"home, car_passenger, leisure, walk, work, walk, leisure, walk, work, adpt, home, walk, home",
"home, adpt, work, walk, work, walk, work, pt, home", "home, car, work, pt, leisure, adpt, work, car, home, car, home",
"home, adpt, other, adpt, home, car, home", "home, adpt, other, adpt, home",
"home, education, walk, shop, walk, education, pt, outside, home, adpt, leisure, adpt, home",
"home, adpt, work, adpt, home, walk, home", "home, adpt, work, pt, leisure, adpt, work, adpt, work, adpt, home, adpt, other, walk, home",
"home, adpt, work, adpt, home, adpt, work, adpt, home, walk, leisure, walk, home",
"home, adpt, work, adpt, home, work, adpt, home, walk, leisure, walk, home",
"home, adpt, work, adpt, home, car_passenger, outside, car_passenger, leisure, car_passenger, home, car_passenger, home",
"home, adpt, other, adpt, home, car, work, car, home", "home, adpt, education, adpt, leisure, adpt, home, walk, leisure, walk, home",
"home, car_passenger, other, pt, home, walk, other, walk, home, car_passenger, other, walk, home, adpt, other, adpt, home",
"home, work, pt, work, adpt, work, adpt, home", "home, adpt, leisure, adpt, home, car, shop, car, other, car, home",
"home, adpt, work, adpt, home, walk, other, adpt, home", "home, adpt, work, adpt, home, car_passenger, leisure, car_passenger, home",
"home, car, other, car, home, adpt, shop, adpt, home", "home, pt, work, adpt, home",
"home, adpt, work, adpt, home", "home, adpt, work, adpt, home",
"home, walk, education, adpt, home, walk, education, walk, home, bike, leisure, bike, home",
"home, adpt, shop, adpt, home, car, home", "home, adpt, leisure, walk, leisure, walk, leisure, adpt, home",
"home, adpt, shop, pt, home, adpt, other, adpt, home", "home, adpt, other, adpt, home, car_passenger, leisure, walk, home",
"home, adpt, work, adpt, home, car_passenger, shop, car_passenger, home",
"home, adpt, other, adpt, work, adpt, home", "home, adpt, work, adpt, home, adpt, other, walk, shop, walk, home, car, outside, car, outside, car, outside, car, home",
"home, adpt, other, adpt, home", "home, adpt, education, adpt, home, adpt, education, adpt, home",
"home, pt, work, adpt, work, adpt, work, adpt, work, adpt, home, adpt, work, adpt, home",
"home, walk, other, car_passenger, education, walk, home, car_passenger, education, adpt, home",
"home, walk, shop, walk, home, walk, leisure, adpt, leisure, adpt, home",
"home, adpt, work, adpt, home, walk, shop, walk, home, walk, leisure, walk, home, walk, home",
"home, adpt, leisure, adpt, home", "home, walk, leisure, walk, home, adpt, other, adpt, shop, walk, leisure, walk, home",
"home, pt, leisure, adpt, home, pt, outside, pt, home, bike, leisure, bike, home",
"home, pt, outside, pt, home, walk, home, walk, other, adpt, shop, pt, home, car_passenger, leisure, adpt, home",
"home, adpt, work, adpt, home, adpt, shop, adpt, work, adpt, home",
"home, adpt, shop, adpt, other, walk, home", "home, walk, other, walk, home, walk, home, adpt, other, adpt, home, adpt, shop, adpt, home, car, other, car, home, adpt, other, adpt, home",
"home, adpt, leisure, pt, home", "home, leisure, adpt, home",
"home, adpt, leisure, pt, shop, walk, home, walk, shop, walk, home",
"home, car, outside, car, outside, leisure, car, outside, car, outside, car, home, adpt, other, adpt, home",
"home, adpt, work, adpt, shop, walk, home", "home, adpt, other, walk, work, adpt, home, adpt, other, adpt, work, adpt, home, adpt, leisure, adpt, home",
"home, adpt, leisure, adpt, home, car, shop, car, home", "home, walk, shop, adpt, home, car, other, car, home, adpt, other, adpt, home",
"home, walk, leisure, walk, home, adpt, work, adpt, home", "home, adpt, work, adpt, home",
"home, adpt, leisure, pt, shop, adpt, home, adpt, leisure, walk, home",
"home, walk, other, walk, leisure, walk, home, car, leisure, car, home, walk, leisure, adpt, home",
"home, adpt, work, adpt, home", "home, walk, leisure, walk, home, adpt, leisure, adpt, home, adpt, leisure, walk, home",
"home, walk, home, walk, shop, walk, home, walk, leisure, walk, home, adpt, other, adpt, home",
"home, car_passenger, outside, car_passenger, outside, car_passenger, home, adpt, other, adpt, home",
"home, walk, education, adpt, home", "home, adpt, education, walk, home, bike, education, bike, home",
"home, adpt, other, adpt, home, adpt, shop, pt, home", "home, adpt, other, adpt, shop, walk, home, adpt, leisure, car_passenger, home",
"home, adpt, work, adpt, other, adpt, home", "home, adpt, work, adpt, home",
"home, adpt, work, adpt, home, walk, home", "home, car, work, adpt, leisure, adpt, work, car, home",
"home, adpt, shop, adpt, home, car, other, car, home, car_passenger, outside, car_passenger, home",
"home, adpt, work, pt, home, car, shop, car, home", "home, walk, other, adpt, work, adpt, shop, adpt, shop, adpt, home",
"home, adpt, leisure, adpt, shop, adpt, leisure, pt, home", "home, adpt, leisure, adpt, shop, adpt, home",
"home, car, outside, car, outside, car, outside, car, outside, car, home, adpt, education, pt, home",
"home, adpt, work, adpt, home", "home, adpt, shop, adpt, home",
"home, adpt, education, adpt, home, adpt, education, adpt, home",
"home, adpt, other, adpt, other, walk, leisure, adpt, other, adpt, home",
"home, adpt, work, adpt, home", "home, adpt, work, adpt, home, car, other, car, home",
"home, car, work, car, shop, car, home, adpt, work, adpt, home, car, home",
"home, walk, other, walk, education, adpt, home, adpt, education, walk, home, walk, home",
"home, adpt, shop, walk, leisure, adpt, home", "home, adpt, shop, walk, home, adpt, work, adpt, home",
"home, adpt, leisure, adpt, shop, walk, home", "home, walk, other, adpt, shop, walk, home, walk, other, walk, home, walk, other, walk, other, adpt, home",
"home, adpt, education, walk, home, walk, education, walk, home, walk, home",
"home, bike, education, bike, home, adpt, education, adpt, home, walk, home"
)), row.names = c(NA, 100L), class = "data.frame")

Body:
I'm not quite sure what exactly it is you want to do, but I understand that you are interested in detecting a pattern of the occurrences of the activity adpt. This is often done in NLP, below is a solution using the tidytext package. I split up the leg_activity column in what is called n-grams, i.e. I break up the text in consecutive sequence of words. A sequence of two consequtive words is called bi-gram, three consecutive words tri-gram etc. When we then count these n-grams we learn which activities most often preceed adpt and which most often come after adpt.

Here is how to do it forbi-grams:

df %>%
  unnest_tokens(bigram, leg_activity, token = "ngrams", n = 2) %>%
  filter(str_detect(bigram, "adpt")) %>%
  count(bigram, sort = TRUE)

           bigram   n
1       home adpt 100
2       adpt home  97
3       work adpt  51
4       adpt work  48
5    leisure adpt  27
6      adpt other  26
7      other adpt  26
8    adpt leisure  24
9       adpt shop  22
10      shop adpt  13
11 adpt education  10
12 education adpt  10

So adpt is most often preceeded by "home" and "home" is also what comes directly after "adpt" most often. If we were interested in the three activities cosecutively occuring together and including "adpt" we can do the same for tri-grams:

df %>%
  unnest_tokens(bigram, leg_activity, token = "ngrams", n = 3) %>%  #n is the only thing that changed
  filter(str_detect(bigram, "adpt")) %>%
  count(bigram, sort = TRUE)

                    bigram  n
1                work adpt home 42
2                adpt work adpt 40
3                home adpt work 36
4               home adpt other 22
5               adpt other adpt 21
6             home adpt leisure 20
7             leisure adpt home 19
8               other adpt home 18
9             adpt leisure adpt 16
10               adpt home adpt 15
11               home adpt shop 12
12                adpt home car 11
13               adpt home walk 11
14               adpt shop adpt 11
15          home adpt education 10
16          education adpt home  9
[list continues]

This list is considerably longer, since now there are more possible combinations. Here a link to a good tutorial on n-grams if you want to learn more. Is this what you wanted to do?


来源: stackexchange

问:
How to play intro, that it's only played when app is installed, when a button is clicked?
Before the user uses the app there is an intro that explains how the app is used. However I want to add a button to the homepage that ables the user to see the intro again. How should I do that?
I already tried to call the class Intro in the class Homepage but nothing happens
Here is the code of my Intro: </p>

```<code>    class Intro : AppCompatActivity() {

private val introSliderAdapter = IntroSliderAdapter(
    listOf(
        IntroSlide("Capture a ignição",
            "Tire uma fotografia á ignição que avista. Por favor mantanha o telemóvel na vertical",
            R.drawable.image1),
        IntroSlide("Localização",
            "É necessário que tenha o GPS ligado do seu telémovel. Ao capturar a fotografia serão automáticamente gravados a sua localização e o ângulo a que o fogo se encontra",
            R.drawable.image2),
        IntroSlide("Envio para os operacionais ",
            "Após os passos anteriores devidamente cumpridos, a informação fornecida será  avaliada por operacionais responsáveis.",
            R.drawable.image3)
    )
)

private var PRIVATE_MODE = 0
private val PREF_NAME = "mindorks-welcome"

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //setContentView(R.layout.activity_main)
    val sharedPref: SharedPreferences = getSharedPreferences(PREF_NAME, PRIVATE_MODE)
    if (sharedPref.getBoolean(PREF_NAME, false)) {
        val homeIntent = Intent(this, HomePage::class.java)
        startActivity(homeIntent)
        finish()
    } else {
        setContentView(R.layout.activity_intro)
        playIntro()
        val editor = sharedPref.edit()
        editor.putBoolean(PREF_NAME, true)
        editor.apply()
    }
}

fun playIntro()
{
    introSliderViewPager.adapter=introSliderAdapter
    setupIndicators()
    setCurrentIndicator(0)
    introSliderViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){
        override fun onPageSelected(position: Int) {
            setCurrentIndicator(position)

        }
    })

    buttonNext.setOnClickListener {
        if(introSliderViewPager.currentItem+1 < introSliderAdapter.itemCount){
            introSliderViewPager.currentItem+=1
        }else{

            Intent(applicationContext, HomePage::class.java).also {
                startActivity(it)
                finish()
            }

        }

    }
    buttonSkip.setOnClickListener {
        Intent(applicationContext, HomePage::class.java).also {
            startActivity(it)
            finish()
        }
    }

}
private fun setupIndicators(){
    val indicators = arrayOfNulls<ImageView>(introSliderAdapter.itemCount)
    val layoutParams : LinearLayout.LayoutParams = LinearLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT
    )
    layoutParams.setMargins(8,0,8,0)
    for (i in indicators.indices){
        indicators[i]  = ImageView(applicationContext)
        indicators[i].apply {
            this?.setImageDrawable(
                ContextCompat.getDrawable(
                    applicationContext,
                    R.drawable.indicator_inactive
                )
            )
            this?.layoutParams = layoutParams
        }
        indicatorsContainer.addView(indicators[i])
    }
}
private fun setCurrentIndicator(index:Int ){
    val childCount = indicatorsContainer.childCount
    for(i in 0 until childCount){
        val imageView = indicatorsContainer[i] as ImageView
        if(i==index){
            imageView.setImageDrawable(
                ContextCompat.getDrawable(
                    applicationContext,
                    R.drawable.indicator_active
                )
            )
            buttonNext.text ="PRÓXIMO"
        }else{
            imageView.setImageDrawable(
                ContextCompat.getDrawable(
                    applicationContext,
                    R.drawable.indicator_inactive
                )
            )
            buttonNext.text ="PRÓXIMO"

        }

    }
    if(index == introSliderAdapter.itemCount -1)
    {
        buttonNext.text ="FIM"
    }
}
 }
</code>```

答:
Add an Intent extra to the Intent that you reopen it with, for example

```<code>intent.putExtra("FORCE", true)
startActivity(intent)
</code>```

Then in your Intro Activity, check both the extra and the SharedPreference to decide whether to finish:

```<code>if (sharedPref.getBoolean(PREF_NAME, false) && !intent.getExtra("FORCE", false)) {
    //...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Before the user uses the app there is an intro that explains how the app is used. However I want to add a button to the homepage that ables the user to see the intro again. How should I do that?
I already tried to call the class Intro in the class Homepage but nothing happens
Here is the code of my Intro:

    class Intro : AppCompatActivity() {

private val introSliderAdapter = IntroSliderAdapter(
    listOf(
        IntroSlide("Capture a ignição",
            "Tire uma fotografia á ignição que avista. Por favor mantanha o telemóvel na vertical",
            R.drawable.image1),
        IntroSlide("Localização",
            "É necessário que tenha o GPS ligado do seu telémovel. Ao capturar a fotografia serão automáticamente gravados a sua localização e o ângulo a que o fogo se encontra",
            R.drawable.image2),
        IntroSlide("Envio para os operacionais ",
            "Após os passos anteriores devidamente cumpridos, a informação fornecida será  avaliada por operacionais responsáveis.",
            R.drawable.image3)
    )
)

private var PRIVATE_MODE = 0
private val PREF_NAME = "mindorks-welcome"

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //setContentView(R.layout.activity_main)
    val sharedPref: SharedPreferences = getSharedPreferences(PREF_NAME, PRIVATE_MODE)
    if (sharedPref.getBoolean(PREF_NAME, false)) {
        val homeIntent = Intent(this, HomePage::class.java)
        startActivity(homeIntent)
        finish()
    } else {
        setContentView(R.layout.activity_intro)
        playIntro()
        val editor = sharedPref.edit()
        editor.putBoolean(PREF_NAME, true)
        editor.apply()
    }
}

fun playIntro()
{
    introSliderViewPager.adapter=introSliderAdapter
    setupIndicators()
    setCurrentIndicator(0)
    introSliderViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){
        override fun onPageSelected(position: Int) {
            setCurrentIndicator(position)

        }
    })

    buttonNext.setOnClickListener {
        if(introSliderViewPager.currentItem+1 < introSliderAdapter.itemCount){
            introSliderViewPager.currentItem+=1
        }else{

            Intent(applicationContext, HomePage::class.java).also {
                startActivity(it)
                finish()
            }

        }

    }
    buttonSkip.setOnClickListener {
        Intent(applicationContext, HomePage::class.java).also {
            startActivity(it)
            finish()
        }
    }

}
private fun setupIndicators(){
    val indicators = arrayOfNulls<ImageView>(introSliderAdapter.itemCount)
    val layoutParams : LinearLayout.LayoutParams = LinearLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT
    )
    layoutParams.setMargins(8,0,8,0)
    for (i in indicators.indices){
        indicators[i]  = ImageView(applicationContext)
        indicators[i].apply {
            this?.setImageDrawable(
                ContextCompat.getDrawable(
                    applicationContext,
                    R.drawable.indicator_inactive
                )
            )
            this?.layoutParams = layoutParams
        }
        indicatorsContainer.addView(indicators[i])
    }
}
private fun setCurrentIndicator(index:Int ){
    val childCount = indicatorsContainer.childCount
    for(i in 0 until childCount){
        val imageView = indicatorsContainer[i] as ImageView
        if(i==index){
            imageView.setImageDrawable(
                ContextCompat.getDrawable(
                    applicationContext,
                    R.drawable.indicator_active
                )
            )
            buttonNext.text ="PRÓXIMO"
        }else{
            imageView.setImageDrawable(
                ContextCompat.getDrawable(
                    applicationContext,
                    R.drawable.indicator_inactive
                )
            )
            buttonNext.text ="PRÓXIMO"

        }

    }
    if(index == introSliderAdapter.itemCount -1)
    {
        buttonNext.text ="FIM"
    }
}
 }

Body:
Add an Intent extra to the Intent that you reopen it with, for example

intent.putExtra("FORCE", true)
startActivity(intent)

Then in your Intro Activity, check both the extra and the SharedPreference to decide whether to finish:

if (sharedPref.getBoolean(PREF_NAME, false) && !intent.getExtra("FORCE", false)) {
    //...


问:
Nested Class factory with tkinter
I'm trying to build a script for import in my future projects.
That Script should create some tk.Frames in a tk.Frame and let me edit the created ones in a main.

I think, the best way to get there is to create a Holder_frame class and put some nested classes in.
so I could call them in my main with Holder_frame.F1.
I tried a lot of code and I ended up here making me an account.
Anyway here is where Im at:

```<code>import tkinter as tk
from tkinter import Frame,Button

class BaseClass(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.master = master
        self.pack()

class Holder_frame(tk.Frame):
    Names = []
    def __init__(self, master, frames=2):
        tk.Frame.__init__(self, master)
        self.master = master
        frame_names = Holder_frame.Names
        for i in range(0,frames):
            frame_names.append("F"+str(i+1))
        print(frame_names)
        Holder_frame.factory()
    def factory():
        print(Holder_frame.Names)
        print(type(BaseClass))
        for idex,i in enumerate (Holder_frame.Names):
            print(i)
            class NestedClass(BaseClass):
                pass

            NestedClass.__name__ = i
            NestedClass.__qualname__ = i

if __name__ == "__main__":
    root = tk.Tk()
    def raise1():
        Holder_frame.F1.tkraise()
    def raise2():
        Holder_frame.F2.tkraise()

    holder=Holder_frame(root,frames=2)
    holder.grid(row=1,column=0)
    b1 = tk.Button(root, text='1', command=raise1)
    b1.grid(row=0,column=0)
    b2 = tk.Button(root, text='2', command=raise2)
    b2.grid(row=0,column=1)

    root.mainloop()
</code>```

Everything works fine, till I try to call a Frame.
(AttributeError 'Holder_frame' object has no attribute 'F1')
I think my problem is the structure but need some help to solve it.

Any suggestions?

答:
One solution to this problem, I think, as I don't fully understand your question, but this here was my solution:

```<code>import tkinter as tk
from tkinter import Frame,Button

class BaseClass(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.master = master
        self.pack()

class Holder_frame(tk.Frame):
    def __init__(self, master, frames=2):
        tk.Frame.__init__(self, master)
        self.master = master
        self.frame_names = []
        for i in range(frames):
            Holder_frame.create_frames("F"+str(i+1), self)

    @classmethod
    def create_frames(cls, name, master):
        setattr(cls, name, tk.Frame(master))

if __name__ == "__main__":
    root = tk.Tk()
    def raise1():
        print(type(Holder_frame.F1))
    def raise2():
        print(type(Holder_frame.F2))

    holder=Holder_frame(root,frames=2)
    holder.grid(row=1,column=0)
    b1 = tk.Button(root, text='1', command=raise1)
    b1.grid(row=0,column=0)
    b2 = tk.Button(root, text='2', command=raise2)
    b2.grid(row=0,column=1)
    print(Holder_frame.__dict__.items())

    root.mainloop()
</code>```

The use of setattr allows one to add variables to the class, just like if you were to type a function into the code. This allows you to access frames from outside the class as somewhat of a "global variable"

I used a file to test if it work outside as an imported module too:

# main.py
from nested_class import Holder_frame
import tkinter as tk

root = tk.Tk()
holder=Holder_frame(root,frames=1000)
holder.grid(row=1,column=0)
print(Holder_frame.__dict__.items())

root.mainloop()
```

<p>I hope this answers your question,</p>

<p>James</p>

<p>EDIT:</p>

<p>After thinking there is, what I think, to be a cleaner system for what you want. With the code from this post one can see that your my written system could be replaced by a <code>ttk.Notebook</code>, and by removing the top bar by using <code>style.layout('TNotebook.Tab', [])</code>, one can see that you would get a frame widget that could have frame widgets inside of it:</p>

<pre class="lang-py prettyprint-override"><code>import tkinter as tk
import tkinter.ttk as ttk

class multiframe_example:
    def __init__(self, master):
        self.master = master

        style = ttk.Style()
        style.layout('TNotebook.Tab', [])
        notebook = ttk.Notebook(self.master)
        notebook.grid(row=0, column=0)

        self.master.grid_rowconfigure(0, weight=1)
        self.master.grid_columnconfigure(0, weight=1)

        tab1 = tk.Frame(self.master,  width=500, height=500, background="green")
        tab2 = tk.Frame(self.master,  width=500, height=500)
        tab3 = tk.Frame(self.master,  width=500, height=500)

        notebook.add(tab1)
        notebook.add(tab2)
        notebook.add(tab3)

        notebook.select(0) # select tab 1
        notebook.select(1) # select tab 2
        notebook.select(2) # select tab 3

def main():
    root = tk.Tk()
    root.geometry("500x500")
    multiframe_example(root)
    root.mainloop()

if __name__ == '__main__':
    main()
</code>```

Hope this code can support you and does as you would like!

Title: Nested Class factory with tkinter

Body:
I'm trying to build a script for import in my future projects.
That Script should create some tk.Frames in a tk.Frame and let me edit the created ones in a main.

I think, the best way to get there is to create a Holder_frame class and put some nested classes in.
so I could call them in my main with Holder_frame.F1.
I tried a lot of code and I ended up here making me an account.
Anyway here is where Im at:

import tkinter as tk
from tkinter import Frame,Button

class BaseClass(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.master = master
        self.pack()

class Holder_frame(tk.Frame):
    Names = []
    def __init__(self, master, frames=2):
        tk.Frame.__init__(self, master)
        self.master = master
        frame_names = Holder_frame.Names
        for i in range(0,frames):
            frame_names.append("F"+str(i+1))
        print(frame_names)
        Holder_frame.factory()
    def factory():
        print(Holder_frame.Names)
        print(type(BaseClass))
        for idex,i in enumerate (Holder_frame.Names):
            print(i)
            class NestedClass(BaseClass):
                pass

            NestedClass.__name__ = i
            NestedClass.__qualname__ = i

if __name__ == "__main__":
    root = tk.Tk()
    def raise1():
        Holder_frame.F1.tkraise()
    def raise2():
        Holder_frame.F2.tkraise()

    holder=Holder_frame(root,frames=2)
    holder.grid(row=1,column=0)
    b1 = tk.Button(root, text='1', command=raise1)
    b1.grid(row=0,column=0)
    b2 = tk.Button(root, text='2', command=raise2)
    b2.grid(row=0,column=1)

    root.mainloop()

Everything works fine, till I try to call a Frame.
(AttributeError 'Holder_frame' object has no attribute 'F1')
I think my problem is the structure but need some help to solve it.

Any suggestions?

Body:
One solution to this problem, I think, as I don't fully understand your question, but this here was my solution:

import tkinter as tk
from tkinter import Frame,Button

class BaseClass(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.master = master
        self.pack()

class Holder_frame(tk.Frame):
    def __init__(self, master, frames=2):
        tk.Frame.__init__(self, master)
        self.master = master
        self.frame_names = []
        for i in range(frames):
            Holder_frame.create_frames("F"+str(i+1), self)

    @classmethod
    def create_frames(cls, name, master):
        setattr(cls, name, tk.Frame(master))

if __name__ == "__main__":
    root = tk.Tk()
    def raise1():
        print(type(Holder_frame.F1))
    def raise2():
        print(type(Holder_frame.F2))

    holder=Holder_frame(root,frames=2)
    holder.grid(row=1,column=0)
    b1 = tk.Button(root, text='1', command=raise1)
    b1.grid(row=0,column=0)
    b2 = tk.Button(root, text='2', command=raise2)
    b2.grid(row=0,column=1)
    print(Holder_frame.__dict__.items())

    root.mainloop()

The use of setattr allows one to add variables to the class, just like if you were to type a function into the code. This allows you to access frames from outside the class as somewhat of a "global variable"

I used a file to test if it work outside as an imported module too:

# main.py
from nested_class import Holder_frame
import tkinter as tk

root = tk.Tk()
holder=Holder_frame(root,frames=1000)
holder.grid(row=1,column=0)
print(Holder_frame.__dict__.items())

root.mainloop()

I hope this answers your question,

James

EDIT:

After thinking there is, what I think, to be a cleaner system for what you want. With the code from this post one can see that your my written system could be replaced by a ttk.Notebook, and by removing the top bar by using style.layout('TNotebook.Tab', []), one can see that you would get a frame widget that could have frame widgets inside of it:

import tkinter as tk
import tkinter.ttk as ttk

class multiframe_example:
    def __init__(self, master):
        self.master = master

        style = ttk.Style()
        style.layout('TNotebook.Tab', [])
        notebook = ttk.Notebook(self.master)
        notebook.grid(row=0, column=0)

        self.master.grid_rowconfigure(0, weight=1)
        self.master.grid_columnconfigure(0, weight=1)

        tab1 = tk.Frame(self.master,  width=500, height=500, background="green")
        tab2 = tk.Frame(self.master,  width=500, height=500)
        tab3 = tk.Frame(self.master,  width=500, height=500)

        notebook.add(tab1)
        notebook.add(tab2)
        notebook.add(tab3)

        notebook.select(0) # select tab 1
        notebook.select(1) # select tab 2
        notebook.select(2) # select tab 3

def main():
    root = tk.Tk()
    root.geometry("500x500")
    multiframe_example(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Hope this code can support you and does as you would like!


问:
A question about billboard matrix convert
```<code>vec3 camPosInModelSpace = (inverse(mat_world) * vec4(worldCamPos, 1)).xyz;
vec3 axisZ = normalize(camPosInModelSpace);
vec3 axisY = axisZ.y > 0.999 ? vec3(0, 0, 1) : vec3(0, 1, 0);
vec3 axisX = normalize(cross(axisY, axisZ));
axisY = normalize(cross(axisZ, axisX));

mat4x4 rotate = mat4x4(vec4(axisX, 0), vec4(axisZ, 0), vec4(-axisY, 0), vec4(0, 0, 0, 1));

//vec3 vertexModelSpace = (transpose(rotate) * vec4(vPosition, 1)).xyz; // Here is my confused point
vertexModelSpace = axisX * vPosition.x + axisZ * vPosition.y + -axisY * vPosition.z;
gl_Position = mat_mvp * vec4(vertexModelSpace, 1);
</code>```

As you can see, the billboard's GLSL code is very simple, but I just have a question about it, after I got the 3 axis under the model space, why can't I use the matrix to convert the vertex(when I did that, only the Y-axis seemed works right), but when I used the tutorial's way, it works fine.

Please help me, I am really confused with this, thank you.

答:
OepnGL and GLSL is build with column-major as the default matrix layout in mind, consequently, mat4 m; m[c][r] is used to access the r-th row of c-th column and m[c] will return the c-th colum as vec4. Consistently to that, the matrix constructor uses the column vectors: mat4 m(c0,c1,c2,c3), hence

```<code>mat4x4 rotate = mat4x4(vec4(axisX, 0), vec4(axisZ, 0), vec4(-axisY, 0), vec4(0, 0, 0, 1));
</code>```

will result in a matrix in mathematical notation:

```<code>axisX.x    axisZ.x  -axisY.x    0
axisX.y    axisZ.y  -axisY.y    0
axisX.z    axisZ.z  -axisY.z    0
   0          0         0       1
</code>```

and therefore

```<code>vertexModelSpace = (transpose(rotate) * vec4(vPosition, 1)).xyz;
</code>```

is not equivalent to

```<code>vertexModelSpace = axisX * vPosition.x + axisZ * vPosition.y + -axisY * vPosition.z;
</code>```

but will actually use the transpose of that transform matrix, which happens to be the inverse for rotation matrices.

Body:
vec3 camPosInModelSpace = (inverse(mat_world) * vec4(worldCamPos, 1)).xyz;
vec3 axisZ = normalize(camPosInModelSpace);
vec3 axisY = axisZ.y > 0.999 ? vec3(0, 0, 1) : vec3(0, 1, 0);
vec3 axisX = normalize(cross(axisY, axisZ));
axisY = normalize(cross(axisZ, axisX));

mat4x4 rotate = mat4x4(vec4(axisX, 0), vec4(axisZ, 0), vec4(-axisY, 0), vec4(0, 0, 0, 1));

//vec3 vertexModelSpace = (transpose(rotate) * vec4(vPosition, 1)).xyz; // Here is my confused point
vertexModelSpace = axisX * vPosition.x + axisZ * vPosition.y + -axisY * vPosition.z;
gl_Position = mat_mvp * vec4(vertexModelSpace, 1);

As you can see, the billboard's GLSL code is very simple, but I just have a question about it, after I got the 3 axis under the model space, why can't I use the matrix to convert the vertex(when I did that, only the Y-axis seemed works right), but when I used the tutorial's way, it works fine.

Please help me, I am really confused with this, thank you.

Body:
OepnGL and GLSL is build with column-major as the default matrix layout in mind, consequently, mat4 m; m[c][r] is used to access the r-th row of c-th column and m[c] will return the c-th colum as vec4. Consistently to that, the matrix constructor uses the column vectors: mat4 m(c0,c1,c2,c3), hence

mat4x4 rotate = mat4x4(vec4(axisX, 0), vec4(axisZ, 0), vec4(-axisY, 0), vec4(0, 0, 0, 1));

will result in a matrix in mathematical notation:

axisX.x    axisZ.x  -axisY.x    0
axisX.y    axisZ.y  -axisY.y    0
axisX.z    axisZ.z  -axisY.z    0
   0          0         0       1

and therefore

vertexModelSpace = (transpose(rotate) * vec4(vPosition, 1)).xyz;

is not equivalent to

vertexModelSpace = axisX * vPosition.x + axisZ * vPosition.y + -axisY * vPosition.z;

but will actually use the transpose of that transform matrix, which happens to be the inverse for rotation matrices.


问:
Hackerearth policeman and theives problem
I am trying to solve the Policeman and Theives problem in Hackeearth website. I am able to reduce the time complexity but three test cases are failing. There seems to be a bug in the solution which causes a small mismatch. I am struggling to find the error for weeks. Below are the problem statement and my code,

Policeman and Thieves Problem statement:

You are given a grid of size  that has the following specifications:

Each cell in the grid contains either a policeman or a thief.

A policeman can only catch a thief if both of them are in the same row.

Each policeman can only catch one thief.

A policeman cannot catch a thief who is more than K units away from the policeman.
Write a program to find the maximum number of thieves that can be caught in the grid.

Input format

First line: T (number of test cases)

For each test case,

First-line contains Two space-separated integers N and K

Next N lines contain N space-separated characters (denoting each cell in the grid)

Output format

For each test case, print the maximum number of thieves that can be caught in the grid.

My code:

```<code>import java.io.*;
import java.util.*;

public class TestClass {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter wr = new PrintWriter(System.out);
        int T = Integer.parseInt(br.readLine().trim());
        for(int t_i=0; t_i<T; t_i++)
        {
            String[] line = br.readLine().split(" ");
            int N = Integer.parseInt(line[0]);
            int K = Integer.parseInt(line[1]);
            char[][] A = new char[N][N];
            for(int i_A=0; i_A<N; i_A++)
            {
                String[] arr_A = br.readLine().split(" ");
                for(int j_A=0; j_A<arr_A.length; j_A++)
                {
                    A[i_A][j_A] = arr_A[j_A].charAt(0);
                }
            }

            int out_ = solution(A, K);
            System.out.println(out_);
            System.out.println("");
        }

        wr.close();
        br.close();
    }
    static int solution(char[][] A, int K){
        int count = 0;
        for(int i=0;i<A.length;i++){
            for(int j=0;j<A[i].length;j++){
                if(A[i][j]=='P'){
                    boolean thiefCaptured = false;
                    int x;
                    if(j-K >0){
                        x = j-K;
                    }else {
                        x = 0;
                    }
                    for(;x<j;x++) {
                        if (A[i][x] == 'T') {
                            A[i][x] = 'X';
                            A[i][j] = 'X';
                            count++;
                            thiefCaptured = true;
                            break;
                        }
                    }
                    int y;
                    if(j+K < A[i].length){
                        y = j+K;
                    }else{
                        y = A[i].length - 1;
                    }
                    for(;(y>j) && (thiefCaptured == false);y--){
                        if(A[i][y]=='T'){
                            A[i][y] = 'X';
                            A[i][j] = 'X';
                            count++;
                            break;
                        }
                    }
                }
            }
        }
        return count;
    }
}
</code>```

My Logic
If an element is considered as the center of our search, then I am first looking for the thieves from the farthest left(by k units) and iterating towards the center. If the thief is not found, then I am looking for the thief from the farthest right(by k units) towards the center.

Failing test case input:

```<code>1
18 2
P P T T T P T P P T T P P P T P P T
P P P P T P P T P P T P P P T P T P
P P P T T T T T P P T P T P T T P T
P P P P P P T P P P T T T P T T T P
P P T P P T P P P T T P P T P P P T
P T P P P P P P P P P P T T P T P P
T P T T T P P P P T P T T T T P T P
T T P T P P P P P P P T T T P T P P
P T T T T P T T P T P P P P T T P T
P T P P T T P P P P P T T P T P P P
P T P T T P T P T P T P P P P P P T
P T P P T P T P T P T P T T T P P P
T T P T P P P P P P T T T P T P T P
P T T P P P P P T P T P T P T P P T
P T P T T P T P T P P P P T P T P P
T P P P T P T P P P P P T T P P P P
P P T P P P P P P P P T T T P P T P
T T T P T P T P T P P T P P T P P P
</code>```

Expected Ouput
113

Actual Output
112

Can you guys help me to figure out where I am going wrong? I am actually trying to figure out the solution for weeks but not able to progress. I know there is a different solution out there for the same question. But the thing is I would like to figure out the issue or the hole in my logic. Please help me out.

Link: Policemen and thieves on hackerearth

答:
I have added a logic to fix the bug pointed by @OleV.V. The added logic is, if two thieves are present consecutively to the Police, catch the nearest one first Now the failed test cases are passing but three of the previously passed test cases are getting timed out to time complexity issue. Below is the code, after addressing the bug pointed by @OleV.V. Now have to fix it in terms of time complexity :(

```<code>import java.io.*;
import java.util.*;

public class TestClass {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter wr = new PrintWriter(System.out);
        int T = Integer.parseInt(br.readLine().trim());
        for(int t_i=0; t_i<T; t_i++)
        {
            String[] line = br.readLine().split(" ");
            int N = Integer.parseInt(line[0]);
            int K = Integer.parseInt(line[1]);
            char[][] A = new char[N][N];
            for(int i_A=0; i_A<N; i_A++)
            {
                String[] arr_A = br.readLine().split(" ");
                for(int j_A=0; j_A<arr_A.length; j_A++)
                {
                    A[i_A][j_A] = arr_A[j_A].charAt(0);
                }
            }

            int out_ = solution(A, K);
            System.out.println(out_);
            System.out.println("");
        }

        wr.close();
        br.close();
    }
    static int solution(char[][] A, int K){
        int count = 0;
        for(int i=0;i<A.length;i++){
            for(int j=0;j<A[i].length;j++){
                if(A[i][j]=='P'){
                    ArrayList<Integer> leftarr = new ArrayList<>();
                    ArrayList<Integer> rightarr = new ArrayList<>();
                    int x;
                    if(j-K >0){
                        x = j-K;
                    }else {
                        x = 0;
                    }
                    for(;x<j;x++) {
                        if (A[i][x] == 'T') {
                            leftarr.add(x);
                        }
                    }
                    if(leftarr.size() != 0){
                        Collections.sort(leftarr);
                        A[i][leftarr.get(0)] = 'X';
                        A[i][j] = 'X';
                        count++;
                        continue;
                    }
                    int y;
                    if(j+K < A[i].length){
                        y = j+K;
                    }else{
                        y = A[i].length - 1;
                    }
                    for(;y>j;y--){
                        if (A[i][y]=='T'){
                            rightarr.add(y);
                        }
                    }
                    if(rightarr.size()!=0){
                        Collections.sort(rightarr);
                        A[i][rightarr.get(0)] = 'X';
                        A[i][j] = 'X';
                        count++;
                    }
                }
            }
        }
        return count;
    }
}
</code>```

Body:
I am trying to solve the Policeman and Theives problem in Hackeearth website. I am able to reduce the time complexity but three test cases are failing. There seems to be a bug in the solution which causes a small mismatch. I am struggling to find the error for weeks. Below are the problem statement and my code,

Policeman and Thieves Problem statement:

You are given a grid of size  that has the following specifications:

Each cell in the grid contains either a policeman or a thief.

A policeman can only catch a thief if both of them are in the same row.

Each policeman can only catch one thief.

A policeman cannot catch a thief who is more than K units away from the policeman.
Write a program to find the maximum number of thieves that can be caught in the grid.

Input format

First line: T (number of test cases)

For each test case,

First-line contains Two space-separated integers N and K

Next N lines contain N space-separated characters (denoting each cell in the grid)

Output format

For each test case, print the maximum number of thieves that can be caught in the grid.

My code:

import java.io.*;
import java.util.*;

public class TestClass {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter wr = new PrintWriter(System.out);
        int T = Integer.parseInt(br.readLine().trim());
        for(int t_i=0; t_i<T; t_i++)
        {
            String[] line = br.readLine().split(" ");
            int N = Integer.parseInt(line[0]);
            int K = Integer.parseInt(line[1]);
            char[][] A = new char[N][N];
            for(int i_A=0; i_A<N; i_A++)
            {
                String[] arr_A = br.readLine().split(" ");
                for(int j_A=0; j_A<arr_A.length; j_A++)
                {
                    A[i_A][j_A] = arr_A[j_A].charAt(0);
                }
            }

            int out_ = solution(A, K);
            System.out.println(out_);
            System.out.println("");
        }

        wr.close();
        br.close();
    }
    static int solution(char[][] A, int K){
        int count = 0;
        for(int i=0;i<A.length;i++){
            for(int j=0;j0){
                        x = j-K;
                    }else {
                        x = 0;
                    }
                    for(;x<j;x++) {
                        if (A[i][x] == 'T') {
                            A[i][x] = 'X';
                            A[i][j] = 'X';
                            count++;
                            thiefCaptured = true;
                            break;
                        }
                    }
                    int y;
                    if(j+K j) && (thiefCaptured == false);y--){
                        if(A[i][y]=='T'){
                            A[i][y] = 'X';
                            A[i][j] = 'X';
                            count++;
                            break;
                        }
                    }
                }
            }
        }
        return count;
    }
}

My Logic
If an element is considered as the center of our search, then I am first looking for the thieves from the farthest left(by k units) and iterating towards the center. If the thief is not found, then I am looking for the thief from the farthest right(by k units) towards the center.

Failing test case input:

1
18 2
P P T T T P T P P T T P P P T P P T
P P P P T P P T P P T P P P T P T P
P P P T T T T T P P T P T P T T P T
P P P P P P T P P P T T T P T T T P
P P T P P T P P P T T P P T P P P T
P T P P P P P P P P P P T T P T P P
T P T T T P P P P T P T T T T P T P
T T P T P P P P P P P T T T P T P P
P T T T T P T T P T P P P P T T P T
P T P P T T P P P P P T T P T P P P
P T P T T P T P T P T P P P P P P T
P T P P T P T P T P T P T T T P P P
T T P T P P P P P P T T T P T P T P
P T T P P P P P T P T P T P T P P T
P T P T T P T P T P P P P T P T P P
T P P P T P T P P P P P T T P P P P
P P T P P P P P P P P T T T P P T P
T T T P T P T P T P P T P P T P P P

Expected Ouput
113

Actual Output
112

Can you guys help me to figure out where I am going wrong? I am actually trying to figure out the solution for weeks but not able to progress. I know there is a different solution out there for the same question. But the thing is I would like to figure out the issue or the hole in my logic. Please help me out.

Link: Policemen and thieves on hackerearth

Body:
I have added a logic to fix the bug pointed by @OleV.V. The added logic is, if two thieves are present consecutively to the Police, catch the nearest one first Now the failed test cases are passing but three of the previously passed test cases are getting timed out to time complexity issue. Below is the code, after addressing the bug pointed by @OleV.V. Now have to fix it in terms of time complexity :(

import java.io.*;
import java.util.*;

public class TestClass {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter wr = new PrintWriter(System.out);
        int T = Integer.parseInt(br.readLine().trim());
        for(int t_i=0; t_i<T; t_i++)
        {
            String[] line = br.readLine().split(" ");
            int N = Integer.parseInt(line[0]);
            int K = Integer.parseInt(line[1]);
            char[][] A = new char[N][N];
            for(int i_A=0; i_A<N; i_A++)
            {
                String[] arr_A = br.readLine().split(" ");
                for(int j_A=0; j_A<arr_A.length; j_A++)
                {
                    A[i_A][j_A] = arr_A[j_A].charAt(0);
                }
            }

            int out_ = solution(A, K);
            System.out.println(out_);
            System.out.println("");
        }

        wr.close();
        br.close();
    }
    static int solution(char[][] A, int K){
        int count = 0;
        for(int i=0;i<A.length;i++){
            for(int j=0;j<A[i].length;j++){
                if(A[i][j]=='P'){
                    ArrayList<Integer> leftarr = new ArrayList<>();
                    ArrayList<Integer> rightarr = new ArrayList<>();
                    int x;
                    if(j-K >0){
                        x = j-K;
                    }else {
                        x = 0;
                    }
                    for(;x<j;x++) {
                        if (A[i][x] == 'T') {
                            leftarr.add(x);
                        }
                    }
                    if(leftarr.size() != 0){
                        Collections.sort(leftarr);
                        A[i][leftarr.get(0)] = 'X';
                        A[i][j] = 'X';
                        count++;
                        continue;
                    }
                    int y;
                    if(j+K < A[i].length){
                        y = j+K;
                    }else{
                        y = A[i].length - 1;
                    }
                    for(;y>j;y--){
                        if (A[i][y]=='T'){
                            rightarr.add(y);
                        }
                    }
                    if(rightarr.size()!=0){
                        Collections.sort(rightarr);
                        A[i][rightarr.get(0)] = 'X';
                        A[i][j] = 'X';
                        count++;
                    }
                }
            }
        }
        return count;
    }
}


问:
NSArray becoming invalid after assignment
This is a strange problem, but two of my NSArrays are becoming invalid right after assignment. I went into debug and verified this during assignment. The screenshot shows it all. I must be missing a silly error somewhere - can someone please help!

Link to Screenshot

Thank You!

答: Use -retain- dude. This will solve your problem.                         </p>

ContentLicense: CC BY-SA 3.0


问:
"Message from debugger: Terminated due to code signing error" when debugging a Mac app?
I'm writing a Mac app in the sandbox, and can't seem to get code signing to work. I've selected "Developer ID" from the Info tab for my target, and I've tried letting Xcode set up my provisioning profile automatically as well as creating the profile myself. The app builds without any errors or warnings, but when I try to "build and run," it gives me the following error:

答:
This also can happen when debugging on iOS Simulator, when developing for Mac Catalyst, when ENABLE_HARDENED_RUNTIME set to YES.

Below Xcode configuration helps to avoid this error:

```<code>ENABLE_HARDENED_RUNTIME[sdk=macosx*] = YES
ENABLE_HARDENED_RUNTIME[sdk=iphonesimulator*] = NO
ENABLE_HARDENED_RUNTIME[sdk=iphoneos*] = NO
</code>```

Body:
This also can happen when debugging on iOS Simulator, when developing for Mac Catalyst, when ENABLE_HARDENED_RUNTIME set to YES.

Below Xcode configuration helps to avoid this error:

ENABLE_HARDENED_RUNTIME[sdk=macosx*] = YES
ENABLE_HARDENED_RUNTIME[sdk=iphonesimulator*] = NO
ENABLE_HARDENED_RUNTIME[sdk=iphoneos*] = NO


问:
Accessing item in array returns undefined
When iterating through an array of objects, the properties are always undefined. The function in my Angular component class is as such:

```<code>upload(): void {
    const { fileHandles, relatedThroughID }: { fileHandles: IFileHandle[], relatedThroughID: Guid } = this.form.value;

    const postData: IUploadPost = {
      base64Files: fileHandles.map(fileHandle => ({ data: fileHandle.base64, extension: fileHandle.extension })),
      relatedThroughID: relatedThroughID.toString(),
    };
  }
</code>```

Here's a screenshot of the logged results, because I can't believe what I'm seeing - the values in the second log statement are undefined.

If I access an item by its index, the properties are also undefined. What in the world is happening here, and what can I do to fix it? I've never encountered a problem like this before.

答:
fileHandle in your map function is a reference to the array entry, not the actual array entry's fileHandle property.  Below is modified code.

```<code>upload(): void {
    const { fileHandles, relatedThroughID }: { fileHandles: IFileHandle[], relatedThroughID: Guid } = this.form.value;

    const postData: IUploadPost = {
      base64Files: fileHandles.map(x => ({ data: x.fileHandle.base64, extension: x.fileHandle.extension })),
      relatedThroughID: relatedThroughID.toString(),
    };
  }
</code>```

Body:
When iterating through an array of objects, the properties are always undefined. The function in my Angular component class is as such:

upload(): void {
    const { fileHandles, relatedThroughID }: { fileHandles: IFileHandle[], relatedThroughID: Guid } = this.form.value;

    const postData: IUploadPost = {
      base64Files: fileHandles.map(fileHandle => ({ data: fileHandle.base64, extension: fileHandle.extension })),
      relatedThroughID: relatedThroughID.toString(),
    };
  }

Here's a screenshot of the logged results, because I can't believe what I'm seeing - the values in the second log statement are undefined.

If I access an item by its index, the properties are also undefined. What in the world is happening here, and what can I do to fix it? I've never encountered a problem like this before.

Body:
fileHandle in your map function is a reference to the array entry, not the actual array entry's fileHandle property.  Below is modified code.

upload(): void {
    const { fileHandles, relatedThroughID }: { fileHandles: IFileHandle[], relatedThroughID: Guid } = this.form.value;

    const postData: IUploadPost = {
      base64Files: fileHandles.map(x => ({ data: x.fileHandle.base64, extension: x.fileHandle.extension })),
      relatedThroughID: relatedThroughID.toString(),
    };
  }


问:
Send input value to typescript (without button send)
I have a regular input text:

<form>
    <input type="text" oninput="sendInput()" />
</form>
```

I want to send what the user typed in the box into the typescript file (without a submit button or something) when the user has finished typing, send the input to the typescript.

I try with this code but it's not working.

答:
Demo use ngModel two way binding

```<code><input type="text" [(ngModel)]="inputParam"/>
<p>{{inputParam}}</p>
</code>```

Demo or use ViewChild as a way

component.ts

```<code>inputParam=""
  @ViewChild('input') _input: ElementRef;
  sendInput(){
    this.inputParam= this._input.nativeElement.value;
  }
</code>```

html part

```<code><form >
    <input #input type="text" (input)="sendInput()"/>
</form>
{{inputParam}}
</code>```

Body:
I have a regular input text:

<form>
    <input type="text" oninput="sendInput()" />
</form>

I want to send what the user typed in the box into the typescript file (without a submit button or something) when the user has finished typing, send the input to the typescript.

I try with this code but it's not working.

Body:
Demo use ngModel two way binding

<input type="text" [(ngModel)]="inputParam"/>
<p>{{inputParam}}</p>

Demo or use ViewChild as a way

component.ts

inputParam=""
  @ViewChild('input') _input: ElementRef;
  sendInput(){
    this.inputParam= this._input.nativeElement.value;
  }

html part

<form >
    <input #input type="text" (input)="sendInput()"/>
</form>
{{inputParam}}


问:
ValueError: could not convert string to float: balance = float(clean)
I'm using Python3 in a bot on Telegram, but I'm encountering an error when trying to execute some commands.
The bot is a cryptocurrency wallet, and this bot is connected to a wallet that is running on the same server where the bot is hosted.
The connection is made via RPC commands.
Error follows:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/telegram/ext/dispatcher.py", line 343, in process_update
    handler.handle_update(update, self, check, context)
  File "/usr/local/lib/python3.5/dist-packages/telegram/ext/handler.py", line 122, in handle_update
    return self.callback(dispatcher.bot, update, **optional_args)
  File "command.py", line 86, in funds
    balance  = float(clean)
ValueError: could not convert string to float:
```

<p><img src="https://i.stack.imgur.com/uBLOt.png" alt="enter image description here"></p>

<p>This would be my code:</p>

```#-*- coding: utf-8 -*-

import json
import codecs
import requests
from bs4 import BeautifulSoup, SoupStrainer
import re
import subprocess
from telegram.ext.dispatcher import run_async
from telegram.ext import Updater
from html import escape

updater = Updater(token='TOKEN_TELEGRAM')
dispatcher = updater.dispatcher

import logging
logging.basicConfig(filename='log.log',
                    filemode='w',
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.DEBUG)

def commands(bot, update):
    user = update.message.from_user.username
    bot.send_message(chat_id=update.message.chat_id, text=" List of commands: \n "+
        " /hello \n /commands \n /recharge \n /pay \n /drawout \n /funds \n /price \n /help")

def help(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text=" /pay & /drawout have a specfic format use them like so:"+
        "\n Parameters: \n <user> = target user to pay \n <amount> = amount of SperoCoin to utilise \n <address> = SperoCoin address to withdraw to \n \n Tipping format: \n /pay <user> <amount> \n \n Withdrawing format: \n /drawout <address> <amount>")

def recharge(bot, update):
    user = update.message.from_user.username
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        address = "/usr/local/bin/SperoCoind"
        extra1 = "-datadir=/coin/data"
        extra2 = "-conf=/coin/sperocoin.conf"
        result = subprocess.run([address,extra1,extra2,"getaccountaddress",user],stdout=subprocess.PIPE)
        clean = (result.stdout.strip()).decode("utf-8")
        bot.send_message(chat_id=update.message.chat_id, text="@{0} your depositing address is: {1}".format(user,clean))

def pay(bot,update):
    user = update.message.from_user.username
    target = update.message.text[5:]
    amount =  target.split(" ")[1]
    target =  target.split(" ")[0]
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        machine = "@SperoCoinWalletBot"
        if target == machine:
            bot.send_message(chat_id=update.message.chat_id, text="HODL.")
        elif "@" in target:
            target = target[1:]
            user = update.message.from_user.username
            core = "/usr/local/bin/SperoCoind"
            extra1 = "-datadir=/coin/data"
            extra2 = "-conf=/coin/sperocoin.conf"
            result = subprocess.run([core,extra1,extra2,"getbalance",user],stdout=subprocess.PIPE)
            balance = float((result.stdout.strip()).decode("utf-8"))
            amount = float(amount)
            if balance < amount:
                bot.send_message(chat_id=update.message.chat_id, text="@{0} you have insufficent funds.".format(user))
            elif target == user:
                bot.send_message(chat_id=update.message.chat_id, text="You can't pay yourself!")
            else:
                balance = str(balance)
                amount = str(amount)
                tx = subprocess.run([core,extra1,extra2,"move",user,target,amount],stdout=subprocess.PIPE)
                bot.send_message(chat_id=update.message.chat_id, text="@{0} paid @{1} of {2} SPERO".format(user, target, amount))
        else:
            bot.send_message(chat_id=update.message.chat_id, text="Error that user is not applicable.")

def funds(bot,update):
    user = update.message.from_user.username
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        core = "/usr/local/bin/SperoCoind"
        extra1 = "-datadir=/coin/data"
        extra2 = "-conf=/coin/sperocoin.conf"
        result = subprocess.run([core,extra1,extra2,"getbalance",user],stdout=subprocess.PIPE)
        clean = (result.stdout.strip()).decode("utf-8")
        balance  = float(clean)
        balance =  str(round(balance,3))
        bot.send_message(chat_id=update.message.chat_id, text="@{0} your current balance is: {1} SPERO ".format(user,balance))

def drawout(bot,update):
    user = update.message.from_user.username
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        target = update.message.text[9:]
        address = target[:35]
        address = ''.join(str(e) for e in address)
        target = target.replace(target[:35], '')
        amount = float(target)
        core = "/usr/local/bin/SperoCoind"
        extra1 = "-datadir=/coin/data"
        extra2 = "-conf=/coin/sperocoin.conf"
        result = subprocess.run([core,extra1,extra2,"getbalance",user],stdout=subprocess.PIPE)
        clean = (result.stdout.strip()).decode("utf-8")
        balance = float(clean)
        if balance < amount:
            bot.send_message(chat_id=update.message.chat_id, text="@{0} you have insufficent funds.".format(user))
        else:
            amount = str(amount)
            tx = subprocess.run([core,extra1,extra2,"sendfrom",user,address,amount],stdout=subprocess.PIPE)
            cleantxid = (tx.stdout.strip()).decode("utf-8")
            txid = str(cleantxid)
            bot.send_message(chat_id=update.message.chat_id, text="@{0} has successfully withdrew to address: {1} of {2} SPERO\n\n TXID: https://explorer.sperocoin.org/tx/{3}" .format(user,address,amount,txid))

def hello(bot,update):
    user = update.message.from_user.username
    bot.send_message(chat_id=update.message.chat_id, text="Hello @{0}, how about buying some SPERO at SPERO EXCHANGE?\n https://exchange.sperocoin.org".format(user))

def rain(bot,update):
  bot.send_message(chat_id=update.message.chat_id, text="Stake for a rainy day!")

def price(bot,update):
    speroCapJson = requests.get('https://api.coingecko.com/api/v3/coins/sperocoin').json()
    mk_cap = speroCapJson ['market_data']['market_cap']['brl']
    pricebrl = speroCapJson ['market_data']['current_price']['brl']
    priceusd = speroCapJson ['market_data']['current_price']['usd']
    pricebtc = speroCapJson ['market_data']['current_price']['btc']
    priceeth = speroCapJson ['market_data']['current_price']['eth']
    update.message.reply_text(" Price: \n Cotação/Price: Coingecko \n SPERO Market Cap: R$:{:.2f}".format(mk_cap)+
"\n Price(BRL):  R${:.3f}".format(pricebrl) + "\n Price(USD):  ${:.3f}".format(priceusd) + "\n Price(BTC):  {:.8f}".format(pricebtc) + "\n Price(ETH):  {:.8f}".format(priceeth))

from telegram.ext import CommandHandler

commands_handler = CommandHandler('commands', commands)
dispatcher.add_handler(commands_handler)

rain_handler = CommandHandler('rain', rain)
dispatcher.add_handler(rain_handler)

hi_handler = CommandHandler('hello', hello)
dispatcher.add_handler(hi_handler)

withdraw_handler = CommandHandler('drawout', drawout)
dispatcher.add_handler(withdraw_handler)

deposit_handler = CommandHandler('recharge', recharge)
dispatcher.add_handler(deposit_handler)

tip_handler = CommandHandler('pay', pay)
dispatcher.add_handler(tip_handler)

balance_handler = CommandHandler('funds', funds)
dispatcher.add_handler(balance_handler)

help_handler = CommandHandler('help', help)
dispatcher.add_handler(help_handler)

price_handler = CommandHandler('price', price)
dispatcher.add_handler(price_handler)

updater.start_polling()
```

<p>For the execution of the code, I ran it on a docker:</p>

```RUN apt update && apt install python3 python3-pip -y
RUN pip3 install beautifulsoup4 \
  && pip3 install requests \
  && pip3 install python-telegram-bot --upgrade
```

答:
The mistake was humanly mine ...
The portfolio service had not started with the definition of account activation.
This was not filtering the balance per user.

"enableaccounts=1"

Body:
I'm using Python3 in a bot on Telegram, but I'm encountering an error when trying to execute some commands.
The bot is a cryptocurrency wallet, and this bot is connected to a wallet that is running on the same server where the bot is hosted.
The connection is made via RPC commands.
Error follows:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/telegram/ext/dispatcher.py", line 343, in process_update
    handler.handle_update(update, self, check, context)
  File "/usr/local/lib/python3.5/dist-packages/telegram/ext/handler.py", line 122, in handle_update
    return self.callback(dispatcher.bot, update, **optional_args)
  File "command.py", line 86, in funds
    balance  = float(clean)
ValueError: could not convert string to float:

This would be my code:

#-*- coding: utf-8 -*-

import json
import codecs
import requests
from bs4 import BeautifulSoup, SoupStrainer
import re
import subprocess
from telegram.ext.dispatcher import run_async
from telegram.ext import Updater
from html import escape

updater = Updater(token='TOKEN_TELEGRAM')
dispatcher = updater.dispatcher

import logging
logging.basicConfig(filename='log.log',
                    filemode='w',
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.DEBUG)

def commands(bot, update):
    user = update.message.from_user.username
    bot.send_message(chat_id=update.message.chat_id, text=" List of commands: \n "+
        " /hello \n /commands \n /recharge \n /pay \n /drawout \n /funds \n /price \n /help")

def help(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text=" /pay & /drawout have a specfic format use them like so:"+
        "\n Parameters: \n <user> = target user to pay \n <amount> = amount of SperoCoin to utilise \n <address> = SperoCoin address to withdraw to \n \n Tipping format: \n /pay <user> <amount> \n \n Withdrawing format: \n /drawout <address> <amount>")

def recharge(bot, update):
    user = update.message.from_user.username
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        address = "/usr/local/bin/SperoCoind"
        extra1 = "-datadir=/coin/data"
        extra2 = "-conf=/coin/sperocoin.conf"
        result = subprocess.run([address,extra1,extra2,"getaccountaddress",user],stdout=subprocess.PIPE)
        clean = (result.stdout.strip()).decode("utf-8")
        bot.send_message(chat_id=update.message.chat_id, text="@{0} your depositing address is: {1}".format(user,clean))

def pay(bot,update):
    user = update.message.from_user.username
    target = update.message.text[5:]
    amount =  target.split(" ")[1]
    target =  target.split(" ")[0]
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        machine = "@SperoCoinWalletBot"
        if target == machine:
            bot.send_message(chat_id=update.message.chat_id, text="HODL.")
        elif "@" in target:
            target = target[1:]
            user = update.message.from_user.username
            core = "/usr/local/bin/SperoCoind"
            extra1 = "-datadir=/coin/data"
            extra2 = "-conf=/coin/sperocoin.conf"
            result = subprocess.run([core,extra1,extra2,"getbalance",user],stdout=subprocess.PIPE)
            balance = float((result.stdout.strip()).decode("utf-8"))
            amount = float(amount)
            if balance < amount:
                bot.send_message(chat_id=update.message.chat_id, text="@{0} you have insufficent funds.".format(user))
            elif target == user:
                bot.send_message(chat_id=update.message.chat_id, text="You can't pay yourself!")
            else:
                balance = str(balance)
                amount = str(amount)
                tx = subprocess.run([core,extra1,extra2,"move",user,target,amount],stdout=subprocess.PIPE)
                bot.send_message(chat_id=update.message.chat_id, text="@{0} paid @{1} of {2} SPERO".format(user, target, amount))
        else:
            bot.send_message(chat_id=update.message.chat_id, text="Error that user is not applicable.")

def funds(bot,update):
    user = update.message.from_user.username
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        core = "/usr/local/bin/SperoCoind"
        extra1 = "-datadir=/coin/data"
        extra2 = "-conf=/coin/sperocoin.conf"
        result = subprocess.run([core,extra1,extra2,"getbalance",user],stdout=subprocess.PIPE)
        clean = (result.stdout.strip()).decode("utf-8")
        balance  = float(clean)
        balance =  str(round(balance,3))
        bot.send_message(chat_id=update.message.chat_id, text="@{0} your current balance is: {1} SPERO ".format(user,balance))

def drawout(bot,update):
    user = update.message.from_user.username
    if user is None:
        bot.send_message(chat_id=update.message.chat_id, text="Please set a telegram username in your profile settings!")
    else:
        target = update.message.text[9:]
        address = target[:35]
        address = ''.join(str(e) for e in address)
        target = target.replace(target[:35], '')
        amount = float(target)
        core = "/usr/local/bin/SperoCoind"
        extra1 = "-datadir=/coin/data"
        extra2 = "-conf=/coin/sperocoin.conf"
        result = subprocess.run([core,extra1,extra2,"getbalance",user],stdout=subprocess.PIPE)
        clean = (result.stdout.strip()).decode("utf-8")
        balance = float(clean)
        if balance < amount:
            bot.send_message(chat_id=update.message.chat_id, text="@{0} you have insufficent funds.".format(user))
        else:
            amount = str(amount)
            tx = subprocess.run([core,extra1,extra2,"sendfrom",user,address,amount],stdout=subprocess.PIPE)
            cleantxid = (tx.stdout.strip()).decode("utf-8")
            txid = str(cleantxid)
            bot.send_message(chat_id=update.message.chat_id, text="@{0} has successfully withdrew to address: {1} of {2} SPERO\n\n TXID: https://explorer.sperocoin.org/tx/{3}" .format(user,address,amount,txid))

def hello(bot,update):
    user = update.message.from_user.username
    bot.send_message(chat_id=update.message.chat_id, text="Hello @{0}, how about buying some SPERO at SPERO EXCHANGE?\n https://exchange.sperocoin.org".format(user))

def rain(bot,update):
  bot.send_message(chat_id=update.message.chat_id, text="Stake for a rainy day!")

def price(bot,update):
    speroCapJson = requests.get('https://api.coingecko.com/api/v3/coins/sperocoin').json()
    mk_cap = speroCapJson ['market_data']['market_cap']['brl']
    pricebrl = speroCapJson ['market_data']['current_price']['brl']
    priceusd = speroCapJson ['market_data']['current_price']['usd']
    pricebtc = speroCapJson ['market_data']['current_price']['btc']
    priceeth = speroCapJson ['market_data']['current_price']['eth']
    update.message.reply_text(" Price: \n Cotação/Price: Coingecko \n SPERO Market Cap: R$:{:.2f}".format(mk_cap)+
"\n Price(BRL):  R${:.3f}".format(pricebrl) + "\n Price(USD):  ${:.3f}".format(priceusd) + "\n Price(BTC):  {:.8f}".format(pricebtc) + "\n Price(ETH):  {:.8f}".format(priceeth))

from telegram.ext import CommandHandler

commands_handler = CommandHandler('commands', commands)
dispatcher.add_handler(commands_handler)

rain_handler = CommandHandler('rain', rain)
dispatcher.add_handler(rain_handler)

hi_handler = CommandHandler('hello', hello)
dispatcher.add_handler(hi_handler)

withdraw_handler = CommandHandler('drawout', drawout)
dispatcher.add_handler(withdraw_handler)

deposit_handler = CommandHandler('recharge', recharge)
dispatcher.add_handler(deposit_handler)

tip_handler = CommandHandler('pay', pay)
dispatcher.add_handler(tip_handler)

balance_handler = CommandHandler('funds', funds)
dispatcher.add_handler(balance_handler)

help_handler = CommandHandler('help', help)
dispatcher.add_handler(help_handler)

price_handler = CommandHandler('price', price)
dispatcher.add_handler(price_handler)

updater.start_polling()

For the execution of the code, I ran it on a docker:

RUN apt update && apt install python3 python3-pip -y
RUN pip3 install beautifulsoup4 \
  && pip3 install requests \
  && pip3 install python-telegram-bot --upgrade


问:
Debugging multithreaded applications
I have an application written in C++ and MFC which is multithreaded running on windows. Occasionally I do get some complaints such as deadlocks or an unhandled exception which is caused because of these threads. Normally I use visual studio (if the problem is reproducible) or else use the WinDbg to analyse the dump files generated. Is there any better way of doing this? Can  I use some other tools to do this?</p>

答: I haven't gotten to use it yet, but the Relacy Race Detector sounds pretty useful for tracking down some classes of threading issues.</p>

OwnerDisplayName: Naveen

ContentLicense: CC BY-SA 2.5

Title: Debugging multithreaded applications

LastEditorDisplayName: Jason S

OwnerDisplayName: Dan Olson


问:
Can I control slider value programmatically?
I have used following code

```<code>    for (UIView *view in [volumeView subviews]){
        if ([[[view class] description] isEqualToString:@"MPVolumeSlider"]) {
            volumeViewSlider = (UISlider *) view;
        }
    }

    //[volumeViewSlider setBackgroundColor:[UIColor colorWithRed:1.00 green:0.0 blue:0.0 alpha:1.0]];
    UIImage *stetchLeftTrack = [[UIImage imageNamed:@"leftslide.png"]
                                stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
    UIImage *stetchRightTrack = [[UIImage imageNamed:@"rightslide.png"]
                                 stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
    //    [customSlider setThumbImage: [UIImage imageNamed:@"slider_ball.png"] forState:UIControlStateNormal];
    [volumeViewSlider setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
    [volumeViewSlider setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];
    [volumeViewSlider setMinimumValueImage:[UIImage imageNamed:@"SpeakerSoft.tif"]];
    [volumeViewSlider setMaximumValueImage:[UIImage imageNamed:@"SpeakerLoud.tif"]];

    [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(changeTheTimer) userInfo:nil repeats:NO];
}

-(void)changeTheTimer{
    [volumeViewSlider setValue:0 animated:YES];
    NSLog(@"Value is set to 0");
}
</code>```

I want to stop all playbacks after one minute , but slider moves to zero and leaves of effect of master volume.

答:
You can certainly make use of the UISlider instance method

```<code>- (void)setValue:(float)value animated:(BOOL)animated
</code>```

This will reduce the slider value with or without animation.

UPDATE

Check this link on Controlling Master Volume

Body:
I have used following code

    for (UIView *view in [volumeView subviews]){
        if ([[[view class] description] isEqualToString:@"MPVolumeSlider"]) {
            volumeViewSlider = (UISlider *) view;
        }
    }

    //[volumeViewSlider setBackgroundColor:[UIColor colorWithRed:1.00 green:0.0 blue:0.0 alpha:1.0]];
    UIImage *stetchLeftTrack = [[UIImage imageNamed:@"leftslide.png"]
                                stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
    UIImage *stetchRightTrack = [[UIImage imageNamed:@"rightslide.png"]
                                 stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
    //    [customSlider setThumbImage: [UIImage imageNamed:@"slider_ball.png"] forState:UIControlStateNormal];
    [volumeViewSlider setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
    [volumeViewSlider setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];
    [volumeViewSlider setMinimumValueImage:[UIImage imageNamed:@"SpeakerSoft.tif"]];
    [volumeViewSlider setMaximumValueImage:[UIImage imageNamed:@"SpeakerLoud.tif"]];

    [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(changeTheTimer) userInfo:nil repeats:NO];
}

-(void)changeTheTimer{
    [volumeViewSlider setValue:0 animated:YES];
    NSLog(@"Value is set to 0");
}

I want to stop all playbacks after one minute , but slider moves to zero and leaves of effect of master volume.

Body:
You can certainly make use of the UISlider instance method

- (void)setValue:(float)value animated:(BOOL)animated

This will reduce the slider value with or without animation.

UPDATE

Check this link on Controlling Master Volume


问:
How to make a custom LinkedIn share button using POST
I would like to use my own image for the LinkedIn share button. I've been following the information on this previous post:

How to make a custom LinkedIn share button

It's noted here that: To create a custom Share button for LinkedIn, you need to make POST calls now.

I've read the Linkedin documentation however I don't understand how to incorporate the POST call with my HTML page. Could someone help explain it to me please?

I've initially tried to use this URL which i understand is now not supported by LinkedIn:

https://www.linkedin.com/shareArticle?mini=true&url=articleUrl&title=YourarticleTitle&summary=YourarticleSummary&source=YourarticleSource

It partially works! The image, title and summary are all incomplete or not what I have specified in the URL, however if I click on the LinkedIn post it does actually link to the right page.

Is there anyway of getting this working?

Many thanks

答:
Let's take a quick glance at the Official LinkedIn "Making Your Website Shareable on LinkedIn" Documentation.  The URL format should be...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

And to have it use the other parameters, such as image, etc., set your og: tags in the HTML of the link you are sharing, like so...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Body:
Let's take a quick glance at the Official LinkedIn "Making Your Website Shareable on LinkedIn" Documentation.  The URL format should be...

https://www.linkedin.com/sharing/share-offsite/?url={url}

And to have it use the other parameters, such as image, etc., set your og: tags in the HTML of the link you are sharing, like so...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />