counting after and before change in value, within groups, generating new variables for each unique shift

Question: I am working to count occurrences of unique values within my groups, id. I'm looking at TF. When TF changes I want to count both forward and backwards from that point. This counting should be stored in a new variable PM#, so that PM# holds both plus and minus to each unique shift in  TF. From what I've gathered I need to use rle, but I am kinda stuck.
I made this working example to illustrate my issue.
I have this data
df <- structure(list(id = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L), TF = c(NA, 0L, NA, 0L, 0L, 1L, 1L, 1L, NA, 0L,
0L, NA, 0L, 0L, 0L, 1L, 1L, 1L, NA, NA, 0L, 0L, 1L, 0L, 0L, 1L,
0L, 1L, 1L, 1L)), .Names = c("id", "TF"), class = "data.frame", row.names = c(NA,
-30L))

This is the kinda data I am seeing
df[c(1:12,19:30),]
#>    id TF
#> 1   0 NA
#> 2   0  0
#> 3   0 NA
#> 4   0  0
#> 5   0  0
#> 6   0  1
#> 7   0  1
#> 8   0  1
#> 9   0 NA
#> 10  0  0
#> 11  0  0
#> 12  1 NA
#> 19  1 NA
#> 20  7 NA
#> 21  7  0
#> 22  7  0
#> 23  7  1
#> 24  7  0
#> 25  7  0
#> 26  7  1
#> 27  7  0
#> 28  7  1
#> 29  7  1
#> 30  7  1

I've started meddling with ave, cumsum and with rle, but haven't solved it this way yet.
df$PM01 <- with(df, ifelse(is.na(TF), NA, 1))
df$PM01 <- with(df, ave(PM01, TF, id, FUN=cumsum))

with(df, tapply(TF, rep(rle(id)[[2]], rle(id)[[1]]), count))

This is what I am trying to obtain,
dfa <- structure(list(id = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L), TF = c(NA, 0L, NA, 0L, 0L, 1L, 1L, 1L, NA, 0L,
0L, NA, 0L, 0L, 0L, 1L, 1L, 1L, NA, NA, 0L, 0L, 1L, 0L, 0L, 1L,
0L, 1L, 1L, 1L), PM1 = c(NA, -3L, NA, -2L, -1L, 1L, 2L, 3L, NA,
NA, NA, NA, -3L, -2L, -1L, 1L, 2L, 3L, NA, NA, -2L, -1L, 1L,
NA, NA, NA, NA, NA, NA, NA), PM2 = c(NA, NA, NA, NA, NA, -3L,
-2L, -1L, NA, 1L, 2L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, -1L, 1L, 2L, NA, NA, NA, NA, NA), PM3 = c(NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, -2L, -1L, 1L, NA, NA, NA, NA), PM4 = c(NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, -1L, 1L, NA, NA, NA), PM5 = c(NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, -1L, 1L, 2L, 3L)), .Names = c("id",
"TF", "PM1", "PM2", "PM3", "PM4", "PM5"), class = "data.frame", row.names = c(NA,
-30L))

dfa[c(1:12,19:30),]
#>    id TF PM1 PM2 PM3 PM4 PM5
#> 1   0 NA  NA  NA  NA  NA  NA
#> 2   0  0  -3  NA  NA  NA  NA
#> 3   0 NA  NA  NA  NA  NA  NA
#> 4   0  0  -2  NA  NA  NA  NA
#> 5   0  0  -1  NA  NA  NA  NA
#> 6   0  1   1  -3  NA  NA  NA
#> 7   0  1   2  -2  NA  NA  NA
#> 8   0  1   3  -1  NA  NA  NA
#> 9   0 NA  NA  NA  NA  NA  NA
#> 10  0  0  NA   1  NA  NA  NA
#> 11  0  0  NA   2  NA  NA  NA
#> 12  1 NA  NA  NA  NA  NA  NA
#> 19  1 NA  NA  NA  NA  NA  NA
#> 20  7 NA  NA  NA  NA  NA  NA
#> 21  7  0  -2  NA  NA  NA  NA
#> 22  7  0  -1  NA  NA  NA  NA
#> 23  7  1   1  -1  NA  NA  NA
#> 24  7  0  NA   1  -2  NA  NA
#> 25  7  0  NA   2  -1  NA  NA
#> 26  7  1  NA  NA   1  -1  NA
#> 27  7  0  NA  NA  NA   1  -1
#> 28  7  1  NA  NA  NA  NA   1
#> 29  7  1  NA  NA  NA  NA   2
#> 30  7  1  NA  NA  NA  NA   3

Answer: This was really a tricky one, and I'm sure the code can be further improved. However, I was able to reproduce your expected result.  Please, try this approach with your production data. If OK, I will add an explanation later.
library(data.table)

tmp <- setDT(df)[, rn := .I][!is.na(TF)][, rl := rleid(TF), by = id][
  , c("up", "dn") := .(seq_len(.N), -rev(seq_len(.N))), by = .(id, rl)][]

res <- tmp[tmp[, seq_len(max(rl) - 1L), by = .(id)], on = .(id), allow.cartesian = TRUE][
  rl == V1, PM := dn][rl == V1 + 1L, PM := up][
    , dcast(.SD, id + TF + rn ~ paste0("PM", V1), value.var = "PM")][
      df, on = .(rn, id, TF)][, -"rn"]
res

    id TF PM1 PM2 PM3 PM4 PM5
 1:  0 NA  NA  NA  NA  NA  NA
 2:  0  0  -3  NA  NA  NA  NA
 3:  0 NA  NA  NA  NA  NA  NA
 4:  0  0  -2  NA  NA  NA  NA
 5:  0  0  -1  NA  NA  NA  NA
 6:  0  1   1  -3  NA  NA  NA
 7:  0  1   2  -2  NA  NA  NA
 8:  0  1   3  -1  NA  NA  NA
 9:  0 NA  NA  NA  NA  NA  NA
10:  0  0  NA   1  NA  NA  NA
11:  0  0  NA   2  NA  NA  NA
12:  1 NA  NA  NA  NA  NA  NA
13:  1  0  -3  NA  NA  NA  NA
14:  1  0  -2  NA  NA  NA  NA
15:  1  0  -1  NA  NA  NA  NA
16:  1  1   1  NA  NA  NA  NA
17:  1  1   2  NA  NA  NA  NA
18:  1  1   3  NA  NA  NA  NA
19:  1 NA  NA  NA  NA  NA  NA
20:  7 NA  NA  NA  NA  NA  NA
21:  7  0  -2  NA  NA  NA  NA
22:  7  0  -1  NA  NA  NA  NA
23:  7  1   1  -1  NA  NA  NA
24:  7  0  NA   1  -2  NA  NA
25:  7  0  NA   2  -1  NA  NA
26:  7  1  NA  NA   1  -1  NA
27:  7  0  NA  NA  NA   1  -1
28:  7  1  NA  NA  NA  NA   1
29:  7  1  NA  NA  NA  NA   2
30:  7  1  NA  NA  NA  NA   3
    id TF PM1 PM2 PM3 PM4 PM5

# verify results are identical
identical(res, dfa)

[1] TRUE

In case of more than 9 changes per group paste0("PM", V1) should be replaced by sprintf("PM%02d",V1) in the call to dcast() to ensure the PM columns are ordered properly.
Explanation
tmp <-
  # coerce to data.table
  setDT(df)[
    # create row id column (required for final join to get NA rows back in)
    , rn := .I][
      # ignore NA rows
      !is.na(TF)][
        # number streaks of unique values within each group
        , rl := rleid(TF), by = id][
          # create ascending and descending counts for each streak
          # this is done once to avoid repeatedly creation of counts for each PM
          # (slight performance gain)
          , c("up", "dn") := .(seq_len(.N), -rev(seq_len(.N))), by = .(id, rl)]

tmp[]

    id TF rn rl up dn
 1:  0  0  2  1  1 -3
 2:  0  0  4  1  2 -2
 3:  0  0  5  1  3 -1
 4:  0  1  6  2  1 -3
 5:  0  1  7  2  2 -2
 6:  0  1  8  2  3 -1
 7:  0  0 10  3  1 -2
 8:  0  0 11  3  2 -1
 9:  1  0 13  1  1 -3
10:  1  0 14  1  2 -2
11:  1  0 15  1  3 -1
12:  1  1 16  2  1 -3
13:  1  1 17  2  2 -2
14:  1  1 18  2  3 -1
15:  7  0 21  1  1 -2
16:  7  0 22  1  2 -1
17:  7  1 23  2  1 -1
18:  7  0 24  3  1 -2
19:  7  0 25  3  2 -1
20:  7  1 26  4  1 -1
21:  7  0 27  5  1 -1
22:  7  1 28  6  1 -3
23:  7  1 29  6  2 -2
24:  7  1 30  6  3 -1
    id TF rn rl up dn

For the next step, we need the count of changes V1 within each group
tmp[, seq_len(max(rl) - 1L), by = .(id)]

   id V1
1:  0  1
2:  0  2
3:  1  1
4:  7  1
5:  7  2
6:  7  3
7:  7  4
8:  7  5

Now, we create a "cartesian join" of all possible changes with the rows of each group:
# right join with count of changes within each group
tmp[tmp[, seq_len(max(rl) - 1L), by = .(id)], on = .(id), allow.cartesian = TRUE][
  # copy descending counts to rows before the switch
  rl == V1, PM := dn][
    # copy ascending counts to rows after the switch
    rl == V1 + 1L, PM := up][]

    id TF rn rl up dn V1 PM
 1:  0  0  2  1  1 -3  1 -3
 2:  0  0  4  1  2 -2  1 -2
 3:  0  0  5  1  3 -1  1 -1
 4:  0  1  6  2  1 -3  1  1
 5:  0  1  7  2  2 -2  1  2
 6:  0  1  8  2  3 -1  1  3
 7:  0  0 10  3  1 -2  1 NA
 8:  0  0 11  3  2 -1  1 NA
 9:  0  0  2  1  1 -3  2 NA
10:  0  0  4  1  2 -2  2 NA
11:  0  0  5  1  3 -1  2 NA
12:  0  1  6  2  1 -3  2 -3
13:  0  1  7  2  2 -2  2 -2
14:  0  1  8  2  3 -1  2 -1
15:  0  0 10  3  1 -2  2  1
16:  0  0 11  3  2 -1  2  2
17:  1  0 13  1  1 -3  1 -3
18:  1  0 14  1  2 -2  1 -2
19:  1  0 15  1  3 -1  1 -1
20:  1  1 16  2  1 -3  1  1
21:  1  1 17  2  2 -2  1  2
22:  1  1 18  2  3 -1  1  3
23:  7  0 21  1  1 -2  1 -2
24:  7  0 22  1  2 -1  1 -1
25:  7  1 23  2  1 -1  1  1
26:  7  0 24  3  1 -2  1 NA
27:  7  0 25  3  2 -1  1 NA
28:  7  1 26  4  1 -1  1 NA
29:  7  0 27  5  1 -1  1 NA
30:  7  1 28  6  1 -3  1 NA
31:  7  1 29  6  2 -2  1 NA
32:  7  1 30  6  3 -1  1 NA
33:  7  0 21  1  1 -2  2 NA
34:  7  0 22  1  2 -1  2 NA
35:  7  1 23  2  1 -1  2 -1
36:  7  0 24  3  1 -2  2  1
37:  7  0 25  3  2 -1  2  2
38:  7  1 26  4  1 -1  2 NA
39:  7  0 27  5  1 -1  2 NA
40:  7  1 28  6  1 -3  2 NA
41:  7  1 29  6  2 -2  2 NA
42:  7  1 30  6  3 -1  2 NA
43:  7  0 21  1  1 -2  3 NA
44:  7  0 22  1  2 -1  3 NA
45:  7  1 23  2  1 -1  3 NA
46:  7  0 24  3  1 -2  3 -2
47:  7  0 25  3  2 -1  3 -1
48:  7  1 26  4  1 -1  3  1
49:  7  0 27  5  1 -1  3 NA
50:  7  1 28  6  1 -3  3 NA
51:  7  1 29  6  2 -2  3 NA
52:  7  1 30  6  3 -1  3 NA
53:  7  0 21  1  1 -2  4 NA
54:  7  0 22  1  2 -1  4 NA
55:  7  1 23  2  1 -1  4 NA
56:  7  0 24  3  1 -2  4 NA
57:  7  0 25  3  2 -1  4 NA
58:  7  1 26  4  1 -1  4 -1
59:  7  0 27  5  1 -1  4  1
60:  7  1 28  6  1 -3  4 NA
61:  7  1 29  6  2 -2  4 NA
62:  7  1 30  6  3 -1  4 NA
63:  7  0 21  1  1 -2  5 NA
64:  7  0 22  1  2 -1  5 NA
65:  7  1 23  2  1 -1  5 NA
66:  7  0 24  3  1 -2  5 NA
67:  7  0 25  3  2 -1  5 NA
68:  7  1 26  4  1 -1  5 NA
69:  7  0 27  5  1 -1  5 -1
70:  7  1 28  6  1 -3  5  1
71:  7  1 29  6  2 -2  5  2
72:  7  1 30  6  3 -1  5  3
    id TF rn rl up dn V1 PM

