text:
Q: "java.io.IOException: Host is down" after crawling one hundred thousand files of mounted cifs share in Linux file system I have mounted a CIFS share in Linux. I am crawling metadata of the files and reading the content as you can see in the below code sample. After crawling approximately one hundred thousand files it start throwing exception: java.io.IOException: Host is down
1.if (Files.isReadable(p)) {
2.  //checks here if the file is readable so the metadata can be populated without throwing exceptions.
3.  BasicFileAttributes attr = Files.readAttributes(p, BasicFileAttributes.class);
4.  metadata.setCreated(new DateTime(attr.creationTime().toString()));
5.  metadata.setOriginalSize(attr.size());
6.  metadata.setLastModified(new DateTime(attr.lastModifiedTime().toString()));
7.  metadata.setMimeType(MimeTypeUtil.getContentType(p));
8.  if(Files.getOwner(p) != null) {
9.      metadata.setOwner(Files.getOwner(p).getName());
10  }
11.}

It's throwing an exception when we are trying to get the mime-type at line number: 7 in above code.
public class MimeTypeUtil {

    private static final Tika tika = new Tika();

    public static String getContentType(Path path) {
        try {
            return tika.detect(path.toFile());
        } catch (IOException e) {
            throw e;
        }
    }
}

Exception:
! java.io.IOException: Host is down
! at java.io.FileInputStream.readBytes(Native Method) ~[na:1.7.0_65]
! at java.io.FileInputStream.read(FileInputStream.java:272) ~[na:1.7.0_65]
! at java.io.BufferedInputStream.fill(BufferedInputStream.java:235) ~[na:1.7.0_65]
! at java.io.BufferedInputStream.read(BufferedInputStream.java:254) ~[na:1.7.0_65]
! at org.apache.tika.io.ProxyInputStream.read(ProxyInputStream.java:59) ~[tika-core-1.5.jar:na]
! Causing: org.apache.tika.io.TaggedIOException: Host is down
! at org.apache.tika.io.TaggedInputStream.handleIOException(TaggedInputStream.java:133) ~[tika-core-1.5.jar:na]
! at org.apache.tika.io.ProxyInputStream.read(ProxyInputStream.java:63) ~[tika-core-1.5.jar:na]
! at org.gagravarr.tika.OggDetector.detect(OggDetector.java:52) ~[vorbis-java-tika-0.1.jar:na]
! at org.apache.tika.detect.CompositeDetector.detect(CompositeDetector.java:61) ~[tika-core-1.5.jar:na]
! at org.apache.tika.Tika.detect(Tika.java:133) ~[tika-core-1.5.jar:na]
! at org.apache.tika.Tika.detect(Tika.java:267) ~[tika-core-1.5.jar:na]
! at org.apache.tika.Tika.detect(Tika.java:248) ~[tika-core-1.5.jar:na]
! at org.abc.xyz.util.MimeTypeUtil.getContentType(MimeTypeUtil.java:19) ~[abc2-xyz-2.3.0.jar:na]

I am also getting the same exception when we are to obtaining input bytes from a file from mounted CIFS share in Linux file system. Please help me to identify the cause of the exception.


text:
Q: My shiny app won't deploy correctly on shiny.io server Please I am trying to deploy my app, which runs fine in R studio, but which does not deploy correctly on shiny.io. Below is the app I want to deploy

But here is what I see in my browser, after deployment

I ran a diagnostic in R studio, but couldn't find anything in the log generated. Here it is below:
----- Deployment log started at  2020-05-10 23:51:26  -----
Deploy command:
 rsconnect::deployApp(appDir = "~/mavisanalytics", appFileManifest = "C:/Users/Idiaye/AppData/Local/Temp/ef3a-83e6-a7aa-4236",      appPrimaryDoc = "mavisanalytics.R", account = "mavisnaissanceconsulting",      server = "shinyapps.io", appName = "mavisanalytic", appTitle = "mavisanalytic",      launch.browser = function(url) {         message("Deployment completed: ", url)     }, lint = FALSE, metadata = list(asMultiple = FALSE, asStatic = FALSE),      logLevel = "verbose")

Session information:
R version 3.6.0 (2019-04-26)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 8.1 x64 (build 9600)

Matrix products: default

locale:
[1] LC_COLLATE=English_United Kingdom.1252
[2] LC_CTYPE=English_United Kingdom.1252
[3] LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_3.6.0   rsconnect_0.8.16
Cookies:
[1] "None"
GET /v1/applications/?filter=account_id:143204&filter=name:mavisanalytic&count=100&offset=0 1390ms
----- Bundle upload started at  2020-05-10 23:51:28  -----
[2020-05-10 23:51:28] Inferring App mode and parameters
[2020-05-10 23:51:28] Bundling app dir
[2020-05-10 23:51:29] Generate manifest.json
[2020-05-10 23:54:09] Writing Rmd index if necessary
[2020-05-10 23:54:09] Compressing the bundle
POST /v1/bundles 1370ms
[2020-05-10 23:54:14] Starting upload now
PUT /bundles/application-2275278/689e8c37f6f44015b1666fa66760b5b3.tar.gz?AWSAccessKeyId=ASIA54P7SCTKREC5WZV3&x-amz-acl=bucket-owner-full-control&Expires=1589154867&content-md5=XsmlS3ExioMdAhqFDdJESA%3D%3D&x-amz-security-token=IQoJb3JpZ2luX2VjENL%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCXVzLWVhc3QtMSJHMEUCICKXX2TaFDiqdrRKgsAqldR7%2FiZ2fzYqscA%2BlfJzfHJ0AiEAi9htV1hdEze6kBuHvpbhl0gsyRv2ZEKxEbYBUn80%2FjwqtAMIGxAAGgw5NTQ1NTU1NjkzNjUiDGDy1aBPrmatUSEpOiqRA2uAfFt1xtFrgxv8TiCmPKb5jSignature=BSEK9pBg7SDBnvqzXrbH8He0dm4%3D&content-type=application%2Fx-tar 79750ms
[2020-05-10 23:55:33] Upload complete
POST /v1/bundles/3129156/status 1949ms
GET /v1/bundles/3129156 1129ms
[2020-05-10 23:55:37] Saving deployment record for mavisanalytic -
----- Server deployment started at  2020-05-10 23:55:37  -----
POST /v1/applications/2275278/deploy 1219ms
Waiting for task: 729282360
GET /v1/tasks/729282360 1350ms
  building: Parsing manifest
GET /v1/tasks/729282360 1189ms
  building: Building image: 3492511
GET /v1/tasks/729282360 1300ms
  building: Installing system dependencies
GET /v1/tasks/729282360 1149ms
GET /v1/tasks/729282360 1220ms
  building: Fetching packages
GET /v1/tasks/729282360 1420ms
  building: Installing packages
GET /v1/tasks/729282360 1310ms
GET /v1/tasks/729282360 1340ms
GET /v1/tasks/729282360 1349ms
GET /v1/tasks/729282360 1279ms
GET /v1/tasks/729282360 1360ms
GET /v1/tasks/729282360 1379ms
GET /v1/tasks/729282360 1139ms
GET /v1/tasks/729282360 1200ms
GET /v1/tasks/729282360 1159ms
GET /v1/tasks/729282360 1170ms
GET /v1/tasks/729282360 1149ms
GET /v1/tasks/729282360 1250ms
GET /v1/tasks/729282360 1269ms
GET /v1/tasks/729282360 1250ms
GET /v1/tasks/729282360 1189ms
  building: Installing files
GET /v1/tasks/729282360 1259ms
GET /v1/tasks/729282360 1209ms
  building: Pushing image: 3492511
GET /v1/tasks/729282360 1139ms
GET /v1/tasks/729282360 1290ms
GET /v1/tasks/729282360 1160ms
GET /v1/tasks/729282360 1670ms
GET /v1/tasks/729282360 1230ms
GET /v1/tasks/729282360 1180ms
GET /v1/tasks/729282360 1129ms
GET /v1/tasks/729282360 1359ms
GET /v1/tasks/729282360 1199ms
GET /v1/tasks/729282360 1209ms
GET /v1/tasks/729282360 1189ms
  deploying: Starting instances
GET /v1/tasks/729282360 1280ms
  rollforward: Activating new instances
GET /v1/tasks/729282360 1180ms
  success: Stopping old instances
----- Deployment log finished at  2020-05-10 23:57:01  -----
Deployment completed: https://mavisnaissanceconsulting.shinyapps.io/mavisanalytic/

In the R studio console, I get the error message:
Error in rbind.data.frame(..., stringsAsFactors = FALSE) :
  numbers of columns of arguments do not match

