问:
Imputing into a custom function for a shiny app. R
Hello i am trying to make an app in shiny that will take 3 vectors from a data frame and two entered inputs. I would like the five entries to pass threw the function I have maid below and give the output that the function is maid to give. This would be 4 plots set in a grid (two heat maps, one point plot and a simivariogram). I feel that I have the bulk of the app together but I am having trouble getting my five inputs from the ui to pass threw my function and give out the plots. The function works great in R without shiny i just want it to work as an app now. Also I am pretty new to shiny so i might be missing something simple.

UI:

```<code>    library(shiny)
    library(shinydashboard)
    library(ggplot2)
    library(leaflet)
    library(data.table)
    library(dplyr)

   ################

# App interface
ui <- fluidPage(
# App csv input
  headerPanel("Kriging"),
  sidebarPanel(
    fileInput('file1', 'Choose CSV File',
              accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
    tags$hr(),
    checkboxInput('header', 'Header', TRUE),
# App button selection for var, lat, lon
    fluidRow(
      column(6,radioButtons("xaxisGrp","Var:", c("1"="1","2"="2"))),
      column(6,checkboxGroupInput("yaxisGrp","Lat/Lon:", c("1"="1","2"="2")))
    ),
# App buttons comma and quote
    radioButtons('sep', 'Separator',
                 c(Comma=',', Semicolon=';',Tab='\t'), ','),
    radioButtons('quote', 'Quote',
                 c(None='','Double Quote'='"','Single Quote'="'"),'"'),
    uiOutput("choose_columns")
  ),
  mainPanel(
    tabsetPanel(
      tabPanel("Plot",plotOutput("plot")),
      tabPanel("Data", tableOutput('contents'))
    )
  )
# App sliders for values of definition
  ,
  sliderInput(inputId = "num",
              label = "choose x",
              value = 0.1, min = 0.01, max = 1),
  sliderInput(inputId = "num",
              label = "choose y",
              value = 0.1, min = 0.01, max = 1)

  #initiating kriging
  , actionButton("btn", "Krige")
)

 ##################################################
</code>```

Server:
I have boxed off my function but I need help passing my arguments into the function.

```<code>server <- function(input, output, session) {

  dsnames <- c()

  data_set <- reactive({
    inFile <- input$file1

    if (is.null(inFile))
      return()

    data_set<-read.csv(inFile$datapath, header=input$header,
                       sep=input$sep, quote=input$quote)
  })

  output$contents <- renderTable({data_set()})

  #controlling our buttons
  observe({
    dsnames <- names(data_set())
    cb_options <- list()
    cb_options[ dsnames] <- dsnames
    updateRadioButtons(session, "xaxisGrp",
                       label = "Var",
                       choices = cb_options,
                       selected = "")
    updateCheckboxGroupInput(session, "yaxisGrp",
                             label = "Lat/Lon",
                             choices = cb_options,
                             selected = "")
  })
  output$choose_dataset <- renderUI({
    selectInput("dataset", "Data set", as.list(data_sets))
  })

  ##############################################################
  #My function

  kri <- function(var, lat, lon, defx, defy){

    options(warn = -1)

    #internal function for kriging
    kri3 <- function(var, lat, lon, defx, defy){

      #making a data frame out of the given vector
      spdf <- data.frame(var,lat,lon)

      #makeing spatial point data frame coords
      sp::coordinates(spdf) <- ~ lon + lat
      bbox <- sp::bbox(spdf)

      #variogram stuff
      lzn.vgm <- gstat::variogram(var ~ 1, spdf)

      lzn.fit1 <- gstat::fit.variogram(lzn.vgm, model = gstat::vgm(1, "Sph", 900, 1))

      lzn.fit = automap::autofitVariogram(var ~ 1,
                                          spdf,
                                          model = c("Sph", "Exp", "Gau", "Ste"),
                                          kappa = c(0.05, seq(0.2, 2, 0.1), 5, 10),
                                          fix.values = c(NA, NA, NA),
                                          start_vals = c(NA,NA,NA),
                                          verbose = T)

      #making our grid
      cs <- c(defx, defy)
      bb <- sp::bbox(spdf)
      cc <- bb[,1] + (cs/2)
      cd <- ceiling(diff(t(bb))/cs)
      gold_grd <- sp::GridTopology(cellcentre.offset = cc, cellsize = cs, cells.dim = cd)
      gold_grd
      p4s <- sp::CRS(sp::proj4string(spdf))
      gold_sg <- sp::SpatialGrid(gold_grd, proj4string = p4s)
      summary(gold_sg)

      #kringing and auto kriging
      lzn.kriged <- as.data.frame(gstat::krige(var ~ 1, spdf, gold_sg , model=lzn.fit1))
      lzn.Akriged <- automap::autoKrige(var ~ 1, spdf, gold_sg)

      lzn.Akriged.pred <- lzn.Akriged$krige_output$var1.pred
      lzn.Akriged.var <- lzn.Akriged$krige_output$var1.var

      #making a data frame to use in return
      kriw <- data.frame(lzn.kriged, lzn.Akriged.var, lzn.Akriged.pred)
      return(kriw)
    }

    kriw <- kri3(var, lat, lon, defx, defy)

    #internal function for maping
    Kmap <-  function(var, lat, lon, kriw){

      #making a data spatial point data frame for out variogram plot
      spdf <- data.frame(var,lat,lon)

      #makeing spatial point data frame coords
      sp::coordinates(spdf) <- ~ lon + lat
      bbox <- sp::bbox(spdf)

      #variogram stuff
      lzn.vgm <- gstat::variogram(var ~ 1, spdf)

      lzn.fit = automap::autofitVariogram(var ~ 1,
                                          spdf,
                                          model = c("Sph", "Exp", "Gau", "Ste"),
                                          kappa = c(0.05, seq(0.2, 2, 0.1), 5, 10),
                                          fix.values = c(NA, NA, NA),
                                          start_vals = c(NA,NA,NA),
                                          verbose = T)
      varplot <- plot(lzn.vgm, lzn.fit$var_model, main = "Fitted variogram")

      #making a dataframe for ggplot
      kriw <- as.data.frame(kriw)

      #making a maps
      bbox1 <- ggmap::make_bbox(lon, lat, f = 1.4)
      map <- ggmap::get_map(bbox1)

      #making a heat map
      M1 <- ggmap::ggmap(map) +
        ggplot2::geom_tile(data = kriw, ggplot2::aes(x = lon,
                                                     y = lat, alpha = var1.pred), fill = "red") + ggplot2::ggtitle("Prediction Heat Map")

      M2 <- ggmap::ggmap(map) +
        ggplot2::geom_tile(data = kriw, ggplot2::aes(x = lon,
                                                     y = lat, alpha = var1.var), fill = "red") + ggplot2::ggtitle("Variance Heat Map")
      var2 <- data.frame(var, lat, lon)

      Dplot <- ggmap::ggmap(map) +  ggplot2::geom_point(data = var2,  ggplot2::aes(size=var, color=var, alpha=var)) +
        ggplot2::coord_equal() + ggplot2::ggtitle("Desnisty map") + ggplot2::theme_bw()

      #Placing both heat maps together
      heat <- gridExtra::grid.arrange(M1,M2,varplot,Dplot, ncol=2)

      return(heat)

    }

    #mapping output
    Kmap(var, lat, lon, kriw)

    options(warn = 0)

  }
 ###############################################
 # end of my fucntion

}

shinyApp(ui = ui, server = server)
</code>```

What I get

What i want in the plot box

答:
It appears you need a observe to tie this all together.  Try this at the end of your server function.

```<code>observeEvent(
  # react to button press
  input$btn,
  {
    # to show the input values
    str(input$xaxisGrp)
    str(input$yaxisGrp)
    # you have defined num for both x and y
    #  so I think you will want to change the
    #  inputId to numX and numY in ui
    str(input$num)

    # translate all the inputs into
    #   suitable arguments for kri

    # send the output from kri
    output$plot <- renderPlot({
      kri(...allyourtranslatedargument...)
    })
  }
)
</code>```

Body:
Hello i am trying to make an app in shiny that will take 3 vectors from a data frame and two entered inputs. I would like the five entries to pass threw the function I have maid below and give the output that the function is maid to give. This would be 4 plots set in a grid (two heat maps, one point plot and a simivariogram). I feel that I have the bulk of the app together but I am having trouble getting my five inputs from the ui to pass threw my function and give out the plots. The function works great in R without shiny i just want it to work as an app now. Also I am pretty new to shiny so i might be missing something simple.

UI:

    library(shiny)
    library(shinydashboard)
    library(ggplot2)
    library(leaflet)
    library(data.table)
    library(dplyr)

   ################