Finally, the intermediate result is reshaped from long to wide format.
res <-
  # create a "cartesian join" of all possible changes with the rows of each group
  tmp[tmp[, seq_len(max(rl) - 1L), by = .(id)], on = .(id), allow.cartesian = TRUE][
    # copy descending counts to rows before the switch
    rl == V1, PM := dn][
      # copy ascending counts to rows after the switch
      rl == V1 + 1L, PM := up][
        # reshape from wide to long with the change count as new columns
        , dcast(.SD, id + TF + rn ~ sprintf("PM%02d", V1), value.var = "PM")][
          # join with original df to get NA rows back in
          df, on = .(rn, id, TF)][
            # omit helper column
            , -"rn"]

Comment: truly amazing! I've run it on my _production data_ and it works like a charm. Only hiccup is the sorting of `PM#` when `#` gets more then two digits. As I do not understand all of your code I made a temporarily fix by adding a `sprintf("%02d", ... )` so that I have `paste0("PM", sprintf("%02d",V1)`. This solution also work on my _production data_ (which generates up to `PM12`). This was obviously my mistake. I am truly grateful for your answer!
Comment: You could change/adapt this to `tidyverse` for [this Q](https://stackoverflow.com/questions/46799063/using-tidyverse-counting-after-and-before-change-in-value-within-groups-gener) (which seems very similar to this one)
Comment: @Uwe, I'm trying to make a slight modification to your code. After having spent more then an hour on it I am asking for your help. I don't longer want to collapse/ignore the `NA`'s. Such that case # 3, within `id == 0`, that is currently counted as `-3` is simply `NA` in `PM1`. This would also affect `PM2`, within `id == 0`, such that there is no shift at all there,a s the shift is separated by an `NA`. Could you possible point me to how I make this modification? If you like I am happy to post a new question. Thank you in advance for your kindness.
Comment: @EricFail, I'm afraid I don't have an immediate solution at hand. I need to deep dive in into my own code + I'm not sure I do fully understand what you are after. Perhaps, I need to see the expected result just to make sure that I am on the right track. So, it might be a good idea indeed to post a new question.
Comment: @Uwe, Thanks a lot! As per your suggested I've now posted [an updated version of the question](https://stackoverflow.com/questions/48306565/counting-values-after-and-before-change-in-value-within-groups-generating-new). I'll keep working to see if I can figure it out too. Thanks again!
Answer: I think the cartesian join is unnecessary:
library(data.table)
tmp <- setDT(df)[, rn := .I][!is.na(TF)][, rl := rleid(TF), by = id][
                 , `:=`(up = 1:.N, down = -.N:-1), by = .(id, rl)][
                 , `:=`(last = (rl == max(rl)) * (-down)), by = id]

up   = dcast(tmp, rn ~ rl, value.var = 'up'  , fill = 0)
down = dcast(tmp, rn ~ rl, value.var = 'down', fill = 0)
last = dcast(tmp, rn ~ rl, value.var = 'last', fill = 0)

rl.max = tmp[, max(rl)]
res = down[, 2:rl.max] + up[, 3:(rl.max+1)] + last[, 2:rl.max]

res[res == 0] = NA
res[, rn := up$rn]

setcolorder(res[df, on='rn'][,-'rn'], c('id','TF', 1:(rl.max-1)))[]
#    id TF   1   2   3   4   5
# 1:  0 NA  NA  NA  NA  NA  NA
# 2:  0  0  -3  NA  NA  NA  NA
# 3:  0 NA  NA  NA  NA  NA  NA
# 4:  0  0  -2  NA  NA  NA  NA
# 5:  0  0  -1  NA  NA  NA  NA
# 6:  0  1   1  -3  NA  NA  NA
# 7:  0  1   2  -2  NA  NA  NA
# 8:  0  1   3  -1  NA  NA  NA
# 9:  0 NA  NA  NA  NA  NA  NA
#10:  0  0  NA   1  NA  NA  NA
#11:  0  0  NA   2  NA  NA  NA
#12:  1 NA  NA  NA  NA  NA  NA
#13:  1  0  -3  NA  NA  NA  NA
#14:  1  0  -2  NA  NA  NA  NA
#15:  1  0  -1  NA  NA  NA  NA
#16:  1  1   1  NA  NA  NA  NA
#17:  1  1   2  NA  NA  NA  NA
#18:  1  1   3  NA  NA  NA  NA
#19:  1 NA  NA  NA  NA  NA  NA
#20:  7 NA  NA  NA  NA  NA  NA
#21:  7  0  -2  NA  NA  NA  NA
#22:  7  0  -1  NA  NA  NA  NA
#23:  7  1   1  -1  NA  NA  NA
#24:  7  0  NA   1  -2  NA  NA
#25:  7  0  NA   2  -1  NA  NA
#26:  7  1  NA  NA   1  -1  NA
#27:  7  0  NA  NA  NA   1  -1
#28:  7  1  NA  NA  NA  NA   1
#29:  7  1  NA  NA  NA  NA   2
#30:  7  1  NA  NA  NA  NA   3
#    id TF   1   2   3   4   5

Comment: I'm trying to make a slight modification to your code. After having spent more then an hour on it I am asking for your help. I don't longer want to collapse/ignore the `NA`'s. Such that case # 3, within `id == 0`, that is currently counted as `-3` is simply `NA` in `PM1`. This would also affect `PM2`, within `id == 0`, such that there is no shift at all there,a s the shift is separated by an `NA`. Could you possible point me to how I make this modification? If you like I am happy to post a new question. Thank you in advancef ro your kindness.
Comment: I've now posted [an updated version of the question](https://stackoverflow.com/questions/48306565/counting-values-after-and-before-change-in-value-within-groups-generating-new). Thanks.


Count of selected rows is not updated correctly in a DT datatable

Question: I have a simple shiny app
#ui.r
navbarPage(
  "Application",
  tabPanel("General",
           sidebarLayout(

             sidebarPanel(
               uiOutput("tex2")

             ),
             mainPanel(
               DT::dataTableOutput("hot3")

             )
           )))
#server.r
library(shiny)
library(DT)
library(tidyverse)
server <- function(input, output,session) {
  output$tex2<-renderUI({
    numericInput("text2","Rows selected",
                 value = input$hot3_rows_selected,
                 min=0
    )
  })

  output$hot3 <-DT::renderDataTable(
      iris %>% rowid_to_column("Row") %>% mutate(Row = ""),
      rownames = FALSE,
      extensions = "Select",
      options = list(
        columnDefs = list(list(className = "select-checkbox", targets = 0, orderable = FALSE)),
        select = list(style = "multi", selector = "td:first-child")
      ))
}

I have a numericInput() which should normally display the count of rows selected in the datatable but as you will see it displays only the first row selected and not the count of them.
Answer: To show the count of rows selected you need the length of input$hot3_rows_selected (use length(input$hot3_rows_selected) instead).
library(shiny)
ui <- navbarPage(
    "Application",
    tabPanel("General",
        sidebarLayout(
            sidebarPanel(uiOutput("tex2")),
            mainPanel(DT::dataTableOutput("hot3"))
        )
    )
)
server <- function(input, output,session) {

    library(tidyverse)
    output$tex2 <- renderUI({
        numericInput("text2", "Rows selected",
                     value = length(input$hot3_rows_selected),
                     min = 0)
    })

    output$hot3 <- DT::renderDataTable(
        iris %>%
            rowid_to_column("Row") %>%
            mutate(Row = ""),
        rownames = FALSE,
        extensions = "Select",
        options = list(
            columnDefs = list(list(className = "select-checkbox", targets = 0, orderable = FALSE)),
            select = list(style = "multi", selector = "td:first-child")
        )
    )
}

shinyApp(ui, server)


Questions about the imagefield of CCK

Question:
How can I include the text between the label of image field and the upload button?
How can I remove the text "maximum file size" of the image field in some content types? I want to remove the text "maximum file size" but I want to keep "allowed extensions."
Answer: assuming that you are talking about the 'edit form', you can use css to control the visibility of these fields in this way:

/*---------------------------this rule is to hide the text"maximum file size"and "allowed extensions"*/
div#edit-field-cl-namefiled-upload-wrapper div#edit-field-namefiled-upload-wrapper div.description{
display:none;
}

/*---------------------------this rule is to move your descriptionnear to the field to upload.here you can add the "allowed extensions.." text*/
div#edit-field-namefiled-upload-wrapper > div.description{
margin-top:-70px;
position:absolute;
}

Questions about the imagefield of CCK


Why does custom font appears only after few milliseconds when starting app? Render problem? - Android Studio

Question: I have an app with a splash screen followed by the main activity with some TextViews in it.
I'm using font family "aladin" which I have choosen from Attributes > fontFamily > More Fonts... .
The problem is, when I start my app the splash screen appears correctly BUT when my main activity follows, for a millisecond you can see that the font in my TextView is jumping from "default" to aladin.
In other words, it seems as if it takes too much time for the aladin font to render/load.
How can I fix this??
I have already played around with changing textsize from sp to dp but that doesn't solve my problem.
The aladin font should come up immediately, not after a millisecond, it just doesn't look nice.
Thank you very much in advance.
    <TextView
        android:id="@+id/textViewItem"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="0dp"

        android:fontFamily="@font/aladin"

        android:gravity="center|center_horizontal"
        android:textColor="#000000"
        android:textSize="26sp" />

EDIT:
here is part of my AndroidManifest.xml:
        <activity
            android:name=".SplashActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <activity
            android:name=".MainActivity"
            android:windowSoftInputMode="adjustPan"
            android:label="@string/app_name">

and here is part of my SplashActivity.java:
public class SplashActivity extends AppCompatActivity {

    private Handler mHandler;
    private Runnable mRunnable;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        mRunnable = new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(getApplicationContext(), MainActivity.class));
                finish();
            }
        };

        mHandler=new Handler();

        mHandler.postDelayed(mRunnable, 1500);
    }

    @Override
    protected void onDestroy (){
        super.onDestroy();
        if(mHandler!=null && mRunnable !=null)
        mHandler.removeCallbacks(mRunnable);
    }
}

Comment: Could you you delay displaying the splash screen until.the font has loaded?
Comment: @BanksySan I'm not sure if I understood your question correctly: I used DelayTime of 1500 as you can see now in my edited question. Is that helpful? Even after this delay the font still changes for a millisecond when Splashscreen disappears.
Comment: Having the same issue here!

@BanksySan, how can I know whether the font has loaded or not? is there a callback?
Answer: I had a similar problem; when the app starts, the text shows up in its default font for a fraction of a second, and then gets redrawn in the custom font. This probably won't bother most users, but it's definitely noticeable.
I also found out that once the custom font is loaded, the subsequent texts are drawn without showing the default font first.
So, the way I worked around is to load the custom font while the splash screen is showing. First, prepare the custom font.