Below is the code of the app I am trying to deploy. It is a bit messy, but I am hoping some good Samaritan will patiently help me out:
if(interactive()){
library(shiny)
library(shinyalert)
library(shinycssloaders)
library(shinythemes)
library(shinyWidgets)
library(shinyjs)
library(SentimentAnalysis)
library(textclean)
library(reactable)
library(tm)

options(spinner.color="#3498db",
        spinner.color.background="#ffffff",
        spinner.size=1)

ui<-list(useShinyjs(),navbarPage(strong("Mavis Analytic"),theme=shinytheme("cerulean"),
               windowTitle="Mavis Analytic",fluid=TRUE,inverse=FALSE,
               tabPanel(strong("Opinion Miner"),icon=icon("table"),useShinyalert(),
                setBackgroundColor("white"),setBackgroundImage(src="white.jpg"),
                          sidebarLayout(
                          sidebarPanel(width=3,
                          img(src="logo.jpg",height=130,width=150),
                          h4(strong("Enter your texts in these fields")),
                          actionButton("clear",strong("Clear Fields"),icon=icon("broom")),br(),br(),
                          textAreaInput("text","Text Field 1",value="It is a beautiful day"),
                          textAreaInput("texts","Text Field 2",value="I am happy to be here"),
                          textAreaInput("word","Text Field 3",value="Let's have some fun"),
                          textAreaInput("words","Text Field 4",value="It has been a bad outing"),
                          textAreaInput("wordy","Text Field 5",value="I dislike clowns"),
                          actionButton("run",strong("Run Analysis"),icon=icon("caret-right")),br(),hr(),h5(strong("The number of words entered into each text field:")),reactableOutput("count",width="40%")),
                          mainPanel(h4("The Opinion Miner is a tool for conducting sentiment analysis. It is useful for analyzing and scoring the kinds of sentiments expressed in texts, such as in literature, social media posts, or product reviews."),hr(),h3(strong("Table of Sentiment Scores")),withSpinner(reactableOutput("table"),type=1),downloadButton("download",strong("Download Table")),br(),br(),
                                    column(4,selectInput("choice","Select Sentiment Score to Plot",choices=c("QDAP","LoughranM","HarvardIV"))),column(4,selectInput("color","Select Color",choices=c("Blue","Red","Green","Yellow","Purple"))),
                                    fluidRow(column(6,withSpinner(plotOutput("plot",height=350,width=400),type=1)),column(6,withSpinner(plotOutput("graph",height=350,width=400),type=1))),
                                    fluidRow(column(6,downloadButton("plot.down",strong("Download Graph"))))))),

               tabPanel(strong("Financial Ratios Calculator"),icon=icon("chart-bar"),
                        sidebarLayout(
                        sidebarPanel(width=2,h4(strong("Profit figures:")),
                                  actionButton("delete",strong("Clear Fields"),icon=icon("broom")),br(),br(),
                                  textInput("num","Profit 1",value="100000",width=150),
                                  textInput("numb","Profit 2",value="150000",width=150),
                                  textInput("number","Profit 3",value="200000",width=150),
                                  textInput("numbers","Profit 4",value="250000",width=150),
                                  textInput("numbered","Profit 5",value="300000",width=150),
                                  hr(),
                                  h4(strong("Turnover figures:")),
                                  actionButton("remove",strong("Clear Fields"),icon=icon("broom")),br(),br(),
                                  textInput("fig","Turnover 1",value="350000",width=150),
                                  textInput("figs","Turnover 2",value="300000",width=150),
                                  textInput("figu","Turnover 3",value="420000",width=150),
                                  textInput("figur","Turnover 4",value="600000",width=150),
                                  textInput("figure","Turnover 5",value="550000",width=150),
                                  actionButton("go",strong("Calculate Ratio"),icon=icon("caret-right")),
                                  hr(),
                                  h4(strong("Receivables figures:")),
                                  actionButton("vanish",strong("Clear Fields"),icon=icon("broom")),br(),br(),
                                  textInput("deb","Receivables 1",value="150000",width=150),
                                  textInput("debt","Receivables 2",value="100000",width=150),
                                  textInput("debts","Receivables 3",value="50000",width=150),
                                  textInput("debtor","Receivables 4",value="80000",width=150),
                                  textInput("debtors","Receivables 5",value="170000",width=150),
                                  actionButton("away",strong("Calculate Ratio"),icon=icon("caret-right"))),
                        mainPanel(h4("The Financial Ratios Calculator makes possible a comparative analysis of a company's profitability and efficiency ratios over time."),hr(),
                                  h3(strong("Profitability Ratios")),h4("(Profit/Turnover): Calculates how much profit margin (%) a company makes on its sales"),fluidRow(column(6,withSpinner(plotOutput("bar",),type=1)),column(6,withSpinner(plotOutput("pie"),type=1))),
                                  fluidRow(column(6,downloadButton("drop",strong("Download Bar Plot"))),column(6,downloadButton("fall",strong("Download Pie Chart")))),hr(),
                                  h3(strong("Efficiency Ratios")),h4("(Receivables/Turnover): Calculates the average length of time (in days) it takes for a company to recover its debts"),
                                  fluidRow(column(6,withSpinner(plotOutput("sphere"),type=1)),column(6,withSpinner(plotOutput("bin"),type=1))),
                                  fluidRow(column(6,downloadButton("down",strong("Download Pie Chart"))),column(6,downloadButton("plummet",strong("Download Bar Plot")))))

                          )),
               tabPanel(strong("About Mavis Analytic"),icon=icon("info"),mainPanel(h4(div(style="color:#5499c7","Mavis Analytic is designed as a multi-functional web application, with a variety of features that make it a modern business tool.
                                                                                It currently incorporates tools for conducting sentiment analysis and financial performance evaluation. The goal of the designers of Mavis Analytic, Mavis Naissance Consulting,
                                                                                is to keep expanding the scope of the application, by creating more functions that will make it a very versatile software for a wide range of business uses. ")),img(src="New.jpg",height=150,width=150))),
               tabPanel(strong("Send Us Your Feedback"),icon=icon("envelope"),
                    HTML("<iframe src=https://docs.google.com/forms/d/e/1FAIpQLSex-eKi33LdmZE7L3PwjWm4tFbFoEIw_L_KUvsSi6kgdXgJPA/viewform?embedded=true width=1400 height=1000 frameborder=0 marginheight=0 marginwidth=0>Loading.</iframe>")),
               navbarMenu(strong("More"),
               tabPanel(strong("Graphs and Charts"),icon=icon("chart-bar"),sidebarLayout(sidebarPanel(width=3, selectInput("select","Select Variable to Plot",choice=c(
                        "Indegree","Outdegree","Degree","Normalized",
                        "Domain","Proximity","Modularity","Clusters"
              ),selected="Modularity"),sliderInput("slide","Change Pie Chart Angle",min=45,max=180,animate=TRUE,value=45,step=1)),

               mainPanel(fluidRow(column(6,plotOutput("draw")),column(6,plotOutput("art"))),br(),
               fluidRow(column(6,plotOutput("paint")),column(6,plotOutput("part")))))),

               tabPanel(strong("Tables"),icon=icon("table"),
                        mainPanel(h3("Network data pulled from Twitter interactions on different subjects "),actionButton("detail",strong("Table Info")),downloadButton("table.down",strong("Download Table")),reactableOutput("metrics.table"),hr(),
                                  actionButton("more",strong("Table Info")),downloadButton("flat",strong("Download Table")), reactableOutput("freedom.table"))),
               tabPanel(strong("Library"),icon=icon("file-pdf"),
                        fluidRow(column(6,tags$iframe(style="height:400px;width:100%;scrolling=yes",src="analysis.pdf")),column(6,tags$iframe(style="height:400px;width:100%;scrolling=yes",src="Audits.pdf"))),br(),
                        fluidRow(column(6,tags$iframe(style="height:400px;width:100%;scrolling=yes",src="pricing.pdf")),column(6,tags$iframe(style="height:400px;width:100%;scrolling=yes",src="tech.pdf")))))

))
server<-function(input,output,session){

      observeEvent(input$clear,{
      updateTextAreaInput(session,"text",value="",placeholder="Enter new text")
      updateTextAreaInput(session,"texts",value="",placeholder="Enter new text")
      updateTextAreaInput(session,"word",value="",placeholder="Enter new text")
      updateTextAreaInput(session,"words",value="",placeholder="Enter new text")
      updateTextAreaInput(session,"wordy",value="",placeholder="Enter new text")

    })

  observeEvent(input$run,{
    shinyalert(title="Running Analysis",text="Please be patient while the app cleans the texts and runs the analysis",
               closeOnEsc=TRUE,confirmButtonText="OK",timer=10000,animation=TRUE,closeOnClickOutside=TRUE)
  })

  observeEvent(input$detail,{
    shinyalert(title="Disease on Twitter",text="This table contains the metrics underlying the network of Twitter interactions about disease, using the #disease hashtag",
               closeOnEsc=TRUE,closeOnClickOutside=TRUE,animation=TRUE,confirmButtonText="OK",timer=10000)
  })

  observeEvent(input$more,{
    shinyalert(title="Freedom on Twitter",text="This table contains the statistical data of the Twitter conversation about freedom, using the #freedom hashtag",
               closeOnEsc=TRUE,closeOnClickOutside=TRUE,animation=TRUE,confirmButtonText="OK",timer=10000)
  })
  observeEvent(input$delete,{
    updateTextInput(session,"num",value="",placeholder="0")
    updateTextInput(session,"numb",value="",placeholder="0")
    updateTextInput(session,"number",value="",placeholder="0")
    updateTextInput(session,"numbers",value="",placeholder="0")
    updateTextInput(session,"numbered",value="",placeholder="0")
  })
  observeEvent(input$remove,{
    updateTextInput(session,"fig",value="",placeholder="0")
    updateTextInput(session,"figs",value="",placeholder="0")
    updateTextInput(session,"figu",value="",placeholder="0")
    updateTextInput(session,"figur",value="",placeholder="0")
    updateTextInput(session,"figure",value="",placeholder="0")
  })
  observeEvent(input$vanish,{
    updateTextInput(session,"deb",value="",placeholder="0")
    updateTextInput(session,"debt",value="",placeholder="0")
    updateTextInput(session,"debts",value="",placeholder="0")
    updateTextInput(session,"debtor",value="",placeholder="0")
    updateTextInput(session,"debtors",value="",placeholder="0")
  })

  doc<-reactive({c(if(nchar(input$text)>0){input$text},
                   if(nchar(input$texts)>0){input$texts},
                   if(nchar(input$word)>0){input$word},
                   if(nchar(input$words)>0){input$words},
                   if(nchar(input$wordy)>0){input$wordy}
             )
    })
  profit<-reactive({
    as.numeric(c(if(input$num>0){input$num},
                 if(input$numb>0){input$numb},
                 if(input$number>0){input$number},
                 if(input$numbers>0){input$numbers},
                 if(input$numbered>0){input$numbered}))
     })

  turnover<-reactive({
    as.numeric(c(if(input$fig>0){input$fig},
                 if(input$figs>0){input$figs},
                 if(input$figu>0){input$figu},
                 if(input$figur>0){input$figur},
                 if(input$figure>0){input$figure}))

  })

  receivables<-reactive({
    as.numeric(c(if(input$deb>0){input$deb},
                 if(input$debt>0){input$debt},
                 if(input$debts>0){input$debts},
                 if(input$debtor>0){input$debtor},
                 if(input$debtors>0){input$debtors}))

  })

  output$table.down<-downloadHandler(
    filename=function(){
      paste("Metrics",".csv",sep="")
    },
    content=function(file){
      write.csv(disease,file)
    }
  )

  output$flat<-downloadHandler(
    filename=function(){
      paste("Freedom",".csv",sep="")
    },
    content=function(file){
      write.csv(freedom,file)
    }
  )

  disease<-read.csv("metrics.csv",header=TRUE,sep=",")

  disease.df<-data.frame(disease)

  pie.data<-reactive({head(disease$Degree,n=8)})

  bar.data<-reactive({head(freedom$Outdegree,n=6)})

  freedom<-read.csv("Freedom.csv",header=TRUE,sep=",")

  freedom.df<-data.frame(freedom)

  data.X<-reactive({switch(input$select,
                 "Indegree"=disease$Indegree,
                 "Outdegree"=disease$Outdegree,
                 "Degree"=disease$Degree,
                 "Normalized"=disease$Normalized,
                 "Domain"=disease$Domain,
                 "Proximity"=disease$Proximity,
                 "Modularity"=disease$Modularity,
                 "Clusters"=disease$Clusters
                 )})

  data.Y<-reactive({switch(input$choice,
                 "Indegree"=disease$Indegree,
                 "Outdegree"=disease$Outdegree,
                 "Degree"=disease$Degree,
                 "Normalized"=disease$Normalized,
                 "Domain"=disease$Domain,
                 "Proximity"=disease$Proximity,
                 "Modularity"=disease$Modularity,
                 "Clusters"=disease$Clusters
                 )})

  output$metrics.table<-renderReactable({

    reactable(disease.df,
              searchable=TRUE,
              outlined=TRUE,
              highlight=TRUE,
              bordered=TRUE,
              striped=TRUE,
              compact=TRUE,
              defaultColDef=colDef(
                align="center",
                headerStyle=list(background="#5dade2")
              ))
  })

  output$freedom.table<-renderReactable({

    reactable(freedom.df,
              compact=TRUE,
              striped=TRUE,
              searchable=TRUE,
              bordered=TRUE,
              highlight=TRUE,
              defaultColDef=colDef(
                align="center",
                headerStyle=list(background="#5dade2")
              ))
  })
  #This is the function for calculating profitability ratio
  profitability<-function(profit,turnover){
   profitability=round((profit/turnover)*100,1)
   return(profitability)
  }
  profitability.ratio<-reactive({profitability(profit(),turnover())})

  #This is the function for calculating efficiency ratio
  efficiency<-function(receivables,turnover){
    efficiency<-round((receivables/turnover)*365,1)
    return(efficiency)
  }

  efficiency.reactive<-reactive({
    efficiency(receivables(),turnover())
  })

  Analyze<-reactive({
    round(analyzeSentiment(
      replace_symbol(
        replace_number(
          replace_ordinal(
            doc())))),1)})

  QDAP<-reactive({Analyze()$SentimentQDAP})
  LoughranM<-reactive({Analyze()$SentimentLM})
  HarvardIV<-reactive({Analyze()$SentimentGI})

  word.count<-reactive({countWords(doc(),removeStopwords=FALSE)})

  tables<-reactive({
    data.frame(QDAP(),LoughranM(),HarvardIV())
  })

  data<-reactive({switch(input$choice,
                         "QDAP"=tables()$QDAP,
                         "LoughranM"=tables()$LoughranM,
                         "HarvardIV"=tables()$HarvardIV)})

  output$download<-downloadHandler(
    filename=function(){
      paste("table",".csv",sep="")
    },
    content=function(file){
      write.csv(tables(),file)
    }
  )

  output$drop<-downloadHandler(
    filename=function(){
      paste("Barplot",".jpg",sep="")
    },
    content=function(file){
      jpeg(file)
      barplot(profitability.ratio(),
              col=c("#5dade2","#ec7063","#48c9b0","#a569bd","#f4d03f"),
              beside=TRUE,
              border="white",
              xlab="Years",
              ylab="Margins in (%)")
      dev.off()
    }
  )

  output$fall<-downloadHandler(
    filename=function(){
      paste("Piechart",".jpg",sep="")
    },

    content=function(file){
      jpeg(file)
      pie(profitability.ratio(),radius=1.1,col=c("#5dade2","#ec7063","#48c9b0","#a569bd","#f4d03f"),
          border="white",
          clockwise=TRUE,
          init.angle=90,
          labels=profitability.ratio())
      dev.off()
    }
  )

  output$down<-downloadHandler(
    filename=function(){
      paste("Piechart",".jpg",sep="")
    },

    content=function(file){
      jpeg(file)
      pie(efficiency.reactive(),radius=1.1,border="white",clockwise=TRUE,
          init.angle=90,
          labels=efficiency.reactive(),
          col=c("#5dade2","#85c1e9","#3498db","#2e86c1","#2874a6"))
      dev.off()
    }
  )

  output$plummet<-downloadHandler(
    filename=function(){
      paste("Barplot",".jpg",sep="")
    },
    content=function(file){
      jpeg(file)
      barplot(efficiency.reactive(),
              col=c("#5dade2","#85c1e9","#3498db","#2e86c1","#2874a6"),
              border="white",
              beside=TRUE,
              xlab="Years",
              ylab="Days")
      dev.off()
    }
  )

  output$plot.down<-downloadHandler(
    filename=function(){
      paste("Graph",".jpg",sep="")
    },
    content=function(file){
      jpeg(file)
      color<-switch(input$color,
                    "Blue"="#5dade2",
                    "Red"="#e74c3c",
                    "Green"="#1abc9c",
                    "Yellow"="#f7dc6f",
                    "Purple"="#a569bd")
      barplot(data(),col=color,border="white",xlab="Texts",ylab="Sentiment Scores",main="Bar Plot of Sentiment Scores")
      dev.off()
    }
  )

  output$table<-renderReactable({
      input$run
      isolate(reactable(tables(),searchable=TRUE,bordered=TRUE,defaultColDef=colDef(
      align="center",
      headerStyle=list(background="#5dade2"),
      style=function(value){
        if(value>0){color<-"#27ae60"}
        else if(value<0){color<-"#e74c3c"}
        else{color<-"#5dade2"}
        list(color=color,fontWeight="bold")
      }),
      highlight=TRUE,outlined=TRUE,striped=TRUE,filterable=FALSE,compact=TRUE,onClick="expand")
      )
  })

  output$count<-renderReactable({
        input$run
        isolate(reactable(data.frame(word.count()),bordered=TRUE,striped=TRUE,compact=TRUE,
                          defaultColDef=colDef(
                            align="center",
                            headerStyle=list(background="#85c1e9"))
                            ))
       })

  output$plot<-renderPlot({

    color<-switch(input$color,
                  "Blue"="#5dade2",
                  "Red"="#e74c3c",
                  "Green"="#1abc9c",
                  "Yellow"="#f7dc6f",
                  "Purple"="#a569bd")
     input$run
    isolate(barplot(data(),col=color,border="white",xlab="Texts",ylab="Sentiment Scores",main="Bar Plot of Sentiment Scores"))

  })
  output$graph<-renderPlot({

            input$run
            isolate(plotSentiment(data(),xlab="Texts",ylab="Sentiment Scores"))
      })

  output$bar<-renderPlot({

            input$go
            isolate(barplot(profitability.ratio(),
                            col=c("#5dade2","#ec7063","#48c9b0","#a569bd","#f4d03f"),
                            beside=TRUE,
                            border="white",
                            xlab="Years",
                            ylab="Margins in (%)"))

  })

  output$pie<-renderPlot({

            input$go
            isolate(pie(profitability.ratio(),radius=1.1,col=c("#5dade2","#ec7063","#48c9b0","#a569bd","#f4d03f"),
                        border="white",
                        clockwise=TRUE,
                        init.angle=90,
                        labels=profitability.ratio()))

  })

  output$sphere<-renderPlot({

    input$away
    isolate(
      pie(efficiency.reactive(),radius=1.1,border="white",clockwise=TRUE,
          init.angle=90,
          labels=efficiency.reactive(),
          col=c("#5dade2","#85c1e9","#3498db","#2e86c1","#2874a6"))
    )
  })

  output$bin<-renderPlot({
    input$away
    isolate(
      barplot(efficiency.reactive(),
              col=c("#5dade2","#85c1e9","#3498db","#2e86c1","#2874a6"),
              border="white",
              beside=TRUE,
              xlab="Years",
              ylab="Days")
    )
  })

  output$draw<-renderPlot({

    hist(data.X(),border="white",col="#3498db",main="Variable Plots",xlab="Metrics")
  })

  output$art<-renderPlot({

    plot(data.X(),disease$Modularity,col="#e74c3c",xlab="Metrics",ylab="Value",pch=20,
         cex=2,type="h",main="Variable Plots")
  })

  output$paint<-renderPlot({

    pie(pie.data(),radius=1.1,clockwise=TRUE,init.angle=input$slide,
        border="white",col=c("#5dade2","#ec7063","#48c9b0","#a569bd","#f4d03f"),main="Pie Chart of Degrees")
  })

  output$part<-renderPlot({

    barplot(bar.data(),border="white",main="Bar Plot of Outdegrees",
            xlab="Outdegrees",ylab="Values",col=c("#5dade2","#ec7063","#48c9b0","#a569bd","#f4d03f"))
  })

}
}

shinyApp(ui=ui,server=server)

Thanks in advance of getting help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: configparser can't read regular config file, no section configparser (Python 3.7) found no section in regular config file
I don't get why this code won't work, I checked every detail in the doc. What can be wrong with my cnf file format?
File /home/julien/Workspace/BnsManager/data/.secret/.paris.cnf
[ldap]
admin_dn=Directory Manager
admin_password=superpassword

Permissions on .secret folder
ls -la .secret/
drwxrwxr-x 2 julien julien 4096 oct.  16 15:51 .
drwxrwxr-x 6 julien julien 4096 oct.  16 15:42 ..
-rw-rw-r-- 1 julien julien   60 oct.  17 08:48 .paris.cnf

File test.py
import configparser

p = '/home/julien/Workspace/BnsManager/data/.secret/.paris.cnf'
cp = configparser.ConfigParser()
cp.read(p)
print(cp.sections())

The ouput is [] but I expected it to be ['ldap']
Do you see what went wrong?

A: Try this to get the exception with explanation why the file is not read:
import configparser

p = '/home/julien/Workspace/BnsManager/data/.secret/.paris.cnf'
with open(p, 'r'):
  print('file could be opened')
cp = configparser.ConfigParser()
cp.read(p)
print(cp.sections())


text:
Q: Operator precedence in Python 2.7 What is the value of f?
f = lambda x: abs(x) if a == '1' else lambda x: x**2
f(2) gives lambda function if a = '1' and f(2) gives lambda function if a = '2'.
What is the operator precedence here?

A: lambda: has a lower precedence than conditional expressions, as seen in the operator precedence table or by trying something like lambda: 1 if False else 2 in the REPL.
Your statement parses as:
f = lambda x: (abs(x) if a == '1' else (lambda x: x**2))


text:
Q: Fading a background on a view to have a timer start So far in my app I have a ImageView next to a Start button.  When the start button is pressed the ImageView is replaced by a TextView to start a countdown.  Ideally what I am trying to accomplish now is having the Image next to the start button and when the Start button is pressed the background of that image fades just a little bit and a countdown starts in the middle of that image which is not faded.
The only thing I can think of at the moment is to have a TextView and have the image as the background but then my question now is how to fade that background.  Would this be an ideal/correct way of doing this?  If so how would I go about fading the background?  If there is another way of doing this how would I go about doing so?

A: You can use a text view and image view with the image view on top then fade the image view then fade the image view on the button click by using setAlpha on the image view.
There are other ways like using a drawable list but this will save u more work.
http://developer.android.com/reference/android/view/View.html#setAlpha(float)


text:
Q: Using np.interp to find x value for a given y gives wrong answer I want to find the x value for a given y (I want to know at what t, X, the conversion, reaches 0.9). There are questions like this all over SO and they say use np.interp but I did that in two ways and both were wrong. The code is:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

# Create time domain
t = np.linspace(0,4000,100)

# Parameters
A = 1.5*10**(-3) # Arrhenius constant
T = 300 # Temperature [K]
R = 8.31 # Ideal gas constant [J/molK]
E_a= 1000 # Activation energy [J/mol]
V = 5 # Reactor volume [m3]

# Initial condition
C_A0 = 0.1 # Initial concentration [mol/m3]

def dNdt(C_A,t):
    r_A = (-k*C_A)/V
    dNdt = r_A*V
    return dNdt

k=A*np.exp(-E_a/(R*T))
C_A = odeint(dNdt,C_A0,t)
N_A0 = C_A0*V
N_A = C_A*V
X = (N_A0 - N_A)/N_A0

# Plot
plt.figure()
plt.plot(t,X,'b-',label='Conversion')
plt.plot(t,C_A,'r--',label='Concentration')
plt.legend(loc='best')
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Conversion')

Looking at the graph, at roughly t=2300, the conversion is 0.9.
Method 1:
I wrote this function so I can ask for any given point and get the x-value:
def find(x_val,f):
    f = np.reshape(f,len(f))
    global t
    t = np.reshape(t,len(t))
    return np.interp(x_val,t,f)

print('Conversion of 0.9 is reached at: ',int(find(0.9,X)),'s')

When I call the function at 0.9 I get 0.0008858 which gets rounded to 0 which is wrong. I thought maybe something is going wrong when I declare global t??
Method 2:
When I do it outside the function; so I manually reshape X and t and use np.interp(0.9,t,X), the output is 0.9.
X = np.reshape(X,len(X))
t = np.reshape(t,len(t))
print(np.interp(0.9,t,X))

I thought I made a mistake in the order of the variables so I did np.interp(0.9,X,t), and again it surprised me with 0.9.
I'm unsure as to where I'm going wrong. Any help would be appreciated. Many thanks :)

A: On your plot, t is horizontal and X is vertical. You want to find the horizontal coordinate where the vertical one is 0.9. That is, find t for a given X. Saying

find x value for a given y

is bound to lead to confusion, as it did here.
The problem is solved with
print(np.interp(0.9, X.ravel(), t))   # prints  2292.765497278863

(It's better to use ravel for flattening, instead of the reshape as you did). There is no need to reshape t, which is already one-dimensional.

I did np.interp(0.9,X,t), and again it surprised me with 0.9.

That sounds unlikely, you probably mistyped. This was the correct order.


text:
Q: Parse & Unity 3D : Update an existing row Using the example code from the Unity Developer Guide | Parse
@ https://www.parse.com/docs/unity_guide#objects-updating
    // Create the object.
    var gameScore = new ParseObject("GameScore")
    {
        { "score", 1337 },
        { "playerName", "Sean Plott" },
        { "cheatMode", false },
        { "skills", new List<string> { "pwnage", "flying" } },
    };
    gameScore.SaveAsync().ContinueWith(t =>
                                       {
        // Now let's update it with some new data.  In this case, only cheatMode
        // and score will get sent to the cloud.  playerName hasn't changed.
        gameScore["cheatMode"] = true;

It just adds a new row and leaves the original row unchanged.
I guess i'm thinking Parse would do something "SQL like" such as UPDATE where primaryKey = 123.
Searching for an answer i found this code @
https://parse.com/questions/updating-a-field-without-retrieving-the-object-first, but there was no example in C#.  All attempts to port this to C# result in multiple syntax errors.
UnityScript:
// Create a pointer to an object of class Point with id dlkj83d
var Point = Parse.Object.extend("Point");
var point = new Point();
point.id = "dlkj83d";

// Set a new value on quantity
point.set("quantity", 6);

// Save
point.save(null, {
  success: function(point) {
    // Saved successfully.
  },
  error: function(point, error) {
    // The save failed.
    // error is a Parse.Error with an error code and description.
  }
});

Does Parse have some way to update a row that already exists using C#? And where is it in the docs?  And how can their own example be so useless?

A: One of the posts related to my question stated "retrieve the object, then write it back with the changes" and i had not the faintest idea how to execute the stated objective (especially after the epic fail of Parse Documentation's example code)
Here is what i have been able to figure out and make work:
var query = new ParseQuery<ParseObject>("Tokens")
    .WhereEqualTo ("objectId", "XC18riofu9");

query.FindAsync().ContinueWith(t =>
                               {
    var tokens = t.Result;
    IEnumerator<ParseObject> enumerator = tokens.GetEnumerator();
    enumerator.MoveNext();
    var token = enumerator.Current;
    token["power"] = 20;
    return token.SaveAsync();
}).Unwrap().ContinueWith(t =>
                         {
    // Everything is done!
    //Debug.Log("Token has been updated!");
});

the first part retrieves the object with the stated objectId, the second part sets the fields in the object.  The third part reports all is well with the operation.
it's a monkey see, monkey do understanding at this point being that i do not understand the finer points in the code.
the code can be tested by creating a class named "Tokens".  in that class create a tokenName field and a power field.  make a few rows with Fire, water, mud as the tokenNames.   Replace the objectId in the .WhereEqualTo clause with a valid objectId or any other search parameters you like. Execute the code and observe the changes in the Parse Data Browser.
For extra credit create the class required to implement the example code from the Chaining Tasks Together section of Parse's Documentation.
https://www.parse.com/docs/unity_guide#tasks-chaining


text:
Q: In a class method, what is the difference between using variable from Classname. vs cls In a class method, what is the difference between using variable from Classname.Varname vs cls.Varname ?

A: The effect depends on whether you are subclassing:
class Parent:
    @classmethod
    def use_cls(cls):
        return cls.__name__

    @classmethod
    def use_classname(cls):
        return Parent.__name__

class Child(Parent):
    pass

Now in the shell:
>>> p, c= Parent(), Child()
>>> p.use_cls()
'Parent'
>>> p.use_classname()
'Parent'

With the subclass we get differing results:
>>> c.use_cls()
'Child'
>>> c.use_classname()
'Parent'


text:
Q: while loop which executes five times and each time displaying a random digit I'm trying to create program segment that uses a single while loop which executes its loop body five times, each time displaying a random digit from this set of values. { 1 , 2 , 3 , 4 , 5 , 6 }
The while loop executes only once enter code here
public static void main(String[] args){
        int num = 0;
        int count = 0;
        while (count < 5)
            count ++;
        num = (int)(Math.random()* 6);

    System.out.println(num);

I also tried to do that with arrays.
 public static void main(String[] args){
            int[] num = { 1 , 2 , 3 , 4 , 5 , 6 };
            int count = 0;
            while (count < 5)
                count++;
            num [count] = (int)(Math.random()* 6);
            System.out.println(num);

Any tips will be helpful.

A: The while loop has no braces, so the body is only the next statement. Which increments count. Add braces.
while (count < 5) {
    count ++;
    num = (int) (Math.random() * 6);
    System.out.println(num);
}

Or, in Java 8+, with an IntStream like
IntStream.generate(() -> (int) (Math.random() * 6))
        .limit(5).forEachOrdered(System.out::println);

A: You need to put the last two lines inside the while loop
eg:
int[] num = { 1 , 2 , 3 , 4 , 5 , 6 };
int count = 0;
while (count < 5) {
    count++;
    num = (int)(Math.random()* 6);
    System.out.println(num);
}

Another solution would be to use a 'for' loop:
for(int i = 0; i < 5; i++) {
    num = (int)(Math.random()* 6);
    System.out.println(num);
}


text:
Q: Let $a,b,c$ be integers such that
$\gcd(a,6)=3=\gcd(b,6)$. Show that $\gcd(a+b,6)=6$. Let $a,b,c$ be integers such that
$\gcd(a,6)=3=\gcd(b,6)$.
Show that $\gcd(a+b,6)=6$.
Attempt:
Let $d = \gcd(a+b,6)$.
Then, by definition, $d \mid (a+b)$ and $d \mid 6$. It means that $d=1,2,3$ or $6$. On the other hand, we have
$3\mid a$ and $3 \mid b$. Write
$a = 3m$ and $b=3n$ for some integers $m$ and $n$. Then, $a+b=3m+3n=3(m+n)$ and so
$3 \mid (a+b)$. But, $d \mid (a+b)$. Now, $a+b = dp$ for some integer $p$.
Thus, we have $3 \mid dp$ which means $3 \mid d$ or $3 \mid p$.
If $3 \mid d$, then $d=3k$ for some integer $k$. Hence, $d$ is either $3$ or $6$.
But, how to get $d=6$?

A: Since $\gcd(a,6)=\gcd(b,6)=3$, then $a=3m$ and $b=3n$ for some odd $m$ and $n$.
Thus, $a+b=3(m+n)$ while $m+n$ is even, so $6\mid a+b$.


text:
Q: for i in {00..03} doesn't work with nohup The for loop submitted to nohup doesn't work, normally:
  $ for i in {00..03};do echo $i;done
  00
  01
  02
  03

But write these code to test.sh, nohup ./test.sh & gives following output:
  $ nohup ./test.sh &
  {00..03}

cannot produce 00 01 02 03, why ?
Ps. on debian 8 or ubuntu 15.10 ('seq -w' works)

A: If your file has no shebang, it depends on the shell nohup runs the script in. Prepend this line to the file:
  #!/bin/bash

A: Since brace-expansion is not a POSIX shell feature, and many system services are run in POSIX mode, this doesn't work.
The portable way to solve this for just four items is to use
for i in 00 01 02 03; do
  something
done

If you get into the habit of doing things the POSIX way you'll run into less surprises of this sort.


text:
Q: How to use rownames_to_column with dates I am trying to convert my yahoo price downloads to a "tidy" format, but in the reprex below, the dates lose their format and are converted to rownumbers.  Stated differently, how do I convert from xts to tibble and preserve the dates?
prices <- getSymbols("QQQ", adjustOHLC = TRUE, auto.assign = FALSE) %>%
  as_tibble() %>%
  rownames_to_column(var = "Date")
head(prices)

A: To keep it in all in a single tidyverse pipe, simply convert to a data frame first:
library(quantmod)
library(tibble)

getSymbols("QQQ", adjustOHLC = TRUE, auto.assign = FALSE) %>%
  as.data.frame() %>%
  rownames_to_column(var = "Date") %>%
  as_tibble()

#> # A tibble: 3,419 x 7
#>    Date       QQQ.Open QQQ.High QQQ.Low QQQ.Close QQQ.Volume QQQ.Adjusted
#>    <chr>         <dbl>    <dbl>   <dbl>     <dbl>      <dbl>        <dbl>
#>  1 2007-01-03     43.5     44.1    42.5      43.2  167689500         38.3
#>  2 2007-01-04     43.3     44.2    43.2      44.1  136853500         39.1
#>  3 2007-01-05     44.0     44.0    43.5      43.8  138958800         38.9
#>  4 2007-01-08     43.9     44.1    43.6      43.9  106401600         38.9
#>  5 2007-01-09     44.0     44.3    43.6      44.1  121577500         39.1
#>  6 2007-01-10     44.0     44.7    43.8      44.6  121070100         39.6
#>  7 2007-01-11     44.7     45.2    44.7      45.1  174029800         40.0
#>  8 2007-01-12     45.0     45.3    45.0      45.3  104217300         40.2
#>  9 2007-01-16     45.3     45.4    45.1      45.3   95690500         40.1
#> 10 2007-01-17     45.1     45.3    44.8      44.9  127142600         39.8
#> # ... with 3,409 more rows

Created on 2020-08-02 by the reprex package (v0.3.0)

A: I think you should use index() on the .xts rather than rownames_to_column() on the tibble
library(quantmod)
library(dplyr)

price.xts <-getSymbols("QQQ", adjustOHLC = TRUE, auto.assign = FALSE)
price<-as_tibble(price.xts)
price$Date <-index(price.xts)

head(price)
tail(price)


text:
Q: Add self signed certificate using PHPMailer on Gmail account Is it possible to use self signed or dedicated certificates on a Gmail account with the library PHPMailer? How to do this? And is this a secure option?

A: you can do :
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsMail();

$mail->AddAddress("contact@example.com");
$mail->Subject = "Test";
$mail->Body = "Test";

$mail->sign_cert_file = "/cert/key.pem";
$mail->sign_key_file = "/key/key.pem";
$mail->sign_key_pass = "password";

$mail->Send();

But, i don't know if Google gonna accept your certificate...
Code Source : http://www.adam-makes-websites.com/discoveries/sending_secure_certified_s-mime_emails_via_php


text:
Q: Android RecyclerView with GridLayoutManager make item span multiple rows I have a collection of photos, and I'm using a RecyclerView to display them. I want to have the first element in my RecyclerView span 2 columns AND 2 rows:

I know I can span 2 columns with setSpanSizeLookup:
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    @Override
    public int getSpanSize(int position) {
        if (position == 0) {
            return 2;
        } else {
            return 1;
        }
    }
});

but how can I also make the first item span 2 rows as well?
I have tried setting the first item's height to be different by inflating a different layout with double the height of the others, but that resulted in every item on the same row as the first item also being stretched to that height:
@Override
public ProfilePicViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView;
    if (viewType == TYPE_MAIN_PHOTO) {
        itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_main_profile_photo, parent, false);
    } else {
        itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_profile_photo, parent, false);
    }
    return new ProfilePicViewHolder(itemView);
}

A: You cannot achieve this behavior with GridLayoutManager, because it only supports spanning multiple columns.
Nick Butcher is currently implementing a custom SpannedGridLayoutManager that does exactly what you want. It allows you to span multiple rows and columns at the same time. The implementation is still WIP, but already works quite well.
SpannedGridLayoutManager.java
package io.plaidapp.ui.recyclerview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.PointF;
import android.graphics.Rect;
import android.support.annotation.Keep;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import io.plaidapp.R;

/**
 * A {@link RecyclerView.LayoutManager} which displays a regular grid (i.e. all cells are the same
 * size) and allows simultaneous row & column spanning.
 */
public class SpannedGridLayoutManager extends RecyclerView.LayoutManager {

    private GridSpanLookup spanLookup;
    private int columns = 1;
    private float cellAspectRatio = 1f;

    private int cellHeight;
    private int[] cellBorders;
    private int firstVisiblePosition;
    private int lastVisiblePosition;
    private int firstVisibleRow;
    private int lastVisibleRow;
    private boolean forceClearOffsets;
    private SparseArray<GridCell> cells;
    private List<Integer> firstChildPositionForRow; // key == row, val == first child position
    private int totalRows;
    private final Rect itemDecorationInsets = new Rect();

    public SpannedGridLayoutManager(GridSpanLookup spanLookup, int columns, float cellAspectRatio) {
        this.spanLookup = spanLookup;
        this.columns = columns;
        this.cellAspectRatio = cellAspectRatio;
        setAutoMeasureEnabled(true);
    }

    @Keep /* XML constructor, see RecyclerView#createLayoutManager */
    public SpannedGridLayoutManager(
            Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        TypedArray a = context.obtainStyledAttributes(
                attrs, R.styleable.SpannedGridLayoutManager, defStyleAttr, defStyleRes);
        columns = a.getInt(R.styleable.SpannedGridLayoutManager_spanCount, 1);
        parseAspectRatio(a.getString(R.styleable.SpannedGridLayoutManager_aspectRatio));
        // TODO use this!
        int orientation = a.getInt(
                R.styleable.SpannedGridLayoutManager_android_orientation, RecyclerView.VERTICAL);
        a.recycle();
        setAutoMeasureEnabled(true);
    }

    public interface GridSpanLookup {
        SpanInfo getSpanInfo(int position);
    }

    public void setSpanLookup(@NonNull GridSpanLookup spanLookup) {
        this.spanLookup = spanLookup;
    }

    public static class SpanInfo {
        public int columnSpan;
        public int rowSpan;

        public SpanInfo(int columnSpan, int rowSpan) {
            this.columnSpan = columnSpan;
            this.rowSpan = rowSpan;
        }

        public static final SpanInfo SINGLE_CELL = new SpanInfo(1, 1);
    }

    public static class LayoutParams extends RecyclerView.LayoutParams {

        int columnSpan;
        int rowSpan;

        public LayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
        }

        public LayoutParams(int width, int height) {
            super(width, height);
        }

        public LayoutParams(ViewGroup.MarginLayoutParams source) {
            super(source);
        }

        public LayoutParams(ViewGroup.LayoutParams source) {
            super(source);
        }

        public LayoutParams(RecyclerView.LayoutParams source) {
            super(source);
        }
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        calculateWindowSize();
        calculateCellPositions(recycler, state);

        if (state.getItemCount() == 0) {
            detachAndScrapAttachedViews(recycler);
            firstVisibleRow = 0;
            resetVisibleItemTracking();
            return;
        }

        // TODO use orientationHelper
        int startTop = getPaddingTop();
        int scrollOffset = 0;
        if (forceClearOffsets) { // see #scrollToPosition
            startTop = -(firstVisibleRow * cellHeight);
            forceClearOffsets = false;
        } else if (getChildCount() != 0) {
            scrollOffset = getDecoratedTop(getChildAt(0));
            startTop = scrollOffset - (firstVisibleRow * cellHeight);
            resetVisibleItemTracking();
        }

        detachAndScrapAttachedViews(recycler);
        int row = firstVisibleRow;
        int availableSpace = getHeight() - scrollOffset;
        int lastItemPosition = state.getItemCount() - 1;
        while (availableSpace > 0 && lastVisiblePosition < lastItemPosition) {
            availableSpace -= layoutRow(row, startTop, recycler, state);
            row = getNextSpannedRow(row);
        }

        layoutDisappearingViews(recycler, state, startTop);
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public RecyclerView.LayoutParams generateLayoutParams(Context c, AttributeSet attrs) {
        return new LayoutParams(c, attrs);
    }

    @Override
    public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
        if (lp instanceof ViewGroup.MarginLayoutParams) {
            return new LayoutParams((ViewGroup.MarginLayoutParams) lp);
        } else {
            return new LayoutParams(lp);
        }
    }

    @Override
    public boolean checkLayoutParams(RecyclerView.LayoutParams lp) {
        return lp instanceof LayoutParams;
    }

    @Override
    public void onAdapterChanged(RecyclerView.Adapter oldAdapter, RecyclerView.Adapter newAdapter) {
        removeAllViews();
        reset();
    }

    @Override
    public boolean supportsPredictiveItemAnimations() {
        return true;
    }

    @Override
    public boolean canScrollVertically() {
        return true;
    }

    @Override
    public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state){
        if (getChildCount() == 0 || dy == 0) return 0;

        int scrolled;
        int top = getDecoratedTop(getChildAt(0));

        if (dy < 0) { // scrolling content down
            if (firstVisibleRow == 0) { // at top of content
                int scrollRange = -(getPaddingTop() - top);
                scrolled = Math.max(dy, scrollRange);
            } else {
                scrolled = dy;
            }
            if (top - scrolled >= 0) { // new top row came on screen
                int newRow = firstVisibleRow - 1;
                if (newRow >= 0) {
                    int startOffset = top - (firstVisibleRow * cellHeight);
                    layoutRow(newRow, startOffset, recycler, state);
                }
            }
            int firstPositionOfLastRow = getFirstPositionInSpannedRow(lastVisibleRow);
            int lastRowTop = getDecoratedTop(
                    getChildAt(firstPositionOfLastRow - firstVisiblePosition));
            if (lastRowTop - scrolled > getHeight()) { // last spanned row scrolled out
                recycleRow(lastVisibleRow, recycler, state);
            }
        } else { // scrolling content up
            int bottom = getDecoratedBottom(getChildAt(getChildCount() - 1));
            if (lastVisiblePosition == getItemCount() - 1) { // is at end of content
                int scrollRange = Math.max(bottom - getHeight() + getPaddingBottom(), 0);
                scrolled = Math.min(dy, scrollRange);
            } else {
                scrolled = dy;
            }
            if ((bottom - scrolled) < getHeight()) { // new row scrolled in
                int nextRow = lastVisibleRow + 1;
                if (nextRow < getSpannedRowCount()) {
                    int startOffset = top - (firstVisibleRow * cellHeight);
                    layoutRow(nextRow, startOffset, recycler, state);
                }
            }
            int lastPositionInRow = getLastPositionInSpannedRow(firstVisibleRow, state);
            int bottomOfFirstRow =
                    getDecoratedBottom(getChildAt(lastPositionInRow - firstVisiblePosition));
            if (bottomOfFirstRow - scrolled < 0) { // first spanned row scrolled out
                recycleRow(firstVisibleRow, recycler, state);
            }
        }
        offsetChildrenVertical(-scrolled);
        return scrolled;
    }

    @Override
    public void scrollToPosition(int position) {
        if (position >= getItemCount()) position = getItemCount() - 1;

        firstVisibleRow = getRowIndex(position);
        resetVisibleItemTracking();
        forceClearOffsets = true;
        removeAllViews();
        requestLayout();
    }

    @Override
    public void smoothScrollToPosition(
            RecyclerView recyclerView, RecyclerView.State state, int position) {
        if (position >= getItemCount()) position = getItemCount() - 1;

        LinearSmoothScroller scroller = new LinearSmoothScroller(recyclerView.getContext()) {
            @Override
            public PointF computeScrollVectorForPosition(int targetPosition) {
                final int rowOffset = getRowIndex(targetPosition) - firstVisibleRow;
                return new PointF(0, rowOffset * cellHeight);
            }
        };
        scroller.setTargetPosition(position);
        startSmoothScroll(scroller);
    }

    @Override
    public int computeVerticalScrollRange(RecyclerView.State state) {
        // TODO update this to incrementally calculate
        if (firstChildPositionForRow == null) return 0;
        return getSpannedRowCount() * cellHeight + getPaddingTop() + getPaddingBottom();
    }

    @Override
    public int computeVerticalScrollExtent(RecyclerView.State state) {
        return getHeight();
    }

    @Override
    public int computeVerticalScrollOffset(RecyclerView.State state) {
        if (getChildCount() == 0) return 0;
        return getPaddingTop() + (firstVisibleRow * cellHeight) - getDecoratedTop(getChildAt(0));
    }

    @Override
    public View findViewByPosition(int position) {
        if (position < firstVisiblePosition || position > lastVisiblePosition) return null;
        return getChildAt(position - firstVisiblePosition);
    }

    public int getFirstVisibleItemPosition() {
        return firstVisiblePosition;
    }

    private static class GridCell {
        final int row;
        final int rowSpan;
        final int column;
        final int columnSpan;

        GridCell(int row, int rowSpan, int column, int columnSpan) {
            this.row = row;
            this.rowSpan = rowSpan;
            this.column = column;
            this.columnSpan = columnSpan;
        }
    }

    /**
     * This is the main layout algorithm, iterates over all items and places them into [column, row]
     * cell positions. Stores this layout info for use later on. Also records the adapter position
     * that each row starts at.
     *

     * Note that if a row is spanned, then the row start position is recorded as the first cell of
     * the row that the spanned cell starts in. This is to ensure that we have sufficient contiguous
     * views to layout/draw a spanned row.
     */
    private void calculateCellPositions(RecyclerView.Recycler recycler, RecyclerView.State state) {
        final int itemCount = state.getItemCount();
        cells = new SparseArray<>(itemCount);
        firstChildPositionForRow = new ArrayList<>();
        int row = 0;
        int column = 0;
        recordSpannedRowStartPosition(row, column);
        int[] rowHWM = new int[columns]; // row high water mark (per column)
        for (int position = 0; position < itemCount; position++) {

            SpanInfo spanInfo;
            int adapterPosition = recycler.convertPreLayoutPositionToPostLayout(position);
            if (adapterPosition !=  RecyclerView.NO_POSITION) {
                spanInfo = spanLookup.getSpanInfo(adapterPosition);
            } else {
                // item removed from adapter, retrieve its previous span info
                // as we can't get from the lookup (adapter)
                spanInfo = getSpanInfoFromAttachedView(position);
            }

            if (spanInfo.columnSpan > columns) {
                spanInfo.columnSpan = columns; // or should we throw?
            }

            // check horizontal space at current position else start a new row
            // note that this may leave gaps in the grid; we don't backtrack to try and fit
            // subsequent cells into gaps. We place the responsibility on the adapter to provide
            // continuous data i.e. that would not span column boundaries to avoid gaps.
            if (column + spanInfo.columnSpan > columns) {
                row++;
                recordSpannedRowStartPosition(row, position);
                column = 0;
            }

            // check if this cell is already filled (by previous spanning cell)
            while (rowHWM[column] > row) {
                column++;
                if (column + spanInfo.columnSpan > columns) {
                    row++;
                    recordSpannedRowStartPosition(row, position);
                    column = 0;
                }
            }

            // by this point, cell should fit at [column, row]
            cells.put(position, new GridCell(row, spanInfo.rowSpan, column, spanInfo.columnSpan));

            // update the high water mark book-keeping
            for (int columnsSpanned = 0; columnsSpanned < spanInfo.columnSpan; columnsSpanned++) {
                rowHWM[column + columnsSpanned] = row + spanInfo.rowSpan;
            }

            // if we're spanning rows then record the 'first child position' as the first item
            // *in the row the spanned item starts*. i.e. the position might not actually sit
            // within the row but it is the earliest position we need to render in order to fill
            // the requested row.
            if (spanInfo.rowSpan > 1) {
                int rowStartPosition = getFirstPositionInSpannedRow(row);
                for (int rowsSpanned = 1; rowsSpanned < spanInfo.rowSpan; rowsSpanned++) {
                    int spannedRow = row + rowsSpanned;
                    recordSpannedRowStartPosition(spannedRow, rowStartPosition);
                }
            }

            // increment the current position
            column += spanInfo.columnSpan;
        }
        totalRows = rowHWM[0];
        for (int i = 1; i < rowHWM.length; i++) {
            if (rowHWM[i] > totalRows) {
                totalRows = rowHWM[i];
            }
        }
    }

    private SpanInfo getSpanInfoFromAttachedView(int position) {
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            if (position == getPosition(child)) {
                LayoutParams lp = (LayoutParams) child.getLayoutParams();
                return new SpanInfo(lp.columnSpan, lp.rowSpan);
            }
        }
        // errrrr?
        return SpanInfo.SINGLE_CELL;
    }

    private void recordSpannedRowStartPosition(final int rowIndex, final int position) {
        if (getSpannedRowCount() < (rowIndex + 1)) {
            firstChildPositionForRow.add(position);
        }
    }

    private int getRowIndex(final int position) {
        return position < cells.size() ? cells.get(position).row : -1;
    }

    private int getSpannedRowCount() {
        return firstChildPositionForRow.size();
    }

    private int getNextSpannedRow(int rowIndex) {
        int firstPositionInRow = getFirstPositionInSpannedRow(rowIndex);
        int nextRow = rowIndex + 1;
        while (nextRow < getSpannedRowCount()
                && getFirstPositionInSpannedRow(nextRow) == firstPositionInRow) {
            nextRow++;
        }
        return nextRow;
    }

    private int getFirstPositionInSpannedRow(int rowIndex) {
        return firstChildPositionForRow.get(rowIndex);
    }

    private int getLastPositionInSpannedRow(final int rowIndex, RecyclerView.State state) {
        int nextRow = getNextSpannedRow(rowIndex);
        return (nextRow != getSpannedRowCount()) ? // check if reached boundary
                getFirstPositionInSpannedRow(nextRow) - 1
                : state.getItemCount() - 1;
    }

    /**
     * Lay out a given 'row'. We might actually add more that one row if the requested row contains
     * a row-spanning cell. Returns the pixel height of the rows laid out.
     *

     * To simplify logic & book-keeping, views are attached in adapter order, that is child 0 will
     * always be the earliest position displayed etc.
     */
    private int layoutRow(
            int rowIndex, int startTop, RecyclerView.Recycler recycler, RecyclerView.State state) {
        int firstPositionInRow = getFirstPositionInSpannedRow(rowIndex);
        int lastPositionInRow = getLastPositionInSpannedRow(rowIndex, state);
        boolean containsRemovedItems = false;

        int insertPosition = (rowIndex < firstVisibleRow) ? 0 : getChildCount();
        for (int position = firstPositionInRow;
             position <= lastPositionInRow;
             position++, insertPosition++) {

            View view = recycler.getViewForPosition(position);
            LayoutParams lp = (LayoutParams) view.getLayoutParams();
            containsRemovedItems |= lp.isItemRemoved();
            GridCell cell = cells.get(position);
            addView(view, insertPosition);

            // TODO use orientation helper
            int wSpec = getChildMeasureSpec(
                    cellBorders[cell.column + cell.columnSpan] - cellBorders[cell.column],
                    View.MeasureSpec.EXACTLY, 0, lp.width, false);
            int hSpec = getChildMeasureSpec(cell.rowSpan * cellHeight,
                    View.MeasureSpec.EXACTLY, 0, lp.height, true);
            measureChildWithDecorationsAndMargin(view, wSpec, hSpec);

            int left = cellBorders[cell.column] + lp.leftMargin;
            int top = startTop + (cell.row * cellHeight) + lp.topMargin;
            int right = left + getDecoratedMeasuredWidth(view);
            int bottom = top + getDecoratedMeasuredHeight(view);
            layoutDecorated(view, left, top, right, bottom);
            lp.columnSpan = cell.columnSpan;
            lp.rowSpan = cell.rowSpan;
        }

        if (firstPositionInRow < firstVisiblePosition) {
            firstVisiblePosition = firstPositionInRow;
            firstVisibleRow = getRowIndex(firstVisiblePosition);
        }
        if (lastPositionInRow > lastVisiblePosition) {
            lastVisiblePosition = lastPositionInRow;
            lastVisibleRow = getRowIndex(lastVisiblePosition);
        }
        if (containsRemovedItems) return 0; // don't consume space for rows with disappearing items

        GridCell first = cells.get(firstPositionInRow);
        GridCell last = cells.get(lastPositionInRow);
        return (last.row + last.rowSpan - first.row) * cellHeight;
    }

    /**
     * Remove and recycle all items in this 'row'. If the row includes a row-spanning cell then all
     * cells in the spanned rows will be removed.
     */
    private void recycleRow(
            int rowIndex, RecyclerView.Recycler recycler, RecyclerView.State state) {
        int firstPositionInRow = getFirstPositionInSpannedRow(rowIndex);
        int lastPositionInRow = getLastPositionInSpannedRow(rowIndex, state);
        int toRemove = lastPositionInRow;
        while (toRemove >= firstPositionInRow) {
            int index = toRemove - firstVisiblePosition;
            removeAndRecycleViewAt(index, recycler);
            toRemove--;
        }
        if (rowIndex == firstVisibleRow) {
            firstVisiblePosition = lastPositionInRow + 1;
            firstVisibleRow = getRowIndex(firstVisiblePosition);
        }
        if (rowIndex == lastVisibleRow) {
            lastVisiblePosition = firstPositionInRow - 1;
            lastVisibleRow = getRowIndex(lastVisiblePosition);
        }
    }

    private void layoutDisappearingViews(
            RecyclerView.Recycler recycler, RecyclerView.State state, int startTop) {
        // TODO
    }

    private void calculateWindowSize() {
        // TODO use OrientationHelper#getTotalSpace
        int cellWidth =
                (int) Math.floor((getWidth() - getPaddingLeft() - getPaddingRight()) / columns);
        cellHeight = (int) Math.floor(cellWidth * (1f / cellAspectRatio));
        calculateCellBorders();
    }

    private void reset() {
        cells = null;
        firstChildPositionForRow = null;
        firstVisiblePosition = 0;
        firstVisibleRow = 0;
        lastVisiblePosition = 0;
        lastVisibleRow = 0;
        cellHeight = 0;
        forceClearOffsets = false;
    }

    private void resetVisibleItemTracking() {
        // maintain the firstVisibleRow but reset other state vars
        // TODO make orientation agnostic
        int minimumVisibleRow = getMinimumFirstVisibleRow();
        if (firstVisibleRow > minimumVisibleRow) firstVisibleRow = minimumVisibleRow;
        firstVisiblePosition = getFirstPositionInSpannedRow(firstVisibleRow);
        lastVisibleRow = firstVisibleRow;
        lastVisiblePosition = firstVisiblePosition;
    }

    private int getMinimumFirstVisibleRow() {
        int maxDisplayedRows = (int) Math.ceil((float) getHeight() / cellHeight) + 1;
        if (totalRows < maxDisplayedRows) return 0;
        int minFirstRow = totalRows - maxDisplayedRows;
        // adjust to spanned rows
        return getRowIndex(getFirstPositionInSpannedRow(minFirstRow));
    }

    /* Adapted from GridLayoutManager */

    private void calculateCellBorders() {
        cellBorders = new int[columns + 1];
        int totalSpace = getWidth() - getPaddingLeft() - getPaddingRight();
        int consumedPixels = getPaddingLeft();
        cellBorders[0] = consumedPixels;
        int sizePerSpan = totalSpace / columns;
        int sizePerSpanRemainder = totalSpace % columns;
        int additionalSize = 0;
        for (int i = 1; i <= columns; i++) {
            int itemSize = sizePerSpan;
            additionalSize += sizePerSpanRemainder;
            if (additionalSize > 0 && (columns - additionalSize) < sizePerSpanRemainder) {
                itemSize += 1;
                additionalSize -= columns;
            }
            consumedPixels += itemSize;
            cellBorders[i] = consumedPixels;
        }
    }

    private void measureChildWithDecorationsAndMargin(View child, int widthSpec, int heightSpec) {
        calculateItemDecorationsForChild(child, itemDecorationInsets);
        RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) child.getLayoutParams();
        widthSpec = updateSpecWithExtra(widthSpec, lp.leftMargin + itemDecorationInsets.left,
                lp.rightMargin + itemDecorationInsets.right);
        heightSpec = updateSpecWithExtra(heightSpec, lp.topMargin + itemDecorationInsets.top,
                lp.bottomMargin + itemDecorationInsets.bottom);
        child.measure(widthSpec, heightSpec);
    }

    private int updateSpecWithExtra(int spec, int startInset, int endInset) {
        if (startInset == 0 && endInset == 0) {
            return spec;
        }
        int mode = View.MeasureSpec.getMode(spec);
        if (mode == View.MeasureSpec.AT_MOST || mode == View.MeasureSpec.EXACTLY) {
            return View.MeasureSpec.makeMeasureSpec(
                    View.MeasureSpec.getSize(spec) - startInset - endInset, mode);
        }
        return spec;
    }

    /* Adapted from ConstraintLayout */

    private void parseAspectRatio(String aspect) {
        if (aspect != null) {
            int colonIndex = aspect.indexOf(':');
            if (colonIndex >= 0 && colonIndex < aspect.length() - 1) {
                String nominator = aspect.substring(0, colonIndex);
                String denominator = aspect.substring(colonIndex + 1);
                if (nominator.length() > 0 && denominator.length() > 0) {
                    try {
                        float nominatorValue = Float.parseFloat(nominator);
                        float denominatorValue = Float.parseFloat(denominator);
                        if (nominatorValue > 0 && denominatorValue > 0) {
                            cellAspectRatio = Math.abs(nominatorValue / denominatorValue);
                            return;
                        }
                    } catch (NumberFormatException e) {
                        // Ignore
                    }
                }
            }
        }
        throw new IllegalArgumentException("Could not parse aspect ratio: '" + aspect + "'");
    }

}

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

    <declare-styleable name="SpannedGridLayoutManager">
        <attr name="android:orientation" />
        <attr name="spanCount" />
        <attr name="aspectRatio" format="string" />
    </declare-styleable>