# App interface
ui <- fluidPage(
# App csv input
  headerPanel("Kriging"),
  sidebarPanel(
    fileInput('file1', 'Choose CSV File',
              accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
    tags$hr(),
    checkboxInput('header', 'Header', TRUE),
# App button selection for var, lat, lon
    fluidRow(
      column(6,radioButtons("xaxisGrp","Var:", c("1"="1","2"="2"))),
      column(6,checkboxGroupInput("yaxisGrp","Lat/Lon:", c("1"="1","2"="2")))
    ),
# App buttons comma and quote
    radioButtons('sep', 'Separator',
                 c(Comma=',', Semicolon=';',Tab='\t'), ','),
    radioButtons('quote', 'Quote',
                 c(None='','Double Quote'='"','Single Quote'="'"),'"'),
    uiOutput("choose_columns")
  ),
  mainPanel(
    tabsetPanel(
      tabPanel("Plot",plotOutput("plot")),
      tabPanel("Data", tableOutput('contents'))
    )
  )
# App sliders for values of definition
  ,
  sliderInput(inputId = "num",
              label = "choose x",
              value = 0.1, min = 0.01, max = 1),
  sliderInput(inputId = "num",
              label = "choose y",
              value = 0.1, min = 0.01, max = 1)

  #initiating kriging
  , actionButton("btn", "Krige")
)

 ##################################################

Server:
I have boxed off my function but I need help passing my arguments into the function.

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

  dsnames <- c()

  data_set <- reactive({
    inFile <- input$file1

    if (is.null(inFile))
      return()

    data_set<-read.csv(inFile$datapath, header=input$header,
                       sep=input$sep, quote=input$quote)
  })

  output$contents <- renderTable({data_set()})

  #controlling our buttons
  observe({
    dsnames <- names(data_set())
    cb_options <- list()
    cb_options[ dsnames] <- dsnames
    updateRadioButtons(session, "xaxisGrp",
                       label = "Var",
                       choices = cb_options,
                       selected = "")
    updateCheckboxGroupInput(session, "yaxisGrp",
                             label = "Lat/Lon",
                             choices = cb_options,
                             selected = "")
  })
  output$choose_dataset <- renderUI({
    selectInput("dataset", "Data set", as.list(data_sets))
  })

  ##############################################################
  #My function

  kri <- function(var, lat, lon, defx, defy){

    options(warn = -1)

    #internal function for kriging
    kri3 <- function(var, lat, lon, defx, defy){

      #making a data frame out of the given vector
      spdf <- data.frame(var,lat,lon)

      #makeing spatial point data frame coords
      sp::coordinates(spdf) <- ~ lon + lat
      bbox <- sp::bbox(spdf)

      #variogram stuff
      lzn.vgm <- gstat::variogram(var ~ 1, spdf)

      lzn.fit1 <- gstat::fit.variogram(lzn.vgm, model = gstat::vgm(1, "Sph", 900, 1))

      lzn.fit = automap::autofitVariogram(var ~ 1,
                                          spdf,
                                          model = c("Sph", "Exp", "Gau", "Ste"),
                                          kappa = c(0.05, seq(0.2, 2, 0.1), 5, 10),
                                          fix.values = c(NA, NA, NA),
                                          start_vals = c(NA,NA,NA),
                                          verbose = T)

      #making our grid
      cs <- c(defx, defy)
      bb <- sp::bbox(spdf)
      cc <- bb[,1] + (cs/2)
      cd <- ceiling(diff(t(bb))/cs)
      gold_grd <- sp::GridTopology(cellcentre.offset = cc, cellsize = cs, cells.dim = cd)
      gold_grd
      p4s <- sp::CRS(sp::proj4string(spdf))
      gold_sg <- sp::SpatialGrid(gold_grd, proj4string = p4s)
      summary(gold_sg)

      #kringing and auto kriging
      lzn.kriged <- as.data.frame(gstat::krige(var ~ 1, spdf, gold_sg , model=lzn.fit1))
      lzn.Akriged <- automap::autoKrige(var ~ 1, spdf, gold_sg)

      lzn.Akriged.pred <- lzn.Akriged$krige_output$var1.pred
      lzn.Akriged.var <- lzn.Akriged$krige_output$var1.var

      #making a data frame to use in return
      kriw <- data.frame(lzn.kriged, lzn.Akriged.var, lzn.Akriged.pred)
      return(kriw)
    }

    kriw <- kri3(var, lat, lon, defx, defy)

    #internal function for maping
    Kmap <-  function(var, lat, lon, kriw){

      #making a data spatial point data frame for out variogram plot
      spdf <- data.frame(var,lat,lon)

      #makeing spatial point data frame coords
      sp::coordinates(spdf) <- ~ lon + lat
      bbox <- sp::bbox(spdf)

      #variogram stuff
      lzn.vgm <- gstat::variogram(var ~ 1, spdf)

      lzn.fit = automap::autofitVariogram(var ~ 1,
                                          spdf,
                                          model = c("Sph", "Exp", "Gau", "Ste"),
                                          kappa = c(0.05, seq(0.2, 2, 0.1), 5, 10),
                                          fix.values = c(NA, NA, NA),
                                          start_vals = c(NA,NA,NA),
                                          verbose = T)
      varplot <- plot(lzn.vgm, lzn.fit$var_model, main = "Fitted variogram")

      #making a dataframe for ggplot
      kriw <- as.data.frame(kriw)

      #making a maps
      bbox1 <- ggmap::make_bbox(lon, lat, f = 1.4)
      map <- ggmap::get_map(bbox1)

      #making a heat map
      M1 <- ggmap::ggmap(map) +
        ggplot2::geom_tile(data = kriw, ggplot2::aes(x = lon,
                                                     y = lat, alpha = var1.pred), fill = "red") + ggplot2::ggtitle("Prediction Heat Map")

      M2 <- ggmap::ggmap(map) +
        ggplot2::geom_tile(data = kriw, ggplot2::aes(x = lon,
                                                     y = lat, alpha = var1.var), fill = "red") + ggplot2::ggtitle("Variance Heat Map")
      var2 <- data.frame(var, lat, lon)

      Dplot <- ggmap::ggmap(map) +  ggplot2::geom_point(data = var2,  ggplot2::aes(size=var, color=var, alpha=var)) +
        ggplot2::coord_equal() + ggplot2::ggtitle("Desnisty map") + ggplot2::theme_bw()

      #Placing both heat maps together
      heat <- gridExtra::grid.arrange(M1,M2,varplot,Dplot, ncol=2)

      return(heat)

    }

    #mapping output
    Kmap(var, lat, lon, kriw)

    options(warn = 0)

  }
 ###############################################
 # end of my fucntion

}

shinyApp(ui = ui, server = server)

What I get

What i want in the plot box

Body:
It appears you need a observe to tie this all together.  Try this at the end of your server function.

observeEvent(
  # react to button press
  input$btn,
  {
    # to show the input values
    str(input$xaxisGrp)
    str(input$yaxisGrp)
    # you have defined num for both x and y
    #  so I think you will want to change the
    #  inputId to numX and numY in ui
    str(input$num)

    # translate all the inputs into
    #   suitable arguments for kri

    # send the output from kri
    output$plot <- renderPlot({
      kri(...allyourtranslatedargument...)
    })
  }
)


来源: stackexchange

问:
Spring Webflux : Webclient : Get body on error
I am using the webclient from spring webflux, like this :

```<code>WebClient.create()
            .post()
            .uri(url)
            .syncBody(body)
            .accept(MediaType.APPLICATION_JSON)
            .headers(headers)
            .exchange()
            .flatMap(clientResponse -> clientResponse.bodyToMono(tClass));
</code>```

It is working well.
I now want to handle the error from the webservice I am calling (Ex 500 internal error). Normally i would add an doOnError on the "stream" and isu the Throwable to test the status code,

But my issue is that I want to get the body provided by the webservice because it is providing me a message that i would like to use.

I am looking to do the flatMap whatever happen and test myself the status code to deserialize or not the body.

答: Note that as of writing this, 5xx errors no longer result in an exception from the underlying Netty layer. See https://github.com/spring-projects/spring-framework/commit/b0ab84657b712aac59951420f4e9d696c3d84ba2</p>

ContentLicense: CC BY-SA 3.0

Body:
I am using the webclient from spring webflux, like this :

WebClient.create()
            .post()
            .uri(url)
            .syncBody(body)
            .accept(MediaType.APPLICATION_JSON)
            .headers(headers)
            .exchange()
            .flatMap(clientResponse -> clientResponse.bodyToMono(tClass));

It is working well.
I now want to handle the error from the webservice I am calling (Ex 500 internal error). Normally i would add an doOnError on the "stream" and isu the Throwable to test the status code,

But my issue is that I want to get the body provided by the webservice because it is providing me a message that i would like to use.

I am looking to do the flatMap whatever happen and test myself the status code to deserialize or not the body.


问:
iOS - Crash at loadViewIfRequired
I typically wouldn't want to ask SO for help understanding my crash report, but (a) I can learn a lot about reading crash reports from the experts here, and (b), I realize that I don't understand as much about navigation flow as I hoped (this part is specific to the crash report below I think).

So I'm hoping that someone has come across the same issue and can help me understand why my app is crashing.

It only crashes sometimes, which is beyond me as to why it is intermittent. However, when it does crash, it crashes at the same place, with the same stack trace (shown below).