res/font/ubuntu_mono.xml

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

res/value/preloaded_fonts.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="preloaded_fonts" translatable="false">
        <item>@font/ubuntu_mono</item>
    </array>
</resources>

AndroidManifest.xml

    ...

    <meta-data
        android:name="preloaded_fonts"
        android:resource="@array/preloaded_fonts" />

And then in the splash screen's layout, add a TextView with no text in it. This will load the custom font, and by the time the main shows up, the custom font will be ready.

res/layout/splash.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraint_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        ...

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text=""
            app:fontFamily="@font/ubuntu_mono"             <-- custom font
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

Answer: Some fonts are large in size so they take some time to load i.e. a few milliseconds,
there is a simple solution which is to load the fonts programmatically before they appear in the UI by creating an instance of Typeface class  :
For example if you are going to use a specific font called "aladin" do the following :
//First you need to initialize and hook your textview
TextView textView;
textView = findViewById(R.id.textViewItem);

//initialize the font from ressources
Typeface typeFace = ResourcesCompat.getFont(getApplicationContext(),R.font.aladin);
//set the font to the textview
textView.setTypeface(typeFace);

Now you can avoid the delay that occurs when a custom font is loaded from a file. This is because the font is downloaded and cached by the font provider, so it can be accessed more quickly when needed.
Hope this has solved your problem :)


multiple sha1 file hashes conversion

Question: Issue Description:
I'm trying to comply with our Security Advisories. The advisories contain nearly 1000 MD5 & Sha 256 file hashes. I need to convert them into sha1 and update them in our endpoint security product because our endpoint security product only accepts SHA1 hashes. Normally, we use Virus Total (https://www.virustotal.com/#/home/search) to get the SHA1 hashes. But I can only put 1 SHA256 or MD5 hash at a time. Converting hashes into Sha1 is definitely going to take up a lot of production time.
Question:
Is there any way, I can automate the conversion process?
PS: We are running a Windows environment.
TIA
Comment: Where do the hashes come from? Files? Strings? You can use simple shell scripts and command line tools to create hashes from both.
Comment: @GeraldSchneider If OP has *only* the MD5 and SHA256 hashes, then getting the corresponding SHA1 hashes is going to be rather difficult. Thankfully, if your answer is accurate, that's not quite the situation they're in.
Answer: If I understand your question correctly, you have hashes for malware and you need the SHA1 hashes of those malware code instead of MD5 and SHA256.
If this is the case, you can use the API of the VirusTotal site you are already using to query their database directly.
First you need to get an API key.

In order to use the API you must sign up to VirusTotal Community. Once you have a valid VirusTotal Community account you will find your personal API key in your personal settings section. This key is all you need to use the VirusTotal API.

With this API key you can use the API to get the SHA1 hashes from their database.
The API is documented here:
https://developers.virustotal.com/v2.0/reference#file-search
There are also libraries for most popular scripting and programming languages to make the usage of the API easier:
https://support.virustotal.com/hc/en-us/articles/115002146469-API-scripts
Comment: Thanks for your response. I'm looking for bulk conversion of sha1 hashes from sha256 & md5 hashes. I've just singed up on Virus Total. But I'm still trying to understand if this will get the job done. Lastly, how can I use the API Scripts. Thanks.
Comment: It is not possible to "convert" one hash to another. hashes are not reversable. VirusTotal has a database that allows you to look up one hash, and provides you with different hashes of the same source. This is your only way except to get all source files and generate the hashes yourself.
Comment: The API is well documented. We don't provide finished scripts here, you have to do something yourself. You have a list of your hashes. Loop over it with a script and query the API one by one.
Comment: Thanks Gerald, appreciated your support. I was wondering what would make a difference by going that way as you can already get the sha1 hash but only one at a time. What I was looking for was any automation, like python, powershell or Shell scripting to get multiple sha1 hashes from sha256s and md5s. Thanks mate! Cheers!

multiple sha1 file hashes conversion


The letters ABCDEFGH are to be used to form strings of length four

Question:
The letters ABCDEFGH are to be used to form strings of length four.
  How many strings contain the letter A if repetitions are not allowed?

The answer that I have is :
$$ \frac{n!}{(n-r)!} - \frac{(n-1)!}{(n-r)!} = \frac{8!}{4!} - \frac{7!}{4!} = 8 \times 7 \times 6 \times 5 - (7 \times 6 \times 5) = 1470 $$ strings.
If you could confirm this for me or kindly guide in me the right direction, please do let me know.
Comment: you have 7!/4! ways of having 3 letter strings (we are excluding A). Then insert A in 4 places for each. So, the answer is $7!/4! \times 4 = 840$. Posted this here because I may have made a mistake.
Comment: I see your logic, but do you also see my logic ? I do not know which is right , maybe someone else will get in on this.
Comment: Your second term is incorrect. It should be $(n-1)!/((n-1)-r)!$, not $(n-1)!/(n-r)!$.
Comment: If we do it your way (which is fine), note that you should be subtracting "$\dfrac{(n-1)!}{(n-1-r)!}$" which is $7\times 6\times 5\times 4$.
Answer: Fix A first, then the then you have $7$ choices for the remaining $3$ places, then number of possible arrangements: $$7 \times 6 \times 5$$
Now there are exactly $4$ places where the that A possible fit, making the total number of possible arrangements as: $$7 \times 6 \times 5 \times 4 = 840$$
Answer: The answer you have is trying to count as follows: there are $8\times 7\times 6\times 5$ strings of four letters from among ABCDEFGH with no repetitions, and no further restrictions.
If we exclude $A$, then we have $7\times 6\times 5\times 4$ strings of four letters from among BCDEFGH with no repetitions.
So the total number that do include A is equal to the total number, minus those that do not contain $A$.
However, the second term for this count is incorrect: you should have
$$\frac{(n-1)!}{((n-1)-r)!} = \frac{7!}{3!},$$
not  what you have.
Comment: Thank you , I see my mistake, I did 7 choose 3 instead of 7 choose 4. Rookie mistake.
Answer: I presume I am correct. Here is a detailed proof.
First exclude 'A' and permute the rest (7P3). Which can be done in $\frac{7!}{4!}$ ways.
Then, include 'A' back into those permuted cases. $|X_1|X_2|X_3|$ and as indicated by the vertical lines can be in 4 locations. So, the answer is
$$\frac{7!}{4!} \times 4 = 840$$
Answer: There are ${7\choose 3}=35$ ways to choose 3 letters from BCDEFGH. Add an "A" to this set and arrange these four distinct letters in $4!$ ways. This gives $35\cdot 24=840$ strings in total.


How to display only some terms of a specific vocabulary in Views

Question: I have a taxonomy vocabulary (Drupal 7) called "Categories", with 6 terms: a, b, c, d, e, f
I can't see a way to create a view that will show just terms b, d, e (i.e. any sub-set of the full term list).
This seems like something that should be easy to do. Hopefully it is and I am just missing something, though an hour of searching has turned up nothing...
Any suggestions?
Answer: This can be achieve through View,

Create a view based on the Taxonomy (Strucutre->view->View settings)
Choose Page or Block View.
Select the desire fields in the field section
Add the taxonomy vocabulary ( categories) and Add term in Filter criteria, and select the Drop down, select the select the hirarchy.

Then it will show the term what you want to filter, select the b,d,e terms over there
And then, b,d and e terms only will be shown in View.
Comment: That was it! I feel silly that I couldn't figure that out, but now I know... Thanks!


ldapsearch formatted table output into file awk

Question: I retrieve from LDAP all kerberos users (but only some of their variables e.g. kerberosid,location, mail, name, surname,... ) into a flat file (delimiter is pipeline).
I tried to use LDAP syntax from LDAPSEARCH into table format
but I am getting mixed values I mean (I can see e.g. the same name in next line, but next line in the file starts with second LDAP record, etc.)
Performance is important.
I would prefer to have even empty string in position where value is missing. I am not sure if this is not happening because in some previous records whole index (variable e.g. mail) is missing and from this position all is shifted...
Code block from the link :
$ ldapsearch -x -D "cn=something" | awk -v OFS=',' '{split($0,a,": ")} /^mail:/{mail=a[2]} /^uidNumber:/{uidNumber=a[2]} /^uid:/{uid=a[2]} /^cn/{cn=a[2]; print uid, uidNumber,cn , mail}' > ldap_dump.csv

Ldap search output:
dn: xxxxx
objectClass: top
mail: 11111
uidNumber: 222 222
uid: 333, 3333
cn: 44444
somethingnext: 5555

dn: new records
objectClass: top
mail: aaaaa
uidNumber: bbbbb
uid: cccc, cccc
cn: ddddd
somethingnext: eeeee

each line is on new line and between records is empty new line
Needed output in a file should be :
11111|222 222|333, 3333|44444
aaaaa|bbbbb|cccc, cccc|ddddd

Comment: What is the output of `ldapsearch -x -D "cn=something"`? And how would you like it to be presented?
Answer: Use the following awk:
awk 'BEGIN{RS=""; OFS="|"}
     { mail = cn = uidNumber = uid = ""
       for(i=1;i<=NF;++i) {
          if ($i ~ /^mail:/) { mail=substr($i,7) }
          else if ($i ~ /^uidNumber:/) { uidNumber=substr($i,12) }
          else if ($i ~ /^uid:/      ) { uid=substr($i,6) }
          else if ($i ~ /^cn:/       ) { cn=substr($i,5) }
       }
       print mail,uidNumber,uid,cn
     }'

A corrected version of your original version is:
awk 'BEGIN{FS=": *"; OFS="|"}
     (NF==0) { print uid,uidNumber,cn,mail }
     (NF==0) { mail = uidNumber = uid = cn = ""; next }
     {split($0,a,": ")}
     /^mail:/{mail=a[2]}
     /^uidNumber:/{uidNumber=a[2]}
     /^uid:/{uid=a[2]}
     /^cn/{cn=a[2]}
     END{ print uid,uidNumber,cn,mail }'

Comment: actually values have various length. I am using split function to put them into array.

I took idea form the example, so far I've got here but it doesn't work:

$ ldapsearch -x -D "cn=something" | awk -v OFS=',' '{split($0,a,": ")} { mail="";
 if(a[1] ~ /^mail:/) mail=a[2];}  /^uidNumber:/{uidNumber=a[2]} /^uid:/{uid=a[2]} /^cn/{cn=a[2]; print uid, uidNumber,cn , mail}' > ldap_dump.csv

What am I doing wrong ?
I am beginner with this...
Comment: I found that the mail is not always. It means that first record has mail: 11111  but second doesn't even "mail :"
Comment: @Matt the above should work, as the length of the strings `mail: ` and `uid: ` are always the same.
Comment: @Matt your problem is that you do not reset the variables to an empty string. you should check if you have zero fields for the reset. I.e. your first awk line should read `(NF==0){mail=uidNumber=uid=cn=""}`
Comment: is it possible to transform it somehow for my example with the split command ?


Memory fences: acquire/load and release/store

Question: My understanding of std::memory_order_acquire and std::memory_order_release is as follows:
Acquire means that no memory accesses which appear after the acquire fence can be reordered to before the fence.
Release means that no memory accesses which appear before the release fence can be reordered to after the fence.
What I don't understand is why with the C++11 atomics library in particular, the acquire fence is associated with load operations, while the release fence is associated with store operations.
To clarify, the C++11 <atomic> library enables you to specify memory fences in two ways: either you can specify a fence as an extra argument to an atomic operation, like:
x.load(std::memory_order_acquire);

Or you can use std::memory_order_relaxed and specify the fence separately, like:
x.load(std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);

What I don't understand is, given the above definitions of acquire and release, why does C++11 specifically associate acquire with load, and release with store?  Yes, I've seen many of the examples that show how you can use an acquire/load with a release/store to synchronize between threads, but in general it seems that the idea of acquire fences (prevent memory reordering after statement) and release fences (prevent memory reordering before statement) is orthogonal to the idea of loads and stores.
So, why, for example, won't the compiler let me say:
x.store(10, std::memory_order_acquire);