</resources>

The code is also available here.
Example usage
The code requires RecyclerView 23.2.0 or higher.
So add the following line to your build.gradle, if you didn't already do so.
dependencies {
    compile 'com.android.support:recyclerview-v7:24.2.1'
}

To achieve the layout shown in the initial post, we define the LayoutManager as follows
recyclerView.setLayoutManager(new SpannedGridLayoutManager(
        new SpannedGridLayoutManager.GridSpanLookup() {
            @Override
            public SpannedGridLayoutManager.SpanInfo getSpanInfo(int position) {
                if (position == 0) {
                    return new SpannedGridLayoutManager.SpanInfo(2, 2);
                } else {
                    return new SpannedGridLayoutManager.SpanInfo(1, 1);
                }
            }
        },
        3 /* Three columns */,
        1f /* We want our items to be 1:1 ratio */));

A: You can use SpannedGridLayoutManager library wrote by Arasthel in here
This is the result

A: You can achieve this behavior by using RecycleView for rows only, with ViewHolder for each row. So you will have RowViewHolder for simple rows and something like DoubleRowViewHolder for custom layout that will have 3 items, just the way you want.


text:
Q: Stop Tail when a certain string is found in log file Need to monitor a log file for a particular string "Server running at http". Once that string is found in the log file , I need to stop checking and want to continue to rest of the code.
currently I am currently using "tail -f my-file.log | grep -q "Server running at http" . But this doesn't seem to work.tail command is still running.
tail -f my-file.log | grep -q "Server running at http"