Now I see that it is crashing in cmdPressed (there's a lot of code in this method), but it's hard for me to understand anything deeper than that.

From reading the crash report below, does anyone have any advice as to why my app is crashing??? And why it might be inconsistent?

```<code>Thread 0 Crashed:
0   libobjc.A.dylib                     0x344dd5aa _objc_msgSend + 10
1   UIKit                               0x3374458d -[UIViewController loadViewIfRequired] + 365
2   UIKit                               0x33799133 -[UIViewController contentScrollView] + 27
3   UIKit                               0x33799079 -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 29
4   UIKit                               0x33798f5d -[UINavigationController _layoutViewController:] + 33
5   UIKit                               0x33798e81 -[UINavigationController _updateScrollViewFromViewController:toViewController:] + 273
6   UIKit                               0x337985c1 -[UINavigationController _startTransition:fromViewController:toViewController:] + 65
7   UIKit                               0x337984a9 -[UINavigationController _startDeferredTransitionIfNeeded:] + 325
8   UIKit                               0x337e54b1 -[UINavigationController defaultFirstResponder] + 129
9   UIKit                               0x33797849 -[UIResponder(Internal) _deepestDefaultFirstResponder] + 25
10  UIKit                               0x337976fb -[UIResponder(Internal) _promoteDeepestDefaultFirstResponder] + 31
11  UIKit                               0x33813349 -[UIWindowController transitionViewDidStart:] + 81
12  UIKit                               0x337bf8db -[UITransitionView transition:fromView:toView:removeFromView:] + 991
13  UIKit                               0x33a00059 __91-[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:]_block_invoke_0236 + 389
14  UIKit                               0x33812961 -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:] + 4761
15  UIKit                               0x33810fc7 -[UIViewController presentViewController:withTransition:completion:] + 3395
16  UIKit                               0x33933257 -[UIViewController presentModalViewController:animated:] + 31
17  MyApp                               0x00044973 -[AppViewController cmdPressed] (AppViewController.mm:553)
18  UIKit                               0x338100a5 -[UIApplication sendAction:to:from:forEvent:] + 73
19  UIKit                               0x33810057 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 31
20  UIKit                               0x33810035 -[UIControl sendAction:to:forEvent:] + 45
21  UIKit                               0x3380f8eb -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 503
22  UIKit                               0x3380fde1 -[UIControl touchesEnded:withEvent:] + 489
23  UIKit                               0x337385f1 -[UIWindow _sendTouchesForEvent:] + 525
24  UIKit                               0x33725801 -[UIApplication sendEvent:] + 381
25  UIKit                               0x3372511b _UIApplicationHandleEvent + 6155
26  GraphicsServices                    0x389085a3 _PurpleEventCallback + 591
27  GraphicsServices                    0x389081d3 PurpleEventCallback + 35
28  CoreFoundation                      0x3a5c8173 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 35
29  CoreFoundation                      0x3a5c8117 __CFRunLoopDoSource1 + 139
30  CoreFoundation                      0x3a5c6f99 __CFRunLoopRun + 1385
31  CoreFoundation                      0x3a539ebd _CFRunLoopRunSpecific + 357
32  CoreFoundation                      0x3a539d49 _CFRunLoopRunInMode + 105
33  GraphicsServices                    0x389072eb _GSEventRunModal + 75
34  UIKit                               0x337792f9 _UIApplicationMain + 1121
35  MyApp                               0x0003d083 main (main.m:44)
</code>```

Any advice is greatly appreciated. Thanks!!!

答: I faced the same issue. For me, the problem was that I changed the xib file but forgot to connect all the previous outlets.

Title: iOS - Crash at loadViewIfRequired

Body:
I typically wouldn't want to ask SO for help understanding my crash report, but (a) I can learn a lot about reading crash reports from the experts here, and (b), I realize that I don't understand as much about navigation flow as I hoped (this part is specific to the crash report below I think).

So I'm hoping that someone has come across the same issue and can help me understand why my app is crashing.

It only crashes sometimes, which is beyond me as to why it is intermittent. However, when it does crash, it crashes at the same place, with the same stack trace (shown below).

Now I see that it is crashing in cmdPressed (there's a lot of code in this method), but it's hard for me to understand anything deeper than that.

From reading the crash report below, does anyone have any advice as to why my app is crashing??? And why it might be inconsistent?

Thread 0 Crashed:
0   libobjc.A.dylib                     0x344dd5aa _objc_msgSend + 10
1   UIKit                               0x3374458d -[UIViewController loadViewIfRequired] + 365
2   UIKit                               0x33799133 -[UIViewController contentScrollView] + 27
3   UIKit                               0x33799079 -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 29
4   UIKit                               0x33798f5d -[UINavigationController _layoutViewController:] + 33
5   UIKit                               0x33798e81 -[UINavigationController _updateScrollViewFromViewController:toViewController:] + 273
6   UIKit                               0x337985c1 -[UINavigationController _startTransition:fromViewController:toViewController:] + 65
7   UIKit                               0x337984a9 -[UINavigationController _startDeferredTransitionIfNeeded:] + 325
8   UIKit                               0x337e54b1 -[UINavigationController defaultFirstResponder] + 129
9   UIKit                               0x33797849 -[UIResponder(Internal) _deepestDefaultFirstResponder] + 25
10  UIKit                               0x337976fb -[UIResponder(Internal) _promoteDeepestDefaultFirstResponder] + 31
11  UIKit                               0x33813349 -[UIWindowController transitionViewDidStart:] + 81
12  UIKit                               0x337bf8db -[UITransitionView transition:fromView:toView:removeFromView:] + 991
13  UIKit                               0x33a00059 __91-[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:]_block_invoke_0236 + 389
14  UIKit                               0x33812961 -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:] + 4761
15  UIKit                               0x33810fc7 -[UIViewController presentViewController:withTransition:completion:] + 3395
16  UIKit                               0x33933257 -[UIViewController presentModalViewController:animated:] + 31
17  MyApp                               0x00044973 -[AppViewController cmdPressed] (AppViewController.mm:553)
18  UIKit                               0x338100a5 -[UIApplication sendAction:to:from:forEvent:] + 73
19  UIKit                               0x33810057 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 31
20  UIKit                               0x33810035 -[UIControl sendAction:to:forEvent:] + 45
21  UIKit                               0x3380f8eb -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 503
22  UIKit                               0x3380fde1 -[UIControl touchesEnded:withEvent:] + 489
23  UIKit                               0x337385f1 -[UIWindow _sendTouchesForEvent:] + 525
24  UIKit                               0x33725801 -[UIApplication sendEvent:] + 381
25  UIKit                               0x3372511b _UIApplicationHandleEvent + 6155
26  GraphicsServices                    0x389085a3 _PurpleEventCallback + 591
27  GraphicsServices                    0x389081d3 PurpleEventCallback + 35
28  CoreFoundation                      0x3a5c8173 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 35
29  CoreFoundation                      0x3a5c8117 __CFRunLoopDoSource1 + 139
30  CoreFoundation                      0x3a5c6f99 __CFRunLoopRun + 1385
31  CoreFoundation                      0x3a539ebd _CFRunLoopRunSpecific + 357
32  CoreFoundation                      0x3a539d49 _CFRunLoopRunInMode + 105
33  GraphicsServices                    0x389072eb _GSEventRunModal + 75
34  UIKit                               0x337792f9 _UIApplicationMain + 1121
35  MyApp                               0x0003d083 main (main.m:44)

Any advice is greatly appreciated. Thanks!!!


问:
How to set Banner ad in all activity?
I am new in android app development and I am creating an app in android studio, which has 2 activities. One  is activity_main.xml which has a button to open second activity. When I set the banner ad it shows only on bottom of activity_main.xml and I want to set same banner ad in my second activity. What should I do. Please help me.thanks!!</p>

答:
Create a super class for FirstActivity and SecondActivity by inheriting Activity class. call integrateAdView() from onCreate() method of child class.

integrateAdView() method of super class :

```<code>public void integrateAdView(){

    layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.setGravity(android.view.Gravity.BOTTOM | android.view.Gravity.CENTER_HORIZONTAL);
    addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));

    adView = new AdView(this, AdSize.BANNER, ADV_PUB_ID);
    adView.setAdListener(new AdListener(){
       ...
    });
    layout.addView(adView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

    AdRequest request = new AdRequest();
    request.addTestDevice(AdRequest.TEST_EMULATOR);
    adView.loadAd(request);
}
</code>```

Title: How to set Banner ad in all activity?

Body:
Create a super class for FirstActivity and SecondActivity by inheriting Activity class. call integrateAdView() from onCreate() method of child class.

integrateAdView() method of super class :

public void integrateAdView(){

    layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.setGravity(android.view.Gravity.BOTTOM | android.view.Gravity.CENTER_HORIZONTAL);
    addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));

    adView = new AdView(this, AdSize.BANNER, ADV_PUB_ID);
    adView.setAdListener(new AdListener(){
       ...
    });
    layout.addView(adView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

    AdRequest request = new AdRequest();
    request.addTestDevice(AdRequest.TEST_EMULATOR);
    adView.loadAd(request);
}


问:
Why is my database empty during rails testing, when it should have at least one entry?
I have a rails server that I'm trying to run tests against using RSpec, Capybara, and Selenium on a mac.  I have a command line program that incorporates the library that performs iOS calls and am attempting to call said program during testing.  Problem is, as far as the controller is concerned, the appropriate table in the database is empty, even after a save call.

So the test looks like:

```<code>let(:device) {FactoryGirl.create(:device)}
before do
  puts Device.count
  Capybara.current_driver = :selenium #otherwise, never even asks for the controller
  Capybara.current_session.mode #not sure why this is necessary, but it appears that without this line, the test fails.  Looks like a timing issue.
  device.save #created by the previous let call via FactoryGirl
  puts Device.count #spits out a count of 1, the device object
  @transactions = Transaction.count
  system(networkTester, serverURL, device.id, device.password)
end
it "should give an expected response" do
  response.status.should eq(200) #response is empty
  json = JSON.parse(response.body)
  Transaction.count.should be @transactions + 2
end
</code>```

Inside the devices controller, I've added the debugging code:

```<code>puts params
@device = Device.[matching criteria].first
puts @device
puts Device.count
</code>```

The idea being that I should be able to see the appropriate parameters (I do), and that the device count should be non-zero (it isn't; it's always zero).

I have to use selenium for this; if I leave the driver at rack_test, then the command line function never gets called (ie, that puts params line never gets called).  I also have to call Capybara.current_session.mode # for the same reason; ie, without that, the controller never seems to get called (I figured that out through puts-based debugging).

The test result itself, at this point, looks like:

```<code>Rack::File headers parameter replaces cache_control after Rack 1.5.
Run options: include {:focus=>true}
0
1
{"authcheck"=>nil, ....}

0
2013-07-05 17:58:42.788 NetworkTester[893:707] Not Authorized.
</code>```

That first zero is the first puts Device.count, the 1 is the result of puts Device.count after device.save is called.  The {} is the params puts from inside the controller, then a blank line for puts @device, and 0 for the count of the Device table.  As far as I can tell, that means that in the controller, the Device table is empty; however, from the testing side, the Device table has one entry.  Because there's nothing in the database as far as the controller is concerned, the NetworkTester fails.

If I run the code outside of the testing environment, the output looks more reasonable; ie, the Device table has contents, as far as the controller is concerned.

So why would the Device table either have no entries or have one entry during testing?  More importantly, how can I get the Device table to have contents during the entire course of the test?

This is Rails 3.2.13, RSpec core of 2.13.1, rspec-rails at 2.13.2, capybara 2.0.3, and selenium-webdriver 2.33.0.  I can provide other versions if necessary.

答:
Just put

```<code>config.use_transactional_fixtures = false
</code>```

in spec/spec_helper.rb

Body:
I have a rails server that I'm trying to run tests against using RSpec, Capybara, and Selenium on a mac.  I have a command line program that incorporates the library that performs iOS calls and am attempting to call said program during testing.  Problem is, as far as the controller is concerned, the appropriate table in the database is empty, even after a save call.

So the test looks like:

let(:device) {FactoryGirl.create(:device)}
before do
  puts Device.count
  Capybara.current_driver = :selenium #otherwise, never even asks for the controller
  Capybara.current_session.mode #not sure why this is necessary, but it appears that without this line, the test fails.  Looks like a timing issue.
  device.save #created by the previous let call via FactoryGirl
  puts Device.count #spits out a count of 1, the device object
  @transactions = Transaction.count
  system(networkTester, serverURL, device.id, device.password)
end
it "should give an expected response" do
  response.status.should eq(200) #response is empty
  json = JSON.parse(response.body)
  Transaction.count.should be @transactions + 2
end

Inside the devices controller, I've added the debugging code:

puts params
@device = Device.[matching criteria].first
puts @device
puts Device.count

The idea being that I should be able to see the appropriate parameters (I do), and that the device count should be non-zero (it isn't; it's always zero).

I have to use selenium for this; if I leave the driver at rack_test, then the command line function never gets called (ie, that puts params line never gets called).  I also have to call Capybara.current_session.mode # for the same reason; ie, without that, the controller never seems to get called (I figured that out through puts-based debugging).

The test result itself, at this point, looks like:

Rack::File headers parameter replaces cache_control after Rack 1.5.
Run options: include {:focus=>true}
0
1
{"authcheck"=>nil, ....}

0
2013-07-05 17:58:42.788 NetworkTester[893:707] Not Authorized.

That first zero is the first puts Device.count, the 1 is the result of puts Device.count after device.save is called.  The {} is the params puts from inside the controller, then a blank line for puts @device, and 0 for the count of the Device table.  As far as I can tell, that means that in the controller, the Device table is empty; however, from the testing side, the Device table has one entry.  Because there's nothing in the database as far as the controller is concerned, the NetworkTester fails.

If I run the code outside of the testing environment, the output looks more reasonable; ie, the Device table has contents, as far as the controller is concerned.

So why would the Device table either have no entries or have one entry during testing?  More importantly, how can I get the Device table to have contents during the entire course of the test?

This is Rails 3.2.13, RSpec core of 2.13.1, rspec-rails at 2.13.2, capybara 2.0.3, and selenium-webdriver 2.33.0.  I can provide other versions if necessary.

Body:
Just put

config.use_transactional_fixtures = false

in spec/spec_helper.rb


问:
Different timestamp php and android
why i get different timestamp on android (firebase servertime) and php ? i use http://currentmillis.com to read its value. (UTC+9h)

on android i got
1498500983065  currentmillis.com output was Tue Jun 27 2017 03:16:23

while on php i got 1498500646140 , currentmillis.com output was Tue Jun 27 2017 03:10:46

its around 6 minutes apart.

my android time actually nearly as accurate as what currentmilistime shown.

on php i use :

```<code>$servertime = round(microtime(true) * 1000);
</code>```

where is the problem ?

edit :  i executed the code both only within seconds apart. and several times with the same result.

答: i am using hostinger as my hosting and the problem solved when i upgrade the plan. the free version give me bad server time. </p>

Title: Different timestamp php and android

Body:
why i get different timestamp on android (firebase servertime) and php ? i use http://currentmillis.com to read its value. (UTC+9h)

on android i got
1498500983065  currentmillis.com output was Tue Jun 27 2017 03:16:23

while on php i got 1498500646140 , currentmillis.com output was Tue Jun 27 2017 03:10:46

its around 6 minutes apart.

my android time actually nearly as accurate as what currentmilistime shown.

on php i use :

$servertime = round(microtime(true) * 1000);

where is the problem ?

edit :  i executed the code both only within seconds apart. and several times with the same result.


问:
Convert Unicode characters to human readable string in PHP
I am having problem with converting Unicode characters to human readable text in php.

I have string of unicode characters like following

```<code>$chars = "\u1006\u1092\u1019\u1021\u102c\u101b\u1036\u102f \u1019\u1002\u1062\u1007\u1004\u1039\u1038 (\u1042\u1040\u1041\u1046 \u1007\u1030\u101c\u102d\u102f\u1004\u1039)";
</code>```

If I echo like this

```<code>echo $chars
</code>```

It will not convert to human readable string. But If I echo like this

```<code>$text = '<script type="text/javascript">
document.write("\u1006\u1092\u1019\u1021\u102c\u101b\u1036\u102f \u1019\u1002\u1062\u1007\u1004\u1039\u1038 (\u1042\u1040\u1041\u1046 \u1007\u1030\u101c\u102d\u102f\u1004\u1039)");
</script>';

echo $text;
</code>```

It can print the human readable string like below.

Using that way I can show the result to user. But the problem is I want to store as human readable string in database. So I can do other operation with that string. So my questions are

How can I convert that Unicode characters into human readable string in PHP?

OR

How can I assign the result of the JavaScript as in second method into a string in php?

Here is the same question I asked long ago, Converting Unicode character to text in PHP is not working.

答:
PHP 7+

As of PHP 7, you can use the Unicode codepoint escape syntax to do this.

echo "\u{1006}\u{1092}\u{1019}\u{1021}\u{102c}\u{101b}\u{1036}\u{102f} \u{1019}\u{1002}\u{1062}\u{1007}\u{1004}\u{1039}\u{1038}";

outputs

ဆ႒မအာရံု မဂၢဇင္း.

Does that answer your question ?

ContentLicense: CC BY-SA 4.0

Body:
I am having problem with converting Unicode characters to human readable text in php.

I have string of unicode characters like following

$chars = "\u1006\u1092\u1019\u1021\u102c\u101b\u1036\u102f \u1019\u1002\u1062\u1007\u1004\u1039\u1038 (\u1042\u1040\u1041\u1046 \u1007\u1030\u101c\u102d\u102f\u1004\u1039)";

If I echo like this

echo $chars

It will not convert to human readable string. But If I echo like this

$text = '';

echo $text;

It can print the human readable string like below.

Using that way I can show the result to user. But the problem is I want to store as human readable string in database. So I can do other operation with that string. So my questions are

How can I convert that Unicode characters into human readable string in PHP?

OR

How can I assign the result of the JavaScript as in second method into a string in php?

Here is the same question I asked long ago, Converting Unicode character to text in PHP is not working.


问:
how can i write as one query to get count in mysql

I want to get the today count of users and yesterday's users count for that i want to write only one query how can i do that..?

these are my queries I want only one query:

```<code>SELECT COUNT(*) FROM visitors group by visited_date ORDER by visited_date DESC limit 1,1 as todayCount

SELECT COUNT(*) FROM visitors group by visited_date ORDER by visited_date DESC limit 1,0 as yesterdayCount
</code>```