I realize I can accomplish the above by using memory_order_relaxed, and then a separate atomic_thread_fence(memory_order_acquire) statement, but again, why can't I use store directly with memory_order_acquire?
A possible use case for this might be if I want to ensure that some store, say x = 10, happens before some other statement executes that might affect other threads.
Comment: In a typical lock-free algorithm, you read an atomic to see if a shared resource is ready for consumption (ready to be acquired), and you write an atomic to indicate that a shared resource is ready to be used (to release the resource). You don't want reads of the shared resource to move before the atomic guarding it is checked; and you don't want initialization of the to-be-shared resource to move after the atomic is written to, indicating release.
Comment: In the example only `atomic_thread_fence(std::memory_order_acquire)` is a true fence.  See **1.10:5 Multi-threaded executions and data races [intro.multithread]** in the standard, which says (quoting the draft n3797) _"A synchronization operation without an associated memory location is a fence and can be either an acquire fence, a release fence, or both an acquire and release fence."_  In contrast, `x.load(std::memory_order_acquire)` is an _atomic operation_ that does an _acquire_ operation on `x`, it would be a _synchronization operation_ if the value matches a store _release_ into x.
Comment: In the introduction the standard (draft n3797) doesn't restrict acquire operations to loads and release operations to stores.  That is unfortunate.  You have to go to clause **29.3:1 Order and consistency  [atomics.order]** to find _"memory_order_acquire, memory_order_acq_rel, and memory_order_seq_cst: a load operation performs an acquire operation on the affected memory location"_ and _"memory_order_release, memory_order_acq_rel, and memory_order_seq_cst: a store operation performs a release operation on the affected memory location"_
Comment: @amdn But even a "true fence" doesn't have to produce a CPU fence at all; it interacts with precedent or subsequent atomic operations to produce some effect. Only very naive compilers will associate a given CPU instruction to each source code occurrence of a "true fence".
Comment: "_is orthogonal to the idea of loads and stores_" Under atomic semantics as reads aren't even ordered events in the modification order. You need a write to get a place into that order; even you just always write the exact same value, the writes of the exact same value is ordered. Then you speak of after that write event in the modification order. (Physically that means a cache has taken the cache line.) But a release read would be ambiguous as other reads of the same write event aren't ordered. Would you change the semantic to include reads in the modification order?
Comment: OTOH adding acquire writes to the semantic seems simpler as they are ordered but just don't observe a write. Just pretend the previous write was observed, and its value was ignored, like what I call the throw-away-acq: `(void)x.load(mo_acquire);` (which is an operation that is seldom used).
Comment: I just found [this article](https://dev.to/kprotty/understanding-atomics-and-memory-ordering-2mom) which describes concept of acquire/release synchronization with good example , that may be helpful for someone who is confused about it .
Answer: Say I write some data, and then I write an indication that the data is now ready. It's imperative that no other thread who sees the indication that the data is ready not see the write of the data itself. So prior writes cannot move past that write.
Say I read that some data is ready. It's imperative that any reads I issue after seeing that take place after the read that saw that the data was ready. So subsequent reads cannot move behind that read.
So when you do a synchronized write, you typically need to make sure that all writes you did before that are visible to anyone who sees the synchronized write. And when you do a synchronized read, it's typically imperative that any reads you do after that take place after the synchronized read.
Or, to put it another way, an acquire is typically reading that you can take or access the resource, and subsequent reads and writes must not be moved before it. A release is typically writing that you are done with the resource, and preceding writes must not be moved to after it.
Answer: (Partial answer correcting a mistake in the early part of the question.  David Schwartz's answer already nicely covers the main question you're asking.  Jeff Preshing's article on acquire / release is also good reading for another take on it.)

The definitions you gave for acquire / release are wrong for fences; they only apply to acquire operations and release operations, like x.store(mo_release), not std::atomic_thread_fence(mo_release).

Acquire means that no memory accesses which appear after the acquire fence can be reordered to before the fence.  [wrong, would be correct for acquire operation]

Release means that no memory accesses which appear before the release fence can be reordered to after the fence.  [wrong, would be correct for release operation]

They're insufficient for fences, which is why ISO C++ has stronger ordering rules for acquire fences (blocking LoadStore / LoadLoad reordering) and release fences (LoadStore / StoreStore).
Of course ISO C++ doesn't define "reordering", that would imply there is some global coherent state that you're accessing.  ISO C++ instead
Jeff Preshing's articles are relevant here:

Acquire and Release Semantics (acquire / release operations such as loads, stores, and RMWs)
Acquire and Release Fences Don't Work the Way You'd Expect explains why those one-way barrier definitions are incorrect and insufficient for fences, unlike for operations.  (Because it would let the fence reorder all the way to one end of your program and leave all the operations unordered wrt. each other, because it's not tied to an operation itself.)

A possible use case for this might be if I want to ensure that some store, say x = 10, happens before some other statement executes that might affect other threads.

If that "other statement" is a load from an atomic shared variable, you actually need std::memory_order_seq_cst to avoid StoreLoad reordering.  acquire / release / acq_rel won't block that.
If you mean make sure the atomic store is visible before some other atomic store, the normal way is to make the 2nd atomic store use mo_release.
If the 2nd store isn't atomic, it's unlikely any reader could safely sync with anything in a way that it could observe the value without data-race UB.
(Although you do run into a use case for a release fence when hacking up a SeqLock that uses plain non-atomic objects for the payload, to allow a compiler to optimize.  But that's an implementation-specific behaviour that depends on knowing how std::atomic stuff compiles for real CPUs.  See Implementing 64 bit atomic counter with 32 bit atomics for example.)
Comment: I should've provided Jeff's post as a comment rather than a pure link-only answer. But actually it's even greater to have this nice answer. So thank you and my answer can keep hidden :)
Answer: std::memory_order_acquire fence only ensures all load operation after the fence is not reordered before any load operation before the fence, thus memory_order_acquire cannot ensure the store is visible for other threads when after loads are executed. This is why memory_order_acquire is not supported for store operation, you may need memory_order_seq_cst to achieve the acquire of store.
As an alternative, you may say
x.store(10, std::memory_order_releaxed);
x.load(std::memory_order_acquire);  // this introduce a data dependency

to ensure all loads not reordered before the store. Again, the fence not work here.
Besides, memory order in atomic operation could be cheaper than a memory fence, because it only ensures the order relative to the atomic instruction, not all instruction before and after the fence.
See also formal description and explanation for detail.
Comment: The first sentence is not quite right (-1). Actually, *any memory access* that follows an acquire fence cannot be reordered with any load operation that precedes that fence. (Conversely, any memory access that precedes a release fence cannot be reordered with any store operation that follows that fence.)
Comment: @Aditya stores and loads to the same atomic variable (in the same thread) cannot be reordered.
Comment: @JohnWickerson Actually `memory_order_releaxed` only ensures loads after fence happens after any atomic operation or fence with `memory_order_release`. It do not provides any ordering in stores after the fence. See atomic-fence synchronization section in [`atomic_thread_fence`](http://en.cppreference.com/w/cpp/atomic/atomic_thread_fence)
Comment: Interesting! I believe that the cppreference.com website that you refer to is actually wrong here. According to the official C11 standard, release and acquire fences behave in the way I described.
Comment: If you're interested, I have written a little more about the issue on my blog: https://johnwickerson.wordpress.com/2016/08/11/cppreference-acquirerelease-wrong/
Comment: I have a question regarding the code mentioned in this answer. I think the code here does not make any sense, since the 'x.store' operation itself can be reordered after the acquire fence. So, even if the loads after the acquire may not be reordered before the acquire fence, the store itself can go after the acquire, right?


Drupal upload file size error message

Question: Keep getting an error message re: file size: "The selected file could not be uploaded. The file is 53 KB which would exceed your disk quota of 2 MB." It says I am allowed 2MB per dowload, so if this file is 53KB, how can I be exceeding my quota?  I am stuck.
Comment: What module are you using for the uploads?  Is it the Drupal core, or a CCK module?
Answer: If you're using the Drupal core "Upload" module... go to [your site]?q=admin/settings/uploads, there are settings for the file uploads.  You more than likely have a file upload limit on the "per user" settings, and you've used that up so far.  Bump that up really high, and you should be just fine.
Answer: Quota is total usage. This means you have less than 53kb left until you reach 2mb.

Drupal upload file size error message


two definition of variance identity

Question: $I_n$ is the indicator rv where $I_n=1$ if $A_n$ occurs and 0 otherwise.
Then define $\eta_n = \sum_{k=1}^n I_k$
I'm given this statement:

But in another post about the same proof, I have this:

$X_n$ is the same r.v. as $\eta_n$
But in the first case, $\sigma^2(\eta_n)$ is the standard deviation but in the second case, $V(X_n)$ is variance.
Are variance and standard deviations supposed to be equal?
This is the link to the first case page 8
This is the link to the second case enter link description here
Answer: Usually, the standard deviation is denoted with $\sigma$ and it is the square root of the variance. It seems to me that there is a mistake in the upper statement: the standard deviation should be $\sigma$ (without the square); so they should either have written "we denote the standard deviation by $\sigma(X)$" or "we denote the variance by $\sigma^2(X)$". That is the only way the equation is correct anyway.
Comment: thanks for the clarification!

two definition of variance identity


Multi-users chat room data structure in Firebase Database

Question: I'm having hard time figuring out how to structure multi users chat room FirebaseDatabase architecture properly.
Basically, the app supports private messages between users (could be between 2 users or multiple users). If it was between 2 users only, the data structure is quite easy really.
I'm trying to reduce the cost (I don't want when the current logged user is having a chat with someone and the observer is getting all the messages that are no related to this particular chat) and structure the data properly. If it was between 2 users only, I could always add the recepient under the current user ID and query only that node. But with multiple users (not even sure how many of them) I need to rely on a chat room Id but I'm having hard time with that.
So, here's the idea, let's say the user selects another to start a chat with. I was thinking about something like this:

The problem that I'm facing with this is maintaining that chatId. Every time the user is about to send a new message, how do I check if there's already a chat with the same recepient (or recepients) based on the chatId. This is the confusing part for me. I'm stuck on this for days now and I can't figure out a proper way to maintain that chatId and query it properly. Any help is welcome.
Comment: @FrankvanPuffelen what if you have 30 participants? Wouldnt the `uid` get way too long? I'm not sure if there's a max limit when it comes to the `id` lenght in `Firebase`. Like, let's say your typical user `uid` is this long `5JiKVeb2FmdMD626iyYjRyKDkkf2`. Now if we get ALL of the user `uid`s, would that be allowed/accepted as `roomId` value since it's gonna be soooo long?
Comment: I typically recommend using a "room ID" that is based on the UIDs of the participants. That means that you'll always get the same room ID for the same participants. For a simple example of this, see http://stackoverflow.com/questions/33540479/best-way-to-manage-chat-channels-in-firebase
Comment: You could do a hash of the concatenated UIDs in that case. Chances of collisions seem very small to me. Alternatively you can create a separate lookup of room IDs for each user, such as shown here: https://stackoverflow.com/questions/51885395/how-to-extract-all-child-in-firebase-with-certain-part-of-the-id-iqual-to-some-s/51889179#51889179 and https://stackoverflow.com/questions/50146628/loading-chats-from-firebase-swift/50146697#50146697 and here https://stackoverflow.com/questions/48178492/how-to-observe-all-firebase-database-events-between-two-users-at-concurrent-time/48179082#48179082
Answer: If I understand the question, the app has multiple users and those users could have chats 1-1 or 1-many and you want to avoid users getting events for chats they are not part of.
Let's start with a users node
users
  uid_0
    name: "Bill"
    chats:
      chat_id_0: true
      chat_id_9: true
  uid_1
    name: "Jesse"
    chats:
      chat_id_0: true
      chat_id_6: true
  .
  .
  .

and then a simplified chats node
chats
   chat_id_0:
     uid_0: "Hey there, Jesse"
     uid_1: "Sup Bill?"
   chat_id_6:
     uid_0: "This is Bill, anyone around?"
   chat_id_9:
     uid_1: "Look ma, no hands"
     uid_7: "Impressive"

In the above, chat_id_x is created with .childByAutoId when the user starts a chat.
When Bill logs in (uid_0) read in his chats node and then add observers to the chats listed within that node. In this case, Bill is part of chat_id_0 and chat_id_9. Do the same process for Jesse who is part of 0 and 6.
Both Bill and Jesse are having a chat in chat_id_0, Bill is awaiting a reply from any users also watching chat_id_6 and Jesse is conversing with uid_7 in chat_id_9.
From there any time there's an event (.childAdded when a new message is added to a chat for example) only those users observing that chat ('subscribed') will receive an event.
Obviously more detail would be included in each chat node (timestamp etc)

how do I check if there's already a chat with the same recepient (or
  recepients) based on the chatId

There's several ways to tackle this;
One is that when an observer is added to each of the chats you are part of (.childAdded) each child node within that chat node will be returned to your app. This is good for two things - one is to populate the UI with the existing chat messages and secondly... you will then know who was involved with that chat. Keep those UID's in an array with the chat id, and before sending a chat to that person see if they exist in the array as an existing chat.
A second option is to query for all the chat's the users uid appears in (query using .observeSingleEvent). That will return all of the chat nodes they belong to and then have the uid's of who else they've chatting with and the chat id's as well.
Another option is when the chat is created, /chat_id_0, add a child node called /who_dat that keeps a list of who was invited to the chat
chats
  chat_id_0
     who_dat
        uid_0: true
        uid_1: true
        uid_2: true
     messages:
        uid_0: "Hey there, Jesse"
        uid_1: "Sup Bill?"

in this case uid_2 was also added to chat_id_0 but haven't heard from them yet.
Comment: Excellent! Thank you for the detailed explanation, I feel like I'll have further questions, but I'll post them separately as I reach that point. Thank you again!


Question on continuous functions

Question: This is according to Tao Theorem 15.1.6 (c) the last part. Let $R > 0$ be the radius of convergence of some formal power series
$$
\sum_{n=0}^\infty c_n(c-a)^n
$$ Then we may define
$$
 f: (a-R,a+R) \rightarrow \mathbb R: x \mapsto \sum_{n=0}^\infty c_n(x-a)^n
$$
We know that for all $0 < r < R$ the series $\sum_{n=0}^\infty c_n(x-a)^n$ converges uniformly on $[a-r,a+r]$ (Weierstrass M-test) to a continuous function $f$ which is the function $f$ defined above restricted to that compact interval. Now I have to show that $f$ is continuous. My attempt:
Let $x_0 \in (a-R,a+R)$. Then $|a-x_0| < R$. Then we can find some $r \in \mathbb R$ such that
$$
|x_0-a| < r < R
$$ In particular $|x_0-a| \leq r < R$. Thus $x_0 \in [a-r,a+r]$ with $0 < r < R$. On that interval $f$ is continuous. Thus $f$ is in $x_0$ continuous. Since $x_0$ was arbitrary the claim follows.
Is that correct ?
Comment: You should state $|x_0-a|<r$ implies $x_0\in(a-r,a+r)$. $f$ restricted to $[a-r, a+r]$ is continuous at the *interior* point $x_0$; so $f$ is continuous at the point $x_0$.
Answer: The idea is correct, but your write up is a bit off. Knowing that $x_0\in  [a-r, a+r]$ tells you that $f$ restricted to $[a-r,a+r]$ is continuous. Then $f$ will be continuous at $x_0$ if $x_0\in (a-r,a+r)$ (you can't conclude the same from the foregoing if  $x_0$ is one of $a-r$ or $a+r$).
But you're ok; in fact $|a-x_0|<r$ implies $x_0\in(a-r,a+r)$. So change your second to last paragraph to something like:
"We have $|x_0-a| <r < R$. Thus $x_0 \in (a-r,a+r)\subset[a+r,a-r]$ with $0 < r < R$. On the interval $ (a-r,a+r)$,  $f$ is continuous. Thus $f$ is    continuous at the point $x_0$. Since $x_0$ was arbitrary the claim follows."
Comment: Thanks for your answer. Just for clarification of your first paragraph: You say we know $f$ is continuous on $[a-r,a+r]$ from which we may not conclude that that if $x_0 \in \{a-r,a+r\}$ follows that $f$ is continuous in $x_0$ ?
Comment: @André Yes. You could only conclude the appropriate one-sided continuity.

Question on continuous functions


How to identify the normalized feature

Question: I have been trying to solve a problem stated in an exam of coursera. I am not seeking the solution but I need to get the steps and concepts to resolve this.
Can any one share the concept and steps to help me find the solution.

UPDATE:
I was expecting a down-vote and its not unusual, as its the most easiest thing people can do. I am seeking the direction to solve the problem as I wasn't able to get the idea to solve it after watching the videos on Coursera. I hope someone sensible out there can share a direction and step to achieve the mentioned goal.
Comment: The answer is in the hint. You need to normalize the features and then see what that turns out to be for the third training example. The keywords in the hint are the __max__ , __min__ and __mean normalization__
Answer: Mean Normalization
Mean normalization, also known as 'standardization', is one of the most popular techniques of feature scaling.

Andrew Ng describes it in the 12a slide of lecture 4:

How to resolve the problem
The problem asks you to standardize the first feature in the third example: midterm = 94;
well, we have just to resolve the equation!

Just for clarity, the notation:
μ (mu) = "avg value of x in training set", in other words: the mean of the x1 column.
σ (sigma) = "range (max-min)", literaly σ = max-min (of the x1 column).

So:
μ = ( 89 + 72 + 94 +69 )/4 = 81
σ = ( 94 - 69 ) = 25
x_std = (94 - 81)/25 = 0.52
Result: 0.52

Best regards,
Marco.
Answer: The first step of solving this question is to identify what is , from the content of the lecture, it refers to the first feature of the third training case. Which is the unsquared version of the midterm score in the third row of the table.
Secondly, you need to understand the concept of normalization. The reason why we need normalization is that the value of some features among all training examples may much larger than the value of other features, which may make the cost function have pretty bad shape and this will make it harder gradient descent to find the minimum. In order to solve this, we want to make all features have nearly the same scale, and make the range of the feature to be centered at zero.
In this question, we want to scale every feature to a scale of 1, in order to do this, you need to find the max and min value of the feature among all training cases. Then squeeze the range of the feature to 0 and 1. The second step is to find the center value of the feature (average value in this case) and move the center value of the feature to 0.
I think this is pretty much all hints I can give you, you will totally be able to calculate the answer to this question by yourself from this point.

How to identify the normalized feature


What do the features in this neural network simulator mean?

Question: While learning about neural networks, I stumbled upon this really cool resource where you can tinker around with NN's architecture and hyperparameters in a point classification problem.
What I'm confused about is the meaning of the input layer which they call the "features."

Since the data is just points, I would assume there could only be two features: the X value and the Y value of each point.
My question:
What do their features mean and why aren't they just using the (X,Y) coordinates of the points as the input data?
Are they perhaps transforming the (X,Y) values into these other features? If so, what are the actual numerical values they are getting transformed into?
Answer: You're right, they are transformed, hand-crafted features, obtained from the original ones, $X_1,X_2$, according to the figure. They could have used only the original features and let the neural network decide which ones to invent. Though this is a tougher process, this is usually what's being done in current deep learning literature. We don't usually have input pixels being squared etc. Or, if you think the hand-crafted features are important by domain knowledge, you can include them to not reinvent the wheel. The transformed values depend on the transformation. For example, if you use $\sin(X_1)$ the value range will be $[-1, 1]$ irrespective of $X_1$'s range.
Comment: The blogpost has a colorbar. Orange to blue means -1 to 1. Colors represent possible transformed values of each (x,y) points. That's why $X_1^2$ has no orange and it's white-ish around $0$ because values around $0$ correspond to white in the colorbar.
Comment: If X1 simply refers to raw value of the x coordinate, what do the colors mean in the little thumbnail? In other words, why is the left side orange and right side blue?


Most universal non-abelian factor group?

Question: $\require{AMScd}$
I understand that given a group $G$, all homomorphisms from $G$ to an abelian group factor through the abelianization of $G$, i.e. maps $G\to A$ factor through projection $G\to G/\left[G, G\right]$.
I was wondering if you could define the same for codomain groups that are not abelian. I am not even sure if "largest non-abelian factor" is well-defined, but I came up with this idea.
Consider $G_0 = G$ in the sequence
$\require{tikzcd}$
\begin{CD}
    G_0 @>\zeta_1>> G_1 @>\zeta_2>> \cdots
\end{CD}
where $G_{i + 1}$  is $G_i / Z(G_i)$ and $\zeta_i$ is projection mod $Z(G_i)$ (alternatively, visualize a herringbone of ses's).
What if at some point
\begin{CD}
\cdots @>\zeta^*>> G^* @>\zeta{^*}'\, \overset{\huge\color{red}?}{=} \,\,\mathrm{id}\,>> G^*
\end{CD}
Certainly this sequence must end if $G$ is finitely generated. If that isn't the case, then my question concerns $G^* = \displaystyle\lim_{\longrightarrow} G_i$.
What exactly lies at the end of this tunnel? As far as I can tell, projection onto $G^*$ uniquely factors all epimorphisms $G\to \text{a non-abelian group}$. Is that right?
Is $Z(G)$ dual to $[G, G]$? What does $G^*$, if it exists, say about $G$?
Comment: Well, you'd have to factor the identity map from $G$ to $G$. In particular if $G$ is nonabelian, you won't be able to find a nontrivial quotient that the identity factors through.
Answer: Already your favourite non-abelian group of order $p^3$ ($p$ any prime) and the identity function show that taking the epimorphisms to non-abelian groups does not work (as commented by Grumpy Parsnip).
Try epimorphisms to center-free groups instead!
For understanding your $G^*$ take a look at the kernels of your maps $\zeta_1:G_0\to G_1$, $\zeta_2\circ\zeta_1:G_0\to G_2$, $\zeta_3\circ\zeta_2\circ\zeta_1:G_0\to G_3$, $\dots$, which are the elements of the upper central series (read also the following section "Connection between lower and upper central series" in the wikipedia for your last question).
Comment: Hint: The image of the center of $G$ under an epimorphism is contained in the center of the image, so if the image has trivial center, the center of $G$ is contained in the kernel of the epimorphism. Now induct.


Product of topological space pairs

Question: I was reading Weintraub's Fundamentals of Algebraic Topology, and encountered a rather strange definition to me: the product of two pairs $(X,A)$ and $(Y,B)$ is $(X\times Y,X\times B\cup A\times Y)$. I don't know where does this $X\times B\cup A\times Y$ come from.
Comment: I do presume you know very well what a product of topological spaces is. Ok. And now you have a "definition" of "a pair". Presumably this definition is made with some purpose in mind. If we know that purpose, it would most likely explain the specific set-theoretic description of "product of a pair". In particular, for example, the product of $(X,A)$ and $(Y,B)$ is not $(X\times Y,A\times B)$, though it's certainly easy enough, notationally, to write that. So, surely the best explanation is to think what "pair" is meant to accomplish, and what a "product" of two would accomplish.
Comment: Do you know some category theory?
Comment: @PaulFrost I do, I know there are product and coproduct, and they are special cases of limit and colimit.
Comment: Okay, then please add the context where the "product pair" appears. Künneth formula?
Answer: In the category of pointed topological spaces, the universal property is $[(X\wedge Y,(x_0,y_0)),(Z,z_0)]=[(X,x_0),((Z,z_0)^{(Y,y_0)},\omega_0)]$ where $[X,Y]$ denotes the set of continuous maps from $X$ to $Y$ while $Z^Y$ denotes the space of continuous maps from $Y$ to $Z$ (with the compact-open topology) and $\omega_0$ is the constant map. The first guy here is the smash product $X\wedge Y=X\times Y/(X\times y_0\cup x_0\times Y)$ which is much more analogous to the tensor product than the categorical product (this is essentially the tensor-hom adjunction, notice that maps between topological spaces themselves form a topological space similar to how homs themselves form a module!) I think that the general case where you're taking a pair relative to an arbitrary subset $A$ should be similar, but I don't quite know what $\omega_0$ would become. Perhaps it makes more sense to consider this as the smash product of $X/A$ and $Y/B$?
Comment: I think more generally, it should be $[(X\times Y,X\times B\cup A\times Y),(Z,C)]=[(X,A),((Z,C)^{(Y,B)},D)]$ where $D$ is the spaces of maps $Y\to Z$ whose image lies in $C$. Thus it is left adjoint to "homs" (space of continuous maps) which becomes a topological pair as described.

Product of topological space pairs


error with submitting a form in wordpress

Question: i've created a plugin (simple form) and this is the shortcode.php file:
<?php
add_shortcode('contact_form','contact_form');

function contact_form(){
    if (isset($_POST['submit'])){
        global $wpdb, $table_prefix;
        $name = $_POST['name'];
        $data = array('name'=>$name,'message'=>'message');
        $wpdb->insert($table_prefix.'contact_form',$data,array('%s','%s'));
        echo 'added';
    }

    ?>
    <form method="POST" action="" id="contact_form">
        Name: <input type="text" name="name">

        <input type="submit" name="submit" value="submit">
    </form>
<?php
}

when I submit the form, if I write sth in the text field, is says 'The page doesn't exist' but if i leave it empty, it submits the form.
what is the problem?
I have used this shortcode in a page.
Comment: Did you add a reference to `action` ?
Answer: See this question on the WordPress StackExchange site.  In summary, WordPress gets confused by a field called name.  Try renaming it to (say) contact_name.
Loads more detail here (also wpse).


Notice: Undefined index: tid in taxonomy_field_formatter_prepare_view() (line 1669 of

Question: I'm getting this error on my website. I have tried cleaning up the content type of all fields but it still shows up.
Any ideas what could be causing it, and how to debug?
Thanks a lot,
Chiko
Comment: Getting a similar issue, how did you fix it ?
Answer: Your content have an taxonomy_term reference field which have invaild data, maybe it break.
You can install devel module and use error display with debug_backtrace and you will see where it comming.
Answer: 1 Open Content Type,
2 manage field tab, clieck save.
3 manage display tab, click teaser , default,  and save


pdo fetchAll() returns empty array()

Question: I have been trying for over a day now to get FetchAll() method to help me display array from database. But all my efforts have failed. Instead of the print_r() returning an array, it gives me this array(). Kindly, help me out.
The code in class page :
class Article {
public function fetch_all(){
    global $conn;
    $ass = $conn->prepare("SELECT * FROM articles");
    $ass->execute();
     return $ass->fetchAll();

    }

}

while the code in display page is:
$article = new Article;
$articles = $article->fetch_all();
 print_r($articles);

Comment: Nice variable naming!
Comment: Check your error logs or try/catch from PDO. Are you sure that PDO correctly connect to the Database? Check `$conn` with `var_dump();`!
Comment: I am sure my PDO connected correctly to the Database.  I used try catch, and it doesn't throw any exception.  The var_dump(); didn't show anything.
Answer: $query is not defined in your code, $ass->fetchAll(); is what you should have.
Comment: the problem persists when I use $ass->fetchAll(); This has been frustrating. Can you think up another reason why the array will be empty?
Answer: $query is not defined. Consider injecting your database object into the Article object to avoid using globals.
class Article {
   public function fetch_all(PDO $conn){
    $ass = $conn->prepare("SELECT * FROM articles");
    $ass->execute();
        return $ass->fetchAll();
    }

}

$article = new Article;
$articles = $article->fetch_all($conn);
print_r($articles);

Injecting your PDO object can make changing the code easier down the line.
Comment: I have changed $query to $ass, but the array() is still empty. I keep the database object separate because I want the coding to be tidy. Can the use of global cause the problem of empty array()?
Answer: I have tried the following code below it works perfect.
class Article {
        public function fetch_all(){
            global $connection;
            $ass = $connection->prepare("SELECT * FROM test");
            $ass->execute();
            return $ass->fetchAll();
        }
    }

    $article = new Article;
    $articles = $article->fetch_all();
    print_r($articles);

As you see above i have used my $connection and it works perfect.
So, the problem is definitely on your $conn (connection).
check your connection again.
Comment: Test, I shall try cheking my connection
Answer: It has eventually started returning full array. All I did was to uninstal the WAMPserver I was using and replace it with another one.

pdo fetchAll() returns empty array()


Generate Javascript file with PHP

Question: My current code
I have started writing an API that loads, minifies and returns javascript files into one file using PHP. This is achieved by pointing to a PHP file from a script tag in HMTL like so:

This jsapi.php page processes the javascript files and outputs the minified javascript, with the header:
header("Content-Type: text/javascript");

My Question
Is this a bad method to load javascript files? Would it be much faster and reliable to load the javascript files individually by simply pointing to the .js file in the src attribute?
If you wish to see my code for the the full API, have a look at this. The mentioned link also explains in detail what it is I am doing and why.
Comment: Nothing bad. Loading together speeds up your web application. You'd better hide your `php` file as `js`, this can be done with `.htaccess`
Comment: No, headers still will be needed. For IE7 (as far as I remember) at least (he is stupid).
Comment: @BogdanBurim Yeah thats what I am going to do :-) If I rewrite the js file to php, will that mean that I do not have to output headers from PHP?
Comment: @BogdanBurim Thought they might have been :-)
Answer: Faster as .js yes, but marginally. The reason being that it would be a static file so wouldn't need the processing time PHP will take.
That said there's nothing wrong with feeding JavaScript through PHP like this. You could even come up with caching methods as well to reduce the processing impact.
Comment: Thank you for your answer, this is what I thought to be honest :-) The reason I asked the question was simply because I was advised not to by the user that answered my question on the Code Review link supplied in the question

Generate Javascript file with PHP


php-fpm-5.6.2 and mod_vhost_alias ProxyPassMatch

Question: I've been using successfully fcgi for php and mod_vhost_alias. Now with new server I was looking into php-fpm which looks interesting with Apache/2.4.6 on CentOS 7. php-fpm setup is working fine but together with mod_vhost_alias I"m not able to construct proper ProxyPassMatch rule.
My mod_vhost_alias setup is VirtualDocumentRoot /var/www/vhosts/%-2.0.%-1.0/%-3+/
Any ideas how to create proper match for any .php to pass to php-fpm running on fcgi://127.0.0.1:9000.
No matter what I do I get only AH01071: Got error 'Primary script unknown\n'
Answer: Try with FilesMatch \.php$ instead of ProxyPassMatch.
Eg.
  <FilesMatch \.php$>
    SetHandler "proxy:unix:/var/run/php5-fpm.sock|fcgi://localhost"
  </FilesMatch>

See a full example: Dynamic development area with Apache 2.4 and PHP-FPM
I hope this help.
Comment: I've been banging my head against the wall on this for over a week. Note that this method requires Apache 2.4.10 or above, so it isn't useful for default Apache 2.4.6 that comes in the CentOS 7 base repositories.


Como resolver um erro de formatação de string?

Question: Estava programando normalmente no VS em modo "Console" quando me deparo com está mensagem:

"A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
  An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
  Additional information: Índice (baseado em zero) deve ser maior ou igual a zero e menor que o tamanho da lista de argumentos.
  The program '[1124] ConsoleApplication4.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0)"

Do que se trata e como resolver?
Código:
string A1;
string A2;
string A3;
string A4;
string A5;
String A6;
String A7;
String A8;

A1 = Console.ReadLine();
A2 = Console.ReadLine();
A3 = Console.ReadLine();
A4 = Console.ReadLine();
A5 = Console.ReadLine();
A6 = Console.ReadLine();
A7 = Console.ReadLine();
A8 = Console.ReadLine();

Console.Write("Segunda: {0}, {1}, {2}, {3}", A1, A2, A3, A4);
Console.ReadLine();
Console.Write("Terça: {4}, {7}, {5}, {1}, {6}", A5, A8, A6, A2, A7);

Console.ReadKey();

Comment: Ao fazer o debug, poste o código de onde a exceção foi acionada, assim, poderemos apontar o problema. Pela msg de erro, o problema está em um dos parâmetros que passou pra alguma função, ou um valor negativo, ou um valor maior que o permitido.
Comment: Passa mais informações, Como o debug mostrada acima, Ou o trecho dos seu código que gera essa exception, Só a mensagem de erro esta muito vago.
Answer: O problem a é que você colocou número do argumento que não existe. Esse números dentro das chaves é o número na ordem que vem argumentos depois do texto de formatação. O primeiro sempre será 0 e vai, 1, 2, e assim por diante quantos tiver, então o último será a quantidade de argumentos passadas menos 1. Se passou 4, eles vão de 0 à 3. Não pode usar os números que usou. O erro ocorreu porque ele não encontrou um argumento de número 4. A string de formatação está com problemas nesse contexto, por isso gera uma exceção em tempo de execução.
Mas podemos fazer de forma mais simples e evitar esse erro. Podemos modernizar esse código simplificando-o bastante. Não precisa declarar a variável antes de atribuir um valor pra ela, não precisa dizer o tipo dela, e não precisa passar argumentos depois da string de formatação.
Use var para fazer inferência, using static para importar a classe estática, e interpolação de string para usar argumentos dentro da string. Assim fica melhor:
using static System.Console;

public class Program {
    public static void Main() {
        var A1 = ReadLine();
        var A2 = ReadLine();
        var A3 = ReadLine();
        var A4 = ReadLine();
        var A5 = ReadLine();
        var A6 = ReadLine();
        var A7 = ReadLine();
        var A8 = ReadLine();
        Write($"Segunda: {A1}, {A2}, {A3}, {A4}");
        ReadLine();
        Write($"Terça: {A5}, {A8}, {A6}, {A2}, {A7}");
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Answer: Seu erro esta nesta linha:
Console.Write("Terça: {4}, {7}, {5}, {1}, {6}", A5, A8, A6, A2, A7);

Os índices neste Console.Write devem começar em 0 e ir até no máximo o número de parâmetros menos 1. Para corrigir, basta trocar os índices dos parametros da escrita, assim:
Console.Write("Terça: {0}, {1}, {2}, {3}, {4}", A5, A8, A6, A2, A7);


Smallest topology containing all topologies

Question:
Let $\{T_\alpha\}$ be a family of topologies on $X$. Show that there is a unique smallest topology on $X$ containing all the collections $T_\alpha$, and a unique largest topology contained in all $T_\alpha$.

We can check that $\bigcap T_\alpha$ is a topology on $X$, so it is the unique largest topology contained in all $T_\alpha$.
Now, a topology containing all $T_\alpha$ must contain $\bigcup T_\alpha$. It must also contain arbitrary unions and finite intersections of sets in $\bigcup T_\alpha$. Since the union of the sets in $T_\alpha$ is $X$, this is the topology generated by the subbasis $\bigcup T_\alpha$. How can we prove that it is the unique smallest one containing all the collections $T_\alpha$?
Answer: Let $\sigma _1$ be the topology generated by $\cup T_{\alpha}$ as a subbasis. Verify that any topology $\sigma_2$ on $X$ that contains $\cup T_{\alpha}$ must satisfy $\sigma_1\subseteq \sigma_2$.


ODE without solutions

Question: Is it possible to find functions $a,b,c$ defined on $\mathbb{R}$, such that
\begin{equation*}
ay'+by=c
\end{equation*}
has no global solution and $a(x)$ and $b(x)$ are never both zero ?
If $c=0$ there is always $y=0$ but I don't know about the general case. I think there is always a solution but I don't know how to prove it and it doesn't fall into the Cauchy-Lipschitz realm.
My question comes from the theory of pasting solutions: when $a(x)$ is zero the affine subset of solutions can be of dimension 0,1,2 according as to how solutions of homogenous equations paste around the singularity. I wonder if it can be empty.
The condition on $a$ and $b$ is to avoid trickery counter-examples like $x^3y'+3x^2y=2x$ whose solutions $y=\frac{1}{x}+\frac{\lambda}{x^3}$ are not global.
Comment: If you do not have any restrictions on the functions a,b,c then it is. It is enough to consider $\text{dom}(a)\cap\text{dom}(b)\cap\text{dom}(c)=\emptyset$.
Comment: @PavelR. I wasn't precise enough, I edited to take into account your remark.
Answer: If $a(x)\ne 0$, then this is not posible. The general solution is
$$
y= \int\frac{c(x)}{a(x)} \exp\left(\int\dfrac{b(x)}{a(x)}\, dx\right)\, dx\;\cdot\;
\exp\left(-\int\dfrac{b(x)}{a(x)}\, dx\right),
$$
or, if we denote as $G(x)$ some antiderivative
of $\frac{b(x)}{a(x)}$ and as $F(x)$ some antiderivative of $\frac{c(x)}{a(x)} \exp\left(G(x)\right)$,
$$\tag{1}
y=(F(x)+C)\cdot \exp(-G(x))=C \exp(-G(x))+F(x)\exp(-G(x)).
$$
Indeed,
$$
y'= C \exp(-G(x))(-G'(x))+F'(x)\exp(-G(x))+
F(x)\exp(-G(x))(-G'(x))
$$
$$
=-C \frac{b(x)}{a(x)}\exp(-G(x))+\frac{c(x)}{a(x)} \exp\left(G(x)\right)\exp(-G(x))-\frac{b(x)}{a(x)}
F(x)\exp(-G(x));
$$
substituting this into the original equation, one obtains
$$
-C b(x)\exp(-G(x))+c(x) -b(x)
F(x)\exp(-G(x))
+C b(x) \exp(-G(x))+b(x)F(x)\exp(-G(x))=c(x).
$$
Consider the initial value problem
$$
a(x)y'+b(x)y=c(x),\quad y(x_0)=y_0.
$$
For any the initial point $(x_0,y_0)$ from (1) we have
$$\tag{2}
y_0=C \exp(-G(x_0))+F(x_0)\exp(-G(x_0))
$$
For any $(x_0,y_0)$ the corresponding constant $C$ can be found:
$$
C=\exp(G(x_0))\left( y_0- F(x_0)\exp(-G(x_0)) \right),
$$
thus, (1) gives a solution for any initial point. Hence, it is a general solution.
Finally, note that (1) gives us a continuous function because the antiderivative of a continuous function is continuous. Hence, the solution is globally defined.
Comment: Thank you very much for your answer, but my interest lies precisely in the case $a(x)=0$. I'll add some motivation as to why in my question.
Answer: Let $a=x,b=1$ and $c=2x$ for positive $x$, $c=0$ for negative $x$.
Then $y=\frac{\lambda}{x}$ on $\mathbb{R}^{*}_{-}$ and $y=x+\frac{\mu}{x}$ on $\mathbb{R}^{*}_{+}$, so the only hope for pasting is $\lambda=\mu=0$ but then $y$ wouldn't be differentiable in $0$.
Another example can be obtained with $c=\text{sgn}(x)\sqrt{|x|}$ where again $y=\frac{2}{3}\sqrt{x}$ is not differentiable in $0$.
Differentiability fails in both examples, but continuity doesn't. If I am not mistaken you can prove (by using the explicit formulae given by AVK) that there is always a solution that extends by continuity to the zero of $A$ (but there may be pasting problems for several zeroes).

ODE without solutions


Why we need Socks Proxy?

Question: Is there any specific reason for customers to choose SOCKS proxy when compared to HTTP Proxy?
Comment: SOCKS can support UDP as well as TCP, also can accept incoming connections with the SOCKS BIND command in SOCKS5.  An HTTP proxy can be used for general TCP connections to other ports (with the CONNECT method), but can only do outbound connections.
Answer: When you don't want to proxy HTTP traffic.
Comment: Or when you want to proxy HTTP **and** other TCP traffic but want to keep your proxy as simple as possible. (One software is easier to maintain than two.)

Why we need Socks Proxy?


Use Rules to create new content and fill the corresponding node_reference field

Question:
I want to use a button to create a new article.
I write two rules to do the following work
snapshot 2

snapshot 3

The snapshot 2 creates a new content; the snapshot 3 fills the field of the content just created.
I can't fill the node reference field; how can i do that?
The button I put is on a different kind of content type.
I hope some body can help me fix this article.
Answer: I found how to fix my own problem
<code>$node->field_YOURFIELD[LANGUAGE_NONE][0]['uid']=$userid;
$node->field_YOURFIELD[LANGUAGE_NONE][0]['nid']=$nid;
</code>
Answer: Perhaps you could have a PHP action like this:
<code>$nid = arg(1); //Gets the nid from the url
$node = node_load($nid);
$node->field_YOURFIELD['und'][0]['target_id'] = 10; //nid of referenced node
node_save($node);
</code>
This works with the Entity References module. I don't know about the node reference module. It might be 'value' instead of 'target id'. You can use the Devel module to find out.
You'll need to enable the PHP module.
Comment: thx for answering, but i have a question,if i change the URL alias,the code "$nid = arg(1)" still can get the node id ?
Comment: It works in D7 even with aliased nodes. Not sure about D6. You need to make sure the code is not firing on the home page otherwise you'll get an error.
Comment: Sorry, i have a PHP action and wrote the same code above.But the return value of arg(1) is 'AJAX' and the return value of arg(0) is 'system'. The corresponding url is "http://localhost/test2/node/35".Could u plz tell me where's problem?
Comment: Thx!i fixed the problem


local variable initiated to zero explicitly and not have an unknown value in c++ language

Question: Testing some snippets, I found a very strange behaviour. I have 2 local variables that it's not initialized. And one that it's used later in the program is always initialized to zero, the other has a garbage value (what I expected to get as a normal behavior). As if the compiler checks that I will use it in a while loop and it initialized to zero implicitly. I don't understand this behavior.
<code>int i,j; // variable declaration and initialization
cout << i <<' '<< j << endl;
while ( i < 10 ) // condition
   { cout << i << '\n';
     i++; // variable update
   }
</code>
If I include the above snippet in a main program, it seems it works well always. The value of i is always zero before it enters the while loop and the while loop works well always. But the variable j has any unknown variable  (garbage)
In fact,I copied this snippet directly from the book: Jumping into C++ by Alex Allain, page # 74. (I added variable j for comparison only)
Comment: Cannot reproduce (probably because it isn't reproducible, as others already said). For yourself, try to boil down your snippet to [example] - not a "snippet to include", but something that is a whole, self-consistent compilable thing. (e.g. I needed to provide `main`, include `iostream` and use `std` in order to compile your code, which means it's already probably different than yours.) Then you can use `-S` switch to see the assembly and see for yourself what is happening. (For C++ you're likely to get over a thousand lines, so keeping it C-only would let you see a clearer picture.)
Comment: https://en.cppreference.com/w/cpp/language/ub
Comment: You can't tell a zero that comes from an initialisation from a zero that just happens to be there. Zero is no less "garbage" than any other number.
Answer: Line 1 of the program is a declaration, not an initialization.  Using uninitialized variables leads to undefined behavior.   It's pure luck that the loop variable i is initialized to 0 if it indeed is 0.


Prove that $\lim_{n\to\infty} \left(\frac{\sqrt{n}(1 + 8\sqrt{n})}{4n - 1}\right) =2$

Question:
Prove that $$\left(\displaystyle\frac{\sqrt{n}(1 + 8\sqrt{n})}{4n - 1}\right)_{n \in \mathbb{N}}\to 2$$

My idea was to find some $N$ to do the definition job of convergence.
\begin{align}\left |\dfrac{\sqrt{n}(1 + 8\sqrt{n})}{4n - 1}-2 \right |&=\left |\dfrac{\sqrt{n}(1 + 8\sqrt{n})-8n+2}{4n - 1} \right |\\
&=\left |\dfrac{\sqrt{n}+8n-8n+2}{4n - 1} \right |\\
&=\left |\dfrac{\sqrt{n}+2}{4n - 1} \right |\\
&\leq \left |\dfrac{\sqrt{n}+2}{n}\right |\\
&\leq \left |\dfrac{\sqrt{n}}{n}\right |+ \left |\dfrac{2}{n}\right |\\
&\leq \dfrac{1}{\sqrt{n}}+2\\
&\leq 3
\end{align}
so I concluded that the sequence is bounded, so my idea was trying to show that this sequence is monotonous, so I could conclude that it converges. Taking $n = 4k$ I get a subsequence that converges to $2$, so if I knew that the sequence is convergent, the problem would be over.
Answer: With what you've done, you don't need to show the sequence is monotonous. To show this converges, we want to say that for all $\varepsilon > 0$ there exists an $N$ such that for all $n>N$
$$\left |\dfrac{\sqrt{n}(1 + 8\sqrt{n})}{4n - 1}-2 \right | < \varepsilon$$
And if we stop before your last step, we get
$$\left |\dfrac{\sqrt{n}(1 + 8\sqrt{n})}{4n - 1}-2 \right | \leq \frac{1}{\sqrt{n}}+\frac{2}{n}$$
Then, pick $N$. one choice might be $N=\lceil 4/\varepsilon^2\rceil$, in which case (for all $\varepsilon <1$)
$$\left |\dfrac{\sqrt{N}(1 + 8\sqrt{N})}{4n - 1}-2 \right | \leq \frac{1}{\sqrt{N}}+\frac{2}{N} \leq \frac{\varepsilon}{2}+\frac{\varepsilon^2}{2}< \varepsilon$$
And since $1/\sqrt{n}+2/n$ is decreasing in $n$, for any fixed $\varepsilon>0$, we have chosen an $N$ such that for all $n>N$
$$\left |\dfrac{\sqrt{N}(1 + 8\sqrt{N})}{4n - 1}-2 \right | < \varepsilon$$
And that is precisely the definition of a convergent sequence.
Answer: What you could have also done is
$$\left(\frac{\sqrt{x}(1 + 8\sqrt{x})}{4x - 1}\right)'=-\frac{4 \left(x+4 \sqrt{x}\right)+1}{2 (4 x-1)^2 \sqrt{x}} <0$$ So, the squence is decreasing.
Now, for large values of $n$
$$\frac{\sqrt{n}(1 + 8\sqrt{n})}{4n - 1}=2+\frac 1 {4\sqrt n}+O\left(\frac{1}{n}\right)$$
Answer: Don't be afraid to simplify even more, eliminate all additions if possible.
Get also rid of fractions by bounding them with an integer (here $\frac 23<1$).
For $n$ large then $2<\sqrt{n}$ (i.e. $n>4$) and $-1>-n$
$$\left|\frac{\sqrt{n}+2}{4n-1}\right|<\left|\frac{\sqrt{n}+\sqrt{n}}{4n-n}\right|=\left|\frac{2}{3\sqrt{n}}\right|<\frac 1{\sqrt{n}}\to 0$$ much easier to pick $N,\epsilon$ now.


Unique Key and Index - Should I use both

Question: I have a table with some "phone numbers", "zip codes" and "house numbers", so they are Unique in the table (phone X can only be at zipcode Y and house number Z one time ) so I created a unique key with these 3 together, but I also want to search for a phone number, find which phones are in a zipcode.
So... Should I use a unique key for the 3 combined and create one index for each or the unique key already does the job to search only for a specific number ?
Answer: I'm pretty sure that under the hood, MySQL implements unique keys as indexes with the additional constraint that the column or columns comprising the index must be unique.
In your particular case, I wouldn't create any additional indexes. The unique key should cover you nicely for phone number lookup and phone number / zip code look up.
If you're worried that perhaps your query isn't using the key to do the lookup, pop the keyword EXPLAIN in front of the query and MySQL will display the "query plan", which will include information about which keys/indexes are being used for that query. It should be pretty easy to find articles on the web that explain how to interpret this output.
Answer: keys (indexes) are only useful from left-most towards the right up until the column that is not used (but in the index) in that query down that index path.
For single column indexes, naturally, there is only one left-most column for that index.
A composite key in mysql is a key that is a combination of more than one column. The key itself can be a unique key (a unique combination of the columns is allowed, but only 1 row of data as such).
So if you have a composite key on(a,b,c), it is useful for just a, for a and b together, or all three. But only partially if searching for a and c together. Partially, meaning, after its use for a, it converts into a non-index search (as a where) thereafter to pick up c. So it gets you close, but almost a mini or micro table scan thereafter, to coin a phrase.
One will often have a few composite keys, flipping around the left-most weighted column. But everything comes at a cost. Searching is great. It slows inserts and updates.
Please see the Manual page Multiple-Column Indexes to read more. And focus on the left-most concept of it.
And keep your composite indexes thin. Three int columns in a composite can be great if used well. A few larger varchars in there, bad.

Whatever you do, don't fool yourself into thinking that just because you create an index that it will be used. That can only be determined through the use of tools such as the Explain facility in mysql. If they are not used, you just slowed down all those inserts and updates. See also the article Using Explain to Write Better Mysql Queries.


Chamar um ajax dentro do sucess de outro ajax contido no primeiro ajax

Question: No clique de um botão classe cantor é retornado o nome do cantor e botões com classe musica com seus respectivos nomes das musicas (data). Ao clicar em um botão classe musica é retornado a letra da musica (data2), nesse ponto gostaria de adicionar um botão para acionar o primeiro ajax (classe cantor) para relacionar o cantor e suas respectivas musicas novamente. Fiz uma tentativa como se pode ver nos comentários do script abaixo, porém não funciona. Existe alguma forma de realizar essa operação?
$('.cantor').click(function() {

    $th = $(this);
      $.ajax({
        url: "pagina1.php",
        type: 'GET',
        data: {cantor: $th.attr( "title" )},
        success: function(data){
            $("#resultados").html(data);

                        $('.musica').click(function() {
                          $thm = $(this);
                          $.ajax({
                            url: "pagina2.php",
                            type: 'GET',
                            data: {identificador: $thm.attr( "title" )},
                            success: function(data2){

                                /*########### tentativa coloquei um button class cantor - não funciona ###### */
                                $("#resultados").html('<button class="cantor" title="Fulano de Tal">Fulano de Tal</button>'+data2);

                            },
                            error: function(){
                                $("#resultados").html("Ouve um erro ao enviar sua URL");
                            }
                         });//ajax
                    });

        },
        error: function(){
            $("#resultados").html("Ouve um erro ao enviar sua URL");
        }
     });//ajax
});

Comment: A solução passa pelo friend @Barmar neste post   https://stackoverflow.com/questions/65727230/calling-an-ajax-within-the-success-of-another-ajax/65727449#65727449
Answer: Seria isso?

$('.musica').click(function (e) {
    e.preventDefault();

    $thm = $(this);
    $.ajax({
        url: "pagina2.php",
        type: 'GET',
        data: { identificador: $thm.attr("title") },
        success: function (data2) {

            /*########### tentativa coloquei um button class cantor - não funciona ###### */
            $("#resultados").html('<button class="cantor" title="Fulano de Tal">Fulano de Tal</button>' + data2);

        },
        error: function () {
            $("#resultados").html("Ouve um erro ao enviar sua URL");
        }
    });//ajax
});

$('.cantor').click(function (e) {
    e.preventDefault();

    $th = $(this);
    $.ajax({
        url: "pagina1.php",
        type: 'GET',
        data: { cantor: $th.attr("title") },
        success: function (data) {
            $("#resultados").html(data);

            // Chama o evento de clique
            $('.musica').trigger('click');

        },
        error: function () {
            $("#resultados").html("Ouve um erro ao enviar sua URL");
        }
    });//ajax
});
Comment: Não está voltando para as musicas por causa dessa linha.
****
essa tag a esta fazendo um redirect para a pagina, ai ela recarrega os valores iniciais.


A RDLC subreport without subreport processing event

Question: I want to use subreport in my main report but without working or dealing with subreport processing event.
As I am making a generic form which will have the report viewer control, I just have to send a report to this control. the containing report may or may not have sub report.
Kindly suggest me any possible scenario or other reporting control which may fit in the above stated case.
View Model Code
<code>Microsoft.Reporting.WinForms.LocalReport report = new Microsoft.Reporting.WinForms.LocalReport();
            var reportDataSource = new Microsoft.Reporting.WinForms.ReportDataSource { Name = "AllEmployeeData", Value = EmployeeList };
            report = new Microsoft.Reporting.WinForms.LocalReport();
            report.ReportEmbeddedResource = "RDLCReport.Reports.RptEmployee.rdlc";
            report.DataSources.Add(reportDataSource);
            //This is the event which publish and subscribed in view to display report
            EventAggregator.GetEvent<ShowReport>().Publish(new Dictionary<string, object>() { { "Rpt", report } });
</code>
View Code
<code> private void ShowReport(Dictionary<string, object> obj)
        {
            this.ReportViewer.Report = new RDLCPrinter((Microsoft.Reporting.WinForms.LocalReport)obj["Rpt"]);
            this.ReportViewer.SetFitToWindowMode();
        }
</code>
Comment: Can describe what exactly you want to achieve ?
Comment: I am making a Generic View Form in WPF(MVVM). My this view form will get a property report and display it. The report might be single or subreport . you may consider the report a generic option.
Comment: In that case, subscribe to the subreport processing event whenever you need to ?
Comment: As all the creation of report done in ViewModel I dont want to work with subreportprocessing event on view. would you like me to put the code here
Comment: yes, please show us some code
Comment: I tried but find out that I cant avoid subreportprocessing event. Let me modify my code and take my way along with this event.
Comment: From what I understand, your RDLC report contains subreports. I don't think of any reason why it should be a problem to use the subreport processing event. If you explicitly don't want to use that event, you have to overwork your RDLC report and remove the subreport. This is possible if your data is in 1:1 relation. If it's 1:M, subreports must be used.
Comment: yes @DTs, well My plan was to avoid, but as you said and I also tried seems no way to run away from subreport processing. Will I change the scenario and now working with subreport processing event
Answer: The subreport processing event exists because the subreport would contain data, which is relative to the data showed in the main report.
For example:
You have Ivoices report. For each invoice, there is a list of products in this invoice. You get the products for the specific invoice in the Subreport processing event.
If you don't need to use the Subreport processing event, this means that you probably don't need to use subreports.
Comment: I dont want to work with subreportprocessing event. I am looking for alternative if there is any possibilities


Como embaralhar uma lista de objetos através de um valor padrão?

Question: Tenho o seguinte objeto:
public class Object{
    public String ID{get;set;}
}

E em um momento no meu código eu recebo uma lista deles:
List<Object> objs = new List<Object>();
objs.add(new Object{ID = "1"});
objs.add(new Object{ID = "2"});
objs.add(new Object{ID = "3"});
objs.add(new Object{ID = "4"});

E depois eu randomizo os objetos:
objs = objs.OrderBy(a => Guid.NewGuid()).ToList();
Debug.WriteLine(objs.ID);
// 1 4 2 3

Se eu executar objs.OrderBy(a => Guid.NewGuid()).ToList(); vou receber uma ordem totalmente aleatória // 3 2 4 1.
Preciso passar uma "seed"(um número inteiro) e randomizar em relação a ele, por exemplo, se eu passo o numero 1 e recebo // 3 2 4 1, quando eu executar o numero 1 de novo eu preciso receber a mesma ordem.
Existe algum recurso no c# para fazer isso?
Answer: Ao invés de usar GUID dentro do método Enumerable.OrderBy use o  método Random.Next(int maxValue) de um objeto Random instanciado pelo constructor Random(int seed), assim que gerando a mesma sequencia de números pseudo-aleatórios a cada seed.
Exemplo:
var rand = new Random(4);
var ListaEmbaralhada = Lista.OrderBy(a => rand.Next(Lista.Count)).ToList();

Answer: Existe sim. O Random aceita essa seed que você estava a falar. Se você iniciar sempre com o mesmo valor ele produzirá sempre a mesma sequência.
var r = new Random(4);
var list = new List<int>(){1, 2, 3, 4, 5};
for(int i = 0; i < list.Count; ++i){
    var idx = r.Next(list.Count);
    var aux = list[idx];
    list[idx] = list[i];
    list[i] = aux;
}
list.Dump();


interpolation: getting a value between two samples

Question: Let's say I have a signal with a sampling rate of 4ms. for example:-
time index value
0    0      15
4    1      17
8    2       4
12   3      71
16   4      54
20   5      21
and, I have a time value that defines which value I want to access. for example I want to know what the value at time 17.9834ms is. The naive way would be to just match the time 17.9834ms to the nearest known value (16ms). Which is not what I want.
The other way would be to use interpolation. I implemented linear interpolation and it works alright but the appropriate shape for interpolation would be a polynomial not a straight line. I want to know how to get the best approximation for the value at 17.9834ms. I looked at using sinc filter, but I did not understand.
Could someone help with this? Thanks.
Comment: Cubic-spline may give you the quality of result that you're interested in.
Answer: Choosing the nearest value is actually interpolation; it's called nearest neighbor interpolation.
Linear interpolation is a very fine way to go.
There are actually a plethora of ways to interpolate.  Sinc interpolation multiplies each value that you have with a sinc function (where $sinc(x) = sin(x)/x$) and then sums up all those functions at the point that you're interested in.  This interpolation is perfect if your signal was band limited and your sample rate was greater than the bandwidth.
If you feel like you want something smoother than linear interpolation, cubic-spline interpolation is a good way to go.  It ensures that the derivative of your resulting function is continuous.
Comment: @RitwickJha you would center one sinc at 4ms and evaluate it at 9.87.  Then you would center another sinc at 8ms, evaluate it at 9.87 and add it to your previous sum.  Continue for all data points that you have.
Comment: could you give me a small example of sinc? lets say I have 4 data points at time 0ms, 4ms, 8ms, 12ms and I want the value at 9.87ms. how do I apply sinc interpolation to get that value?
Comment: @RitwickJha I should have said that you scale the arguments of the sinc so that the zero crossings occur where the other samples are located.


IIS 7 .NET Globalization settings

Question: For an ASP.NET MVC app I need to set my local culture settings in IIS 7 .NET Globalization.
The problem is that these settings (Culture and UI Culture) periodically keep resetting back to default ones: Invariant Language (Invariant Country).
I suspect (though not sure) that this is somehow connected with Application Pool Recycling.
How could I fix that problem?
Answer: Yay! My first contribution!
I've been having this problem for a few weeks...
I'm working on a migration projet :
- .Net 1.1 -> 4.0
- IIS6 -> IIS7, etc.
The problem was that in a specific case numbers were multiplied by 1000. By setting the site .Net Globalization parameters to "fr-FR" (we're in France) the problem was sold... for a few days. Except the problem came back randomly... or so I thought.
Actually by doing so, IIS created a web.config file at the root of the site and from times to times I was deleting this file, because it shouldn't be there... Why? Because the application wasn deploying in a separate directory within the site's directory.
The web.confing was saying this :
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.web>
        <globalization culture="fr-FR" uiCulture="fr-FR" />
    </system.web>
</configuration>

And then all became clear : this should be written in the web.config of the application.
Actually, I'm testing the solution, but it seems to be on the right track.
Answer: You could modify machine config file from C:\WINDOWS\Microsoft.NET\Framework(64 or 32)\<.net version>\Config and set globalization culture="en-US" uiCulture="en-US" for example.

IIS 7 .NET Globalization settings