A: You can try something like :
tail -f my-file.log | awk '/Server running at http/ { print | bash file_with_code}'

P.S. instead of a different file it can be a function within the same script, needless to say that in such a case you will not need to say bash before function
Another possible solution can be:
tail -f my-file.log | egrep -m 1 "Server running at http";echo "found the pattern"

A: You have to specify, how many matches you need. As you need first hit
tail -f server.log | grep -m 1 "mystring"

once "mystring" found for the first hit, program will exit automatically.


text:
Q: Border bottom and the header move together In my nav, I am separating my section with some text and a horizontal line. For each section this repeats. I am doing this as shown below:
.navSectionHeader {
  font-size: 1em;
  color: #fff;
  margin-left: 5px;
  margin-bottom: 10px;
  font-family: "Roboto";
  font-weight: 700 !important;
  border-bottom: 2px solid #6c6c6c;
}

/*.navSectionHeader::after {
    content: ' ';
    display: block;
    border: 2px solid;
    border-color: #6c6c6c;
    margin-left: 0px !important;
}*/

The issue is, my text is now pretty much stuck to the left of the parent div. It should be with some margin to the left while keeping the bottom border start from 0px to the left. When I try to move it with margin-left: 5px; it ends up moving the border-bottom as well. I tried this with ::after as shown in the commented bit, adding !important to the end but nothing changes. Am I doing this the wrong way? Sorry, I'm a front-end noob!
Edit: The section header is in a  if it makes a difference.