My expected results or only 2 columns

```<code>todayCount yesterdayCount
     2          4
</code>```

答:
Just try this simple query

```<code>select visited_date as date, COUNT(*) as count from `visitors`
group by `visited_date` order by `visited_date` asc
</code>```

It will produce output as

It will work for you.

Body:
I want to get the today count of users and yesterday's users count for that i want to write only one query how can i do that..?

these are my queries I want only one query:

SELECT COUNT(*) FROM visitors group by visited_date ORDER by visited_date DESC limit 1,1 as todayCount

SELECT COUNT(*) FROM visitors group by visited_date ORDER by visited_date DESC limit 1,0 as yesterdayCount

My expected results or only 2 columns

todayCount yesterdayCount
     2          4

Body:
Just try this simple query

select visited_date as date, COUNT(*) as count from `visitors`
group by `visited_date` order by `visited_date` asc

It will produce output as

It will work for you.


问:
SSL/TLS error with website
I have a website using tls1.2,1.1 and 1.0(ssllabs) . I am using websense proxy to access it. Have enabled tls1.1 and tls1.2 on the WCG. I am still getting Peer disconnected error. The website worked once and is giving the error randomly. I have websense 8 and the URL in question is https://rem2.piiapps.com/site/login. It works fine with websense 7. I dont have a ssl bypass option due to security restrictions. Sometimes the browser indicates that the certificate is broken and sometimes it is healthy.

答: I did some analysis and found that this URL was using a real time communication protocol which is not supported by deafult in websense. It has to be tunneled in the incident list.</p>

Title: SSL/TLS error with website


问:
Google Calendar Attendee Groups added by API are different than groups added by UI
Whenever I add a Google group to a calendar event in the web UI I get an option to expand the group, and sends individual invitations to the group members. But when I add a group to a calendar event via the API (as an attendees[].email ) it does NOT send individual invitations and does not allow expanding the group. I also cannot later add the group via the web UI to get the individual emails without first deleting the group from the invite, then re-adding them.

How can I get events created from the API to match an event created from the UI when a Google group is among the attendees?

答: First of all, you need to use the Calendar Get Event API from both the created events and the existing event of the Google Group. Then compare the eventId of the created event to the existing event from the Google Group to match the created event to the existing event.</p>


问:
JDBC can't pull data rows while using MYSQL query with WHERE statement
I'm using this Maven dependency to execute Mysql queries:

```<code><dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
    </dependency>
</code>```

And this is my java code:

```<code>Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection con = DriverManager.getConnection("jdbc:mysql://...", "root", "xxxxx");
    Statement st = con.createStatement();
    ResultSet res = st.executeQuery("SELECT * FROM User WHERE userName='username'");
    while (res.next()) {
        String s = res.getString("id");
    }
</code>```

I can pull data with simple queries like:

```<code>SELECT * FROM USER;
</code>```

But

If I want to execute above query with WHERE statement the ResultSet.Next is always false!

Please help.
And thanks in advance.

答:
First, try to make sure that string you are writing in the condition is case sensitive

you can use

