text:
Q: Evenly Space longtable columns with multicolumn I'm having a spacing issue in longtable, where the use of multicolumn elongates the last column. Example posted below.
The solution suggested to this question does not appear to work for me (\fill threw up an error), but I suspect the issue is similar.
\documentclass{article}
\usepackage{array}
\usepackage{booktabs}
\usepackage{longtable}

\newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}b{#1}}

\begin{document}
\begin{center}
\begin{longtable}{@{\extracolsep{6pt}}*{5}{L{1.75cm}}}
\toprule\multicolumn{3}{l}{\textbf{Survey Code}} & \multicolumn{2}{r}{\textbf{Month/Year (Sample Size)}} \\ \midrule
\endfirsthead

\multicolumn{5}{c}%
{{\bfseries \tablename\ \thetable{} -- continued from previous page}} \\
\toprule\multicolumn{1}{l}{\textbf{Survey Code}} & \multicolumn{4}{r}{\textbf{Month/Year (Sample Size)}} \\ \midrule
\endhead

\midrule\multicolumn{5}{l}{{Continued on next page}} \\\bottomrule
\endfoot

\bottomrule
\endlastfoot

\multicolumn{3}{l}{Polling Organization} & \multicolumn{2}{r}{(Mo./Yr.) ($N=XXXX$)} \\[1em]
\multicolumn{5}{p{\textwidth}}{\footnotesize \emph{Survey question text goes here.}} \\[1em]
\\[.25em]

\multicolumn{1}{L{2cm}}{Response 1} & \multicolumn{1}{L{2cm}}{Response 2} & \multicolumn{1}{L{2cm}}{Response 3} & \multicolumn{1}{L{2cm}}{Response 4} & \multicolumn{1}{L{2cm}}{Response 5}\\\cmidrule{1-1}\cmidrule{2-2}\cmidrule{3-3}\cmidrule{4-4}\cmidrule{5-5}
\nopagebreak
\multicolumn{1}{p{2cm}}{20\%} & \multicolumn{1}{p{2cm}}{56\%} & \multicolumn{1}{p{2cm}}{6\%} & \multicolumn{1}{p{2cm}}{8\%} & \multicolumn{1}{p{2cm}}{10\%} \\[2em]
\end{longtable}
\end{center}
\end{document}

A: If I correctly understood your question, than you like to have the following table (unfortunately it is not clear, what is in the not showing rows, ore there only numbers?):

(red lines indicate text borders)

*

*table has equal width of columns determined with p{\dimexpr0.2\textwidth-2\tabcolsep}

*for \multicolumns are defined shortnes with use of the xparse package

\documentclass{article}
\usepackage{booktabs, longtable, makecell}

\usepackage{xparse}
\NewExpandableDocumentCommand\mcl{O{1}m}
    {\multicolumn{#1}{l}{#2}}
\NewExpandableDocumentCommand\mcr{O{1}m}
    {\multicolumn{#1}{r}{#2}}
\newcommand\mcp[1]{\multicolumn{1}{p{0.16\linewidth}}{#1}}
%---------------- show page layout. don't use in a real document!
\usepackage{showframe}
\renewcommand\ShowFrameLinethickness{0.15pt}
\renewcommand*\ShowFrameColor{\color{red}}
%---------------------------------------------------------------%
\usepackage{lipsum}

\begin{document}
\begingroup
\begin{longtable}{ *{5}{p{\dimexpr0.2\textwidth-2\tabcolsep}}
                 }
    \caption{Caption on the first page of the table}
    \label{tab:longtable}                               \\
    \toprule
\mcl[2]{\textbf{Survey Code}}
            & \mcr[3]{\textbf{Month/Year (Sample Size)}} \\
    \midrule
\endfirsthead
    \caption[]{Caption on the first page of the table}  \\
    \toprule
\mcl[2]{\textbf{Survey Code}}
            & \mcr[3]{\textbf{Month/Year (Sample Size)}} \\
    \midrule
\endhead
    \midrule[\heavyrulewidth]
\mcr[5]{r}{\small\textit{Continued on next page}}       \\
\endfoot
    \bottomrule
\endlastfoot
%%%% table body
\mcl[2]{Polling Organization}
            & \mcr[3]{(Mo./Yr.) ($N=XXXX$)}             \\
    \midrule
    \addlinespace
\multicolumn{5}{>{\small}p{\dimexpr\linewidth-2\tabcolsep}}{\emph{Survey question text goes here.}

        \medskip
        \lipsum[11]}                                    \\ % dummy text
    \addlinespace
{Response 1}
        & {Response 2}
                    & {Response 3}
                            & {Response 4}
                                    & {Response 5}      \\
    \cmidrule(r){1-1}\cmidrule(r){2-2}
    \cmidrule(r){3-3}\cmidrule(r){4-4}\cmidrule{5-5}
20\,\%  & 56\,\%    & 6\,\% & 8\,\% & 10\,\%            \\
   \end{longtable}
\endgroup
\end{document}
    \end{longtable}
\endgroup
\end{document}


text:
Q: undefined control sequence using enumerate  \begin{enumerate}
     \item[1.] Choose $N\sim \text{Poisson}(\xi)$.

 \item[2.] Choose $\theta \sim \text{Dir}(\alpha)$.
 \item[3.] For each of the $N$ words $w_n$:
   \begin{enumerate}
   \item[(a)] Choose a topic $z_n \sim \text{Multinomial}(\theta)$.
   \item[(b)] Choose a word $w_n$ from $p(w_n | z_n, \beta)$, a multinomial probability conditioned on the topic $z_n$.
   \end{enumerate}
 \end{enumerate}

When I use the above code to generate some equations, it gives me the following errors:
Undefined control sequence. \item[1.] Choose $N\sim \text
Undefined control sequence. \item[2.] Choose $\theta \sim \text
Undefined control sequence. \item[(a)] Choose a topic $z_n \sim \text

I don't understand what is causing these errors. Can anyone help? thanks.

A: I would just add  a simpler way to use enumerate, with enumitem, which uses what you type manually as default:
\documentclass{article}
\usepackage{showframe}
\renewcommand{\ShowFrameLinethickness}{0.3pt}
\usepackage{enumitem}
\usepackage{amsmath}

\begin{document}

\begin{enumerate}[ wide = 0pt, leftmargin = *]
     \item Choose $N\sim \text{Poisson}(\xi)$.

 \item Choose $\theta \sim \mathrm{Dir}(\alpha)$.
 \item For each of the $N$ words $w_n$:
   \begin{enumerate}[wide = 0pt]
   \item Choose a topic $z_n \sim \mathrm{Multinomial}(\theta)$.
   \item Choose a word $w_n$ from $p(w_n \,|\, z_n, \beta)$, a multinomial probability conditioned on the topic $z_n$.
   \end{enumerate}
 \end{enumerate}

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reactive reading and rendering a shapefile my purpose is to render a reactive map through Shiny + Leaflet: I want to use two overlapped layers, "confini.comuni.WGS84" and "confini.asl.WGS84", on which to draw a reactive layer.
Based on the value 'inputId = "Year.map"', the server reads a layer 'zone.WGS84' ('layer = paste0 ("zone_", anno.map ())', EX "zone_2015") and colors the polygons based on the value one of the fields in the dataframe ("SIST_NERV", "MESOT", "TUM_RESP") selected via 'inputId = "Pathology.map"'.
The shapefiles "zone_2000.shp" etc.. are stored in "App/shapes/zone", the shapefiles "rt.confini.comunali.shp" and "rt.confini.regionali.shp" are stored in "App/shapes/originali"
The App and the files are here:
The data.frame related to the shapesfile "zone_2016" is:
 EXASLNOME                     Anno SIST_NERV SIST_NERVp MESOT MESOTp TUM_RESP TUM_RESPp
 Az. USL 1 di Massa Carrara    2016        43         41     1      1        4         4
 Az. USL 2 di Lucca            2016        45         45    11     10        3         3
 Az. USL 3 di Pistoia          2016        26         21    13     13        5         5
 Az. USL 4 di Prato            2016         6          6     8      8       NA        NA
 Az. USL 5 di Pisa             2016       155        146     3      3        2         2
 Az. USL 6 di Livorno          2016       137        136    17     17       20        18
 Az. USL 7 di Siena            2016        29         24     1      1       NA        NA
 Az. USL 8 di Arezzo           2016        31         29     3      3        2         2
 Az. USL 9 di Grosseto         2016        35         34     2      2        1         1
 Az. USL 10 di Firenze         2016        34         33    24     13       11         4
 Az. USL 11 di Empoli          2016        30         29     2      2       20        20
 Az. USL 12 di Viareggio       2016       130        129     7      7        3         3

Next, Leaflet must create a reactive label built on the data 'EXASLNOME' and 'pat.map()' of the data.frame.
Finally, a map() map must be generated via renderLeaflet sent to output$Map.ASL.
This generates this error:

Warning: Error in domain: could not find function "domain" Stack trace
  (innermost first): 91: colorQuantile 90:
  [C:/Users/User/Downloads/Prova_mappe/App_per_Stackoverflow.r#63] 79:
  mappa 78: func
  [C:/Users/User/Downloads/Prova_mappe/App_per_Stackoverflow.r#95] 77:
  origRenderFunc 76: output$Mappa.ASL  1: runApp

I can not use all the reactive components to pass as parameters to the Leaflet function, can you tell me something?
  require(shiny)
  require(stringr)
  require(shinythemes)
  require(leaflet)
  require(RColorBrewer)
  require(rgdal)
  require(rgeos)

  #### UI ####
  ui <- fluidPage(
    theme = shinytheme("spacelab"),
    titlePanel("Indice"),
    navlistPanel(
      tabPanel(title = "Mappe",
         fluidRow(column(6, sliderInput(inputId = "Anno.map",
                                        label = "Anno di manifestazione",
                                        min = 2000,
                                        max = 2016,
                                        value = 2016,
                                        step = 1,
                                        ticks = FALSE,
                                        sep = "")),
                  column(6, selectInput(inputId = "Patologia.map",
                                        label = "Patologia",
                                        choices = list("SIST_NERV", "MESOT","TUM_RESP"),
                                        selected = "SIST_NERV",
                                        multiple = FALSE))),
         fluidRow(column(6, leafletOutput(outputId = "Mappa.ASL", height = "600px", width = "100%")))
    )
   )
  )

 #### SERVER ####
 server <- function(input, output) {

    # NOT REACTIVE
    confini.comuni <- readOGR(dsn = "shapes/originali", layer = "rt.confini.comunali", stringsAsFactors = FALSE)
    confini.comuni.WGS84 <- spTransform(confini.comuni, CRS("+proj=longlat +datum=WGS84 +no_defs"))

    confini.asl <- readOGR(dsn = "shapes/originali", layer = "rt.confini.asl", stringsAsFactors = FALSE)
    confini.asl.WGS84 <- spTransform(confini.asl, CRS("+proj=longlat +datum=WGS84 +no_defs"))

    # REACTIVE
    anno.map <- reactive({input$Anno.map})

    pat.map <- reactive({input$Patologia.map})

    mappa <- reactive({
        zone.WGS84 <- spTransform(readOGR(dsn = "shapes/zone",
                                  layer = paste0("zone_", anno.map()), stringsAsFactors = FALSE),
                                  CRS("+proj=longlat +datum=WGS84 +no_defs"))

        domain <- paste0("zone_", anno.map(), "@data$", pat.map())
        labels.1 <- paste0("zone_", anno.map(), "@data$EXASLNOME")
        labels.2 <- paste0("zone_", anno.map(), "@data$", pat.map())
        labels.3 <- paste0("zone_", anno.map(), "@data$", pat.map(), "p")

        pal <- colorQuantile(palette = "YlOrRd",
                             domain = domain(), n = 6,
                             na.color = "808080", alpha = FALSE, reverse = FALSE, right = FALSE)
        labels <- sprintf("%s
%g Segnalazioni
 %g con nesso positivo",
                   labels.1(), labels.2(), labels.3()) %>%
                   lapply(htmltools::HTML)

    leaflet(options = leafletOptions(zoomControl = FALSE, dragging = FALSE, minZoom = 7.5, maxZoom = 7.5)) %>%
            addPolygons(data = confini.comuni.WGS84,
            weight = 1,
            opacity = 1,
            color = "black") %>%
    addPolygons(data = confini.asl.WGS84,
                weight = 2,
                opacity = 1,
                color = "red")  %>%
    addPolygons(data = zone.WGS84(),
                fillColor = ~pal(domain()),
                weight = 2,
                opacity = 1,
                color = "white",
                dashArray = "3",
                fillOpacity = 0.7,
                highlight = highlightOptions(weight = 5,
                                             color = "666",
                                             dashArray = "",
                                             fillOpacity = 0.7,
                                             bringToFront = TRUE),
                label = labels())
    })

   output$Mappa.ASL <- renderLeaflet({mappa()})

  }

  # Run the application
  shinyApp(ui = ui, server = server)

A: The error msg should be quite clear. You are using a function domain() which you never assigned.
ColorQuantile needs numeric values for the domain, so you have to provide a column with numeric values in it. Based on them leaflet will produce the colors.
 pal <- colorQuantile(palette = "YlOrRd",
                             domain =  dataframe$numericVariable,
                             n = 6,
                             na.color = "808080",
                             alpha = FALSE, reverse = FALSE,
                             right = FALSE)

and change this line in the second addPolygon function:
fillColor = pal(dataframe$numericVariable),

You have to adapt dataframe$numericVariable to the column of your data.frame which you want to use for coloring.
See the following example:
library(shiny)
library(leaflet)

dataframe <- data.frame(
  x = runif(n = 40, 15, 18),
  y = runif(n = 40, 50, 55),
  numericVariable = runif(n = 40, 1, 100)
)

ui <- fluidPage(
  leafletOutput("map")
)

server <- function(input, output){

  output$map <- renderLeaflet({
    pal <- colorQuantile(palette = "YlOrRd",
                         domain =  dataframe$numericVariable,
                         n = 6,
                         na.color = "808080",
                         alpha = FALSE, reverse = FALSE,
                         right = FALSE)

    leaflet() %>%
      addTiles() %>%
      addCircleMarkers(lng = ~x, lat = ~y, data=dataframe,
                       fillColor = pal(dataframe$numericVariabl), fillOpacity = 1)
  })
}
shinyApp(ui, server)

A: Thanks, I tried to follow your advice: I created a data.frame from the shape using
map <- reactive({readOGR(dsn = "shapes/zone",
                         layer = paste0("zone_", anno.map()), stringsAsFactors = FALSE)})

map.df <- reactive({map() %>%
                    as.data.frame() %>%
                    select(EXASLNOME, pat.map(), pat.map.p())})

Note thant both "map" and "map.df" are reactive.
"pat.map" is the name of a column of the data.frame "map.df" taken as input value (input $ Pathology.map) and "pat.map.p" is the name of another column of the same data.frame.
I used the numeric field map.df () [, 2] as the "domain" parameter of the "pal" function
pal <- colorQuantile(palette = "YlOrRd",
                            domain = map.df()[,2],
                            n = 6,
                            na.color = "808080",
                            alpha = FALSE,
                            reverse = FALSE,
                            right = FALSE)

I've also created a reactive label with
labels <- sprintf("%s
 %d Segnalazioni
 %d con nesso positivo",
                            map.df()[,1], map.df()[,2], map.df()[,3]) %>%
                            lapply(htmltools::HTML)

This is the new script
require(shiny)
require(stringr)
require(shinythemes)
require(leaflet)
require(RColorBrewer)
require(rgdal)
require(rgeos)

#### UI ####
ui <- fluidPage(
    theme = shinytheme("spacelab"),
    titlePanel("Indice"),
    navlistPanel(
        tabPanel(title = "Mappe",
                fluidRow(column(6, sliderInput(inputId = "Anno.map",
                                               label = "Anno di manifestazione",
                                               min = 2000,
                                               max = 2016,
                                               value = 2016,
                                               step = 1,
                                               ticks = FALSE,
                                               sep = "")),
                        column(6, selectInput(inputId = "Patologia.map",
                                              label = "Patologia",
                                              choices = list("SIST_NERV", "MESOT","TUM_RESP"),
                                              selected = "SIST_NERV",
                                              multiple = FALSE))),
                fluidRow(column(6, leafletOutput(outputId = "Mappa.ASL", height = "600px", width = "100%")))
        )
    )
)

#### SERVER ####
server <- function(input, output) {

# NOT REACTIVE
confini.comuni <- readOGR(dsn = "shapes/originali", layer = "rt.confini.comunali", stringsAsFactors = FALSE)
confini.comuni.WGS84 <- spTransform(confini.comuni, CRS("+proj=longlat +datum=WGS84 +no_defs"))

confini.zone <- readOGR(dsn = "shapes/originali", layer = "rt.confini.exasl", stringsAsFactors = FALSE)
confini.zone.WGS84 <- spTransform(confini.zone, CRS("+proj=longlat +datum=WGS84 +no_defs"))

confini.asl <- readOGR(dsn = "shapes/originali", layer = "rt.confini.asl", stringsAsFactors = FALSE)
confini.asl.WGS84 <- spTransform(confini.asl, CRS("+proj=longlat +datum=WGS84 +no_defs"))

mappa.base <- leaflet(options = leafletOptions(zoomControl = FALSE,
                                             dragging = FALSE,
                                             minZoom = 7.5,
                                             maxZoom = 7.5)) %>%
addPolygons(data = confini.comuni.WGS84,
            weight = 1,
            opacity = 1,
            color = "black") %>%
addPolygons(data = confini.zone.WGS84,
            weight = 2,
            opacity = 1,
            color = "black")

# REACTIVE
anno.map <- reactive({input$Anno.map})
pat.map <- reactive({input$Patologia.map})
pat.map.p <- reactive({paste0(pat.map(), "p")})

map <- reactive({spTransform(readOGR(dsn = "shapes/zone",
                             layer = paste0("zone_", anno.map()), stringsAsFactors = FALSE),
                             CRS("+proj=longlat +datum=WGS84 +no_defs"))})

map.df <- reactive({map() %>%
                    as.data.frame() %>%
                    select(EXASLNOME, pat.map(), pat.map.p())})

mappa <- reactive({
        pal <- colorQuantile(palette = "YlOrRd",
                            domain = map.df()[,2],
                            n = 6,
                            na.color = "808080",
                            alpha = FALSE,
                            reverse = FALSE,
                            right = FALSE)

        labels <- sprintf("%s
 %d Segnalazioni
 %d con nesso positivo",
                            map.df()[,1], map.df()[,2], map.df()[,3]) %>%
                            lapply(htmltools::HTML)

        leafletProxy(mapId = "mappa.base", data = map()) %>%
        addPolygons(fillColor = ~pal(map.df()[,2]),
                    weight = 2,
                    opacity = 1,
                    color = "white",
                    dashArray = "3",
                    fillOpacity = 0.7,
                    highlight = highlightOptions(weight = 5,
                                                 color = "666",
                                                 dashArray = "",
                                                 fillOpacity = 0.7,
                                                 bringToFront = TRUE),
                    label = labels()
                    )
        })

    output$Mappa.ASL <- renderLeaflet({mappa()})

}

# Run the application
shinyApp(ui = ui, server = server)

launching the app, there seems to be a problem with "labels"
> runApp('App')

Listening on http://127.0.0.1:3307
OGR data source with driver: ESRI Shapefile
Source: "shapes/originali", layer: "rt.confini.comunali"
with 274 features
It has 11 fields
OGR data source with driver: ESRI Shapefile
Source: "shapes/originali", layer: "rt.confini.exasl"
with 12 features
It has 2 fields
OGR data source with driver: ESRI Shapefile
Source: "shapes/originali", layer: "rt.confini.asl"
with 3 features
It has 1 fields
OGR data source with driver: ESRI Shapefile
Source: "shapes/zone", layer: "zone_2016"
with 12 features
It has 40 fields
Warning: Error in labels.default: argument "object" is missing, with no default
Stack trace (innermost first):
    108: labels.default
    107: labels
    106: safeLabel
    105: evalAll
    104: evalFormula
    103: invokeMethod
    102: eval
    101: eval
    100: %>%
    99: addPolygons
    98: function_list[[k]]
    97: withVisible
    96: freduce
    95: _fseq
    94: eval
    93: eval
    92: withVisible
    91: %>%
    90: <reactive:mappa> [S:\ProgettiR\ReportMalprof_ShinyApp\App/app.R#86]
    79: mappa
    78: func [S:\ProgettiR\ReportMalprof_ShinyApp\App/app.R#103]
    77: origRenderFunc
    76: output$Mappa.ASL
    1: runApp

A: There were several mistakes in your code, the missing labels were just a minor problem.
First of all, you can put all non reactive values outside the server function and maybe you should save the confini.* shapefiles to an RDS-file or a DB and load them from there. I guess that would speed up your App.

Your leaflet plot was never showing, because you rendered the object mappa() to the output ID = Mappa.ASL. The reactive mappa doesnt create a map though, its not returning a map or any object, so you should change the reactive to an observer. The LeafletProxy just adds stuff on the original map (in your case mappa.base), which you never used in the UI.

Your error came from calling labels = labels() in addPolygons, as if labels was a reactive object, but you defined it in the same reactive environment so you call it without parenthesis like:
labels = labels

Instead of making a reactive value out of those:
anno.map <- reactive({input$Anno.map})
pat.map <- reactive({input$Patologia.map})
pat.map.p <- reactive({paste0(pat.map(), "p")})

You can just use them as reactives like:
input$Anno.map
input$Patologia.map
paste0(pat.map(), "p")

I also wouldnt use a reactive (map) which always reads a shapefile from disk and reprojects it straight away. Can you maybe merge them together to one shapefile and then filter from it and reproject them beforehand, so you dont have to do it everytime the app is called?
The following app should work. At least a bit, as you will run in errors in the colorQuantile function like this one, as there are NA-values in the datasets (eg. years 2009-2006 for 'SIST_NERV')

Warning: Error in cut.default: 'breaks' are not unique

You could just change the colorQuantile to colorBin and drop the n = 6 argument.
require(shiny)
require(stringr)
require(shinythemes)
require(leaflet)
require(RColorBrewer)
require(rgdal)
require(rgeos)

# NOT REACTIVE
confini.comuni <- readOGR(dsn = "shapes/originali", layer = "rt.confini.comunali", stringsAsFactors = FALSE)
confini.comuni.WGS84 <- spTransform(confini.comuni, CRS("+proj=longlat +datum=WGS84 +no_defs"))

confini.zone <- readOGR(dsn = "shapes/originali", layer = "rt.confini.exasl", stringsAsFactors = FALSE)
confini.zone.WGS84 <- spTransform(confini.zone, CRS("+proj=longlat +datum=WGS84 +no_defs"))

confini.asl <- readOGR(dsn = "shapes/originali", layer = "rt.confini.asl", stringsAsFactors = FALSE)
confini.asl.WGS84 <- spTransform(confini.asl, CRS("+proj=longlat +datum=WGS84 +no_defs"))

#### UI ####
ui <- {fluidPage(
  theme = shinytheme("spacelab"),
  titlePanel("Indice"),
  navlistPanel(
    tabPanel(title = "Mappe",
             fluidRow(column(6, sliderInput(inputId = "Anno.map",
                                            label = "Anno di manifestazione",
                                            min = 2000, max = 2016, value = 2016, step = 1,
                                            ticks = FALSE, sep = "")),
                      column(6, selectInput(inputId = "Patologia.map",
                                            label = "Patologia", choices = list("SIST_NERV", "MESOT","TUM_RESP"),
                                            selected = "SIST_NERV", multiple = FALSE))),
             fluidRow(column(6,
                             leafletOutput(outputId = "mappa.base", height = "600px", width = "100%")
                             ))
    )
  )
)}

#### SERVER ####
server <- function(input, output) {

  # REACTIVE
  map <- reactive({
    req(input$Anno.map)
    spTransform(readOGR(dsn = "shapes/zone", layer = paste0("zone_", input$Anno.map), stringsAsFactors = FALSE),
                CRS("+proj=longlat +datum=WGS84 +no_defs"))
  })

  output$mappa.base <- renderLeaflet({
    leaflet(options = leafletOptions(zoomControl = FALSE, dragging = FALSE,
                                     minZoom = 7.5, maxZoom = 7.5)) %>%
      addTiles() %>%
      addPolygons(data = confini.comuni.WGS84,
                  weight = 1, opacity = 1, color = "black") %>%
      addPolygons(data = confini.zone.WGS84,
                  weight = 2, opacity = 1, color = "black")
  })

  map.df <- reactive({
    req(input$Anno.map)
    map() %>%
      as.data.frame() %>%
      dplyr::select(EXASLNOME, input$Patologia.map, paste0(input$Patologia.map, "p"))
  })

  mappa <- observe({
    pal <- colorQuantile(palette = "YlOrRd",  domain = map.df()[,2],
                         n = 6,  na.color = "808080",
                         alpha = FALSE, reverse = FALSE,
                         right = FALSE)

    labels <- sprintf("%s
 %d Segnalazioni
 %d con nesso positivo",
                      map.df()[,1], map.df()[,2], map.df()[,3]) %>% lapply(htmltools::HTML)

    leafletProxy(mapId = "mappa.base", data = map()) %>%
      addPolygons(fillColor = ~pal(map.df()[,2]),
                  weight = 2,
                  opacity = 1,
                  color = "white",
                  dashArray = "3",
                  fillOpacity = 0.7,
                  highlight = highlightOptions(weight = 5,
                                               color = "666",
                                               dashArray = "",
                                               fillOpacity = 0.7,
                                               bringToFront = TRUE),
                  label = labels
      )
  })
}

# Run the application
shinyApp(ui = ui, server = server)


text:
Q: I need to read data from file into a vector of struct i hope you guys can help as the title says i need to read data from a file into vector of struct, but i need to use the readfile function to read different structs at different times. Its the for loop that puzzles me
for(temp; getline(infile, temp.whatever) && getline(infile, temp.whatever2); i++)
    structname.pushback(temp);

this ties the function to an individual struct. Its a bit counter productive to write another function to read in a different struct. Obviously this works but is there a way to make this more reusable. Thanks in advance

A: Yes, you can do something to make the code usable for different struct types.
However, all struct types must have the fields used inside the function.
It could look something like this:
template<typename T>
void readData(vector<T>& v, istream& infile)
{
    T temp;
    while(getline(infile, temp.whatever) && getline(infile, temp.whatever2))
    {
        v.push_back(temp);
    }
}

int main() {
    // Add code for infileA and infileB

    vector<myStructA> va;
    readData(va, infileA);  // or readData<myStructA>(va, infileA); if you prefer

    vector<myStructB> vb;
    readData(vb, infileB);  // or readData<myStructB>(vb, infileB); if you prefer

    ....
    ....

    return 0;
}

So here both myStructA and myStructB must have the member whatever and whatever2. This could be implemented by using a common base class for myStructA and myStructB.


text:
Q: Removing values from a multivalue field in Access I have a table called Users with a multivalue field named Area. I am creating a simple SQL statement that simply deletes an area designated to a single user. In the below example: Removing area "G1" from the user with a badge number of "123".
Here's my SQL Statement:
DELETE Users.Area.Value
FROM Users
WHERE (((Users.Area.Value)="G1") AND ((Users.badgeNumber)="123"));

This somehow manages to result in an Enter Parameter Value dialog box. After double checking, all the parameters should be entered correctly. In fact, changing DELETE to SELECT creates a successful SQL statement.
Looking at the Microsoft help page, I found this example.
DELETE Issues.AssignedTo.Value
FROM Issues
WHERE (((Issues.AssignedTo.Value)=6));

This removes a value from the entire database. I'd like to remove the value from just a  single user.
So now I am bit lost. Any help you can provide would be appreciated. Thanks.

A: I'm still unsure why the Enter Parameter dialog popped up, but I decided to just redo my code using the following method. It cleared out the entire User's area preferences and then set them again.
To clear the MVF area it looked like this:
DELETE Users.Area.Value
FROM Users
WHERE Users.BadgeNumber = "123"

To add to a MVF, I used the following:
Dim varReport As Variant
For i = 0 To Me.boxArea.ListCount - 1
    If Me.boxArea.Selected(i) = True Then
         sqlString = "INSERT INTO Users ([area].[Value]) VALUES ('" & Me.boxArea.Column(boundColumnZeroBasedIndex, i) & "') WHERE badgeNumber = '" + txtBadgeNumber + "';"
         CurrentDb.Execute sqlString, dbFailOnError
    End If
Next i

A: I just solved the same problem. It's unbelievable but changing the order in the where clause works:
DELETE Users.Area.Value
FROM Users
WHERE (((Users.badgeNumber)="123") AND ((Users.Area.Value)="G1"));


text:
Q: Bipartite matching with a twist I'm working on a scheduling problem assigning speakers to slots, with speakers having varying availability. A maximum matching unweighed bipartite graph works for a simple solution where each speaker is assigned to a single slot.
Now assume after every slot someone speaks in, an empty slot should follow (except the last). How can this be modelled?
Finally, can graph theory be used when some speakers should speak for consecutive slots?
Thanks

A: If

*

*every speaker who is available for an odd-numbered slot is also available for the following (even-numbered) slot, and

*there is at most one speaker who needs 2 consecutive slots, and no speakers who need 3 or more,

then a very simple algorithm works: use unweighted maximum bipartite matching, but only allocate odd-numbered slots, leaving every even-numbered slot empty.  If someone needs 2 consecutive slots, all that happens is that, for all pairs of slots following him/her, slot usage is swapped so that odd-numbered slots are left empty and even-numbered slots are used.


text:
Q: cmake c++ library with opencv addexternal I would like to build a C++ library using cmake.
The library would require a on-the-fly opencv download and build then this library will be used in an other cmake project as a library.
The project structure is like that:
template_matching_project
    |
    |-- build
    |-- template_matching_project
    |              |
    |              |-- template_matching_library
    |                              |
    |                              | -- src
    |                              | -- include
    |                              | -- CMakeLists.txt
    |-- main.cpp
    |-- CMakeLists.txt

The template_matching_library performs some image processing using opencv, there is the content of its cmake file in template_matching_project/template_matching_library/CMakeLists.txt:
cmake_minimum_required(VERSION 3.0)
set(CMAKE_CXX_STANDARD 11)
project(template_matching)

# third party
include(ExternalProject)
set(EXTERNAL_INSTALL_LOCATION ${CMAKE_BINARY_DIR}/3rdparty)
set(EXTERNAL_DOWNLOAD_LOCATION ${CMAKE_BINARY_DIR}/Download)

# OpenCV
ExternalProject_Add(opencv-contrib
  GIT_REPOSITORY https://github.com/opencv/opencv_contrib.git
  GIT_TAG e6f32c6
  SOURCE_DIR "${EXTERNAL_DOWNLOAD_LOCATION}/opencv-contrib"
  CONFIGURE_COMMAND ""
  BUILD_COMMAND ""
  INSTALL_COMMAND ""
)

ExternalProject_Add(opencv
  GIT_REPOSITORY https://github.com/opencv/opencv.git
  GIT_TAG 01b2c5a
  SOURCE_DIR "${EXTERNAL_DOWNLOAD_LOCATION}/opencv"
  CMAKE_ARGS
    -DBUILD_DOCS:BOOL=OFF
     ...
)
add_dependencies(opencv opencv-contrib)

# set source directories
set(PROJECT_SOURCE_DIR source)
set(INCLUDE_DIR include)

# set source files
file(GLOB_RECURSE SRCS ${PROJECT_SOURCE_DIR}/*)
file(GLOB_RECURSE HEADERS ${INCLUDE_DIR}/*)

# build library
link_directories(${EXTERNAL_INSTALL_LOCATION}/opencv/lib)

include_directories(${EXTERNAL_INSTALL_LOCATION}/opencv/include/opencv4)
include_directories(${INCLUDE_DIR})

add_library(${PROJECT_NAME} SHARED ${SRCS} ${HEADERS})
add_dependencies(${PROJECT_NAME} opencv)

target_link_libraries(${PROJECT_NAME} opencv_core opencv_highgui opencv_imgproc)

target_include_directories(${PROJECT_NAME} PUBLIC ${INCLUDE_DIR})

The template_matching_library is correctly build with this cmake, but the build of the main.cpp executable fails
Here is the template_matching_project/CMakeLists.txt:
cmake_minimum_required(VERSION 3.0)

set(CMAKE_CXX_STANDARD 11)

project(markers)

# include library
add_subdirectory(template_matching_library)
set(EXTERNAL_INSTALL_LOCATION ${CMAKE_BINARY_DIR}/3rdparty)
include_directories(${EXTERNAL_INSTALL_LOCATION}/opencv/include/opencv4)

# add file to compile
set(SRCS main.cpp)

# add executable
add_executable(${PROJECT_NAME} ${SRCS})

# add dependencies
target_link_libraries(${PROJECT_NAME} template_matching)

Then trying the build with the convetional
cd build
cmake .. -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Debug
make

I have the following error
[ 95%] Building CXX object CMakeFiles/markers.dir/main.cpp.o
[100%] Linking CXX executable markers
/usr/bin/ld: cannot find -lopencv_core
/usr/bin/ld: cannot find -lopencv_highgui
/usr/bin/ld: cannot find -lopencv_imgproc
collect2: error: ld returned 1 exit status

Any suggestion to solve my problem? Should I change one/both of those CMakeLists.txt.
Thanks.

A: I have it worked with those two CMakeLists.txt, if some have any suggestions or better solution.
template_matching_project/CMakeLists.txt:
cmake_minimum_required(VERSION 3.0)
set(CMAKE_CXX_STANDARD 11)
project(markers)

add_subdirectory(template_matching_library)
set(SRCS main.cpp)
add_executable(${PROJECT_NAME} ${SRCS})
target_link_libraries(${PROJECT_NAME} template_matching ${OpenCV_LIBS})

template_matching_project/template_matching_library/CMakeLists.txt:
cmake_minimum_required(VERSION 3.0)
set(CMAKE_CXX_STANDARD 11)
project(template_matching)

# third party
include(ExternalProject)
set(EXTERNAL_INSTALL_LOCATION ${CMAKE_BINARY_DIR}/3rdparty)
set(EXTERNAL_DOWNLOAD_LOCATION ${CMAKE_BINARY_DIR}/Download)

# OpenCV
ExternalProject_Add(opencv-contrib
  GIT_REPOSITORY https://github.com/opencv/opencv_contrib.git
  GIT_TAG e6f32c6
  SOURCE_DIR "${EXTERNAL_DOWNLOAD_LOCATION}/opencv-contrib"
  ...
)

ExternalProject_Add(opencv
  GIT_REPOSITORY https://github.com/opencv/opencv.git
  GIT_TAG 01b2c5a
  SOURCE_DIR "${EXTERNAL_DOWNLOAD_LOCATION}/opencv"
  CMAKE_ARGS
    -DBUILD_DOCS:BOOL=OFF
    ...
    -DOPENCV_EXTRA_MODULES_PATH:PATH=${EXTERNAL_DOWNLOAD_LOCATION}/opencv-contrib/modules
)
add_dependencies(opencv opencv-contrib)
set(OpenCV_DIR ${EXTERNAL_INSTALL_LOCATION}/opencv/lib/cmake/opencv4)
find_package(OpenCV REQUIRED PATHS ${EXTERNAL_INSTALL_LOCATION}/opencv)

# set source directories
set(PROJECT_SOURCE_DIR source)
set(INCLUDE_DIR include)

# set source files
file(GLOB_RECURSE SRCS ${PROJECT_SOURCE_DIR}/*)
file(GLOB_RECURSE HEADERS ${INCLUDE_DIR}/*)

# build library
include_directories(${EXTERNAL_INSTALL_LOCATION}/opencv/include/opencv4)
include_directories(${INCLUDE_DIR})

add_library(${PROJECT_NAME} SHARED ${SRCS} ${HEADERS})
add_dependencies(${PROJECT_NAME} opencv)

target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})

target_include_directories(${PROJECT_NAME} PUBLIC ${INCLUDE_DIR})

Nevertheless, using my two CMakeLists.txt, I do have to run twice cmake and make commands, unless I have a links errors with opencv, like the following:
cd build
cmake .. -G "Unix Makefiles
make
cmake .. -G "Unix Makefiles
make

Is there a way to have work with a single run cmake/make?
I try some FetchContent but was not able to make it worked. My cmake version is 3.5.1


text:
Q: C Does passing argument from function to function will copy it's content? The code:
//function prototype
void efg(int x);
//mother functioon
abc()
{
int a=1;
efg(a);
}

When efg is executing, changing x is not changing a then we have a copy of a. But what if we dont want a copy to use memory efficiently?
One way is to pass the a's pointer &a.
I have som constrants:

*

*Don't want to pass anything. Since I have about 20 variable.

*Don't want it's pointer's. I want direct access to it.

*Dont want to being globally static.

*Reluctant to use Heap dynamic allocation since it's embedded also it forces me to use pointer's instead of direct access.

I want my sub function (efg) be able to use the mother function's variable (a in abc) .It means efg being able to access a directly. Why not? Also I want a being being freed after abc execution finishes, since in the way explained the variables are in stack they will freed after function finishes.
The exact problem is: sub_functions initiate some structures in the memory. After sub function is finihed its job (CPU returns to mother function) the memories must be staying untouched untill the mother function finishes (CPU return to main) and here the memory must being freed.
My best dreaming solution is to use extern variable declare to use mother function stack in sub routine.

A:
Don't want to pass anything. Since I have about 20 variable.

I hope you aren't planning to pass 20 variables to a function or you need to start placing related variables together in the same struct. If you have 20 variables total, well what does that have to do with anything?

Don't want it's pointer's. I want direct access to it.

That doesn't make any sense without a rationale why you want direct access. Indirect access vs direct access is such a minor performance difference that one shouldn't even bother considering it. Manually optimize when you actually have real time constraints or bottlenecks, don't optimize just for the heck of it.
If you worry about performance, then one sensible approach is to use small functions with internal linkage that will surely be inlined by the compiler. Note however that inlining is an execution speed over program size optimization.

Dont want to being globally static.

That's kind of contradicting, I assume you mean declared with static storage class specified but declared at file scope. Using such variables may or may not be valid design depending on use-case. For single core embedded systems, there's not really anything wrong with such variables.

Reluctant to use Heap dynamic allocation since it's embedded also it forces me to use pointer's instead of direct access.

Yes heap allocation should be avoided for multiple reasons in such systems. I wrote a summary of all the problems here: Why should I not use dynamic memory allocation in embedded systems? However, avoiding indirect access is not a valid reason.

The exact problem is: sub_functions initiate some structures in the memory. After sub function is finihed its job (CPU returns to mother function) the memories must be staying untouched untill the mother function finishes (CPU return to main) and here the memory must being freed.

So that's solved by declaring the variables as local, on the stack, then pass its address to the other function. If you don't want any other part of the program to touch that memory in the meantime, then simply refrain from writing code which does that...
Summary: don't state a bunch of ultimatums out of the blue, for which you can't sensibly argue in favour for or against. It's pretty clear that you have limited experience of program design, let alone manual code optimization. So for now the best thing you can do is to write code as readable as possible, following well-known best practices (const correctness, private encapsulation etc etc). Because readable code also tends to be efficient, bug-free code. Whereas needlessly contrived and complex code tends to be slow, buggy and hard to maintain.


text:
Q: Not getting my parameter from the body of the request I try and hit my API Controller which I'm able to make it there.  However the method is not getting my parameter from the body of the request. I know this is something small.
I've tried moving the service around adding parameters in many different ways. Nothing so far seems to work.
Key Things to Note
This is a MVC 4 application if that helps.  I believe it's something in the angular syntax or possibly the controller attributes.
I'm using a HTTPPost.
Service
(function () {
'use strict';
var rmdsnewServices = angular.module('rmdsnewServices', ['ngResource']);

rmdsnewServices.factory('rmds', ['$resource',
  function ($resource) {
      return {
          rmdnewly: $resource('/api/rmd/', {}, {
              query: {
                  method: 'GET', params: {}, url: '/api/rmd/getNewly/', isArray: false,
                  transformResponse: function (data) { return { list: angular.fromJson(data) } }
              }
          }),

          rmdsave: $resource('/api/rmd/AddRMD/:newrmd', { newrmd: '@newrmd' }, {
              save: {

                  method: 'POST', params: { newrmd: '@newrmd' }

              }

          })

      };
  }]);
})();

API Controller
[Route("api/rmd/AddRMD")]
    [HttpPost]
    public HttpResponseMessage AddRMD([FromBody]string newrmd)
    {
        var rmd = newrmd;

        bool result;
        //result = rs.AddRMD(newrmd);
        result = true;
        if (result)
        {
            return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
        }
        else
        {
            return new HttpResponseMessage(System.Net.HttpStatusCode.ExpectationFailed);
        }
    }

A: Your controller action expects a string.
Also, your $resource doesn't need to send the :param on the url:
                      rmdsave: $resource('/api/rmd/AddRMD/', { }, {
                      save: {
                          method: 'POST'
                      }
                  })

Then sending simply a string, will hit your controller:
        angular.module('rmdsnewServices').controller('MyController', ['rmds', function (rmds) {
        this.click = function() {
            rmds.rmdsave.save("'asd'");
        }
    }]);

To send an object instead of the string:
rmds.rmdsave.save({Name:"someName"});

  public class Test
    {
        public string Name { get; set; }
    }

    public class rmdController : ApiController
    {
        [HttpPost, Route("api/rmd/AddRMD")]
        public HttpResponseMessage SomePath([FromBody] Test newrmd)
        { ...


text:
Q: SUMIFS to sum data between custom date range I am building a dashboard to summarize purchase data. I have a worksheet for purchase data, there is a reference tables worksheet with the start and end dates for fiscal months, with the associated fiscal year, and fiscal month (summarized below), and the dashboard worksheet.
Table: oetFiscalMonths
Start Date | End Date | Month    | Year
10/1/17    | 10/30/17 | October  | 2018
10/31/17   | 11/1/17  | November | 2018

On the dashboard there is a table of data formatted as below
         | Beginning Budget | Total Purchases | Remaining Budget |
October  | $XXXXXXXXX.00    | $XXXXXX.00      | $XXXXXXXXXX.00   |
November | $XXXXXXXXX.00    | $XXXXXX.00      | $XXXXXXXXXX.00   |
December | $XXXXXXXXX.00    | $XXXXXX.00      | $XXXXXXXXXX.00   |
January  | $XXXXXXXXX.00    | $XXXXXX.00      | $XXXXXXXXXX.00   |

The formula I am looking to enter would go in the Total purchases, and would sum all purchases made in the fiscal month on the right, based on the table for fiscal months, while meeting several other criteria, which I have been able to complete with the SUMIFS formula. I am just not sure how to handle the date range portion as they do not follow the calendar months even remotely mostly, and the table for the dates is formatted the way it is as several other portions utilize its current format.
Any help is greatly appreciated!

A: You can try also by sumproduct formula, its benefit without open worksheet formula calculating.
=SUMPRODUCT(--(B:B>=H3)*(B:B<=I3),(C:C))
C:C = Sum range
B:B = Date search range
H3 = Value of start date
I3 = Value of end date

A: You can use the SUMIFS like I've shown below.  Excuse the random row and cell usage.  I will try to explain below.
=SUMIFS(C:C,A:A,">="&G1,A:A,"<="&H1)
C:C = Sum range
A:A = Date search range
G1 = Value of start date
H1 = Value of end date
EDIT:
I would suggest moving the months column to the front and then the dates after like shown below.  That way you can use a vlookup to find the date and then incorporate a vlookup into the sumifs.
  Month  | Start Date | End Date | Year
October  | 10/1/17    | 10/30/17 | 2018
November | 10/31/17   | 11/1/17  | 2018

=SUMIFS(G:G,F:F,">="&VLOOKUP(J6,M:O,2,0),F:F,"<="&VLOOKUP(J6,M:O,3,0))

M:O is your fiscal year table
J6 is where you would type the month you are searching for
Column 2 in the first VLOOKUP will give you start date
Column 3 in the second VLOOKUP will give you end date

Let me know if you have any questions, it may be kind of confusing since I am using random rows and columns.

A: Assuming sheet1 is your dashboard, sheet2 contains your oetFiscalMonths table and sheet3 contains the purchases and their corresponding dates of purchase you want to SUM, you can make use of SUMIFS combined with INDEX + MATCH to suite your current file structure:
=SUMIFS(sheet3!C:C,sheet3!B:B,">="&INDEX(sheet2!A:A,MATCH(sheet1!A2,sheet2!C:C,0)),sheet3!B:B,"<="&INDEX(sheet2!B:B,MATCH(sheet1!A2,sheet2!C:C,0)))

Legends are as follows:
sheet3!C:C contains the purchase values you want to SUM
sheet3!B:B contains the date of purchases
sheet2!A:A contains the start dates of your months
sheet2!B:B contains the end dates of your months
sheet2!C:C contains your months
sheet1!A2 contains the first month you want to get the SUM of purchases of.


text:
Q: Want a solution for printf
Possible Duplicate:
how to printf uint64_t?

I want to print u_int64_t in C.
I want to know the format specifier for this?
I am a C user, I want to do a printf().

A: #include <inttypes.h>
#include <stdio.h>

uint64_t t = 42;
printf("%" PRIu64 "\n", t);

A: You can use the L modifier for 64-bit integers, eg:
u_in64_t number;
printf("%Lu", number);


text:
Q: Compressing increasing sequence of unique integers I have a sequence of two-byte integers ranging from 0 to 2^16-1 = 65535.
They are sorted so the sequence is always increasing and there are no repetitions.
This sequence usually have around 270~500 numbers. If it were denser(ie >=32768 elements), I could save the numbers that are not in the sequence, but thats not the case... Now here is the challenge, I have to compress then using less than 6 bits per integer(on average)!
The best guess I had was to use Bloom Filters. In this manner, to decompress the sequence, I would have to iterate over all integers from 0 to 65535 asking if they are in set. But I don't know how to handle false positives. I could store them, but I'm afraid it would take too much data.

A: It is not possible to use less than 6 bits per integer on average.  You can count the number of ways to pick 270 or 500 things from a set of 65536 without repetitions, and determine that the number of bits required to represent a pick is 9.34 bits per thing and 8.46 bits per thing respectively.
If you were picking 2721 things or more out of 65536, then you could represent them in 6 bits or less.


text:
Q: Having trouble with user input in tkinter I am working on a program for class and am having trouble with user input. This is what I have, can someone help me figure out what I am doing wrong? All of the buttons work (this is only part of the code), but the user input area for menu3A doesn't seem to accept the user input. It tells me that variable1 is undefined.
Module 1:
from tkinter import *
from tkinter import ttk
import functions
import finance

def donothing():
   filewin = Toplevel(root)
   button = Button(filewin, text="Do nothing button")
   button.pack()

# Menu 1 - opening menu

def menu1():
    filewin = Toplevel(root)
    button1 = Button(filewin, text="Use your own CSV Data", command = menu3A)
    button1.pack()
    button2 = Button(filewin, text="Use Data Included in program", command = menu2)
    button2.pack()

# Menu 2 - Menu 2 is only used if Data from Menu1 specifies program data used
def menu2():
    FileName = ''
    filewin = Toplevel(root)
    Label(root, text="Enter the ticker symbol for your chosen stock or type Back to go back: ").grid(row=0, sticky=W)  #label
    Entry(root, textvariable = FileName).grid(row=0, column=1, sticky=E) #entry textbox

    WSignUp = Button(root, text="Enter", command=functions.getvalue2).grid(row=3, column=0, sticky=W) #button

# Menu 3A - loading CSV File - only used if Data from Menu1 specifies user wishes to load CSV
    variable1=StringVar()

    ttk.Entry(root, width=7, textvariable=variable1).grid(column=2, row=1)

    ttk.Label(root, text="Enter Filename: ").grid(column=1, row=1)

    ttk.Button(root, text="Enter", command=functions.getvalue1()).grid(column=2, row=13)

root = Tk()
root.title('Rachels Stocks Python Program')
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=menu1)

filemenu.add_separator()

filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Undo", command=donothing)

editmenu.add_separator()

editmenu.add_command(label="Cut", command=donothing)
editmenu.add_command(label="Copy", command=donothing)
editmenu.add_command(label="Paste", command=donothing)
editmenu.add_command(label="Delete", command=donothing)
editmenu.add_command(label="Select All", command=donothing)

menubar.add_cascade(label="Edit", menu=editmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)

root.config(menu=menubar)

root.mainloop()

Module 2:
import finance

#Function that menu 3A uses to print and use CSV filename
def getvalue1():
    FileName = variable1.get()
    print(f"Filename entered is: {FileName}")
    finance.CSV_Finance_Tool(FileName)

If I try to do this:
WSignUp = Button(root, text="Enter", command=functions.getvalue2(variable1)).grid(row=3, column=0, sticky=W) #button

Then it automatically seems to pass the empty variable onto CSV_Finance_Tool and I am getting the file exception response of file not found. It doesn't wait for the user input.


text:
Q: VSTS Test result update API is not working Hi iam using VSTS test management APIS for upating test results.
First iam using {collection name}/{projectname}/_apis/test/runs/{result id}/results?api-version=2.0-preview
with JSON value
[{"testResult":{"id":100000},"testCase":{"id":417},"priority":1,"outcome":"Failed","testPoint":{"id":51},"state":"Completed ","associatedWorkItems":[452]}]

all works fine suddenly it will updated test result but work item bug is not linked with test result.
When i use 3.0-preview
[{"id":100000,"outcome":"Failed","state":"Completed ","associatedBugs":[199,200]}]

Still not working
What iam using wrong.

A: It seems both for results REST API and results (1.0) REST API, bugs can not be linked by updating test results for a test run.
I reported Update test results for a test run REST API can not link bugs for it, you can follow up.


text:
Q: Laravel not recognizing input file when $validation->fails() I am using dropzone.js to upload files. Whenever $validation->fails()==true, my response::make breaks with the following error:
"Call to a member function first() on a non-object","file"
Code:
     public function uploadPhotosAction()
    {
        if(Input::file('file')){
         $input = Input::all();
          $rules = array(
              'file' => 'mimes:jpeg,bmp,png|max:5120|min:265', //Only allow files of the type "image" no smaller than 256 kb and no larger than 5 mb
          );
          $validation = Validator::make($input, $rules);
      if ($validation->fails())
      {
        return Response::make($validation->errors->first('file'), 400);
      }

A: try using  $input = Input::file('file') instead of  $input=Input::all()
I recomend you to read the docs http://laravel.com/docs/requests#files

A: It's a method not property, so simply this:
return Response::make($validation->errors()->first('file'), 400);


text:
Q: IIS - Resource not found while Directory is browsable I have a little strange issue on my system. I have hosted a Service, Rest Service (Be Specific) on my system. When I try to access the svc page of the same service it gives me HTTP 404 (The resource cannot be found.) error while I can browse the whole directory and in that directory it shows that the svc file lies with in the folder but when I click on svc file i get the 404 error.
I tried to host the same service on other system and it works fine. I am not sure what causing it not to display on my system.
Any clue would be great help.


text:
Q: Cannot mount new dvd, old dvd's work I can mount any (?) dvd that I have looked at before. If I buy an new DVD, and try to watch it, I cannot mount it. Sometimes ejecting the DVD and inserting it again 20 times or so helps. This is odd.

My output of dmesg is as follows:
marc@ultima-thule:~$ dmesg -T | grep dvd
[Fri Feb 18 17:17:42 2022] sr 3:0:0:0: [sr0] scsi3-mmc drive: 48x/48x writer dvd-ram cd/rw xa/form2 cdda tray
[Fri Feb 18 17:18:32 2022] pktcdvd: pktcdvd0: writer mapped to sr0

Edit : Following up on a comment, the output of smartctl is as follows :
Vendor:               TSSTcorp
Product:              CDDVDW SH-224BB
Revision:             SB00

Terminate command early due to bad response to IEC mode page

=== START OF READ SMART DATA SECTION ===
Current Drive Temperature:     0 C
Drive Trip Temperature:        0 C
Error Counter logging not supported
Device does not support Self Test logging


text:
Q: Python IMAP Search from or to designated email address I am using this with Gmail's SMTP server, and I would like to search via IMAP for emails   either sent to or received from an address.
This is what I have:
mail = imaplib.IMAP4_SSL('imap.gmail.com')

mail.login('user', 'pass')
mail.list()
mail.select("[Gmail]/All Mail")

status, email_ids = mail.search(None, 'TO "tech163@fusionswift.com" OR FROM "tech163@fusionswift.com"')

The last line of the error is: imaplib.error: SEARCH command error: BAD ['Could not parse command']
Not sure how I'm supposed to do that kind of OR statement within python's imaplib. If someone can quickly explain what's wrong or point me in the right direction, it'd be greatly appreciated.

A: The error you are receiving is generated from the server because it can't parse the search query correctly. In order to generate a valid query follow the RFC 3501, in page 49 it is explained in detail the structure.
For example your search string to be correct should be:
'(OR (TO "tech163@fusionswift.com") (FROM "tech163@fusionswift.com"))'

A: Try to use IMAP query builder from https://github.com/ikvk/imap_tools
from imap_tools import A, AND, OR, NOT
# AND
A(text='hello', new=True)  # '(TEXT "hello" NEW)'
# OR
OR(text='hello', date=datetime.date(2000, 3, 15))  # '(OR TEXT "hello" ON 15-Mar-2000)'
# NOT
NOT(text='hello', new=True)  # 'NOT (TEXT "hello" NEW)'
# complex
A(OR(from_='from@ya.ru', text='"the text"'), NOT(OR(A(answered=False), A(new=True))), to='to@ya.ru')

Of course you can use all library tools


text:
Q: Detect value change in custom MutableMapping class with unkown depth I'm implementing a wrapper for a config file (json) with the abstract base class MutableMapping. The code is shown below:
import collections
import json

class ConfigWrapper(collections.MutableMapping):

    def __init__(self, file_path):
        self._data = None
        self.file_path = file_path
        self._read()

    def __getitem__(self, key):
        return self._data[key]

    def __setitem__(self, key, value):
        if self._data[key] != value:
            self._data[key] = value
            self._commit()

    def __delitem__(self, key):
        del(self._data[key])

    def __iter__(self):
        return iter(self._data)

    def __len__(self):
        return len(self._data)

    def _read(self):
        with open(self.file_path) as file:
            self._data = json.load(file)

    def _commit(self):
        with open(self.file_path, "w") as file:
            json.dump(self._data, file, indent=4)

I want my wrapper to automatically save changes to the config file if __setitem__ is invoked:
config = ConfigWrapper("afile.json")
config["key"] = "value"  # first case
config["section"]["key"] = "value"  # second case

The first case works just fine. The second case however doesn't trigger _commit() because the __setitem__ method of the standard dict _data is used.
The json file may contain nested dicts with unknown depth.
Question: How would I solve this problem even if wanted to commit a change in say config["a"]["b"]["c"]["d"] = "value"?
Thanks in advance.


text:
Q: Using '<' character in Xml Documentation of C# code How can I put characters like '<' in C# Xml Documentations:
/// <summary>
/// This produces an empty tag like <tagname/>
/// </summary>
public string GenerateEmptyTag(string tagname)
{
    return string.Format("<{0}/>", tagname);
}

In above example, the <tagname/> in the documentation causes error as it contains < character

A: You should escape it, like you would do with XML since the inline documentation is Visual Studio is in fact a XML fragment:
/// This produces an empty tag like <tagname/>


text:
Q: Templated requires-expression I want a Functor concept in C++20.
A functor is a higher-kinded type that can be mapped over. A simple example is std::optional; with a function from type A to type B and a std::optional<A>, you can easily create a std::optional<B> by applying the function to the value if it exists and returning an empty optional otherwise. This operation is called fmap in Haskell.
template<typename A, typename B>
std::optional<B> fmap(std::function<B(A)> f, std::optional<A> fa) {
    if (!fa) {
        return std::optional<B>{};
    }
    return std::optional<B>(f(*fa));
}

A concept for all functors is simple enough to write. I've come up with this (using GCC—you'll have to remove bool to get this working in Clang, I think):
template<template<typename> typename F, typename A, typename B>
concept bool Functor = requires(std::function<B(A)> f, F<A> fa) {
    { fmap(f, fa) } -> F<B>;
};

And a simple additional function to make sure this works:
template<typename A, typename B>
std::function<B(A)> constant(B b) {
    return [b](A _) { return b; };
}

template<template<typename> typename F, typename A, typename B>
F<B> replace(B b, F<A> fa) requires Functor<F,A,B> {
    return fmap(constant<A,B>(b), fa);
}

It works. But it's not pretty. What I want is for the signature of replace to read like so:
template<Functor F, typename A, typename B>
F<B> replace(B b, F<A> fa);

No need for a requires-clause here. Much nicer, don't you agree? To get this to work, however, I'd have to reduce the template on my concept to a single argument. Something like this:
template<template<typename> typename F>
concept bool Functor = requires(function<B(A)> f, F<A> fa) {    // Uh-oh
    { fmap(f, fa) } -> F<B>;
};

Problem is, I've not declared types A and B. As far as I can tell, there's nowhere I can declare them before I have to use them. Can what I want be done, and can it be done simply and elegantly?
One possible solution that comes to my mind is to make the requires-expression in the concept a template (or at least a template-like thing). I'd then have something like this:
template<template<typename> typename F>
concept bool Functor = requires<typename A, typename B>(function<B(A)> f, F<A> fa) {
    { fmap(f, fa) } -> F<B>;
};

Unfortunately, this is not valid by the C++20 standard and will not compile with g++-8. Could something like this be viable? Could it make it into the standard?

A: C++ doesn't have parametric polymorphism like this - you can't do things like "for any type" in the way you want to, and in the way you can in Haskell. I think that's fundamentally impossible in a world where overloading exists.
What you have is the following (I went ahead and removed the erroneous bool, which isn't part of C++20 concepts, and fixed -> Type, which was also removed):
template<template<typename> class F, typename A, typename B>
concept Functor = requires(std::function<B(A)> f, F<A> fa) {
    { fmap(f, fa) } -> std::same_as<F<B>>;
};

What you want to say is for any types a and b, given an a -> b, you can call this function. We can't do that. But we can just pick arbitrary types ourselves. One way of doing that is to pick secret types that the functor implementation just wouldn't know about:
namespace secret {
    struct A { };
    struct B { };

    template <typename From, typename To>
    struct F {
        auto operator()(From) const -> To;
    };
}

template <template <typename> class F>
concept Functor = requires(secret::F<secret::A, secret::B> f, F<secret::A> fa) {
    { fmap(f, fa) } -> std::same_as<F<secret::B>>;
};

That's probably your best bet. You could even add multiple a/b pairs to make this more likely to be correct.
Regardless, this:
template<Functor F, typename A, typename B>
F<B> replace(B b, F<A> fa);

Isn't going to happen anyway, since we don't have that kind of terse syntax for constrained template template parameters. You'd have to write it this way:
template <template <typename> class F, typename A, typename B>
    requires Functor<F>
F<B> replace(B b, F<A> fa);

As a side note, this is a bad implementation of fmap for optional:
template<typename A, typename B>
std::optional<B> fmap(std::function<B(A)> f, std::optional<A> fa);

Taking a std::function<Sig> means this will only work if you pass in specifically a std::function. Not for lambdas or function pointers or other function objects (like the secret::F I used earlier). And even if it did work, you wouldn't want to do this anyway, since it's needless overhead.
You want:
template <typename F, typename A, typename B = std::invoke_result_t<F&, A const&>>
std::optional<B> fmap(F f, std::optional<A> fa);

I have a whole post about this exact problem, Declarations Using Concepts.

A: Your "Functor" concept represents a complex relationship between three different types: F (a one-parameter template that is the template being projected over), A (the starting object type), and B (the resulting object type). Your concept represents a relationship between 3 parameters, so your concept is going to have to take 3 parameters.
Terse template syntax is for simple cases: constraints relating to a single (type) parameter. Your case is not simple, so you're going to have to spell it out with a requires clause. Anytime you have a concept with multiple parameters like this, you'll have to spell it out.
As for whether it is "pretty" or not, that's a value judgement. But given the complex relationship on display here, seeing it spelled out makes it clear what the relationship between all of these parameters is. And clarity has a beauty all its own.


text:
Q: How to use Tooling API to get available values from picklist How would one get the values available values of a System Custom Field?
Here are the details of the "System Custom Field":
Field Label: "Working Status"
Field Name: "Working_Status"
API Name: Working_Status__c
Object Name: "System"
Data Type: "Picklist"
Values: { "Running", "Starting Up", "Unknown"}
I am using the following query:
SELECT Values FROM CustomField WHERE ObjectName = 'System.Working_Status__c'
However, this is not working.  I can use the describe the Lightning Platform REST API describe method of doing this, but it returns every possibility in the system.
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_sobject_describe.htm
What do I need to change in my SOQL query to make this happen?

A: It's worth noting you don't need any API calls at all to get this information, and can simply use the field describe (which is also accessible via REST API).
List<PicklistEntry> entries = System.Working_Status__c.getDescribe().getPicklistValues();

List<String> values = new List<String>();
for (PicklistEntry entry : entries)
{
    values.add(entry.getValue());
}

A: Yes you can do that using tooling API. You have to specify the ObjectName and FieldName.
If you check metadata for CustomField ObjectName is called as TableEnumOrId
and FieldName is called as DeveloperName.
The picklist values/valueset are stored in a field called as "Metadata".
So your SOQL will be.
SELECT Id,NameSpacePrefix, DeveloperName, TableEnumOrId,Metadata FROM CustomField WHERE TableEnumOrId = 'Account' and DeveloperName='License_Type'

When I tried it in workbench it returns the picklist valueset.
Note: Developer Console doesn't support the return of complex return type so you have to view this in Workbench or any other rest client.
*As pointed by @Sfdcfox, When you query metadata you can query a single field at a time.


text:
Q: Get correlations from multiple rows which have the same value (Python) So I'm working on a script to compare data and I need to correlate the gathered data. The DataFrame consists of a column of genes which are compared with other genes to get the duplicates. I need a correlation of the genes that have the same duplicate gene.
Example data:
Index  Gene    Duplicate of  Value1  Value2  Value3  Etc.
0      Gene1   DGene1        0.1     14      13      ..
1      Gene14  DGene1        0       13      17      ..
2      Gene4   DGene3        20      0       0       ..
3      Gene90  DGene3        25      0       10      ..
4      Gene22  DGene31       0       10      0       ..
5      Gene40  DGene31       10      0.5     0       ..
6      Gene130 DGene31       10      1       0       ..
7      Gene600 DGene31       12      0       0       ..

In case of the example above, I would want three correlations: 1 of genes Gene1 and Gene14, 1 of Gene4 and Gene90 and lastly one of Gene22, Gene40, Gene130 and Gene600. The correlations would exist out of all the values (Value1, etc) from those rows.
I tried to group the data by Duplicate of (CGENE is the Duplicate of),
df_com2.groupby(CGENE).apply(lambda x: x.index.tolist())
but I can't find a way to select all values from the corresponding genes after doing so.
Any help would be appreciated!

A: It's not completely clear what you're looking for out of the groupby, but I suspect you're looking for .agg to aggregate fields.
For example, this will give a comma-separated list of genes, and the average of Value1:
In [26]: df
Out[26]:
   Index     Gene Duplicate_of  Value1  Value2  Value3 Etc.
0      0    Gene1       DGene1     0.1    14.0      13   ..
1      1   Gene14       DGene1     0.0    13.0      17   ..
2      2    Gene4       DGene3    20.0     0.0       0   ..
3      3   Gene90       DGene3    25.0     0.0      10   ..
4      4   Gene22      DGene31     0.0    10.0       0   ..
5      5   Gene40      DGene31    10.0     0.5       0   ..
6      6  Gene130      DGene31    10.0     1.0       0   ..
7      7  Gene600      DGene31    12.0     0.0       0   ..

In [27]: df.groupby("Duplicate_of").agg({'Gene': ', '.join, 'Value1': np.mean})
Out[27]:
                                          Gene  Value1
Duplicate_of
DGene1                           Gene1, Gene14    0.05
DGene3                           Gene4, Gene90   22.50
DGene31       Gene22, Gene40, Gene130, Gene600    8.00


text:
Q: Игнорировать определенные символы в preg_replace Я нашел в интернете очень удобную штуку, но там сказано что такие символы как ",.?\" нельзя вводить так как они есть символами-атрибутами. Как прописать код так что бы он игнорировал(не удалял) все буквы алфавита, цифры и символы ",./?!" ?
Что есть:
$name = preg_replace("/[^а-яa-zA-ZА-Я0-9\s]+/u","",$string);

A: Требуется экранировать данные символы
 preg_replace("/[^а-яa-zA-ZА-Я0-9\,\.\/\?\!\s]+/u","",$string);

Специальные символы

A: Вам нужно экранировать /, а остальные символы в квадратных скобках можете перечислять без экрана. Вот так, например:
$name = preg_replace('/[^\d\s\/.,!?a-zа-яё]/iu','', $string);


text:
Q: Concurrency errors when using scala iterators in gatling I'm using gatling to run load tests. I'm not a gatling or scala expert, but it seems to me that this particular problem might be more related to scala (and Akka) than to gatling itself. I'll start at the end: When running at high load on a not-so-strong machine, I occasionally get this error:

07:04:42.071 [ERROR]
  i.g.c.a.b.SessionHookBuilder$$anonfun$build$1$$anon$1 -
  'sessionHook-29' crashed on session
  Session(searchOrder,5348761459522421680-8295,Map(),1433329482056,0,
  OK,List(),), forwarding to the next one
  java.lang.UnsupportedOperationException: tail of empty list
          at scala.collection.immutable.Nil$.tail(List.scala:422) ~[scala-library-2.11.6.jar:na]
          at scala.collection.immutable.Nil$.tail(List.scala:417) ~[scala-library-2.11.6.jar:na]
          at scala.collection.LinearSeqLike$$anon$1.next(LinearSeqLike.scala:46)
  ~[scala-library-2.11.6.jar:na]
          at scala.collection.TraversableOnce$FlattenOps$$anon$1.next(TraversableOnce.scala:450)
  ~[scala-library-2.11.6.jar:na]
          at MyNamespace.Tenants$.next(Tenants.scala:21) ~[na:na]
          at MyNamespace.LoadTests$$anonfun$run$1.apply(LoadTests.scala:43)
  ~[na:na]
          at MyNamespace.LoadTests$$anonfun$run$1.apply(LoadTests.scala:41)
  ~[na:na]
          at io.gatling.core.action.SessionHook.executeOrFail(SessionHook.scala:35)
  ~[gatling-core-2.1.5.jar:2.1.5]
          at io.gatling.core.action.Failable$class.execute(Actions.scala:71)
  ~[gatling-core-2.1.5.jar:2.1.5]
          at io.gatling.core.action.SessionHook.execute(SessionHook.scala:28)
  ~[gatling-core-2.1.5.jar:2.1.5]
          at io.gatling.core.action.Action$$anonfun$receive$1.applyOrElse(Actions.scala:29)
  ~[gatling-core-2.1.5.jar:2.1.5]
          at scala.PartialFunction$OrElse.applyOrElse(PartialFunction.scala:171)
  ~[scala-library-2.11.6.jar:na]
          at akka.actor.Actor$class.aroundReceive(Actor.scala:465) ~[akka-actor_2.11-2.3.9.jar:na]
          at io.gatling.core.akka.BaseActor.aroundReceive(BaseActor.scala:22)
  ~[gatling-core-2.1.5.jar:2.1.5]
          at akka.actor.ActorCell.receiveMessage(ActorCell.scala:516) ~[akka-actor_2.11-2.3.9.jar:na]
          at akka.actor.ActorCell.invoke(ActorCell.scala:487) ~[akka-actor_2.11-2.3.9.jar:na]
          at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:254) ~[akka-actor_2.11-2.3.9.jar:na]
          at akka.dispatch.Mailbox.run(Mailbox.scala:221) ~[akka-actor_2.11-2.3.9.jar:na]
          at akka.dispatch.Mailbox.exec(Mailbox.scala:231) ~[akka-actor_2.11-2.3.9.jar:na]
          at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
  ~[scala-library-2.11.6.jar:na]
          at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
  ~[scala-library-2.11.6.jar:na]
          at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
  [scala-library-2.11.6.jar:na]
          at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
  [scala-library-2.11.6.jar:na]

I suspect it has to do with using
Iterator.continually([some collection]).flatten

where [some collection] is the collection that I'm trying to loop through circularly. Could it be that when lots of concurrent threads try to access an iterator defined in this way that it occasionally fails? Is there a better way to create a circular iterator that is also thread safe?
As in the tenants object created by the "save" method below (in practice there is more code here that fills the collection retrieved by the get method, so it is actually never empty):
import io.gatling.core.Predef._

object Tenants {
  type TenantKeys = Map[String, Map[String, String]]
  val key = "tenants"
  val elementKey = "tenant"
  var tenants: Iterator[Map[String, String]] = Iterator(Map[String, String]())

  def get(session: Session): TenantKeys = {
    session(key)
      .asOption[TenantKeys]
      .getOrElse(Map[String, Map[String, String]]())
  }

  def save(session: Session): Session = {
    val mapped = get(session).map(_._2).toSeq
    tenants = Iterator.continually(mapped).flatten
    session
  }
}

A: What you're doing can't simply work. It's not a matter of Scala but one of concurrent programming.
Just like Java Iterators, Scala ones are not thread-safe.
Use Gatling's feed() that's thread-safe.


text:
Q: How to install gulp jshint using npm? Unable to install JSHint. Can anyone suggest me what I am doing wrong?
I am using below command.
npm install --save-dev gulp-jshint gulp-jscs jshint-stylish
It is showing the following "gulp-jshint@2.0.4 requires a peer of jshint@2.x but none was installed-UNMET peer dependency"

A: Try executing the following command npm install --save-dev jshint gulp-jshint gulp-jscs jshint-stylish

A: peer dependency is not installed by npm you must install it manually before.
In your case :
npm install --save-dev jshint

Update
Peer dependency is a dependency for a library that is not required. It is considered as a plugin.
You can find more informations here for npm or here for nodejs


text:
Q: Update statement SQL with case statement how to update values for following condition
CREATE TABLE T
  (
     C VARCHAR(10)
  );

INSERT INTO T
VALUES      ('0000'),
            ('123456789'),
            ('A'),
            (''),
            ('    '),
            (NULL);

I need to leave the NULL values or values which has 0000 as is and update the remaining to 1234.
expected output as below:
0000
1234
1234
1234
1234
NULL

I have tried with below statement but is there a better way to do this?
UPDATE T SET C=CASE WHEN C IS NULL then null
when C='0000' then '0000' else '1234' END

A: just use where clause ,you can try like below
update T
set C='1234'
where C<>'0000'

A: You don't need to use case expression use where clause instead :
UPDATE t
     SET C = '1234'
WHERE C IS NOT NULL OR C <> '0000';

A: Simply
UPDATE T SET C='1234' where c <> '0000'

Will work since the null comparisons aren't true.
SQL>UPDATE T SET C='1234' where c <> '0000';

                  4 rows updated

SQL>select * from t;
C
==========
0000
1234
1234
1234
1234
-

                  6 rows found


text:
Q: Find a plane parallel to a line and perpendicular to $5x-2y+z=3$. Find a plane parallel to the following line: $$x=3t+2, y=-t+1, z=t-1$$ and perpendicular to:
$$5x-2y+z=3.$$
I've tried the following:
The normal vector to the plane above is <5,-2,1>.
The normal/direction vector to line is <3, -1, 1>.
I did the dot product on these two normal vectors, and I got 18. Now I'm not sure where to go from here to get the equation of the plane I'm supposed to be finding.

A: If a plane is given by $Ax + By + Cz = D$, then the direction of the vector normal to a plane is $\begin{bmatrix} A \\ B \\ C\end{bmatrix}$.
If a line is given by $x = M_1t + B_1, y = M_2t + B_2, z = M_3t + B_3$, then the direction of the line is $\begin{bmatrix} M_1 \\ M_2 \\ M_3\end{bmatrix}$
A line is parallel to a plane (I'm assuming this is what you mean) if it never intersects the plane or always intersects the plane.  That means that the normal vector of the plane and the direction of the line are perpendicular.
Two vectors, $\begin{bmatrix} x_1 \\ y_1 \\ z_1\end{bmatrix}$ and $\begin{bmatrix} x_2 \\ y_2 \\ z_2\end{bmatrix}$, are perpendicular if and only if $x_1x_2 + y_1y_2 + z_1z_2 = 0$.


text:
Q: Android short screen brightness code! Anyone who knows why this code ain't lowering the backlight of my application?
Context context = this;

    Settings.System.putInt(context.getContentResolver(),
    Settings.System.SCREEN_BRIGHTNESS, 255);

A: If you want to change the brightness of your current application, use the code hackbod posted
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = <some value between 0 and 1>;
getWindow().setAttributes(lp);

But I cannot fully agree with hackbod's post. It is definitely possible to change the global brightness without using hacks. I just wrote a short demo application.
The trick is, that first the application's brightness has to be changed and then change the global brightness. Otherwise only the "brightness slider" in the settings menu changes its position but this does not affect the brightness. Only if the user taps on the slider, the brightness will be applied.
    WindowManager.LayoutParams localLayoutParams = getWindow()
            .getAttributes();
    localLayoutParams.screenBrightness = 0.12F;
    getWindow().setAttributes(localLayoutParams);

    Settings.System.putInt(this.resolver, "screen_brightness", 30);

application brightness range from 0 - 1
global brightness range from 0 - 255 (0 = display off)
Also it is very important to wait some time to apply the settings if you want to exit afterwards.
    Thread t = new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        System.out.println(e);
                    }
                    System.out.println("finally exit");
                    finish();
                }
            });
    t.start();

A: Applications are no longer allowed to modify the global brightness.  Don't use the tricks people have tried to come up with at various points, these use private APIs and will break in various ways across different devices (and are considered security holes that have been closed on more recent versions of the platform).
The official API to set the brightness is with WindowManager.LayoutParams.screenBrightness, which lets you set the brightness for your own app's window.  The platform will automatically take care of changing the brightness as the user moves in and out of your app.
Use this to change it:
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = <some value between 0 and 1>;
getWindow().setAttributes(lp);

A: follow this code , i think i have put a comment on your previous question about that :)
refer tis tuto


text:
Q: How to remove parenthesis and inside text in r? I have a dataframe with some species names + parenthesis and a number inside + some text, like : "species name(2) V1", which are present in dataframe$species_name.
I need to remove it with gsub so it only returns "species name" and another to return "species name V1".
Thanks in advance!
I've searched around and nothing couldn't find a regular expression pattern for this, in R at least. I could only find code to remove the parenthesis. I'm too noob to know how to remove the rest.

A: The following two regexp solve the two problems in the question.
s <- "species name(2) V1"

sub("(^[^(]*)\\(.*$", "\\1", s)
#[1] "species name"

sub("\\([^)]*\\)", "", s)
#[1] "species name V1"

Now apply them to the column of interest.

A: Because you mentioned gsub(), I assumed you wanted to stick with base R.
Here I create two new variables based on some randomly generated species names that I think match your request.
"(" is a special character and therefore must escaped with "\" but because "\" is a special character itself you must escape it with another "\" resulting the the "\\"s.
"." matches any one character and "*" is a quantifier that says match 0 or more.
"$" indicates the end of the string.
[0-9] matches a single integer.
"+" is another quantifier that says to match one or more.
Thus we have:
set.seed(42)

df <- data.frame(species_name = paste0("species ",
                                       sample(LETTERS, 10),
                                       " name(",
                                       sample(1:10),
                                       ") V",
                                       sample(1:10)))

df$species_name1 <- gsub("\\(.*$", "", df$species_name)

df$species_name2 <- gsub("\\([0-9]*\\)", "", df$species_name)

df

Which produces:
            species_name  species_name1      species_name2
1   species Q name(9) V4 species Q name  species Q name V4
2   species E name(5) V5 species E name  species E name V5
3   species A name(6) V7 species A name  species A name V7
4   species J name(4) V9 species J name  species J name V9
5   species D name(2) V8 species D name  species D name V8
6  species R name(8) V10 species R name species R name V10
7   species Z name(3) V2 species Z name  species Z name V2
8   species O name(7) V3 species O name  species O name V3
9   species G name(1) V6 species G name  species G name V6
10 species V name(10) V1 species V name  species V name V1


text:
Q: Html rendering closing tags automatically I am working on a Native mobile application CMS system using client-side technology(javascript via JQuery for the most part) and have implmented a templating system similar to that of ASP.NET.
So suppose I have a navigation control which has a starttemplate, endtemplate and itemtemplate as follows:

[[Text]]

My problem is the browser as it laods seems to decide to want to fix the html so that the tags are closed "properly" as follows:

[[Text]]

I've tried some workaround and quick hacks to no avail..
I have tried replacing the "<" ">" with certain characters and then replacing them after load but the problem still occurs.

A: Your code is not valid html. You can't interleave tags (open it in one place and close it in a completely different place). Tags have to be properly nested.
Valid:

Invalid:

Note that you can't properly indent the second one without it looking "off". Please make sure your html is correct first, then the browser will behave properly.
-update- since you want client-side templating, what you don't want is the (invalid) html to be parsed as html. However, it's obviously also not valid xml, which is what you might want.
What you could do is wrap the content of the secions as CDATA.

<![CDATA[

    ]]>

<![CDATA[

[[Text]]

    ]]>

<![CDATA[

    ]]>

Now if you would interpret that as xml, the parts within the templates are considered text rather than markup.

A: You can't have
 elements as children of a
 element.

s only accept
 tags as children. Specification
Also, it appears you're nesting the tags incorrectly, here:

You can't close that
 if the
 is still open. That's why the
 is prematurely closed.

A: Basically, you're asking for a way to force a browser to display malformed, messy tag-soup. Thank God most browsers don't just blindly render that kind of code, because the results would be unbearable and make your page unintelligible all together.
That said, if you view the raw page source, you'll probably see the un-corrected, raw markup. But because the browser can't really render it, the engine steps up to the plate and does its best.
But please, don't waste your time finding a way around this, it's just a feature to help you, not to annoy you. Also: HTML5 has a lot more rules about what is allowed and what is not, and how the browser is expected to deal with invalid markup (in your code:

 is deemed invalid, for example). If you feel up to it, you can look at the W3C specifications for more info on the subject.

A: Instead of having tags such as  I used keywords to represent the < and > and then render all the correct html using the templating system and replace those keywords back to , and > and add it to the document afterwards. Annoying syntax in my template tags, but it works the way I need it to.


text:
Q: Insert schema as first row to result of hive query I there a way to add schema/column headers as the first row to the output of a Hive query?
Im doing a typical dump to a local directory using this hive statement
INSERT OVERWRITE LOCAL DIRECTORY '/some_path/'
SELECT
    ... AS column1
    ... AS column2
...
;

In the output I want:
column1    column2
data       data
data       data

A: Since set hive.cli.print.header=true; works only on terminals, it will not print the headers into the file. I would do this in order to achieve that :
bin/hive -e "set hive.cli.print.header=true; select * from demo;" > /path/to/file


text:
Q: ReactJS - Add two items to dictionary - Only second one is added I'm trying to add 2 items to a dictionary state at once, but only the second one is added.
I made an example below, you can also check the codesandbox. When I run add2Items, only "Item2" is added.
Can anyone tell me what's going wrong here?
  const [dict, setDict] = useState({});

  const addItem = (name, value) => {
    console.log("name", name);
    const newItem = { [name]: value };
    const newDict = Object.assign({}, dict, newItem);
    setDict(newDict);
  };

  const add2Items = () => {
    addItem("Item1", "test1");
    addItem("Item2", "test2");
  };

https://codesandbox.io/embed/brave-mountain-ienzbu

A: Could it be that you don't include the current state when assigning a new dictionary and therefore overwriting the state each time?

A: Your messages becomes stale for second call of setMessages. To get rid of it use the callback function with setMessages:
  const addMessage = (name, value) => {
    setMessages(prevMessages => ({...prevMessages, [name]: value}));
  };

function MyFunction() {
  const [messages, setMessages] = React.useState({});

  const addMessage = (name, value) => {
    setMessages(prevMessages => ({...prevMessages, [name]: value}));
  };

  const add2Messages = () => {
    addMessage("Message1", "test");
    addMessage("Message2", "test2");
  };

  return (

      {JSON.stringify(messages)}
      <button onClick={() => add2Messages()}>Add 2 messages</button>

  );
}

ReactDOM.render(<MyFunction />, document.querySelector('.react'));


text:
Q: How to properly configure EC2 Instance for EBS Backed AMI I've created an AMI from an Ubuntu EC2 instance, and have found a weird issue when attempting to connect to a newly launched instance from this AMI. When using the key pair that I chose to connect with, I'm unable to connect, however, I am able to use a keypair that was in the authorized_keys file when creating the instance. I've also noticed that when inspecting the .ssh directory there is another directory titled: authorized_keys with its full path being ~/authorized_keys /etc/ssh/authorized_keys.
On the AMI I have also modified /etc/sshd_config to included /etc/ssh/authorized_keys so I'm thinking this is related to this.
Here's the specific line in sshd_config:
AuthorizedKeysFile %h/.ssh/authorized_keys /etc/ssh/authorized_keys
An answer to this question would provide details on how to properly configure the ~/.ssh... and /etc/ssh/sshd_config directories and configurations so that creating an AMI would work normally on any instance provisioned using the AMI.


text:
Q: Generalize http:outbound-gateway reply-channel Given a gateway that handles service calls to a ws. My goal is to supply the http:outbound-gateway's reply-channel using header-enricher since I'll be adding multiple methods to gateway and I would like to make use of only 1 http:outbound-gateway
I can currently receive the response up to groovy script (2) BUT it doesn't seem to want to return the results to the actual method that calls the service
Any help would be appreciated. Thanks!
<gateway id="registryService" service-interface="RegistryService">
<method name="create" request-channel="create-request-channel"
        reply-channel="create-reply-channel" />
</gateway>

<chain input-channel="create-request-channel" output-channel="create-request-fulfillment-channel">
 <transformer>
   // groovy script that contains the method to be called in the ws (1)
 </transformer>
 <object-to-json-transformer/>
 <header-enricher>
   <reply-channel overwrite="true" ref="create-reply-fulfillment-channel" />
 </header-enricher>
</chain>

<http:outbound-gateway request-channel="create-request-fulfillment-channel"
                       extract-request-payload="true"
                       expected-response-type="java.lang.String"
                       url="http://localhost:4567" http-method="POST" />

<chain input-channel="create-reply-fulfillment-channel"
       output-channel="create-reply-channel">
       <json-to-object-transformer type="JsonRpcResponse"/>
       <transformer>
           //groovy script to manipulate response (2)
       </transformer>
</chain>

A: Do the following:
Each method of your gateway should enrich message with some unique 'routing' header value:
<gateway id="registryService" service-interface="RegistryService">
  <method name="create" request-channel="http-request-channel"
        reply-channel="registryService-create-responseChannel">
    <header name="routingHeader" value="registryService-create" />
  </method>
</gateway>

And then send message straight forward to outbound gateway:
<http:outbound-gateway request-channel="http-request-channel"
                       response-channel="http-response-channel"
                       extract-request-payload="true"
                       expected-response-type="java.lang.String"
                       url="http://localhost:4567" http-method="POST" />

Http outbound gateway sends request to the remote server and then forward response to http-response-channel. To this channel is attached header value router, which basis on the value of routing header, sends (routes) message to the appropriate channel:
<header-value-router input-channel="http-response-channel" header-name="routingHeader">
  <mapping value="registryService-create" channel="registryService-create-responseChannel" />
  <mapping value="someOtherService-otherMethod" channel="someOtherService-otherMethod-responseChannel" />
</header-value-router>

Of course you don't need to send it back directly to the gateway - you can add some additional processing between those components, and all the time you can route message basis on the header value.
It's simpler than hacks with groovy and I use it myself - proven that works ;)


text:
Q: OnTriggerEnter how to work with other objects and not on the object on which the script is located Good afternoon, I have a script that should read the hit of the ball in two different objects that I set as
public GameObject LeftHitTrigger;
public GameObject RightHitTrigger;

how to write OnTriggerEnter so that it works with one object and with another
private void OnTriggerEnter(Collider collision)
    {
        if (LeftHitTrigger.colission, collision.gameObject.tag == "Ball")
        {
            AiCount++;
            Debug.Log(AiCount);
            AiCountText.text = AiCount.ToString();
        }

        if (RightHitTrigger.colission, collision.gameObject.tag == "Ball")
        {
            AvatarCount++;
            Debug.Log(AvatarCount);
            AvatarCountText.text = AvatarCount.ToString();
        }
    }

I tried this but it doesn't work and i get errors after "LeftHitTrigger.colission," and "RightHitTrigger.colission," in brackets.


text:
Q: Users activity history we had some problems in our wordpress web when we changed some issues on the code, and I would like to identify which of the changes made the web crash.
I've tried some plugins as Simple History, but the problem is that you can't get the activity made previously to the installation of the plugin.
Does someone know how could I get the whole activity of the site, even we had no plugins installed?
Thanks in advance.

A: It's not going to show you previous history before the plugin was activated, there's no way to do that as you have to have the plugin activated for it to log and store those.  This is not something done by default in WordPress.
What you need to do instead is to enable WordPress debugging, and then check the logs.
In your wp-config.php file, enable debug logging, by adding this:
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', true);

This will show the errors on screen, set WP_DEBUG_DISPLAY to false to prevent showing on screen.
With WP_DEBUG_LOG set to true, this will create a file located at wp-content/debug.log which you can view to see any errors or warnings from PHP on your site.


text:
Q: Foursquare Explore API not providing venue tips on certain accounts When using the Foursquare Developer API to perform a venue search, I receive different results depending on the account being used.
For a given authorised query (for example, https://api.foursquare.com/v2/venues/explore?ll=40.7,-74) I am given back a collection of items with "reasons" and "venue" objects. On some accounts, it also provides "tips" data; on others it does not.
Is this additional information dependent on certain account settings, or is there something I'm missing?
Thanks in advance!

A: The explore endpoint is tailored to each user and provides dynamic recommendations depending on social context, time of day, and user interests. Thus, two queries are likely to contain different content depending on who is querying the API.
For example, if a friend has left a tip at a nearby venue, it's more likely that you'll see that in your explore results, because it provides social reinforcement to the recommendation.
For other venues, there might be signals more important than tips, so a tip is not surfaced.
The official foursquare apps provide good examples of this data in action, as the explore result panes change format slightly from recommendation to recommendation.
Hope that helps?


text:
Q: Learning Structured Text, function block to controll a "pusher" I come from a background in PC-programming (VB/C# .Net and PHP) and am learning PLC programming in school. At a recent test we had we where to create a function block that would push an element of a production line and into a container.
Now, that is pretty simple, so I have added an Alarm to my code if the "pusher" (for lack of a better word) that will activate if the maneuver is not complete within 10 seconds.
My problem is that the pusher goes into an Alarm state immediately and it seems to be rather buggy :( So any answer would give some direction of how to structure my code better, or figure out why it goes into an alarm so fast...
(* INIT *)
(* Drive the pusher back if its out on init *)

IF M8002 THEN
        SkyvTilbake := TRUE; (* My "Function"/Step to retract the pusher *)
        Ferdig := FALSE; (*Let other components know that the pushers operation has completed *)
        SkyverUtMotor := FALSE; (*This is the engine output for driving the pusher out *)
        SkyverInnMotor := FALSE; (* This is the engine output for driving the pusher in *)
END_IF;

(* "Aktiver" is a input to activate the pusher *)
IF Aktiver THEN
    SkyvTilbake := FALSE;
    SkyvUt := TRUE; (* My "Function"/Step" to push the pusher out *)
    Ferdig := FALSE;
END_IF;

(* Push out step *)
IF SkyvUt AND NOT SkyvTilbake  AND NOT Alarm  THEN
    TON_1(IN:= SkyvUt ,PT:= AlarmTid ,Q:= Alarm ,ET:= TimeLeft );
    SkyverUtMotor := TRUE;

    (* When sensor out activates (input), retract the pusher *)
    IF SensorUte THEN
        SkyvUt := FALSE;
        SkyvTilbake := TRUE;
        SkyverUtMotor := FALSE;
    END_IF;

(* retract the pusher as long as there are no alarms *)
ELSIF SkyvTilbake AND NOT Alarm THEN
    TON_2(IN:= SkyvTilbake  ,PT:= AlarmTid ,Q:= Alarm ,ET:= TimeLeft );
    SkyverInnMotor := TRUE;

     (* When it reach the normal position, activate "Ferdig" *)
     IF SensorInne THEN
            SkyverInnMotor := FALSE;
            SkyvTilbake := FALSE;
            Ferdig := TRUE;
    END_IF;
END_IF;

(* When the alarm activates, stop all the engines *)
IF Alarm THEN
    SkyverUtMotor := FALSE;
    SkyverInnMotor := FALSE;
END_IF;

(* RESET ALARM *)
IF Reset THEN
    Alarm := 0;
    SkyvTilbake := TRUE;
END_IF;

PS. The test was in the middle of december, but I'm looking to learn more about structured text and designing PLC programs. Also the code is designed in to run in a Mitsubishi FXCPU, and written in GX Works 2

A: I don't see where you are actually setting the time duration for your timer ( PT:= AlarmTid ).
Also, as I am not familiar with Mitsubishi PLC's, do timers automatically reset? It looks like once your timer is on, it never turns off.
You nay also want to look into using 'CASE . . . WHERE', it tends to clean up the code.


text:
Q: Alfresco: Unable to search via Lucene by date I am writing an Alfresco webscript to search for content by date, and not having any luck.
My query looks like this:
PATH:\"/app:company_home/st:sites/cm:mysite/cm:documentLibrary/cm:News/*\"
AND @cm\\:created:[2013-09-25T00:00:00.000Z TO NOW]

I have three folders in my News folder:

*

*Folder 1, created on 2013-09-24

*Folder 2, created on 2013-09-24

*Folder 3, created on 2013-09-25   <- Created a day after the other two.

My Lucene search is always returning 3 items. Why does it return three items when the first two were created before the 25th?
And why do I have to search with a range to get any results? Why does this not work when Alfresco's documentation says that truncated datetime formats are supported?
PATH:\"/app:company_home/st:sites/cm:mysite/cm:documentLibrary/cm:News/*\"
AND @cm\\:created:"2013-09-25"

Alfresco version: 3.3
EDIT:
I have checked that the following lines exist in alfresco/model/dataTypeAnalyzers.properties:
d_dictionary.datatype.d_date.analyzer=org.alfresco.repo.search.impl.lucene.analysis.DateAnalyser
# d_dictionary.datatype.d_datetime.analyzer=org.alfresco.repo.search.impl.lucene.analysis.DateAnalyser
d_dictionary.datatype.d_datetime.analyzer=org.alfresco.repo.search.impl.lucene.analysis.DateTimeAnalyser

A: A working example from version 3.x in a freemarker template
<#assign startPunt = companyhome.childrenByLuceneSearch["TYPE:\"wn:zaak\" AND @wn\\:vernietigingsdatum:[MIN TO "+date?string("yyyy-MM-dd'T'HH:mm:ss")+"] "]>