A: Use padding instead of margin.
.navSectionHeader {
   padding-left: 5px;
}

An example to see difference,

div {
   display: inline-block;
   width: 100px;
   height: 20px;
   border-bottom: 1px solid black;
   background: red;
   color: white;
}

.padding {
   padding-left: 5px;
}

.margin {
   margin-left: 5px;
}

margin

padding


text:
Q: Updating a dynamic form from server php javascript but needs to stay on the same page in browser I have to create a form where mid way when the user is filling the input on filling one specific select input I need to send a request to the server where I tell the server which select value was selected and then the server will respond with a new page updating the form with additional input fields related to the selected option the user has chosen.
I am doing this and all is fine but when the server sends back the updated page the browser is stacking the pages. By stacking I mean that after receiving the updated form if the user presses back he will be taken to the old form that was there before the server call and the update.
I don't want this behavior I just want the browser in a way or another to have the same page but with the updated form
This is the javascript code that is triggered when a select is chosen
    function updateForm(value){
    let form=document.forms["form"];
    let input = document.createElement('input');
    input.setAttribute('name', "typeOfCall");
    input.setAttribute('value', 'updateForm');
    input.setAttribute('type', 'hidden');
    form.appendChild(input);
    form.submit();
}

then the server does a lot of stuff accessing the database then does the following to send back an updated page
    public function render_view($view,$params=[]){
    $layout = $this->get_layout();
    $view = $this->get_view($view,$params);
    return str_replace("{{content}}",$view,$layout);
}