statement =con.prepareStatement("SELECT * from User WHERE  userName=
  ?"); statement.setString(1, userName);

Body:
I'm using this Maven dependency to execute Mysql queries:

<dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.6</version>
    </dependency>

And this is my java code:

Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection con = DriverManager.getConnection("jdbc:mysql://...", "root", "xxxxx");
    Statement st = con.createStatement();
    ResultSet res = st.executeQuery("SELECT * FROM User WHERE userName='username'");
    while (res.next()) {
        String s = res.getString("id");
    }

I can pull data with simple queries like:

SELECT * FROM USER;

But

If I want to execute above query with WHERE statement the ResultSet.Next is always false!

Please help.
And thanks in advance.


问:
Python : huge looping in SQL Table
in mySql I have the following table (named "staff" )of 800 records (might be much higher):

```<code>
     day          start_time              end_time
   -----------------------------------------------------------------
 2017-01-05 |   2017-01-05 08:00:00    2017-01-05 17:00:00
 2017-01-06 |   2017-01-06 08:00:00    2017-01-06 17:00:00
 2017-01-09 |   2017-01-09 08:00:00    2017-01-09 17:00:00
  .....     |        ......
</code>```

With a given datetime, my python function looks for the closest day in the table (col0) and returns col1 and col2:

```<code>from datetime import datetime
import MySQLdb
import MySQLdb.cursors as cursors
import time

conn = MySQLdb.connect("localhost","root","","FOO_DATABASE", cursorclass = cursors.SSCursor )

def foo(x):
    c.execute("SELECT start_time, end_time FROM staff WHERE Date >= %s  ORDER BY Date  LIMIT 1", (x,))
    results = c.fetchone()
    col1 = results[0]
    col2 = results[1]
    return col1, col2

#Date_time to look
date_time = datetime.strptime('2017-01-01 12:22:00', "%Y-%m-%d %H:%M:%S")

#The loop
start = time.time()
for i in range(60000):
    c = conn.cursor()
    foo(date_time)
    c.close()

end = time.time()
print round((end - start), 2)
</code>```

For 60 000 loops (which is not so much regarding my program) it runs in 21 seconds.

I look forward to  improve this.

EDIT 1

Well, just created an index on the "day" column and it goes 2 times faster, 9.13 seconds.
Hope to improve it because it's not sufficient for my application

EDIT 2

To make in clearer the loop passes 60,000 different values, the use of the fixed value was for illustration purpose.

In my production scheduling algorithm I have to test many combinations of schedules and thus find out the working times for a given datetime. If the date is not in my table (a weekend for example) the function will return the next opening day working time range. Hope it's clear!

答:
You should try prepared statement:

```<code>    from datetime import datetime
    import MySQLdb
    import MySQLdb.cursors as cursors
    import time

    conn = MySQLdb.connect("localhost","root","","FOO_DATABASE", cursorclass = cursors.SSCursor )
    #Date_time to look
    date_time = datetime.strptime('2017-01-01 12:22:00', "%Y-%m-%d %H:%M:%S")

    #The loop
    start = time.time()

    c = conn.cursor()
    for i in range(60000):
        c.execute("SELECT start_time, end_time FROM staff WHERE Date >= :p_date ORDER BY Date  LIMIT 1", {"p_date", date_time})
        col1, col2 = c.fetchone()
    c.close()

    end = time.time()
    print(round((end - start), 2))
</code>```

Or even better try to write sql that you will get all 60k rows by one sql execution.

Title: Python : huge looping in SQL Table

Body:
in mySql I have the following table (named "staff" )of 800 records (might be much higher):

     day          start_time              end_time
   -----------------------------------------------------------------
 2017-01-05 |   2017-01-05 08:00:00    2017-01-05 17:00:00
 2017-01-06 |   2017-01-06 08:00:00    2017-01-06 17:00:00
 2017-01-09 |   2017-01-09 08:00:00    2017-01-09 17:00:00
  .....     |        ......

With a given datetime, my python function looks for the closest day in the table (col0) and returns col1 and col2:

from datetime import datetime
import MySQLdb
import MySQLdb.cursors as cursors
import time

conn = MySQLdb.connect("localhost","root","","FOO_DATABASE", cursorclass = cursors.SSCursor )

def foo(x):
    c.execute("SELECT start_time, end_time FROM staff WHERE Date >= %s  ORDER BY Date  LIMIT 1", (x,))
    results = c.fetchone()
    col1 = results[0]
    col2 = results[1]
    return col1, col2

#Date_time to look
date_time = datetime.strptime('2017-01-01 12:22:00', "%Y-%m-%d %H:%M:%S")

#The loop
start = time.time()
for i in range(60000):
    c = conn.cursor()
    foo(date_time)
    c.close()

end = time.time()
print round((end - start), 2)

For 60 000 loops (which is not so much regarding my program) it runs in 21 seconds.

I look forward to  improve this.

EDIT 1

Well, just created an index on the "day" column and it goes 2 times faster, 9.13 seconds.
Hope to improve it because it's not sufficient for my application

EDIT 2

To make in clearer the loop passes 60,000 different values, the use of the fixed value was for illustration purpose.

In my production scheduling algorithm I have to test many combinations of schedules and thus find out the working times for a given datetime. If the date is not in my table (a weekend for example) the function will return the next opening day working time range. Hope it's clear!

Body:
You should try prepared statement:

    from datetime import datetime
    import MySQLdb
    import MySQLdb.cursors as cursors
    import time

    conn = MySQLdb.connect("localhost","root","","FOO_DATABASE", cursorclass = cursors.SSCursor )
    #Date_time to look
    date_time = datetime.strptime('2017-01-01 12:22:00', "%Y-%m-%d %H:%M:%S")

    #The loop
    start = time.time()

    c = conn.cursor()
    for i in range(60000):
        c.execute("SELECT start_time, end_time FROM staff WHERE Date >= :p_date ORDER BY Date  LIMIT 1", {"p_date", date_time})
        col1, col2 = c.fetchone()
    c.close()

    end = time.time()
    print(round((end - start), 2))

Or even better try to write sql that you will get all 60k rows by one sql execution.


问:
Add items to cart in php using sessions
Am trying to update the quantity in add to cart session, but the below code only increases the quantity of the first item added twice and then perfoms a merge whenever any other item is added twice, kidly help

$('.add-to-cart-mt').on('click', function(e){
        e.preventDefault();
        var id =$(this).attr('id');
        $('#add-to-cat-dialog').dialog({
            autoOpen:false,
            modal:true,
            hide:"pluff",
            show:"slide",
            height:200,
            open: function() { $(".ui-dialog-titlebar-close").hide(); },

            buttons:{
                "Add":function (){
                    $('#add-to-cat-dialog').dialog("close");
                    $.ajax({
                        url: 'add_to_cart.php',
                        data: {  productId : id },

                        success: function (data) {
                            $('.top-cart-contain').empty();
                            $('.top-cart-contain').load("header_cart_summary.php");
                        },

                        error :function (data, textStatus, jqXHR) {  }
                    });
                },

                "Cancel":function (){
                    $(this).dialog("close");
                }
            }
        });

        $('#add-to-cat-dialog').dialog("open");
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>session_start();
require './database.php';

      if(!empty($_GET["productId"])) {
          $id=$_GET["productId"];
            $productById = $connection->query("SELECT * FROM products WHERE productId='$id';");
            if($productById && (mysqli_num_rows($productById)>0)){
                echo 'query ok';
                $productDetail= mysqli_fetch_assoc($productById);
                $itemArray = array(
                    $productDetail["productId"]=>array(
                        'name'=>$productDetail["productName"],
                        'id'=>$productDetail["productId"],
                        'quantity'=>1,
                        'price'=>$productDetail["productPrice"],
                        'image'=>$productDetail["productsImage1"]
                        )
                    );

                if(!empty($_SESSION["cart_item"])) {
                    if(in_array($productDetail["productId"],array_keys($_SESSION["cart_item"]))) {
                        foreach($_SESSION["cart_item"] as $k => $v) {
                            if($productDetail["productId"] == $k) {
                                  if(empty($_SESSION["cart_item"][$k]["quantity"])) {
                                        $_SESSION["cart_item"][$k]["quantity"] = 0;
                                  }
                                  $_SESSION["cart_item"][$k]["quantity"] += 1;
                            }
                        }
                    } else {
                          $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
                    }
                } else {
                      $_SESSION["cart_item"] = $itemArray;
                }

                //set product count in the bag
                if(!empty($_SESSION['cart_volume'])){
                    $_SESSION['cart_volume'] += 1;
                } else {
                    $_SESSION['cart_volume'] = 1;
                }

            }else {echo ''. mysqli_error($connection);}

      } else {
          echo 'no item';
}</code>```

[enter image description here][1]

  <img class="first-img" src="./productImages/<?php echo $item['productsImage1']; ?>" style="height: 250px;"  alt="">

Quick view Wishlist Compare

<?php echo $item['productName']; ?>

 Special Price Ksh. <?php echo number_format($item['productPrice'], 2) ; ?>

                                              <button type="button" class="add-to-cart-mt" id="<?php echo $item['productId']; ?>">  Add to Cart </button>

```

答:
Take a look at the PHP manual: PHP Manual - array_merge()

The relevant part:

If the input arrays have the same string keys, then the later value
  for that key will overwrite the previous one. If, however, the arrays
  contain numeric keys, the later value will not overwrite the original
  value, but will be appended.

Values in the input array with numeric keys will be renumbered with
  incrementing keys starting from zero in the result array.

Probably, You are using numeric ids. If yes, this IDs are transformed into a numerical sequence that does not match the IDs you need (productIDs)

```<code>$itemArray = array(
    $productDetail["productId"]=>array(
        'name'=>$productDetail["productName"],
        'id'=>$productDetail["productId"],
        'quantity'=>1,
        'price'=>$productDetail["productPrice"],
        'image'=>$productDetail["productsImage1"]
    )
);
</code>```

Check out locally this code:

```<code>$a = array('6' => array('name'=>'john','id'=>'6','quantity'=>1));

$b = array('7' => array('name'=>'bill','id'=>'7','quantity'=>1));

$c = array('8' => array('name'=>'mike','id'=>'8','quantity'=>1));

$d = array('6' => array('name'=>'lucy','id'=>'6','quantity'=>1));

$_SESSION["cart_item"] = array_merge($a, $b, $c, $d);

var_dump($_SESSION["cart_item"]);
unset($_SESSION["cart_item"]);

$a = array('six' => array('name'=>'john','id'=>'6','quantity'=>1));

$b = array('seven' => array('name'=>'bill','id'=>'7','quantity'=>1));

$c = array('eight' => array('name'=>'mike','id'=>'8','quantity'=>1));

$d = array('six' => array('name'=>'lucy','id'=>'6','quantity'=>1));

$_SESSION["cart_item"] = array_merge($a, $b, $c, $d);

var_dump($_SESSION["cart_item"]);
</code>```

The result for me was:

```<code>/am.php:13:
array(4) {
  [0] =>
  array(3) {
    'name' =>
    string(4) "john"
    'id' =>
    string(1) "6"
    'quantity' =>
    int(1)
  }
  [1] =>
  array(3) {
    'name' =>
    string(4) "bill"
    'id' =>
    string(1) "7"
    'quantity' =>
    int(1)
  }
  [2] =>
  array(3) {
    'name' =>
    string(4) "mike"
    'id' =>
    string(1) "8"
    'quantity' =>
    int(1)
  }
  [3] =>
  array(3) {
    'name' =>
    string(4) "lucy"
    'id' =>
    string(1) "6"
    'quantity' =>
    int(1)
  }
}
/am.php:26:
array(3) {
  'six' =>
  array(3) {
    'name' =>
    string(4) "lucy"
    'id' =>
    string(1) "6"
    'quantity' =>
    int(1)
  }
  'seven' =>
  array(3) {
    'name' =>
    string(4) "bill"
    'id' =>
    string(1) "7"
    'quantity' =>
    int(1)
  }
  'eight' =>
  array(3) {
    'name' =>
    string(4) "mike"
    'id' =>
    string(1) "8"
    'quantity' =>
    int(1)
  }
}
</code>```

This shows how array_merge deals with numeric indexes (at least using PHP 7). As you can see, numeric indexes even typed as strings will be handled like numeric, loosing the productIDs reference.

Another thing: your code is vulnerable to SQL injection:

```<code>$id=$_GET["productId"];
$productById = $connection->query("SELECT * FROM products WHERE productId='$id';");
</code>```

Read more about it here: PHP Manual - SQL Injection

Title: Add items to cart in php using sessions

Body:
Am trying to update the quantity in add to cart session, but the below code only increases the quantity of the first item added twice and then perfoms a merge whenever any other item is added twice, kidly help

$('.add-to-cart-mt').on('click', function(e){
        e.preventDefault();
        var id =$(this).attr('id');
        $('#add-to-cat-dialog').dialog({
            autoOpen:false,
            modal:true,
            hide:"pluff",
            show:"slide",
            height:200,
            open: function() { $(".ui-dialog-titlebar-close").hide(); },

            buttons:{
                "Add":function (){
                    $('#add-to-cat-dialog').dialog("close");
                    $.ajax({
                        url: 'add_to_cart.php',
                        data: {  productId : id },

                        success: function (data) {
                            $('.top-cart-contain').empty();
                            $('.top-cart-contain').load("header_cart_summary.php");
                        },

                        error :function (data, textStatus, jqXHR) {  }
                    });
                },

                "Cancel":function (){
                    $(this).dialog("close");
                }
            }
        });

        $('#add-to-cat-dialog').dialog("open");
    });

session_start();
require './database.php';

      if(!empty($_GET["productId"])) {
          $id=$_GET["productId"];
            $productById = $connection->query("SELECT * FROM products WHERE productId='$id';");
            if($productById && (mysqli_num_rows($productById)>0)){
                echo 'query ok';
                $productDetail= mysqli_fetch_assoc($productById);
                $itemArray = array(
                    $productDetail["productId"]=>array(
                        'name'=>$productDetail["productName"],
                        'id'=>$productDetail["productId"],
                        'quantity'=>1,
                        'price'=>$productDetail["productPrice"],
                        'image'=>$productDetail["productsImage1"]
                        )
                    );

                if(!empty($_SESSION["cart_item"])) {
                    if(in_array($productDetail["productId"],array_keys($_SESSION["cart_item"]))) {
                        foreach($_SESSION["cart_item"] as $k => $v) {
                            if($productDetail["productId"] == $k) {
                                  if(empty($_SESSION["cart_item"][$k]["quantity"])) {
                                        $_SESSION["cart_item"][$k]["quantity"] = 0;
                                  }
                                  $_SESSION["cart_item"][$k]["quantity"] += 1;
                            }
                        }
                    } else {
                          $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
                    }
                } else {
                      $_SESSION["cart_item"] = $itemArray;
                }

                //set product count in the bag
                if(!empty($_SESSION['cart_volume'])){
                    $_SESSION['cart_volume'] += 1;
                } else {
                    $_SESSION['cart_volume'] = 1;
                }

            }else {echo ''. mysqli_error($connection);}

      } else {
          echo 'no item';
}

[enter image description here][1]

  <img class="first-img" src="./productImages/<?php echo $item['productsImage1']; ?>" style="height: 250px;"  alt="">

Quick view Wishlist Compare

<?php echo $item['productName']; ?>

 Special Price Ksh. <?php echo number_format($item['productPrice'], 2) ; ?>

                                              <button type="button" class="add-to-cart-mt" id="<?php echo $item['productId']; ?>">  Add to Cart </button>

Body:
Take a look at the PHP manual: PHP Manual - array_merge()

The relevant part:

If the input arrays have the same string keys, then the later value
  for that key will overwrite the previous one. If, however, the arrays
  contain numeric keys, the later value will not overwrite the original
  value, but will be appended.

Values in the input array with numeric keys will be renumbered with
  incrementing keys starting from zero in the result array.

Probably, You are using numeric ids. If yes, this IDs are transformed into a numerical sequence that does not match the IDs you need (productIDs)

$itemArray = array(
    $productDetail["productId"]=>array(
        'name'=>$productDetail["productName"],
        'id'=>$productDetail["productId"],
        'quantity'=>1,
        'price'=>$productDetail["productPrice"],
        'image'=>$productDetail["productsImage1"]
    )
);

Check out locally this code:

$a = array('6' => array('name'=>'john','id'=>'6','quantity'=>1));

$b = array('7' => array('name'=>'bill','id'=>'7','quantity'=>1));

$c = array('8' => array('name'=>'mike','id'=>'8','quantity'=>1));

$d = array('6' => array('name'=>'lucy','id'=>'6','quantity'=>1));

$_SESSION["cart_item"] = array_merge($a, $b, $c, $d);

var_dump($_SESSION["cart_item"]);
unset($_SESSION["cart_item"]);

$a = array('six' => array('name'=>'john','id'=>'6','quantity'=>1));

$b = array('seven' => array('name'=>'bill','id'=>'7','quantity'=>1));

$c = array('eight' => array('name'=>'mike','id'=>'8','quantity'=>1));

$d = array('six' => array('name'=>'lucy','id'=>'6','quantity'=>1));

$_SESSION["cart_item"] = array_merge($a, $b, $c, $d);

var_dump($_SESSION["cart_item"]);

The result for me was:

/am.php:13:
array(4) {
  [0] =>
  array(3) {
    'name' =>
    string(4) "john"
    'id' =>
    string(1) "6"
    'quantity' =>
    int(1)
  }
  [1] =>
  array(3) {
    'name' =>
    string(4) "bill"
    'id' =>
    string(1) "7"
    'quantity' =>
    int(1)
  }
  [2] =>
  array(3) {
    'name' =>
    string(4) "mike"
    'id' =>
    string(1) "8"
    'quantity' =>
    int(1)
  }
  [3] =>
  array(3) {
    'name' =>
    string(4) "lucy"
    'id' =>
    string(1) "6"
    'quantity' =>
    int(1)
  }
}
/am.php:26:
array(3) {
  'six' =>
  array(3) {
    'name' =>
    string(4) "lucy"
    'id' =>
    string(1) "6"
    'quantity' =>
    int(1)
  }
  'seven' =>
  array(3) {
    'name' =>
    string(4) "bill"
    'id' =>
    string(1) "7"
    'quantity' =>
    int(1)
  }
  'eight' =>
  array(3) {
    'name' =>
    string(4) "mike"
    'id' =>
    string(1) "8"
    'quantity' =>
    int(1)
  }
}

This shows how array_merge deals with numeric indexes (at least using PHP 7). As you can see, numeric indexes even typed as strings will be handled like numeric, loosing the productIDs reference.

Another thing: your code is vulnerable to SQL injection:

$id=$_GET["productId"];
$productById = $connection->query("SELECT * FROM products WHERE productId='$id';");

Read more about it here: PHP Manual - SQL Injection


问:
Insert space between arguments to concat function
When I concat($name, $surname), is there a way of putting a space in between the $name $surname using my sql not php so when i get the result it formats a little cleaner?

答: Use CONCAT(name, ' ', surname).

Body: Use CONCAT(name, ' ', surname).

ContentLicense: CC BY-SA 2.5


问:
can you run Java in JRuby?
Note: I'm new to this site, so if you downvote, please comment why so I can edit it and avoid it in the future

I know that you can use Java packages In JRuby, but is it possible to literally run Java in JRuby. For example, can you run Java inside a Ruby block similar to:

```<code>runJava() do
    #Javacode
end
</code>```

I did some research, but I only found how to run JRuby in Java.

答:
You can certainly use java packages from JRuby. This is, in fact, one of the main jruby's selling points (if not THE main).

And no, as far as I know, you can't run inline java code like that.

Title: can you run Java in JRuby?

Body:
Note: I'm new to this site, so if you downvote, please comment why so I can edit it and avoid it in the future

I know that you can use Java packages In JRuby, but is it possible to literally run Java in JRuby. For example, can you run Java inside a Ruby block similar to:

runJava() do
    #Javacode
end

I did some research, but I only found how to run JRuby in Java.


问:
INFO:tensorflow:Summary name conv2d_1/kernel:0 is illegal
I am trying to use the tensorboard callback in keras. When I run the pretrained inceptionv3 model with the tensorboard callback I am getting the following warning:

INFO:tensorflow:Summary name conv2d_95/kernel:0 is illegal; using conv2d_95/kernel_0 instead.

I saw a comment on Github addressing this issue. SeaFX on his comment pointed out that he solved it by replacing variable.name with variable.name.replace(':','_'). I am unsure how to do that. Can anyone please help me. Thanks in advance :)

答:
Not sure on getting name replacement to work however a workaround that may be sufficient for your needs is:

```<code>import tensorflow as tf
tf.logging.set_verbosity(tf.logging.WARN)

import keras
</code>```

This will turn off all INFO level logging but keep warnings, errors etc.

See this question for a discussion on the various log levels and changing them. Personally I found setting the TF_CPP_MIN_LOG_LEVEL environment variable didn't work under Jupyter notebook but I haven't tested on base Python.

Body:
Not sure on getting name replacement to work however a workaround that may be sufficient for your needs is:

import tensorflow as tf
tf.logging.set_verbosity(tf.logging.WARN)

import keras

This will turn off all INFO level logging but keep warnings, errors etc.

See this question for a discussion on the various log levels and changing them. Personally I found setting the TF_CPP_MIN_LOG_LEVEL environment variable didn't work under Jupyter notebook but I haven't tested on base Python.


问:
encoding utf-8 on linux
I have a file CreateTable.sql. When I do :

```<code>file --mime-encoding CreateTable.sql
</code>```

The result is :

```<code>CreateTable.sql: utf-8
</code>```

The command :

```<code>lot of things ...
UNICODE, UNICODEBIG, UNICODELITTLE, US-ASCII, US, UTF-7, UTF-8, UTF-16,
UTF-16BE, UTF-16LE, UTF-32, UTF-32BE, UTF-32LE, UTF7, UTF8, UTF16, UTF16BE,
UTF16LE, UTF32, UTF32BE, UTF32LE, VISCII, WCHAR_T, WIN-SAMI-2, WINBALTRIM,
lot of things
</code>```

But the command more on the file CreateTable.sql print :

```<code>CREATE TYPE enum_branchement_moderattachement AS ENUM(
   $$Inconnu$$,
   $$Relatif par rapport Ã  l'amont Ã©lectrique$$,
   $$N'a jamais Ã©tÃ© rattachÃ©$$,
   $$GÃ©ographique$$,
   $$DÃ©tachÃ©$$,
   $$SimplifiÃ©$$
);
</code>```

What I did wrong ?

答:
I solved my problem with those lines :

```<code>echo $LANG
</code>```

that give me fr_FR

```<code>export LANG=fr_FR.utf8
</code>```

Hope that can help someone else.

Title: encoding utf-8 on linux

Body:
I have a file CreateTable.sql. When I do :

file --mime-encoding CreateTable.sql

The result is :

CreateTable.sql: utf-8

The command :

lot of things ...
UNICODE, UNICODEBIG, UNICODELITTLE, US-ASCII, US, UTF-7, UTF-8, UTF-16,
UTF-16BE, UTF-16LE, UTF-32, UTF-32BE, UTF-32LE, UTF7, UTF8, UTF16, UTF16BE,
UTF16LE, UTF32, UTF32BE, UTF32LE, VISCII, WCHAR_T, WIN-SAMI-2, WINBALTRIM,
lot of things

But the command more on the file CreateTable.sql print :

CREATE TYPE enum_branchement_moderattachement AS ENUM(
   $$Inconnu$$,
   $$Relatif par rapport Ã  l'amont Ã©lectrique$$,
   $$N'a jamais Ã©tÃ© rattachÃ©$$,
   $$GÃ©ographique$$,
   $$DÃ©tachÃ©$$,
   $$SimplifiÃ©$$
);

What I did wrong ?

Body:
I solved my problem with those lines :

echo $LANG

that give me fr_FR

export LANG=fr_FR.utf8

Hope that can help someone else.


问:
Haskell - string function
I need to write function, which is seeking for "Z" in string, and when this function finds it on i index, it appends i+3 Char to table.

Here is my code:

```<code>someFun :: String => String -> String -> String
someFun "" (r:rs) = (r:rs)
someFun (a:b:c:d:xs) (r:rs)
    | a == "Z" = someFun xs ((r:rs)++d)
    | otherwise = someFun (b:c:d:xs) (r:rs)
</code>```

I got bunch of errors that I don't know how to fix due to my poor experience in Haskell programming.

EDIT:
If input is "(C (N (Z 'p')) (A (K (Z 'p') (Z 'q')) (Z 'r')))"
its output should be: ['p','q','r']

答:
You can take advantage of how failing pattern-matches work in list comprehensions and the Data.List.tails function:

```<code>import Data.List (tails)

someFun :: String -> String
someFun s = [x | 'Z':_:_:x:_ <- tails s]
</code>```

The tails function gives you all tails of a list (remember that a String ist just a list of Char), e.g.:

```<code>λ: tails "Overflow"
["Overflow","verflow","erflow","rflow","flow","low","ow","w",""]
</code>```

The pattern ('Z':_:_:x:_) matches any string which starts with a Z and is at least four characters in size. For each pattern match, the character which is three positions after Z is extracted.

The magical part about it is that when the pattern fails (e.g. for tails which don't start with a Z or which are too short), the element is skipped silently and doesn't contribute to the result - exactly what you seem to request.

Title: Haskell - string function

Body:
I need to write function, which is seeking for "Z" in string, and when this function finds it on i index, it appends i+3 Char to table.

Here is my code:

someFun :: String => String -> String -> String
someFun "" (r:rs) = (r:rs)
someFun (a:b:c:d:xs) (r:rs)
    | a == "Z" = someFun xs ((r:rs)++d)
    | otherwise = someFun (b:c:d:xs) (r:rs)

I got bunch of errors that I don't know how to fix due to my poor experience in Haskell programming.

EDIT:
If input is "(C (N (Z 'p')) (A (K (Z 'p') (Z 'q')) (Z 'r')))"
its output should be: ['p','q','r']

Body:
You can take advantage of how failing pattern-matches work in list comprehensions and the Data.List.tails function:

import Data.List (tails)

someFun :: String -> String
someFun s = [x | 'Z':_:_:x:_ <- tails s]

The tails function gives you all tails of a list (remember that a String ist just a list of Char), e.g.:

λ: tails "Overflow"
["Overflow","verflow","erflow","rflow","flow","low","ow","w",""]

The pattern ('Z':_:_:x:_) matches any string which starts with a Z and is at least four characters in size. For each pattern match, the character which is three positions after Z is extracted.

The magical part about it is that when the pattern fails (e.g. for tails which don't start with a Z or which are too short), the element is skipped silently and doesn't contribute to the result - exactly what you seem to request.


问:
laravel read ical file and parse value to a database?
I have ical file locally and I am retrieving it and converting to an array like this:

```<code>    $ical = new ICal('ical/basic.ics');
    $test = ($ical->events());
    dd($test);
</code>```

Which gives me an output like:

ICAL 1

And each item in an array has values such as:

ICAL example

What I want to do is write a loop that would loop throught each array and output for example 'summary' then I will expand it to do what I want it to do however the question is how to write such a loop?

答:
Just loop through the event with foreach:

```<code>foreach ($ical->events() as $event) {
    var_dump($event->summary);
}
</code>```

Body:
I have ical file locally and I am retrieving it and converting to an array like this:

    $ical = new ICal('ical/basic.ics');
    $test = ($ical->events());
    dd($test);

Which gives me an output like:

ICAL 1

And each item in an array has values such as:

ICAL example

What I want to do is write a loop that would loop throught each array and output for example 'summary' then I will expand it to do what I want it to do however the question is how to write such a loop?

Body:
Just loop through the event with foreach:

foreach ($ical->events() as $event) {
    var_dump($event->summary);
}


问:
Using third party JavaFX libraries in OSGi enviroment
I have problems with using third party javafx components with my efxclipse rcp application.

For example ControlsFX. First I used p2-maven-plugin from reficio. Application fails because ControlsFx imports com.sun.* packages not published by EFX. I have tried to add these internal packages to my setup through sistem bundle fragment. Failed again. Then I have tried to bundle all dependencies of component (all jars) to one bundle (with extracted classes and without them / just jars). This method works but breaks css skins of components. So any css and skin operation like caret or icons missed.

I have tried libraries like RichTextFX, ControlsFX, JideFX, JFXtras ... Every time same result. All these libraries work under normal Maven JavaFX application setup. Obviously I am doing it wrong way. What is the right way??!!

答:
I recommend you to transform the library to an OSGI ready bundle. This is simple just follow this: http://cq-ops.tumblr.com/post/21893960212/how-to-turn-a-jdbc-driver-jar-into-an-osgi-bundle
good luck :)</p>


问:
MYSQL count number of times value is in 3 columns
I have a query that gets some data about customers. This customers can have three phone numbers and these can be repeated.

To count the number of times that these phones are repeated a partner have create a subselect:

```<code>(select count(*)
from TABLE_A as k
where (k.phone=a.phone or k.phone2=a.phone or k.phone3=a.phone)
and k.id!=a.id) as repetitionsPhone1
</code>```

This is inside a bigger select like this:

```<code>    SELECT a.*,c.*,b.*,
    (
        select count(*)
        from TABLE_A as k
        where (k.phone=a.phone or k.phone2=a.phone or k.phone3=a.phone)
        and k.id!=a.id
    ) as repetitionsPhone1
    FROM a
    left join c on a.id=c.id
    left join b on a.id=b.id
</code>```

This query takes for 50 rows about 30 seconds, and it should return about 2000 rows every single day.

To optimize this I use explain and I see that this subquery was the problem so I searched and I tried this:

```<code>SELECT phn,sum(count) as phoneRepetitions
from (
    select k.phone1 as phn, count(*) as count
    from k
    group by k.phone1
        UNION
    select k.phone2 as phn,count(*) as count
    from k
    group by k.phone2
        UNION
    select k.phone3 as phn,count(*) as count
    from k
    group by k.phone3
) as aux
    group by phn
</code>```

And this returns #1062 MYSQL error: Duplicate entry for key 'distinct key'

First of all I would like to solve this problem. Anyone knows what is happening? This error seems logic in an insert statement, but in select?

And later, this will help to improve the big select that I must optimize? I will have to do this for the three columns.

Thank you.

答:
```<code>SELECT count(*) from

  (SELECT phones1 FROM k
    union
  SELECT phones2 from k
    union
  SELECT phones3 from k)

AS SumCountPhones
</code>```

This seemed to work for me.

Solution as per How do I add two count(*) results together on two different tables?

You can keep stacking the unions.

Body:
I have a query that gets some data about customers. This customers can have three phone numbers and these can be repeated.

To count the number of times that these phones are repeated a partner have create a subselect:

(select count(*)
from TABLE_A as k
where (k.phone=a.phone or k.phone2=a.phone or k.phone3=a.phone)
and k.id!=a.id) as repetitionsPhone1

This is inside a bigger select like this:

    SELECT a.*,c.*,b.*,
    (
        select count(*)
        from TABLE_A as k
        where (k.phone=a.phone or k.phone2=a.phone or k.phone3=a.phone)
        and k.id!=a.id
    ) as repetitionsPhone1
    FROM a
    left join c on a.id=c.id
    left join b on a.id=b.id

This query takes for 50 rows about 30 seconds, and it should return about 2000 rows every single day.

To optimize this I use explain and I see that this subquery was the problem so I searched and I tried this:

SELECT phn,sum(count) as phoneRepetitions
from (
    select k.phone1 as phn, count(*) as count
    from k
    group by k.phone1
        UNION
    select k.phone2 as phn,count(*) as count
    from k
    group by k.phone2
        UNION
    select k.phone3 as phn,count(*) as count
    from k
    group by k.phone3
) as aux
    group by phn

And this returns #1062 MYSQL error: Duplicate entry for key 'distinct key'

First of all I would like to solve this problem. Anyone knows what is happening? This error seems logic in an insert statement, but in select?

And later, this will help to improve the big select that I must optimize? I will have to do this for the three columns.

Thank you.

Body:
SELECT count(*) from

  (SELECT phones1 FROM k
    union
  SELECT phones2 from k
    union
  SELECT phones3 from k)

AS SumCountPhones

This seemed to work for me.

Solution as per How do I add two count(*) results together on two different tables?

You can keep stacking the unions.


问:
How do I enable --enable-soap in php on linux?
That's much the question. I have PHP 5.2.9 on Apache and I cannot upgrade PHP. Is there a way for me to enable SOAP in PHP 5.2.9? The PHP manual did not help at all when it said, "To enable SOAP support, configure PHP with --enable-soap ."  How do I configure? </p>

答:
In case that you have Ubuntu in your machine, the following steps will help you:

Check first in your php testing file if you have soap (client / server)or not by using phpinfo(); and check results in the browser.
In case that you have it, it will seems like the following image ( If not go   to step 2 ):

Open your terminal and paste: sudo  apt-get install php-soap.

Restart your apache2 server in terminal : service apache2 restart.

To check use your php test file again to be seems like mine in step 1.