The result of this function is then echoed
I am not using any framework because part of the asignment is not to use any framework

A: Without using any external libraries you can use JavaScript Fetch API to call the server and retrieve your information:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Fetch is asynchronous, so you can update your form using the response once it has been received. You can then parse and use this information to populate/edit the form.


text:
Q: Verificación de comentarios Necesito ayuda con este código. Tengo que hacer una verificación de comentarios para una pagina.
Mi idea es que cuando entre un comentario, se verifique si se repite, pero hay un problema, todo el tiempo dice que se repite el comentario.
Quiero pedirles ayuda en que error tengo, ya que yo ya no lo encuentro. Acá les dejo el código:
<?php
$error = false;

if(empty($_POST['comentario']))
{
    $error['comentario'] = "comentario requerido";
}

if(!($_POST['comentario']==$_POST['comentario2']))
{
    $error['comentario'] = "El comentario ya existe";
    $error['comentario2'] = "El comentario ya existe";
}

if(!isset($_GET['id'])){
    $sql_duplicado = "SELECT id
                        FROM comentarios
                        WHERE comentario = '".$_POST['comentario']."'";

    $res_duplicado = ejecutar_query($conex, $sql_duplicado);
    $com_encontrado = mysqli_num_rows($res_duplicado);

    if($com_encontrado!=0){
        $error['comentario'] = "comentario duplicado";
    }
}
?>

A: Es por que en este if:
if(!($_POST['comentario']==$_POST['comentario2']))
{
    $error['comentario'] = "El comentario ya existe";
    $error['comentario2'] = "El comentario ya existe";
}

tienes una negación antes de preguntar si comentario es igual a comentario2 y termina evaluando si son diferentes.
intenta así:
if($_POST['comentario'] == $_POST['comentario2'])
{
    $error['comentario'] = "El comentario ya existe";
    $error['comentario2'] = "El comentario ya existe";
}


text:
Q: Can't deploy app on GitHub using gh-pages I have deployed a few days ago React app on GitHub. Yesterday I made changes and something went wrong - I deleted gh-pages after pushing changes on master branch and when I type in terminal
npm run deploy

I have error like this

I have 2 questions:

*

*How to update website in github.io when I made changes?

*How can I deploy app again on GitHub pages?

Edit:
Here's solution:
https://github.com/facebook/create-react-app/issues/4854

A: If you want that GitHub use your master branch to display your website, you have to rename your repository to xxx.github.io. Or you can push your content to gh-pages branch so GitHub will generate the content under yourname.github.io/repo_name .
Make sure your content is OK. The problem you met seems related to your npm tool.

A: I have my react app running on gh-pages. Here are the changes I made in package.json to get it there:
STEP 1 - Install gh-pages in dev-dependencies:
npm i gh-pages --save-dev

STEP 2 - Add deploy script:
"deploy" : "npm run build&&gh-pages -d build",

STEP 3 - Add homepage key at top of package.json with name key etc.:
"homepage": "https://<username>.github.io/<git-repo-name>/",

STEP 4 - Run command to deploy:
npm run deploy

This should host the app on gh-pages on URL you specified in key homepage. Every time you make changes, just run the command specified in STEP 4 locally to publish changes.


text:
Q: matrix representation of polynomial Here is a polynomial $p(x,y) = (ax + by)^2$, it can be written like this $$p(x,y) = \left(\left[ \begin{array}{cc}
a & b \\
\end{array} \right] \left[ \begin{array}{c}
x\\
y\\
\end{array} \right]\right)^2$$
and I know that it can also be written as something like $v^TMv$, here $v = [x,y]^T$, and $$M = \left[ \begin{array}{cc}
a^2 & ab \\
ab & b^2\\
\end{array} \right]$$. But how could I find out $M$, any technique?
Furthermore, here $p(x,y)$ has degree $2$, and it can be represented with the multiplication of matrix and vector, what if the degree is $3,4...$?

A: Note that if $M=(m_{ij})$, then $$v^TMv=\sum_{i,j}m_{ij}v_iv_j$$ Then compare the coefficients of $v_iv_j\ \forall i,j$ of both sides of the equation to get $m_{ij}$.

A: $$\left[ \begin{array}{cc}
a & b \\
\end{array} \right] \left[ \begin{array}{c}
x\\
y
\end{array} \right] = \left[ \begin{array}{cc}
x & y \\
\end{array} \right] \left[ \begin{array}{c}
a\\
b
\end{array} \right]$$
Then $M= \left[ \begin{array}{c}
a & b
\end{array}\right]  \left[ \begin{array}{c}
a\\
b
\end{array}\right]$
Letting $v=\left[ \begin{array}{c}
x\\
y
\end{array} \right]$ and $A=\left[ \begin{array}{cc}
a & b \\
\end{array} \right]$ we use the first line to note that $Av=v^TA^T$., and hence that $$(Av)^2 = (Av)^T(Av) = v^TA^TAv = v^T(A^TA)v$$
So $M=A^TA$.


text:
Q: SwiftUI: Offset Popover Anchor by Constant Amount
NOTE: This is a macOS question, not iOS.

I would like to anchor a SwiftUI Popover exactly 70 points to the right of the bottom-leading corner of the "20 Hours Ago" button in this image:

I do NOT want to anchor the popover a certain percentage of the button's width (which would be using UnitPoint). The button's text is updated as the user selects different items in the popover and as the button's width changes, the percentage-based anchor point moves, causing the popover to jump around horizontally. No good. I also don't want to anchor the popover exactly at the bottom-leading corner, as that looks dumb.
The trouble is, I can't figure out what to feed SwiftUI to get a constant, simple horizontal offset for the anchor point of the popover. I'm here:
.popover(isPresented: $isShowingPopover, attachmentAnchor: .point(.bottomLeading), arrowEdge: .bottom, content: {
    ...
})

How do I specify: "start at the bottom-leading point and then go 70 points to the right"? (Based on the strings that will appear in the button, I KNOW 70 is a good-looking anchor point for all cases.)

A: You can use .rect:
That defines absolute offsets to the parent content rect, but then you'll have to specify y offset as well.
.popover(isPresented: $show1,
         attachmentAnchor: .rect(.rect(CGRect(x: 70, y: 15, width: 0, height: 0))),
         arrowEdge: .bottom)
{
     Text("Popover")
         .frame(width: 200, height: 100)
}


text:
Q: Why do people use linq to sql? Given the premise:

*

*There are competent sql programmers
(correlary - writing sql queries are not an issue)

*There are competent application developers
(correlary - there is simple/strong/flexible architecture for handling connections and simple queries from code)

Why do people use linq to sql?

*

*There is overhead added to each transaction

*There is strong likelihood of performance loss for moderate-complex calculations (DBs are made for processing sets and calculations and had teams of engineers working out optimization - why mess with this?)

*There is loss of flexibility (if you want to add another ui (non .NET app) or access method, you either have to put the queries back in the db or make a separate data access layer)

*There is loss of security by not having a centralized control of write/update/read on db (for example, a record has changed - if you allow applications to use linq to sql to update, then you cannot prove which application changed it or what instance of an application changed it)

I keep seeing questions about linq to sql and am wondering if I'm missing something.

A: Existing question/answers in the same vein/spirit:

*

*Doesn't Linq to SQL miss the point? Aren't ORM-mappers (SubSonic, etc.) sub-optimal solutions?

*LINQ-to-SQL vs stored procedures?

*What's wrong with Linq to SQL?

*Why do I need Stored Procedures when I have LINQ to SQL

*If using LINQ to SQL is there any good reason to learn SQL queries/syntax anymore?

*https://stackoverflow.com/questions/216569/are-the-days-of-the-stored-procedure-numbered
I personally believe there's no right or wrong answer. It depends on what you're developing and how you're developing it. If you need razor-sharp performance, have an overly-complex data model, etc... skip the abstraction. If you feel the abstraction speeds up your development time, like the idea of capturing all application logic in a single codebase, etc... use it.

A: For me, it takes a lot less time to write linq to sql code than it does to write a bunch of stored procedures. That's especially true when the design isn't finished, in that case I don't yet know how much of the work I want to do on C# objects, and how much I want to do in SQL.
So, I can skip building datasets, I don't have to click click click to add queries, basically, linq to sql means I can change my code in less time.
Also, as a big fan of Haskell, I can write lots of functional-style code with linq to sql and it just works.

A:
I keep seeing questions about linq to sql and am wondering if I'm missing something.

It's not that you're missing something.  It's that you have something most shops don't have:

There are competent sql programmers

Additionally, in your shop those competent sql programmers prefer to write sql.

Here's a point by point response:

There is overhead added to each transaction

Generally true.  This can be avoided by translating the queries before they are needed to run using CompiledQuery for many (but not all!) scenarios.

There is strong likelihood of performance loss for moderate-complex calculations (DBs are made for processing sets and calculations and had teams of engineers working out optimization - why mess with this?)

Either you're writing linq, which is translated to sql, and then a plan is generated from the optimizer - or your writing sql from which a plan is generated by the optimizer.  In both cases you are telling the machine what you want and it is supposed to figure out how to do it.  Are you suggesting that subverting the optimizer by using query hints is a good practice?  Many competent sql programmers will disagree with that suggestion.

There is loss of flexibility (if you want to add another ui (non .NET app) or access method, you either have to put the queries back in the db or make a separate data access layer)

A lot of people using linq are already SOA.  The linq lives in a service.  The non .NET app calls the service.  Bada-bing bada-boom.

There is loss of security by not having a centralized control of write/update/read on db (for example, a record has changed - if you allow applications to use linq to sql to update, then you cannot prove which application changed it or what instance of an application changed it)

This is simply not true.  You prove which application is connected and issuing sql commands the same way you prove which application is connected and calling a sproc.

A: I'm not saying this is an ideal solution or even a great example (it was the result of a high level constraint on the architecture, not something we necessarily would have chosen from scratch), but...
I worked on an app where the code was completely isolated from the database except through a set of exposed stored procs. The code could not "know" anything about the database schema except was was returned from the stored procs.
While this isn't that unusual and it isn't too hard to write a DAL using ADO or whatever, I decided to try out Linq to Sql, even though it wouldn't be using it for its real intended purpose and wouldn't use most of the features. Turns out it was a great decision.
I created the Linq to Sql class, dragged the stored procs from server explorer onto the right side of the designer, then... Wait, there is no then. I was pretty much done.
Linq created strongly typed methods for each stored proc. For the procs that returned rows of data, Linq automatically created a class for the items in each row and returned a List<generatedClass> for them. I wrapped the calls themselves in a lightweight public DAL class that did some verification and some automatic parameter setting and I was done. I wrote a business object class and mapped the dynamically generated Linq class objects to the business object (did this by hand, but it isn't hard to do or maintain).
The program is now immune to any schema change that doesn't affect the stored procedure signatures. If the signatures do change, we just drag off the old proc from the design and drag it back to regenerate the code. A few passes through the unit tests to make changes (which usually don't go higher than the public DAL interface) and it's done. Things upstream of the DAL use Linq to Objects techniques to select, filter, and sort data that isn't in the right format straight from the stored proc calls.
We have some excellent DBAs writing the stored procedures and an entirely different group writing the other code, so maybe it is a good example of why (and how) you can use LINQ in the scenario you describe.

A: Let me list you a few points:

*

*There are small software companies or mid-sized companies who develop their software in-house who might rather focus on getting many application developers than getting a freelancer DB developer or even permanently hire one.

*In most cases the overhead is a non-issue either due to the amount of data to be processed or due to the low traffic. Besides, when used properly, LINQ to SQL can perform as fast as most SQL queries + the associated .net code.

*Many companies just stick with the Microsoft stack and they can only enjoy the integration. Some other company develops using SOA there's just no problem. The others aren't forced to choose LINQ-to-SQL and if they make that choice is their problem how to integrate it. Nobody ever said LINQ-to-SQL is a silver bullet :)

*I believe security is gained with LINQ-to-SQL because I've bumped across lots of SQL queries taking in unescaped data with string concatenation etc and explaining the whole parametrized query idea has never been easy. Besides since all queries are eventually translated into SQL, unless the tracking issue you describe would happen via a stored procedure, there're again no problems at all.

I also believe your question can be posed more generally to address all ORMs and not just LINQ-to-SQL, and still most of what I said would hold true.

A: Some handy features are the debugger picking up sytax errors in your query, compared to writing SQL statements as strings. Mistakes that wont get picked up until runtime.
Plus I find LINQ statements easier to read than SQL.

A: The problem is that it is very rare for somewhere to have a competent SQL developer who likes writing SQL and wouldn't rather be doing something else. I would consider myself competent in SQL, I used to do all my data access layers with stored procs or parametrized queries. Trouble is that it takes ages and is dull. I'd rather be writing great applications than messing around with data access layers that essentially have a select, insert, update and delete SQL statement(or proc) repeated dozens of times for each data object.
Linq-to-SQL takes away some of the repetitive nature. It has a tool to auto generate you business objects from your database schema, and it gives you a nice integrated query language that is compile time type verified and is in your code (Stored procs are a pain to source control neatly)
I can write a DAL in Linq-to-sql several times faster than I can using plain SQL, stored procs or parametrized queries.
If you want to maintain the use of stored procs both linq-to-sql and the EF both support the use of stored procs for all their data access, you just have to set up the appropriate mappings. So, you can still use your stored procs to log details and implement security if you want. We tend to opt for using windows auth, and use that to restrict access to each table for the various users, then we have a bunch of triggers on the tables that track details for audit purposes.
Two things I will quickly note is that firstly, the entity framework seems to be getting more support from MS at the moment, and I suspect that will be considered the kind of default standard for the future in preference to linq-to-sql. Secondly, in .Net 3.5 the EF and linq-to-sql do not have very good support for n-tier disconnected apps. In both of them you kind of have to muck around with either serializing data contexts across your disconnected tiers, or manually detach and re-attach your data objects. This is much improved in the .net 4.0 though. Just something to consider depending on which version you have available to you.

A: It may be a case of convenience triumphing over performance. If you're programming at Facebook levels of uber-performance then you might think about every clock cycle but the simple truth is that the majority of applications don't need this attention and benefit from efficiencies in code maintenance and dev time (100k contractor vs. another $erver).
That said, there's a case for outsourcing as much of the query processing from the DB box in very high scale systems, else the DB is the bottle neck and you need to shard or re-architect down the line. Costly.
I think its fair to say that LINQ will scale better/easier both in terms of servers and from many core in that your LINQ codebase will get m-core for 'free' as soon as MS release C# 4.0.
I do see your point in asking and as a non-ASP.NET dev just beginning a www project for the first time, I can't see the point of 80% of ASP.NET (themes, controls etc.) - it seems I need to learn more and code more than the HTML itself! -- again, I'm sure there's an good reason for it all.
--- I haven't got the 50 pts to comment on the post I want to so I'm doing it here ---
David B suggests that writing some SQL is all there is to getting the most out of SQL Server and that using query hints is the steering mechanism. The same task can be achieved in many different ways in SQL and many with 1000s of times the performance gain. I suggest reading Inside T-SQL Querying (Itzik Ben Gan). Over and over, Itzik shows how to rethink the query and use new commands to shrink the logical reads sometimes from thousands into less than ten.

A: For very simple queries, the overhead of an extra layer adds to the roundtrip cost. For somewhat more complex queries in normal 'business app' scenarios, the optimizations done by the Linq-to-SQL expression->sql translation magic can often save a lot.
As an example, I recently did a 1:1 translation of a customer-supplied 1400+ (!) line stored proc to L2S. Not only did it go from 1400 lines of SQL to 500 lines of much more readable, strongly typed, and commented code. It also started hitting the database with an average of ~1500 reads instead of ~30k reads. This is before I even started looking at db-side optimizations - that saving is something I can 100% attribute to L2S's ability to eliminate predicates that can be evaluated client-side.

A: please repeat after me (min 3x)

*

*there is no silver bullet

*I will not use a technology just because its the latest thing from msft

*I will not use something just to get it on my resume

Not only are their competent SQL coders, any decent app programmer, especially LOB apps, should write intermediate SQL.  If you don't know any SQL and are writing LINQ to SQL, how are you going to debug your data calls?  How are you going to profile them to fix bottlenecks?
We're trying out LINQ to SQL and I think there are major issues with it, such as:

*

*There is no simple way to return the query results to another object.  This in itself seems insane.  Microsoft created the var anonymous datatype, and recommends using it, but there is no way to move this data out of your local method, hence the oo paradigm breaks if you have to use the data in the same function that retrieved it.

*Tables are NOT objects.  Study up on 3rd normal form etc.  Relational databases are for storing data, not using it.  I don't want to be restricted or encouraged to use my tables as objects.  The data I retrieve from the database will very often be joins of multiple tables, and may include SQL casts, functions, operators, etc.

*There is no performance gain, and a slight loss

*Now I have way more code to worry about.  There are the dbml files and still a DAL to actually write the LINQ.  Yes, lots of it is machine-generated, that doesn't mean its not there, its something else that can go wrong (i.e. your dbml files, etc.).
Now that I've given the background, I will attempt to answer you actual question, why do people use LINQ To SQL:

*

*Its the latest thing from Microsoft and I want it on my resume.

*Msft has convinced managers/execs that it will decrease coding time

*Developers hate SQL.  (no good dev environment or debugging except manually--it would be nice to have better intellisense to a sql tool.)

I encourage people not to jump on the bandwagon just because everyone else is, learn enough to put it on your resume, be willing to use it if forced to, but try and really understand the pros and cons first.

A: simple answer, there are two approaches: create exquisite Rube Goldberg contraptions, or just get the job done in a simple way.  Many devs lean towards the former.
Developers get bored easily, and would often personally enjoy doing things a harder way that seems to provide a certain intellectual beauty.  Are you developing an app or writing a PhD?  As my msft director used to yell in the hallways, "I don't want another research project!"


text:
Q: VS2017 Setup project for .NET 4.7.2 Having configured a Setup project for my .NET 4.7.2 codebase the Detected Dependencies shows up with a netstandard.dll.
Is there anyway to tell where this might be coming from?
Again it's just an entire 4.7.2 based code with that target Framework chosen.
The Prerequisites Page has the 4.7.2 chosen and the Launch condition has 4.7.2.
What could be causing the netstandard.dll to be included in the project output?

A:
What could be causing the netstandard.dll to be included in the
  project output?

First, thanks to magicandre1981 for all his help.
You have referenced a net standard nuget packages in your Net Framework 4.7.2 project. And because of the special nature of the package, it needs to refer to netstandard.dll as a runtime environment.
Although Net Frameowork 4.7.2 optimizes the build output file, so netstandard.dll cannot be shown in the project outputpath, but in fact the project will still use it at runtime.
But for the setup project, there is no such feature. Using the netstandard nuget package, all references will be displayed in Detected Dependencies including netstandard.dll.
In addition, Net Standard 2.0 is compatible with Net Frameowork 4.7.2, and you can refer to this document.