问:
How to filter date range for routes in R leaflet shiny app?
My data looks like this:

```<code>Name    ship_date   delivery_date   ShipmentID  Dcity   Dzip    Dlong   Dlat    Route   Seq Origin  Ozip    Olong   Olat
1-0 4/13/2018   4/13/2018   FL1174_4    Alviso  95002   -121.976    37.426  1   0   Alviso  95002   -121.976    37.426
1-1 4/13/2018   4/13/2018   FL1174_4    SANTA CLARA 95050   -121.965    37.35   1   1   Alviso  95002   -121.976    37.426
1-2 4/13/2018   4/13/2018   FL1185_10   EAST PALO ALTO  94303   -122.129    37.448  1   2   Alviso  95002   -121.976    37.426
1-3 4/13/2018   4/13/2018   FL1169_10   SAN CARLOS  94070   -122.274    37.5    1   3   Alviso  95002   -121.976    37.426
1-4 4/13/2018   4/13/2018   FL1174_4    Alviso  95002   -121.976    37.426  1   4   Alviso  95002   -121.976    37.426
2-0 4/10/2018   4/10/2018   FL1174_3    Alviso  95002   -121.976    37.426  2   0   Alviso  95002   -121.976    37.426
2-1 4/10/2018   4/10/2018   FL1174_3    SANTA CLARA 95050   -121.965    37.35   2   1   Alviso  95002   -121.976    37.426
2-2 4/10/2018   4/10/2018   FL1174_3    Alviso  95002   -121.976    37.426  2   2   Alviso  95002   -121.976    37.426
</code>```

What I hope to do is: for each "Route" (the "Route" column), connect the "(Dlong, Dlat)" points sequentially to form a route on the map, and add a date range filter to see the routes on different date ranges. Each (Dlong, Dlat) is a point on map.

I was able to draw the map with just R and leaflet. But when I added shiny (because shiny has the "dateRangeInput" feature), it starts to malfunction.

I used a "for" loop to "addPolylines" with leaflet because I want each route to be drawn with different colors.

The map is shown but the filtered routes are wrong.
Can someone help me solve the problem?
Thanks a lot!

```<code>library(dplyr)
library(shiny)
library(leaflet)
library(readxl)
library(RColorBrewer)

data_dots = read_excel("routes_output.xlsx")

ui <- bootstrapPage(
  tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
  leafletOutput("map", width = "100%", height = "100%"),
  absolutePanel(top = 10, right = 10,

                selectInput("map_version", "Map version",
                            choices = c("Grey", "Geo"), selected = "Grey"),

                dateRangeInput("dateRange", "Date Range Input", start =  min(data_dots$ship_date), end = max(data_dots$ship_date)),

                checkboxInput("legend", "Show legend", TRUE)
  )
)

server <- function(input, output) {
  # Initiate the map
  output$map <- renderLeaflet({
    myMap = leaflet("map") %>%
      addTiles(options = providerTileOptions(noWrap = TRUE)) %>%
      setView(lng=-97.390,lat=37.697,zoom=5) # %>%

      # add dots
      # addCircles(data = data_dots, ~c(Olong,Dlong) , ~c(Olat,Dlat), stroke=FALSE, fillOpacity = 0.7)

  })

    filteredData <- reactive({
      x = data_dots[as.Date(data_dots$ship_date) >= input$dateRange[1] & as.Date(data_dots$ship_date) <= input$dateRange[2],]
      print(x)
    })

    route_id = reactive({ distinct(filteredData(), Route)

  })

  observe({

    for (i in route_id()$Route) {

      myMap = leafletProxy("map") %>%
        addPolylines(
          data = subset(filteredData(), filteredData()$Route == i),
          weight = 3,
          color = sample(c("red","blue", "green", "yellow", "black", "orange", "grey"), 1),
          opacity = 0.8,
          smoothFactor = 1,
          lng = ~Dlong,
          lat = ~Dlat,
          highlight = highlightOptions(
            weight = 5,
            color = "blue",
            bringToFront = TRUE
          ),
          layerId = "all"
          # label = ~ as.character(ShipmentID),
          # popup = ~ as.character(ShipmentID),
          # group = "all"
        )

    }
    myMap

  })

}
shinyApp(ui = ui, server = server)

</code>```

答:
Figured it out by myself. The following code works.</p>

```<code>library(dplyr)
library(shiny)
library(leaflet)
library(readxl)
library(RColorBrewer)
library(maps)
library(leaflet.extras)
library(htmlwidgets)

data_dots = read_excel("routes_output.xlsx")

ui <- bootstrapPage(
  tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
  leafletOutput("map", width = "100%", height = "100%"),
  absolutePanel(top = 10, right = 10,

                dateRangeInput("dateRange", "Date Range Input", start =  min(data_dots$ship_date), end = max(data_dots$ship_date))

  )
)

server <- function(input, output) {

  #n <- 60
  qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual', ]
  col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))

  myMap = leaflet("map") %>%
    addTiles(group = "Base") %>%
    addProviderTiles(providers$CartoDB.Positron, group = "Grey") %>%
    addResetMapButton()

  rv <- reactiveValues(
    filteredData =data_dots,
    ids = unique(data_dots$Route)
  )

  observeEvent(input$dateRange,
               {rv$filteredData = data_dots[as.Date(data_dots$ship_date) >= input$dateRange[1] & as.Date(data_dots$ship_date) <= input$dateRange[2],]

               rv$ids = unique(rv$filteredData$Route)
               }

  )

  # Initiate the map
  output$map <- renderLeaflet({

    for (i in rv$ids) {
      #print(i)
      myMap = myMap %>%
        addPolylines(
          data = subset(rv$filteredData, Route == i),
          weight = 3,
          color = sample(col_vector, 1),
          opacity = 0.8,
          smoothFactor = 1,
          lng = ~Dlong,
          lat = ~Dlat,
          highlight = highlightOptions(
            weight = 5,
            color = "blue",
            bringToFront = TRUE
          ),
          label = ~ as.character(ShipmentID),
          popup = ~ as.character(ShipmentID),
          group = "test"
        )

    }
    myMap

  })

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

Body:
My data looks like this:

Name    ship_date   delivery_date   ShipmentID  Dcity   Dzip    Dlong   Dlat    Route   Seq Origin  Ozip    Olong   Olat
1-0 4/13/2018   4/13/2018   FL1174_4    Alviso  95002   -121.976    37.426  1   0   Alviso  95002   -121.976    37.426
1-1 4/13/2018   4/13/2018   FL1174_4    SANTA CLARA 95050   -121.965    37.35   1   1   Alviso  95002   -121.976    37.426
1-2 4/13/2018   4/13/2018   FL1185_10   EAST PALO ALTO  94303   -122.129    37.448  1   2   Alviso  95002   -121.976    37.426
1-3 4/13/2018   4/13/2018   FL1169_10   SAN CARLOS  94070   -122.274    37.5    1   3   Alviso  95002   -121.976    37.426
1-4 4/13/2018   4/13/2018   FL1174_4    Alviso  95002   -121.976    37.426  1   4   Alviso  95002   -121.976    37.426
2-0 4/10/2018   4/10/2018   FL1174_3    Alviso  95002   -121.976    37.426  2   0   Alviso  95002   -121.976    37.426
2-1 4/10/2018   4/10/2018   FL1174_3    SANTA CLARA 95050   -121.965    37.35   2   1   Alviso  95002   -121.976    37.426
2-2 4/10/2018   4/10/2018   FL1174_3    Alviso  95002   -121.976    37.426  2   2   Alviso  95002   -121.976    37.426

What I hope to do is: for each "Route" (the "Route" column), connect the "(Dlong, Dlat)" points sequentially to form a route on the map, and add a date range filter to see the routes on different date ranges. Each (Dlong, Dlat) is a point on map.

I was able to draw the map with just R and leaflet. But when I added shiny (because shiny has the "dateRangeInput" feature), it starts to malfunction.

I used a "for" loop to "addPolylines" with leaflet because I want each route to be drawn with different colors.

The map is shown but the filtered routes are wrong.
Can someone help me solve the problem?
Thanks a lot!

library(dplyr)
library(shiny)
library(leaflet)
library(readxl)
library(RColorBrewer)

data_dots = read_excel("routes_output.xlsx")

ui <- bootstrapPage(
  tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
  leafletOutput("map", width = "100%", height = "100%"),
  absolutePanel(top = 10, right = 10,

                selectInput("map_version", "Map version",
                            choices = c("Grey", "Geo"), selected = "Grey"),

                dateRangeInput("dateRange", "Date Range Input", start =  min(data_dots$ship_date), end = max(data_dots$ship_date)),

                checkboxInput("legend", "Show legend", TRUE)
  )
)

server <- function(input, output) {
  # Initiate the map
  output$map <- renderLeaflet({
    myMap = leaflet("map") %>%
      addTiles(options = providerTileOptions(noWrap = TRUE)) %>%
      setView(lng=-97.390,lat=37.697,zoom=5) # %>%

      # add dots
      # addCircles(data = data_dots, ~c(Olong,Dlong) , ~c(Olat,Dlat), stroke=FALSE, fillOpacity = 0.7)

  })

    filteredData <- reactive({
      x = data_dots[as.Date(data_dots$ship_date) >= input$dateRange[1] & as.Date(data_dots$ship_date) <= input$dateRange[2],]
      print(x)
    })

    route_id = reactive({ distinct(filteredData(), Route)

  })

  observe({

    for (i in route_id()$Route) {

      myMap = leafletProxy("map") %>%
        addPolylines(
          data = subset(filteredData(), filteredData()$Route == i),
          weight = 3,
          color = sample(c("red","blue", "green", "yellow", "black", "orange", "grey"), 1),
          opacity = 0.8,
          smoothFactor = 1,
          lng = ~Dlong,
          lat = ~Dlat,
          highlight = highlightOptions(
            weight = 5,
            color = "blue",
            bringToFront = TRUE
          ),
          layerId = "all"
          # label = ~ as.character(ShipmentID),
          # popup = ~ as.character(ShipmentID),
          # group = "all"
        )

    }
    myMap

  })

}
shinyApp(ui = ui, server = server)

Body:
Figured it out by myself. The following code works.

library(dplyr)
library(shiny)
library(leaflet)
library(readxl)
library(RColorBrewer)
library(maps)
library(leaflet.extras)
library(htmlwidgets)

data_dots = read_excel("routes_output.xlsx")

ui <- bootstrapPage(
  tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
  leafletOutput("map", width = "100%", height = "100%"),
  absolutePanel(top = 10, right = 10,

                dateRangeInput("dateRange", "Date Range Input", start =  min(data_dots$ship_date), end = max(data_dots$ship_date))

  )
)

server <- function(input, output) {

  #n <- 60
  qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual', ]
  col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))

  myMap = leaflet("map") %>%
    addTiles(group = "Base") %>%
    addProviderTiles(providers$CartoDB.Positron, group = "Grey") %>%
    addResetMapButton()

  rv <- reactiveValues(
    filteredData =data_dots,
    ids = unique(data_dots$Route)
  )

  observeEvent(input$dateRange,
               {rv$filteredData = data_dots[as.Date(data_dots$ship_date) >= input$dateRange[1] & as.Date(data_dots$ship_date) <= input$dateRange[2],]

               rv$ids = unique(rv$filteredData$Route)
               }

  )

  # Initiate the map
  output$map <- renderLeaflet({

    for (i in rv$ids) {
      #print(i)
      myMap = myMap %>%
        addPolylines(
          data = subset(rv$filteredData, Route == i),
          weight = 3,
          color = sample(col_vector, 1),
          opacity = 0.8,
          smoothFactor = 1,
          lng = ~Dlong,
          lat = ~Dlat,
          highlight = highlightOptions(
            weight = 5,
            color = "blue",
            bringToFront = TRUE
          ),
          label = ~ as.character(ShipmentID),
          popup = ~ as.character(ShipmentID),
          group = "test"
        )

    }
    myMap

  })

}
shinyApp(ui = ui, server = server)


来源: stackexchange

问:
What is a Web Framework? How does it compare with LAMP?
I started web development in LAMP/WAMP and it was logical to me.
There is a Web Server program called Apache which does the networking part of setting up a service on port 80 (common port). If the request is regular HTML it serves it using HTTP. And  if the request is a PHP resource, there is a mod_php with which the Apache invokes the PHP interpreter to process the file and it gives back HTML which is again transferred as usual HTML.

Now the question is what is a Web Framework? I came across Python based website creation and there is Flask. What is a flask, how does it compare with LAMP. Further are Django/Ruby on Rails different from flask?

Further is LAMP slower than these common frameworks - most claim that it is easy to deploy web apps using their framework?

Can someone answer me and also give some good places to read on these. Thanks for your answers in advance.

答:
You seem to be a bit confused. I suggest you read from the below link :

How To Choose The Perfect Technology Stack For Your Web
  Development?

to get the correct answers. In the meantime, let me clear your doubts step by step.

A web framework is a software framework that is designed to support the development of dynamic websites, web applications, and web services.

Flask is a Python web framework.

LAMP is a complete web development stack. So comparing flask (a web framework) to LAMP (a web development stack) is simply not accurate. In a non-technical example, imagine comparing a fishing rod string to an entire fishing equipment kit.

If you are comparing Flash to LAMP then it can be only done in one way. LAMP uses PHP, and so this stack is compatible with all the frameworks of PHP. So you should compare Flask to various PHP frameworks like Laravel, Codeigniter, CakePHP, etc.

For further information on web frameworks and web development stacks, I would suggest you read this blog on

The Best Technology Stacks for Web Development

.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
EXC_BAD_ACCESS when appending to array class property
I'm new to working with swift and have been converting some ios firebase cordova plugin stuff, but ran into a situation that I don't fully understand regarding arrays. I have two snippets of code, one that works and one that doesn't.

Works

```<code>var admobTestDevices: [Any] = []
var randomString: String = "abc123"

@objc(FirebasePlugin)
class FirebasePlugin : CDVPlugin {
  func something() {
    admobTestDevices.append(randomString)
  }
}
</code>```

Doesn't work

```<code>@objc(FirebasePlugin)
class FirebasePlugin : CDVPlugin {
  var admobTestDevices: [Any] = []
  var randomString: String = "abc123"

  func something() {
    admobTestDevices.append(randomString)
  }
}
</code>```

The one that doesn't work produces Thread 1: EXC_BAD_ACCESS (code=1, address=0x8) as an error. Why does one work and the other doesn't? What is the proper way to have a mutable array as a class property?

答:
For some reason collections become immutable in the subclass in some cases.

You could fix this two ways:

1. override init() initialise the array then call super.init

```<code>class FirebasePlugin : CDVPlugin {

    var admobTestDevices: [Any] = []
    var randomString: String = "abc123"

    override init() {
        admobTestDevices = [Any]()
        super.init()
    }

  func something() {
    admobTestDevices.append(randomString)
  }
}
</code>```

2. Use the lazy modifier so that the array is initialised when first used.

```<code>class FirebasePlugin : CDVPlugin {

    lazy var admobTestDevices: [Any] = []
    var randomString: String = "abc123"

    func something() {
        admobTestDevices.append(randomString)
    }
}
</code>```

Body:
I'm new to working with swift and have been converting some ios firebase cordova plugin stuff, but ran into a situation that I don't fully understand regarding arrays. I have two snippets of code, one that works and one that doesn't.

Works

var admobTestDevices: [Any] = []
var randomString: String = "abc123"

@objc(FirebasePlugin)
class FirebasePlugin : CDVPlugin {
  func something() {
    admobTestDevices.append(randomString)
  }
}

Doesn't work

@objc(FirebasePlugin)
class FirebasePlugin : CDVPlugin {
  var admobTestDevices: [Any] = []
  var randomString: String = "abc123"

  func something() {
    admobTestDevices.append(randomString)
  }
}

The one that doesn't work produces Thread 1: EXC_BAD_ACCESS (code=1, address=0x8) as an error. Why does one work and the other doesn't? What is the proper way to have a mutable array as a class property?

Body:
For some reason collections become immutable in the subclass in some cases.

You could fix this two ways:

1. override init() initialise the array then call super.init

class FirebasePlugin : CDVPlugin {

    var admobTestDevices: [Any] = []
    var randomString: String = "abc123"

    override init() {
        admobTestDevices = [Any]()
        super.init()
    }

  func something() {
    admobTestDevices.append(randomString)
  }
}

2. Use the lazy modifier so that the array is initialised when first used.

class FirebasePlugin : CDVPlugin {

    lazy var admobTestDevices: [Any] = []
    var randomString: String = "abc123"

    func something() {
        admobTestDevices.append(randomString)
    }
}


问:
Replace multiple (special) characters - most efficient way?
At the texts that I have, I want to replace the following special characters with a single space:

```<code>symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]
</code>```

What is the most efficient way (in terms of time of code execution) to do this?

For example, I want this:

```<code>(Hello World)] *!
</code>```

to become this:

```<code>Hello World
</code>```

The candidate methods seem to be the following:

list comprehension

.replace()

.translate()

regular expressions

答:
After launching some tests, I can say that str.translate() is the best variant.

Input data:

```<code>symbols = {"`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"}
translate_table = {126: None, 93: None, 91: None, 125: None, 92: None, 42: None, 45: None, 94: None, 62: None, 47: None, 35: None, 59: None, 44: None, 58: None, 60: None, 124: None, 61: None, 36: None, 95: None, 43: None, 96: None, 123: None, 64: None, 33: None, 38: None, 63: None, 46: None, 34: None, 41: None, 37: None, 40: None}
regular_expression = "[`~!@#$%^&*()_\-+={[\]}|\\:;\"<,>.?/]"
small_document = "Some**r@an]]\"dom t##xt"
normal_document = "TbsX^Kt$FZ%haZe+sLxu:Al\"xNAL\\Kix[mHp_gn]PrG`DqGd~GdNc;BoEq.SYD?Rp>ukq,UfO<XdTc=RUH}oifc&oP!CB*me@Qv{Qf-Li)gmXL/IQH#mne(Khaj|"
big_document = "QOfY+dymyoGBAxTAoIeM+jEWlaECUZEUXuMvprJOqFtQR*OiHtTFZkUNbYipSTTDPOVkIdGTcjWrQmbmthKBHBSEOZ)lQAIJOrVgmGGFdtqbuFfj<Dls<JWtKczAFMPYMemiJBJHdPeeul\\x>lGIBvUsxBokagvVovrrdxdKMtAKx>MEexYv>DGqPUXYaBQKwiSIUobrPQYjilhHMQunE;RiqOZPTnyOEgRrpxcuobvvmGkFpTqgMxYYhrmRRnauiqgvCmZ\"UauceaXsgAMSakxewzPrlIrYkVCVZaEGh]qiizYyzbkcHPF@qQsQMfHPDEbEnWtrCFoARUYAloOcctqmL@hegZbfhsHaJOxOxzQhZAVjVDgokosATfhKMT!WYyPWKcKAHKCzQGGJOCglYGZbftsuyntXZUKNqgGlsLJqgN,pUcOoA/tStXFXgpoSErgvw/OUMPWjJwt=bhMAIDayOZXJm=ifYYUuAvSIZjwnBfktNvEvZmvQso%HiNZEVqoDR%nQBtCkhjSfVfDuRSRsvp-sCunjDDUYSEVLICQdisxhEfqkUTkiPlLiUNNwrvO#WTDmweZyMeIbgNXkIsvaJeHYXV(HvRcGNZM(PPRIAyyLWivGiqMVBtwObqLfEEISyyjGNEdUU:ys`dXcVawkIEAjFXky`RUXNTm`LDM}mwTOcmsSo}haJXPnkwOhKLYwve}SWifzKq}grw}fMSQXXWguUQtlWpPZQymR^wBKEyolFlZnzEEmehSNenOqDOHWRit[Npm?R?DIPXAmQYYBbmJofxUzzWBsVCoPI?VmpXhoMxCfXyHEHowXzIJvExThiffLhBTtma_jk_NrbkPCGGypXvOuBqBxDYfC{bwIHoaqnJSKytxwWXBNnKG~PKuQklGblEwH~rJoGpKZmm~tTEFnPLdmzfrqJibMYIykzL$RZLPmsZjB$AAbZwFnByOydEOIfFvTaEQaSjbpeBZuUGY&ZfPQgLihmPYrhZxSwMzLrNF.WjFiDCLyXksdkLeMHVCfrdgCAotElQ|"
no_match_document = "XOtasggWqhtSLJpHEGoCmMRepFBlRfAGKTLPcEtKonFVsPgvWgAbvJVeMWILPgLapwAmTgXWVbxOJtUFmMygzIqYPqyAxzwElTFyYcGdtnNa"
</code>```

Code:

```<code>def func1(doc):
    for c in symbols:
        doc = doc.replace(c, "")
    return doc

def func2(doc):
    return doc.translate(translate_table)

def func3(doc):
    return re.sub(regular_expression, "", doc)

def func4(doc):
    return "".join(c for c in doc if c not in symbols)
</code>```

Test results:

```<code>func1(small_document):      0.701037002
func1(normal_document):     1.1260866900000002
func1(big_document):        3.4234831459999997
func1(no_match_document):   0.7740780450000004

func2(small_document):      0.14135037500000003
func2(normal_document):     0.5368806810000004
func2(big_document):        0.8128472860000002
func2(no_match_document):   0.394245089

func3(small_document):      0.3157141610000007
func3(normal_document):     0.927359323000001
func3(big_document):        1.9310377590000005
func3(no_match_document):   0.18656399199999996

func4(small_document):      0.3034549070000008
func4(normal_document):     1.3695875739999988
func4(big_document):        10.115730064
func4(no_match_document):   1.2086623230000022
</code>```

UPD.

Input data I've provided have been "prepared" specially for pure method testing.

To generate translate_table I've used next dict comprehension:

```<code>translate_table = {ord(s): None for s in symbols}
</code>```

Here is link to website for regex validation (it could be helpful).

In case if you want to recalculate tests by yourself, here is code:

```<code>    if __name__ == '__main__':
    import timeit
    print("func1(small_document)", timeit.timeit("func1(small_document)", setup="from __main__ import func1, small_document", number=100000))
    print("func1(normal_document): ", timeit.timeit("func1(normal_document)", setup="from __main__ import func1, normal_document", number=100000))
    print("func1(big_document): ", timeit.timeit("func1(big_document)", setup="from __main__ import func1, big_document", number=100000))
    print("func1(no_match_document): ", timeit.timeit("func1(no_match_document)", setup="from __main__ import func1, no_match_document", number=100000))

    print("func2(small_document): ", timeit.timeit("func2(small_document)", setup="from __main__ import func2, small_document", number=100000))
    print("func2(normal_document): ", timeit.timeit("func2(normal_document)", setup="from __main__ import func2, normal_document", number=100000))
    print("func2(big_document): ", timeit.timeit("func2(big_document)", setup="from __main__ import func2, big_document", number=100000))
    print("func2(no_match_document): ", timeit.timeit("func2(no_match_document)", setup="from __main__ import func2, no_match_document", number=100000))

    print("func3(small_document): ", timeit.timeit("func3(small_document)", setup="from __main__ import func3, small_document", number=100000))
    print("func3(normal_document): ", timeit.timeit("func3(normal_document)", setup="from __main__ import func3, normal_document", number=100000))
    print("func3(big_document): ", timeit.timeit("func3(big_document)", setup="from __main__ import func3, big_document", number=100000))
    print("func3(no_match_document): ", timeit.timeit("func3(no_match_document)", setup="from __main__ import func3, no_match_document", number=100000))

    print("func4(small_document): ", timeit.timeit("func4(small_document)", setup="from __main__ import func4, small_document", number=100000))
    print("func4(normal_document): ", timeit.timeit("func4(normal_document)", setup="from __main__ import func4, normal_document", number=100000))
    print("func4(big_document): ", timeit.timeit("func4(big_document)", setup="from __main__ import func4, big_document", number=100000))
    print("func4(no_match_document): ", timeit.timeit("func4(no_match_document)", setup="from __main__ import func4, no_match_document", number=100000))
</code>```

Body:
At the texts that I have, I want to replace the following special characters with a single space:

symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]

What is the most efficient way (in terms of time of code execution) to do this?

For example, I want this:

(Hello World)] *!

to become this:

Hello World

The candidate methods seem to be the following:

list comprehension

.replace()

.translate()

regular expressions

Body:
After launching some tests, I can say that str.translate() is the best variant.

Input data:

symbols = {"`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"}
translate_table = {126: None, 93: None, 91: None, 125: None, 92: None, 42: None, 45: None, 94: None, 62: None, 47: None, 35: None, 59: None, 44: None, 58: None, 60: None, 124: None, 61: None, 36: None, 95: None, 43: None, 96: None, 123: None, 64: None, 33: None, 38: None, 63: None, 46: None, 34: None, 41: None, 37: None, 40: None}
regular_expression = "[`~!@#$%^&*()_\-+={[\]}|\\:;\"<,>.?/]"
small_document = "Some**r@an]]\"dom t##xt"
normal_document = "TbsX^Kt$FZ%haZe+sLxu:Al\"xNAL\\Kix[mHp_gn]PrG`DqGd~GdNc;BoEq.SYD?Rp>ukq,UfO<XdTc=RUH}oifc&oP!CB*me@Qv{Qf-Li)gmXL/IQH#mne(Khaj|"
big_document = "QOfY+dymyoGBAxTAoIeM+jEWlaECUZEUXuMvprJOqFtQR*OiHtTFZkUNbYipSTTDPOVkIdGTcjWrQmbmthKBHBSEOZ)lQAIJOrVgmGGFdtqbuFfj<Dls<JWtKczAFMPYMemiJBJHdPeeul\\x>lGIBvUsxBokagvVovrrdxdKMtAKx>MEexYv>DGqPUXYaBQKwiSIUobrPQYjilhHMQunE;RiqOZPTnyOEgRrpxcuobvvmGkFpTqgMxYYhrmRRnauiqgvCmZ\"UauceaXsgAMSakxewzPrlIrYkVCVZaEGh]qiizYyzbkcHPF@qQsQMfHPDEbEnWtrCFoARUYAloOcctqmL@hegZbfhsHaJOxOxzQhZAVjVDgokosATfhKMT!WYyPWKcKAHKCzQGGJOCglYGZbftsuyntXZUKNqgGlsLJqgN,pUcOoA/tStXFXgpoSErgvw/OUMPWjJwt=bhMAIDayOZXJm=ifYYUuAvSIZjwnBfktNvEvZmvQso%HiNZEVqoDR%nQBtCkhjSfVfDuRSRsvp-sCunjDDUYSEVLICQdisxhEfqkUTkiPlLiUNNwrvO#WTDmweZyMeIbgNXkIsvaJeHYXV(HvRcGNZM(PPRIAyyLWivGiqMVBtwObqLfEEISyyjGNEdUU:ys`dXcVawkIEAjFXky`RUXNTm`LDM}mwTOcmsSo}haJXPnkwOhKLYwve}SWifzKq}grw}fMSQXXWguUQtlWpPZQymR^wBKEyolFlZnzEEmehSNenOqDOHWRit[Npm?R?DIPXAmQYYBbmJofxUzzWBsVCoPI?VmpXhoMxCfXyHEHowXzIJvExThiffLhBTtma_jk_NrbkPCGGypXvOuBqBxDYfC{bwIHoaqnJSKytxwWXBNnKG~PKuQklGblEwH~rJoGpKZmm~tTEFnPLdmzfrqJibMYIykzL$RZLPmsZjB$AAbZwFnByOydEOIfFvTaEQaSjbpeBZuUGY&ZfPQgLihmPYrhZxSwMzLrNF.WjFiDCLyXksdkLeMHVCfrdgCAotElQ|"
no_match_document = "XOtasggWqhtSLJpHEGoCmMRepFBlRfAGKTLPcEtKonFVsPgvWgAbvJVeMWILPgLapwAmTgXWVbxOJtUFmMygzIqYPqyAxzwElTFyYcGdtnNa"

Code:

def func1(doc):
    for c in symbols:
        doc = doc.replace(c, "")
    return doc

def func2(doc):
    return doc.translate(translate_table)

def func3(doc):
    return re.sub(regular_expression, "", doc)

def func4(doc):
    return "".join(c for c in doc if c not in symbols)

Test results:

func1(small_document):      0.701037002
func1(normal_document):     1.1260866900000002
func1(big_document):        3.4234831459999997
func1(no_match_document):   0.7740780450000004

func2(small_document):      0.14135037500000003
func2(normal_document):     0.5368806810000004
func2(big_document):        0.8128472860000002
func2(no_match_document):   0.394245089

func3(small_document):      0.3157141610000007
func3(normal_document):     0.927359323000001
func3(big_document):        1.9310377590000005
func3(no_match_document):   0.18656399199999996

func4(small_document):      0.3034549070000008
func4(normal_document):     1.3695875739999988
func4(big_document):        10.115730064
func4(no_match_document):   1.2086623230000022

UPD.

Input data I've provided have been "prepared" specially for pure method testing.

To generate translate_table I've used next dict comprehension:

translate_table = {ord(s): None for s in symbols}

Here is link to website for regex validation (it could be helpful).

In case if you want to recalculate tests by yourself, here is code:

    if __name__ == '__main__':
    import timeit
    print("func1(small_document)", timeit.timeit("func1(small_document)", setup="from __main__ import func1, small_document", number=100000))
    print("func1(normal_document): ", timeit.timeit("func1(normal_document)", setup="from __main__ import func1, normal_document", number=100000))
    print("func1(big_document): ", timeit.timeit("func1(big_document)", setup="from __main__ import func1, big_document", number=100000))
    print("func1(no_match_document): ", timeit.timeit("func1(no_match_document)", setup="from __main__ import func1, no_match_document", number=100000))

    print("func2(small_document): ", timeit.timeit("func2(small_document)", setup="from __main__ import func2, small_document", number=100000))
    print("func2(normal_document): ", timeit.timeit("func2(normal_document)", setup="from __main__ import func2, normal_document", number=100000))
    print("func2(big_document): ", timeit.timeit("func2(big_document)", setup="from __main__ import func2, big_document", number=100000))
    print("func2(no_match_document): ", timeit.timeit("func2(no_match_document)", setup="from __main__ import func2, no_match_document", number=100000))

    print("func3(small_document): ", timeit.timeit("func3(small_document)", setup="from __main__ import func3, small_document", number=100000))
    print("func3(normal_document): ", timeit.timeit("func3(normal_document)", setup="from __main__ import func3, normal_document", number=100000))
    print("func3(big_document): ", timeit.timeit("func3(big_document)", setup="from __main__ import func3, big_document", number=100000))
    print("func3(no_match_document): ", timeit.timeit("func3(no_match_document)", setup="from __main__ import func3, no_match_document", number=100000))

    print("func4(small_document): ", timeit.timeit("func4(small_document)", setup="from __main__ import func4, small_document", number=100000))
    print("func4(normal_document): ", timeit.timeit("func4(normal_document)", setup="from __main__ import func4, normal_document", number=100000))
    print("func4(big_document): ", timeit.timeit("func4(big_document)", setup="from __main__ import func4, big_document", number=100000))
    print("func4(no_match_document): ", timeit.timeit("func4(no_match_document)", setup="from __main__ import func4, no_match_document", number=100000))


问:
How to efficiently calculate a row in pascal's triangle?
I'm interested in finding the nth row of pascal triangle (not a specific element but the whole row itself). What would be the most efficient way to do it?

I thought about the conventional way to construct the triangle by summing up the corresponding elements in the row above which would take:

```<code>1 + 2 + .. + n = O(n^2)
</code>```

Another way could be using the combination formula of a specific element:

```<code>c(n, k) = n! / (k!(n-k)!)
</code>```

for each element in the row which I guess would take more time the the former method depending on the way to calculate the combination. Any ideas?

答:
Let me build upon Shane's excellent work for an R solution. (Thank you, Shane!. His code for generating the triangle:

```<code>pascalTriangle <- function(h) {
  lapply(0:h, function(i) choose(i, 0:i))
}
</code>```

This will allow one to store the triangle as a list. We can then index whatever row desired. But please add 1 when indexing!  For example, I'll grab the bottom row:

```<code>pt_with_24_rows <- pascalTriangle(24)
row_24 <- pt_with_24_rows[25] # add one
row_24[[1]] # prints the row
</code>```

So, finally, make-believe I have a Galton Board problem. I have the arbitrary challenge of finding out percentage of beans have clustered in the center: say, bins 10 to 15 (out of 25).

```<code>sum(row_24[[1]][10:15])/sum(row_24[[1]])
</code>```

Which turns out to be 0.7704771.  All good!

Body:
I'm interested in finding the nth row of pascal triangle (not a specific element but the whole row itself). What would be the most efficient way to do it?

I thought about the conventional way to construct the triangle by summing up the corresponding elements in the row above which would take:

1 + 2 + .. + n = O(n^2)

Another way could be using the combination formula of a specific element:

c(n, k) = n! / (k!(n-k)!)

for each element in the row which I guess would take more time the the former method depending on the way to calculate the combination. Any ideas?

Body:
Let me build upon Shane's excellent work for an R solution. (Thank you, Shane!. His code for generating the triangle:

pascalTriangle <- function(h) {
  lapply(0:h, function(i) choose(i, 0:i))
}

This will allow one to store the triangle as a list. We can then index whatever row desired. But please add 1 when indexing!  For example, I'll grab the bottom row:

pt_with_24_rows <- pascalTriangle(24)
row_24 <- pt_with_24_rows[25] # add one
row_24[[1]] # prints the row

So, finally, make-believe I have a Galton Board problem. I have the arbitrary challenge of finding out percentage of beans have clustered in the center: say, bins 10 to 15 (out of 25).

sum(row_24[[1]][10:15])/sum(row_24[[1]])

Which turns out to be 0.7704771.  All good!


问:
Mandelbrot code not exciting when resolution is higher than 320 pixels?
I am learning C and trying new things to test what I can do. I have written code which produces a Mandelbrot set with a given resolution (RES) which is #define RES in the .h file. This works and produces good output for resolutions less than 321. For some reason when RES > 321 then the code no longer executes.

I am running using GCC and plotting the output using Gnuplot. I have tried debugging with a debugger however for RES > 321 the main function no longer gets run? I have added a print in the first line of main() to see and this doesn't get run. An executable is made and the program compiles with no errors?

#include <stdio.h>
#include <math.h>

#define MAX_DEPTH 100
#define RES       321

typedef struct complex_t {
    double re;
    double im;
} complex;

void init_complex_grid(complex complex_grid[RES][RES], double left, double right, double top, double bottom);
int converge(complex a);
complex add_complex(complex a, complex b);
complex square_complex(complex a);
double mag_complex(complex a);
void output_grid(unsigned int grid[RES][RES]);

int main(void) {
    // printf("HERE\n");
    int i, j;
    unsigned int convergence_grid[RES][RES];
    complex complex_grid[RES][RES];
    init_complex_grid(complex_grid, -2.5, 1, 1, -1);
    for (i = 0; i < RES; i++) {
        for (j = 0; j < RES; j++) {
            convergence_grid[i][j] = converge(complex_grid[i][j]);
        }
    }
    output_grid(convergence_grid);
    return 0;
}

void init_complex_grid(complex complex_grid[RES][RES],
                       double left, double right,
                       double top, double bottom) {
    int i, j;
    double restep = (top - bottom) / RES;
    double imstep = (right - left) / RES;
    for (i = 0; i < RES; i++) {
        for (j = 0; j < RES; j++) {
            complex_grid[i][j].re = left + j * imstep;
            complex_grid[i][j].im = bottom + i * restep;
        }
    }
}

int converge(complex a) {
    complex z = { 0, 0 };
    int cnt = 0;
    while (cnt <= MAX_DEPTH && mag_complex(z) <= 2) {
        z = add_complex(square_complex(z), a);
        cnt++;
    }
    return cnt;
}

complex add_complex(complex a, complex b) {
    complex added = { a.re + b.re, a.im + b.im };
    return added;
}

complex square_complex(complex a) {
    complex b;
    b.re = a.re * a.re - a.im * a.im;
    b.im = 2 * a.re * b.im;
    return b;
}

double mag_complex(complex a) {
    return sqrt(a.re * a.re + a.im * a.im);
}

void output_grid(unsigned int grid[RES][RES]) {
    FILE *f = fopen("mandelbrot.dat", "w");
    int i, j;
    for (i = 0; i < RES; i++) {
        for (j = 0; j < RES; j++) {
            fprintf(f, "%d ", grid[i][j]);
        }
        fprintf(f, "\n");
    }
    fclose(f);
    printf("\nFILE CLOSED\n");
}
```

I also added the line printf("\nFILE CLOSED\n"); so I would know that the output had been written to the file but this does not get run either with RES > 321.

答:
You are defining too much data with automatic storage in the main() function: either make the large arrays global, static or allocate them from the heap.

Here is a simple fix you can try:

int main(void) {
    int i, j;
    static unsigned int convergence_grid[RES][RES];
    static complex complex_grid[RES][RES];
    init_complex_grid(complex_grid, -2.5, 1, 1, -1);
    for (i = 0; i < RES; i++) {
        for (j = 0; j < RES; j++) {
            convergence_grid[i][j] = converge(complex_grid[i][j]);
        }
    }
    output_grid(convergence_grid);
    return 0;
}
```

<p>Here is an alternative using heap allocation:</p>

<pre class="lang-c prettyprint-override"><code>int main(void) {
    int i, j;
    unsigned int (*convergence_grid)[RES] = calloc(sizeof(*convergence_grid), RES);
    complex (*complex_grid)[RES] = calloc(sizeof(*complex_grid), RES);
    if (!convergence_grid || !complex_grid) {
        fprintf(stderr, "cannot allocate arrays\n");
        return 1;
    }
    init_complex_grid(complex_grid, -2.5, 1, 1, -1);
    for (i = 0; i < RES; i++) {
        for (j = 0; j < RES; j++) {
            convergence_grid[i][j] = converge(complex_grid[i][j]);
        }
    }
    output_grid(convergence_grid);
    free(complex_grid);
    free(convergence_grid);
    return 0;
}
</code>```

Body:
I am learning C and trying new things to test what I can do. I have written code which produces a Mandelbrot set with a given resolution (RES) which is #define RES in the .h file. This works and produces good output for resolutions less than 321. For some reason when RES > 321 then the code no longer executes.

I am running using GCC and plotting the output using Gnuplot. I have tried debugging with a debugger however for RES > 321 the main function no longer gets run? I have added a print in the first line of main() to see and this doesn't get run. An executable is made and the program compiles with no errors?

#include <stdio.h>
#include <math.h>

#define MAX_DEPTH 100
#define RES       321

typedef struct complex_t {
    double re;
    double im;
} complex;

void init_complex_grid(complex complex_grid[RES][RES], double left, double right, double top, double bottom);
int converge(complex a);
complex add_complex(complex a, complex b);
complex square_complex(complex a);
double mag_complex(complex a);
void output_grid(unsigned int grid[RES][RES]);

int main(void) {
    // printf("HERE\n");
    int i, j;
    unsigned int convergence_grid[RES][RES];
    complex complex_grid[RES][RES];
    init_complex_grid(complex_grid, -2.5, 1, 1, -1);
    for (i = 0; i < RES; i++) {
        for (j = 0; j < RES; j++) {
            convergence_grid[i][j] = converge(complex_grid[i][j]);
        }
    }
    output_grid(convergence_grid);
    return 0;
}

void init_complex_grid(complex complex_grid[RES][RES],
                       double left, double right,
                       double top, double bottom) {
    int i, j;
    double restep = (top - bottom) / RES;
    double imstep = (right - left) / RES;
    for (i = 0; i < RES; i++) {
        for (j = 0; j < RES; j++) {
            complex_grid[i][j].re = left + j * imstep;
            complex_grid[i][j].im = bottom + i * restep;
        }
    }
}

int converge(complex a) {
    complex z = { 0, 0 };
    int cnt = 0;
    while (cnt <= MAX_DEPTH && mag_complex(z) <= 2) {
        z = add_complex(square_complex(z), a);
        cnt++;
    }
    return cnt;
}

complex add_complex(complex a, complex b) {
    complex added = { a.re + b.re, a.im + b.im };
    return added;
}

complex square_complex(complex a) {
    complex b;
    b.re = a.re * a.re - a.im * a.im;
    b.im = 2 * a.re * b.im;
    return b;
}

double mag_complex(complex a) {
    return sqrt(a.re * a.re + a.im * a.im);
}

void output_grid(unsigned int grid[RES][RES]) {
    FILE *f = fopen("mandelbrot.dat", "w");
    int i, j;
    for (i = 0; i < RES; i++) {
        for (j = 0; j < RES; j++) {
            fprintf(f, "%d ", grid[i][j]);
        }
        fprintf(f, "\n");
    }
    fclose(f);
    printf("\nFILE CLOSED\n");
}

I also added the line printf("\nFILE CLOSED\n"); so I would know that the output had been written to the file but this does not get run either with RES > 321.

Body:
You are defining too much data with automatic storage in the main() function: either make the large arrays global, static or allocate them from the heap.

Here is a simple fix you can try:

int main(void) {
    int i, j;
    static unsigned int convergence_grid[RES][RES];
    static complex complex_grid[RES][RES];
    init_complex_grid(complex_grid, -2.5, 1, 1, -1);
    for (i = 0; i < RES; i++) {
        for (j = 0; j < RES; j++) {
            convergence_grid[i][j] = converge(complex_grid[i][j]);
        }
    }
    output_grid(convergence_grid);
    return 0;
}

Here is an alternative using heap allocation:

int main(void) {
    int i, j;
    unsigned int (*convergence_grid)[RES] = calloc(sizeof(*convergence_grid), RES);
    complex (*complex_grid)[RES] = calloc(sizeof(*complex_grid), RES);
    if (!convergence_grid || !complex_grid) {
        fprintf(stderr, "cannot allocate arrays\n");
        return 1;
    }
    init_complex_grid(complex_grid, -2.5, 1, 1, -1);
    for (i = 0; i < RES; i++) {
        for (j = 0; j < RES; j++) {
            convergence_grid[i][j] = converge(complex_grid[i][j]);
        }
    }
    output_grid(convergence_grid);
    free(complex_grid);
    free(convergence_grid);
    return 0;
}


问:
Database upgrade from odoo 9.0 to 10.0 - unmet dependencies errors
I used the OpenUpgrade migrate.py script and successfully upgraded a 9.0 database to 10.0 but when I run my new migrated database on odoo 10.0 I get errors like this (about 50+):

```<code>ERROR db-9.0_migrated odoo.modules.graph: module account_cancel: Unmet dependencies: account
2018-12-06 04:40:05,744 6828 ERROR db-9.0_migrated odoo.modules.graph: module rating: Unmet dependencies: mail
2018-12-06 04:40:05,744 6828 ERROR db-9.0_migrated odoo.modules.graph: module product_extended: Unmet dependencies: mrp, stock_account
2018-12-06 04:40:05,744 6828 ERROR db-9.0_migrated odoo.modules.graph: module pos_restaurant: Unmet dependencies: point_of_sale
2018-12-06 04:40:05,744 6828 ERROR db-9.0_migrated odoo.modules.graph: module website_mass_mailing: Unmet dependencies: mass_mailing
2018-12-06 04:40:05,744 6828 ERROR db-9.0_migrated odoo.modules.graph: module website_issue: Unmet dependencies: website_form, project_issue
2018-12-06 04:40:05,744 6828 ERROR db-9.0_migrated odoo.modules.graph: module sale_mrp: Unmet dependencies: mrp, sale_stock
</code>```

etc.

I tested odoo 10.0 with a new database and it works fine. I'm just getting errors when I use my migrated database. It still allows me to try and login but then I get these errors.

http://localhost:8069/web/login

I am quite lost and new to odoo. Any help would be appreciated! Thank you!

答: Looks like the addons-path in your configuration file is wrong.</p>

Body:
I used the OpenUpgrade migrate.py script and successfully upgraded a 9.0 database to 10.0 but when I run my new migrated database on odoo 10.0 I get errors like this (about 50+):

ERROR db-9.0_migrated odoo.modules.graph: module account_cancel: Unmet dependencies: account
2018-12-06 04:40:05,744 6828 ERROR db-9.0_migrated odoo.modules.graph: module rating: Unmet dependencies: mail
2018-12-06 04:40:05,744 6828 ERROR db-9.0_migrated odoo.modules.graph: module product_extended: Unmet dependencies: mrp, stock_account
2018-12-06 04:40:05,744 6828 ERROR db-9.0_migrated odoo.modules.graph: module pos_restaurant: Unmet dependencies: point_of_sale
2018-12-06 04:40:05,744 6828 ERROR db-9.0_migrated odoo.modules.graph: module website_mass_mailing: Unmet dependencies: mass_mailing
2018-12-06 04:40:05,744 6828 ERROR db-9.0_migrated odoo.modules.graph: module website_issue: Unmet dependencies: website_form, project_issue
2018-12-06 04:40:05,744 6828 ERROR db-9.0_migrated odoo.modules.graph: module sale_mrp: Unmet dependencies: mrp, sale_stock

etc.

I tested odoo 10.0 with a new database and it works fine. I'm just getting errors when I use my migrated database. It still allows me to try and login but then I get these errors.

http://localhost:8069/web/login

I am quite lost and new to odoo. Any help would be appreciated! Thank you!


问:
How does closing a socket affects other's side read
For example we have a server-client application. If the server write a message on the socket and then close it before the client's read. Will the client be able to read the message?</p>

答:
This behavior is implementation specific, in general, you should not assume the client is able to read the message, the close(2) in the Linux manual says:

```<code>Be sure to use shutdown(2) to shut down all parts the connection before closing the socket.
</code>```

If you want to ensure that a client has read that message, make that client acknowledge that action in your application protocol.

When you send data through the socket and then you close that same socket, there's no guarantee that the kernel has emptied it's internal buffers to the network or even could do so (eventual problematic network conditions).

Body:
This behavior is implementation specific, in general, you should not assume the client is able to read the message, the close(2) in the Linux manual says:

Be sure to use shutdown(2) to shut down all parts the connection before closing the socket.

If you want to ensure that a client has read that message, make that client acknowledge that action in your application protocol.

When you send data through the socket and then you close that same socket, there's no guarantee that the kernel has emptied it's internal buffers to the network or even could do so (eventual problematic network conditions).


问:
How to print first 5 rows of all the tables in an oracle database (schema)?
I want to open a database (schema) which holds about 100 tables,
Once it's opened I would like to print the top 5 rows of all the tables along with their column names.

My first step was to try and get the schema and table names in the database.
so this is what I used for that.

```<code>SELECT owner, table_name
  FROM all_tables
</code>```

The expected result will contain the table name, column names and top 5 rows of the table.

I am using Oracle SQL Developer ( Oracle database)

答:
Normally we would use dynamic SQL for this sort of thing. But it's messy to handle the output of 100 different tables in PL/SQL. So, you need to generate a script.

Step 1: Run this in SQL Developer.

```<code>select 'prompt ' || owner ||'.' || table_name ||chr(10)
       ||'select * from ' || owner ||'.' || table_name
       || ' where rownum <=5;'
from all_tables
order by  owner, table_name;
</code>```

Step 2: Cut'n'paste the output into a SQL Worksheet. Unless you're luckier than I am you'll need to edit the annoying double quotes at the start and end of each line (a SQL Developer feature caused by the line break, I think).

Step 3: Run the (edited) output as a script and the Script Output pane will give you the results you want.

Is it possible for me to feed the schema(database) name

Add where owner = '&schema_name' after from all_tables. Or just use USER_TABLES if you're interested in the schema to which you're connected.

Body:
I want to open a database (schema) which holds about 100 tables,
Once it's opened I would like to print the top 5 rows of all the tables along with their column names.

My first step was to try and get the schema and table names in the database.
so this is what I used for that.

SELECT owner, table_name
  FROM all_tables

The expected result will contain the table name, column names and top 5 rows of the table.

I am using Oracle SQL Developer ( Oracle database)

Body:
Normally we would use dynamic SQL for this sort of thing. But it's messy to handle the output of 100 different tables in PL/SQL. So, you need to generate a script.

Step 1: Run this in SQL Developer.

select 'prompt ' || owner ||'.' || table_name ||chr(10)
       ||'select * from ' || owner ||'.' || table_name
       || ' where rownum <=5;'
from all_tables
order by  owner, table_name;

Step 2: Cut'n'paste the output into a SQL Worksheet. Unless you're luckier than I am you'll need to edit the annoying double quotes at the start and end of each line (a SQL Developer feature caused by the line break, I think).

Step 3: Run the (edited) output as a script and the Script Output pane will give you the results you want.

Is it possible for me to feed the schema(database) name

Add where owner = '&schema_name' after from all_tables. Or just use USER_TABLES if you're interested in the schema to which you're connected.


问:
Where does data binding belong in a single page application (JS and HTML)
I'm trying to do my own data binding code, mostly as a learning experience, and so I know exactly what is going on. Where should the relevant details for data binding be specified? I have seen two approaches.

A) Specify custom data attributes on HTML elements to indicate the binding target, attribute, element attribute that is being bound, etc. Something like this:

<input type="text" data-model="myState" data-attr="value:title" data-events="keyup" />
```

data-model specifies the JS object to be bound, attr is the element attribute and the object attribute, and events is what event should trigger the binding. The JS code then can automatically identify and add listeners based on those attributes.

This is an example that I originally based my code on:

https://stackblitz.com/edit/two-way-data-binding-poc

B) The other approach I have seen is to do the data binding from the JS side, and using an element ID, the listeners and attributes are specified with JS code. This means the HTML would only need an ID, and everything else is specified in the JS. If I'm understanding the code correctly, I think that this SO QA is of this type:

How to Implement DOM Data Binding in JavaScript

Both concepts (and I assume data binding in general) would need to know the object, UI element, and attributes to be bound. Is it better to do this in the UI code (A), or the JS code (B)?

Alternatively, are both A and B equally valid under different circumstances? This is for a single page application, and I intend to store as much state information on the server directly, and use JS to handle dynamic interactions.

After some additional thought, a benefit of A is that you can change the visualization of the bound state while only updating the UI code. Option B would require modifying both the UI code and JS code to add or change an element.

答:
I've only ever seen implementation A on libraries that are HTML/CSS libraries that have some JS hook-ins.

For instance, Zurb's Foundation seems to use that for their "Sticky" plugin.

But I would use the tried-and-trusted route, and go with:

B) The other approach I have seen is to do the data binding from the JS side, and using an element ID, the listeners and attributes are specified with JS code. This means the HTML would only need an ID, and everything else is specified in the JS. If I'm understanding the code correctly...

```<code>$('#someid').val(valuehere,codehere,anything);
</code>```

Body:
I'm trying to do my own data binding code, mostly as a learning experience, and so I know exactly what is going on. Where should the relevant details for data binding be specified? I have seen two approaches.

A) Specify custom data attributes on HTML elements to indicate the binding target, attribute, element attribute that is being bound, etc. Something like this:

<input type="text" data-model="myState" data-attr="value:title" data-events="keyup" />

data-model specifies the JS object to be bound, attr is the element attribute and the object attribute, and events is what event should trigger the binding. The JS code then can automatically identify and add listeners based on those attributes.

This is an example that I originally based my code on:

https://stackblitz.com/edit/two-way-data-binding-poc

B) The other approach I have seen is to do the data binding from the JS side, and using an element ID, the listeners and attributes are specified with JS code. This means the HTML would only need an ID, and everything else is specified in the JS. If I'm understanding the code correctly, I think that this SO QA is of this type:

How to Implement DOM Data Binding in JavaScript

Both concepts (and I assume data binding in general) would need to know the object, UI element, and attributes to be bound. Is it better to do this in the UI code (A), or the JS code (B)?

Alternatively, are both A and B equally valid under different circumstances? This is for a single page application, and I intend to store as much state information on the server directly, and use JS to handle dynamic interactions.

After some additional thought, a benefit of A is that you can change the visualization of the bound state while only updating the UI code. Option B would require modifying both the UI code and JS code to add or change an element.

Body:
I've only ever seen implementation A on libraries that are HTML/CSS libraries that have some JS hook-ins.

For instance, Zurb's Foundation seems to use that for their "Sticky" plugin.

But I would use the tried-and-trusted route, and go with:

B) The other approach I have seen is to do the data binding from the JS side, and using an element ID, the listeners and attributes are specified with JS code. This means the HTML would only need an ID, and everything else is specified in the JS. If I'm understanding the code correctly...

$('#someid').val(valuehere,codehere,anything);


问:
Convert date to specific format in javascript?
Hi i want to convert the current date to a format as follows in javascript:
Apr 12, 2011 06:42:03.

Any suggestions?????

答:
Little example I just whipped up for you.  Very easy to tell whats going on.  </p>

```<code>var monthNames = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");

var today = new Date();
var cDate = today.getDate();
var cMonth = today.getMonth();
var cYear = today.getFullYear();

var cHour = today.getHours();
var cMin = today.getMinutes();
var cSec = today.getSeconds();

alert( monthNames[cMonth] + " " +cDate  + "," +cYear + " " +cHour+ ":" + cMin+ ":" +cSec );
</code>```

Body:
Little example I just whipped up for you.  Very easy to tell whats going on.

var monthNames = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");

var today = new Date();
var cDate = today.getDate();
var cMonth = today.getMonth();
var cYear = today.getFullYear();

var cHour = today.getHours();
var cMin = today.getMinutes();
var cSec = today.getSeconds();

alert( monthNames[cMonth] + " " +cDate  + "," +cYear + " " +cHour+ ":" + cMin+ ":" +cSec );


问:
vim CTRL-] keys isn't functioning as expected
In :help tag it says that one can go to a tag definition using the CTRL-] keystroke. But I can't get this to work. I thought I messed some mappings with my plugins, so I cleaned .vimrc. But I still get cursor to a tag word (in help for example). I strike Ctrl and ] simultaneously and nothing happens.

How to fix it? Or maybe I'm reading :help wrong?

答:
For mee, "Ctrl-]" means "Ctrl+Alt GR+)". In other words,

Press "Ctrl"

Press "Alt GR" while "Ctrl" is pressed

Press ")" ("]" is also there) while the two above are pressed


问:
Mapping object keys and values into another object
How would you implement a mapping function, from an object keys to another object that has a property with that specific key, preserving the object structure

For example, given this input object:

```<code>{
    person: {
        first_name: "fn",
        last_name: "ln",
        address: {
            city: "c",
            street: "s",
        },
        movies: [
            {
                title: "movie1"
            },
            {
                title: "movie2"
            }
        ]
    }
}
</code>```

the result should be:

```<code>{
    name: "person",
    children: [
        {
            name: "first_name"
        },
        {
            name: "last_name"
        },
        {
            name: "address",
            children: [
                {
                    name: "city"
                },
                {
                    name: "street"
                }
            ]
        },
        {
            name: "movies",
            children: [
                {
                    name: "title"
                }
            ]
        }
    ]
}
</code>```

I've tried with some recursive object traversals but the implementation was really ugly. I feel that there is an easier way to handle it

答:
You can do that using recursion. Create a function which takes an entry as input. Entry is an array of two element which contains key value pair for an object. [key,value]

const obj = { person: { first_name: "fn", last_name: "ln", address: { city: "c", street: "s", }, movies: [ { title: "movie1" }, { title: "movie2" } ] } }

function getKeys(entry){
  let obj = {
    name:entry[0],
    children:[]
  }
  const { children } = obj
  let val = entry[1]
  for(let k in val){
    if(Array.isArray(val[k])){
      children.push(getKeys([k,val[k][1]]));
    }
    else if(typeof val[k] === "object"){
      children.push(getKeys([k,val[k]]))
    }
    else children.push({name:k})
  }
  if(!obj.children.length) delete obj.children;
  return obj
}
console.log(getKeys(Object.entries(obj)[0]))```

Body:
How would you implement a mapping function, from an object keys to another object that has a property with that specific key, preserving the object structure

For example, given this input object:

{
    person: {
        first_name: "fn",
        last_name: "ln",
        address: {
            city: "c",
            street: "s",
        },
        movies: [
            {
                title: "movie1"
            },
            {
                title: "movie2"
            }
        ]
    }
}

the result should be:

{
    name: "person",
    children: [
        {
            name: "first_name"
        },
        {
            name: "last_name"
        },
        {
            name: "address",
            children: [
                {
                    name: "city"
                },
                {
                    name: "street"
                }
            ]
        },
        {
            name: "movies",
            children: [
                {
                    name: "title"
                }
            ]
        }
    ]
}

I've tried with some recursive object traversals but the implementation was really ugly. I feel that there is an easier way to handle it


问:
Asp.net core - razor pages (.cshtml) vs angular 2+
I’ve been learning both asp.net core and angular, however I am a bit confused on what asp.net core razor pages are. I know that angular is a front-end framework to build dynamic applications and I know asp.net core is for the server side. However asp.net core also includes razor pages (.cShtml) that lets you write html code and also insert c# into it. Razor pages can also include partial views and so on but can you build a full website without using anything like react or angular and still have the same dynamic pages ?
If I do use angular for the front end, are you able to still have the validation that comes from c# for forms and so on ?</p>

答:
Yes, you can build a dynamic site using Razor pages, You can use do like so

@foreach (var item in itemList)
{

@item

}
```

If you decide to use angular, I would assume you will have a steeper learning curve and it will be harder to learn short term however to answer your second question, yes you can use the built in authentication by storing a JWT token and passing it in the headers for each request you make to the server

Edit: Angular 2+ is much better in my opinion as you have more flexibility in what you do but it has a lot more overhead work needed whereas razor will be quicker in the short term but will struggle with scale-ability

Body:
Yes, you can build a dynamic site using Razor pages, You can use do like so

@foreach (var item in itemList)
{
   <p>@item</p>
}

If you decide to use angular, I would assume you will have a steeper learning curve and it will be harder to learn short term however to answer your second question, yes you can use the built in authentication by storing a JWT token and passing it in the headers for each request you make to the server

Edit: Angular 2+ is much better in my opinion as you have more flexibility in what you do but it has a lot more overhead work needed whereas razor will be quicker in the short term but will struggle with scale-ability


问:
Firebase get images without internet connection in Ionic
I have to get some images that come from firebase storage.
I have to load that image without internet connection I have used Firestore for getting data.
Firestore data get data from cache without an internet connection so I have url of an image but the image doesn't load.</p>

答:
The Firestore SDK has a local cache of data that it's seen before. So whenever you read something from Firestore while you are connected to the database, it stores a copy of that data in its local cache. Then when you try to read something when you aren't connected to the database, the Firestore client can read the data from the local cache.

There is no such caching mechanism built into the Cloud Storage SDK of Firebase. But you can build it yourself, by storing the files on the local filesystem, or you can use an image loading library that has such caching built in.


问:
How to make "edit post" method available for only 10 minutes in Rails?
I am making a Instagram clone as a mini project to understand how to use Rails, which I haven't had any prior experience with. One of the "client" requirements is to be able to edit their comments on a post but only for up to 15 minutes.

I have done some research but am struggling to find the best way of implementing this feature. Is there something in Rails that would help me to do this?

Thanks :)

答:
I would use a method to check if it's editable such as:

```<code>def editable?
  Time.now - self.created_at < 10.minutes
end
</code>```

It needs validation as well:

```<code>def validate_is_editable
  if self.persisted? && !self.editable?
    self.errors[:editable] << "can edit in just 10 minutes after creation"
  end
end
</code>```

Body:
I would use a method to check if it's editable such as:

def editable?
  Time.now - self.created_at < 10.minutes
end

It needs validation as well:

def validate_is_editable
  if self.persisted? && !self.editable?
    self.errors[:editable] << "can edit in just 10 minutes after creation"
  end
end


问:
FND-CP-ESP: Child: exec:: No such file or directory error: Solving this without dos2unix
I am using SSH Tectia client.

I have created a symbolic link on my shell script command using :

```<code>ln -s $FND_TOP/bin/fndcpesr  /app/gl/PROD/prod/per/12.0.0/bin/MOVEFILE
</code>```

Though this is creating a symbolic link.

```<code>I am getting a Error: FND-CP-ESP: Child: exec:: No such file or directory error
</code>```

I know this error can be solved by dos2unix. But this command does not work in SSH Tectia. Is there any other cmmand to convert the shell script to unix ?

答: This issue may happen if you edited the script in Windows and transfered it with some FTP tool with the wrong Transfer Type that should be ASCII in this case. If you are using Filezilla you can go to Transfer>Transfer Type and select ASCII before transferring</p>

Body:
I am using SSH Tectia client.

I have created a symbolic link on my shell script command using :

ln -s $FND_TOP/bin/fndcpesr  /app/gl/PROD/prod/per/12.0.0/bin/MOVEFILE

Though this is creating a symbolic link.

I am getting a Error: FND-CP-ESP: Child: exec:: No such file or directory error

I know this error can be solved by dos2unix. But this command does not work in SSH Tectia. Is there any other cmmand to convert the shell script to unix ?


问:
How to deal with situations when a view depends on multiple models in MVVM context?
I am working on a battleship game using WPF. I am having a Coordinate model and the ViewModel which I bind with the Grid object. This ViewModel has the property of list of Coordinate objects and describes each as a Border with the Label.

The problem is that the data of the Coordinate class is not enough for my Border view style. It has only the Row and the Column properties but I want to also know whether it contains Ship and also to know if that Ship is Wounded or Sunk. Depending on these values I want to change the Background colour of my Border object.

Scenario 1

If I bind my Border with the Ship then I will lose the binding with the Coordinate object (which is important and my Border still depends on it).

Scenario 2

If I redefine my ViewModel to become 1 to 1 binding for a Border (number of instances of my ViewModel to match a number of instances of Border objects) then it feels a little dirty and not elegant enough. But in this case I would be able to define all the needed properties which my Border use and will be bound to.

Scenario 3

If I create an additional class which would be the hybrid of Coordinate and Ship and that class will be used in a list as a ViewModel property and that list will be bound with my Border, then I see two issues:

The properties of this class will depend on each other. Let's
say there will be a property HasShip and then it has a property
IsShipSunk. But the latter one doesn't make sense when the first one
has the value of false.

Somehow I need to build a way for my Coordinate and Ship class
to communicate with that additional class so that values would be in
sync. Feels like an extra work.

Scenario 4

If I change my Coordinate model class to contain all the required properties then we are having the same issue I have described in my previous "if" (first point).

Scenario 5

If I don't use bindings at all, then I don't know what would be the best practice (in this case) to implement the linking between my Border view and Coordinate model. Also I will need to get the Battlefield object where that Coordinate belongs to to be able to fetch all the Ship objects from there. And this approach feels like "Why you go for WPF if you are not using MVVM?". I have chosen WPF because I love C# and also because WPF has a great UI Controls architecture.

I am pretty much aware that WPF and MVVM might not be suitable for games like this one and it is designed for different purposes. But I still would like find a nice neat solution in case it exists.

So, in a nutshell: how to build the following:

The user clicks on the Border (looks like a cell)

The corresponding Coordinate object is fetched

The corresponding Battlefield where that Coordinate belongs to
is fetched

The iteration of Ship objects is performed to check if any of
them contain that coordinate

Depending on the result change the colour of my Border
Background (Blue - when missed, Orange - when hit, Black - when the
Ship is sunk (please, note, I want all the related Border objects to change
the colour from Orange to Black when the Ship has sunk))

Thanks a lot in advance.

答:
If you chose that particular representation (list of ships) for your game state for a good reason, you should not change it for the UI presentation. What you do in the View should theoretically not influence you to change the Model.

Number 3 is the solution most fitting to MVVM development. You create a real View Model wrapping your actual model.

Please do remember that you don't need to keep two states, your properties can depend on other properties and objects. You can have a reference to your ship list in the Field and generate its properties based on what it contatins, like:

```<code>public class Field
{
    GameStateModel GameState { get; set; }

    public int Row { get; set; }
    public int Col { get; set; }

    private Ship ShipOnField
    {
        get
        {
            return GameState.Ships.Where(s => s.Row == Row && s.Col == Col).FirstOrDefault();
        }
    }

    public bool HasShip
    {
        get
        {
            return ShipOnField != null;
        }
    }

    public bool IsShipSunk
    {
        get
        {
            return ShipOnField != null && ShipOnField.Ded;
        }
    }
}
</code>```

There are two issues with this solution though. One is performance. Other one is an issue of updating the view on changes in the model. You will either have to update everything on each change, or chain the changes in model to your ViewModel updates.

Body:
If you chose that particular representation (list of ships) for your game state for a good reason, you should not change it for the UI presentation. What you do in the View should theoretically not influence you to change the Model.

Number 3 is the solution most fitting to MVVM development. You create a real View Model wrapping your actual model.

Please do remember that you don't need to keep two states, your properties can depend on other properties and objects. You can have a reference to your ship list in the Field and generate its properties based on what it contatins, like:

public class Field
{
    GameStateModel GameState { get; set; }

    public int Row { get; set; }
    public int Col { get; set; }

    private Ship ShipOnField
    {
        get
        {
            return GameState.Ships.Where(s => s.Row == Row && s.Col == Col).FirstOrDefault();
        }
    }

    public bool HasShip
    {
        get
        {
            return ShipOnField != null;
        }
    }

    public bool IsShipSunk
    {
        get
        {
            return ShipOnField != null && ShipOnField.Ded;
        }
    }
}

There are two issues with this solution though. One is performance. Other one is an issue of updating the view on changes in the model. You will either have to update everything on each change, or chain the changes in model to your ViewModel updates.


答:
Simply put - Razor is the view engine you would use in a classic MVC application which allows you to write server side code (C#) in the html (chtml) whereas angular is a Single Page Application framework on typescript.

You will find yourself still including certain javascript libraries in Razor or NPM packages using angular, it really broils down to the same thing.

The decision to use one or the other come down to a few factors such as but not limited to

Performance

Skill and Experience with the framework

Hosting

Generally you can use both to achieve what you are asking (building a site) but it would be ill advised to use both at the same time.

It seems the current trend is to use Angular as the clientapp and have .net core serve as the backend for business logic CRUD etc.

Title: Asp.net core - razor pages (.cshtml) vs angular 2+

Body:
I’ve been learning both asp.net core and angular, however I am a bit confused on what asp.net core razor pages are. I know that angular is a front-end framework to build dynamic applications and I know asp.net core is for the server side. However asp.net core also includes razor pages (.cShtml) that lets you write html code and also insert c# into it. Razor pages can also include partial views and so on but can you build a full website without using anything like react or angular and still have the same dynamic pages ?
If I do use angular for the front end, are you able to still have the validation that comes from c# for forms and so on ?


问:
How to retrieve sequences metadata from JDBC?
I am trying to retrieve different kind of metadata of my Oracle DB from Java code (using basic JDBC). For example, if I want to retrieve the list of tables with _FOO suffix, I can do something like:

```<code>Connection connection = dataSource.getConnection();
DatabaseMetaData meta = connection.getMetaData();
ResultSet tables = meta.getTables(connection.getCatalog(), null, "%_FOO", new String[] { "TABLE" });
// Iterate on the ResultSet to get information on tables...
</code>```

Now, I want to retrieve all the sequences from my database (for example all sequence named S_xxx_FOO).

How would I do that, as I don't see anything in DatabaseMetaData related to sequences?

Do I have to run a query like select * from user_sequences ?

答:
You can't do this through the JDBC API, because some databases (still) do not support sequences.

The only way to get them is to query the system catalog of your DBMS (I guess it's Oracle in your case as you mention user_sequences)

Body:
I am trying to retrieve different kind of metadata of my Oracle DB from Java code (using basic JDBC). For example, if I want to retrieve the list of tables with _FOO suffix, I can do something like:

Connection connection = dataSource.getConnection();
DatabaseMetaData meta = connection.getMetaData();
ResultSet tables = meta.getTables(connection.getCatalog(), null, "%_FOO", new String[] { "TABLE" });
// Iterate on the ResultSet to get information on tables...

Now, I want to retrieve all the sequences from my database (for example all sequence named S_xxx_FOO).

How would I do that, as I don't see anything in DatabaseMetaData related to sequences?

Do I have to run a query like select * from user_sequences ?


问:
How to retrieve the value(s) of a parameter declared with vararg in an enum in Kotlin
I am new to Kotlin and I have an enum containing many values, those values refer to different states my application has.

Now I need to log something whenever the app enters a state but some state in the enum can log more than one thing (based on other parameters coming from outside the app) and some state does not need to log something.

Here is my enum:

```<code>enum class StateName(vararg log: String) {
    FIRST_CONNECTION(), // no parameter here
    AUTHORIZATION_CHECK("message 1", "message 2"),
    HANDSHAKE_SUCCESS("message")
    //...
}
</code>```

If had declared the enum with a single obligatory parameter StateName(var log: String) I could have used HANDSHAKE_SUCCESS.log to retrieve its value but with vararg the IDE (android studio) does not find log at all.

So how can I retrieve my string with something like log[0]?

Note:

My enum is already defined (without parameters) and in use in my application and I can't use a different method of changing the actual state/adding a logging functionality

I need to use Kotlin even if I just started learning as the project was written with this language so I just want to know if (and how) I can do that.

答:
You need to change it to:

```<code>enum class StateName(vararg val log: String)
</code>```

This way you can access the log

Body:
I am new to Kotlin and I have an enum containing many values, those values refer to different states my application has.

Now I need to log something whenever the app enters a state but some state in the enum can log more than one thing (based on other parameters coming from outside the app) and some state does not need to log something.

Here is my enum:

enum class StateName(vararg log: String) {
    FIRST_CONNECTION(), // no parameter here
    AUTHORIZATION_CHECK("message 1", "message 2"),
    HANDSHAKE_SUCCESS("message")
    //...
}

If had declared the enum with a single obligatory parameter StateName(var log: String) I could have used HANDSHAKE_SUCCESS.log to retrieve its value but with vararg the IDE (android studio) does not find log at all.

So how can I retrieve my string with something like log[0]?

Note:

My enum is already defined (without parameters) and in use in my application and I can't use a different method of changing the actual state/adding a logging functionality

I need to use Kotlin even if I just started learning as the project was written with this language so I just want to know if (and how) I can do that.

Body:
You need to change it to:

enum class StateName(vararg val log: String)

This way you can access the log


问:
Redirect rule not being followed
I have set up the following conf files for my apache site and enabled mod rewrite, but I'm having issues getting the rule to fire.  I'm fairly confident it's a missed configuration, but I'm not sure where it lies.  I have been experimenting with different configurations but can't find one that works

My apache2.conf file contains the following

```<code><Directory /var/www/html>
    Options Indexes FollowSymLinks
    AllowOverride FileInfo
    Require all granted
</Directory>
</code>```

My 000-default.conf file contains the following

```<code><VirtualHost *:80>
    DocumentRoot /var/www/html

    RewriteEngine On
    RewriteRule ^/Foo/([A-Za-z0-9]+)/([A-Za-z0-9]+)$ /Baz/$1/Bar/$2/json

</VirtualHost>
</code>```

If I go to :
http://localhost/Foo/sample/data

The error in the logs:

```<code> File does not exist: /var/www/html/Foo/sample/data
</code>```

However, if i manually go to /Baz/sample/Bar/data/json, I get a 200.

EDIT:
regex was wrong.  fixed but issue still occurs.

答:
Looks like maybe a missing bracket in your groups:

this:

^/Foo/(A-Za-z0-9]+)/(A-Za-z0-9]+)$

should be:

^/Foo/([A-Za-z0-9]+)/([A-Za-z0-9]+)$

This kind of error typically causes the server to complain about malformed configuration. Have you checked the server logs?

Title: Redirect rule not being followed

Body:
I have set up the following conf files for my apache site and enabled mod rewrite, but I'm having issues getting the rule to fire.  I'm fairly confident it's a missed configuration, but I'm not sure where it lies.  I have been experimenting with different configurations but can't find one that works

My apache2.conf file contains the following

<Directory /var/www/html>
    Options Indexes FollowSymLinks
    AllowOverride FileInfo
    Require all granted
</Directory>

My 000-default.conf file contains the following

<VirtualHost *:80>
    DocumentRoot /var/www/html

    RewriteEngine On
    RewriteRule ^/Foo/([A-Za-z0-9]+)/([A-Za-z0-9]+)$ /Baz/$1/Bar/$2/json

</VirtualHost>

If I go to :
http://localhost/Foo/sample/data

The error in the logs:

 File does not exist: /var/www/html/Foo/sample/data

However, if i manually go to /Baz/sample/Bar/data/json, I get a 200.

EDIT:
regex was wrong.  fixed but issue still occurs.


问:
jQuery attr() returns undefined for iframe element
I'm trying to get src property of iframe in order to pass new value for src onclick. I'm trying following :
Call.js

```<code>     jQuery(this).bind('click', function(event){
     event.preventDefault();
                  jQuery('#frame1').ready(function(){
                  var src = jQuery('#frame1');
                  console.log(jQuery('#frame1');) //shows element
                  console.log(src.attr('src')); //undefined
                });
      });
</code>```

call.php

```<code><div id="e-call">
<div class="e-body">
    <iframe width="100%" height="100%" frameborder="0" src="frame.php" noresize="noresize" scrolling="no" id="frame1"></iframe>
</div>
</code>```

So, basically, I got lost already. Google gives me nothing.

EDIT

Posted a bit wrong one, sorry

答:
If you want to override your src with new_src
pass new_src as an arg in attr as below:

```<code>src.attr('src',new_src);
</code>```

Body:
I'm trying to get src property of iframe in order to pass new value for src onclick. I'm trying following :
Call.js

     jQuery(this).bind('click', function(event){
     event.preventDefault();
                  jQuery('#frame1').ready(function(){
                  var src = jQuery('#frame1');
                  console.log(jQuery('#frame1');) //shows element
                  console.log(src.attr('src')); //undefined
                });
      });

call.php

So, basically, I got lost already. Google gives me nothing.

EDIT

Posted a bit wrong one, sorry

Body:
If you want to override your src with new_src
pass new_src as an arg in attr as below:

src.attr('src',new_src);


问:
cant tab what ever i want in emacs indentation mode
in javascript and html mode emacs cant make good indentation and all i want is make it better by hand but when use tab only use self indentation and not listen what i say :D

what can i do?

now

```<code><html>
    <body>
      HTTP 404 ERROR !!
    </body>
</html>
</code>```

what i want

```<code><html>
    <body>
                                  HTTP 404 ERROR !!
    </body>
</html>
</code>```

only example

答:
If you don't want TAB to do indentation, you can bind it to just insert tabs.

```<code>(add-hook 'html-mode-hook
   (lambda () (define-key html-mode-map (kbd "TAB") 'self-insert-command)))
</code>```

Body:
in javascript and html mode emacs cant make good indentation and all i want is make it better by hand but when use tab only use self indentation and not listen what i say :D

what can i do?

now

      HTTP 404 ERROR !!

what i want

                                  HTTP 404 ERROR !!

only example

Body:
If you don't want TAB to do indentation, you can bind it to just insert tabs.

(add-hook 'html-mode-hook
   (lambda () (define-key html-mode-map (kbd "TAB") 'self-insert-command)))


问:
Or statement within np.all() function
Given a 2D array I would like to find rows that are heterogeneous.

I have a 2D numpy-array and applied a condition resulting in another 2D numpy-array of boolean values.
Now I want to find rows that are neither all True or all False.
Is it possible to apply a or statement within np.all?

```<code>x = np.array([[1,1,1,1,1,1],
              [2,2,2,1,2,2],
              [3,3,3,3,3,3,]])

y = x > 1

z = ~np.all((y == True) or (y == False), axis=1)
</code>```

ValueError: The truth value of an array with more than one element is
  ambiguous. Use a.any() or a.all()

A new array[bool] marking heterogeneous rows.
In example: [False, True, False]

Very much welcome: hints to other solutions, or functions.

Title: Or statement within np.all() function

Body:
Given a 2D array I would like to find rows that are heterogeneous.

I have a 2D numpy-array and applied a condition resulting in another 2D numpy-array of boolean values.
Now I want to find rows that are neither all True or all False.
Is it possible to apply a or statement within np.all?

x = np.array([[1,1,1,1,1,1],
              [2,2,2,1,2,2],
              [3,3,3,3,3,3,]])

y = x > 1

z = ~np.all((y == True) or (y == False), axis=1)

ValueError: The truth value of an array with more than one element is
  ambiguous. Use a.any() or a.all()

A new array[bool] marking heterogeneous rows.
In example: [False, True, False]

Very much welcome: hints to other solutions, or functions.

Body:
You need two np.alls before or'ing them.

x = np.array([[1,1,1,1,1,1],
              [2,2,2,1,2,2],
              [3,3,3,3,3,3,]])

y = x > 1

z = ~(np.all(y == True, axis=1) | np.all(y == False, axis=1))


问:
spark.sql.cbo.enabled=true with Hive table
In Spark 2.2 the Cost Based Optimizer option has been enabled. The documentation appears to be saying that we need to analyze the tables in Spark before enabling this option. I would like to know if this option is helpful when we have all the table data coming in from Hive as the Data storage layer. Since spark will read Hive using Hivetablescan (avoiding Map/Reduce) does it make sense to use CBO configuration when data is read from Hive.</p>

答:
spark.sql.cbo.enabled=true is NOT useful for Hive tables unless

ANALYZE TABLE <tblname> COMPUTE STATISTICS NOSCAN(Basic stats for table, use FOR COLUMN for column level statistics)     is fired from Spark.

Spark cannot make of stats collected from running the ANALYZE command from Hive.

It can make use of stats only when computed from Spark engine.

How are stats stored in Hive table

The stats are store in Hive table in TBLPROPERTIES.

All the Spark stats have keys with prefix spark.sql.statistics.

Code reference.


问:
ASP.NET Core: How to pass connection string to DBContext?
There is the working example:
https://www.codeproject.com/Articles/3132485/CRUD-Operation-using-ASP-NET-CORE-2-2-and-React-Re

I'd like to replace the hardcoded connection string in assembly with string from config. It is in the original example:

```<code>public partial class ContactDBContext : DbContext
{
    public ContactDBContext()
    {
    }

    public ContactDBContext(DbContextOptions<ContactDBContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Contacts> Contacts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            //#warning To protect potentially sensitive information
            //in your connection string, you should move it out of source code.
            //See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance
            //on storing connection strings.
            optionsBuilder.UseSqlServer("Server=yourservername ;
                                         Database=ContactDB;Trusted_Connection=True;");
       }
    }
}
</code>```

I have added the code:

```<code>public void ConfigureServices(IServiceCollection services)
{
    //...

    services.AddDbContext<ContactDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString(nameof(ContactDBContext))));//<------?

    //...
}
</code>```

The string is read ok, but it is not used. The hardcoded string still used (see the first piece of code).

I use the context like

```<code>public class ContactService : IContactService
{
    public async Task<List<ContactModel>> GetContacts()
    {
        using (ContactDBContext db = new ContactDBContext())
        {

        //...
</code>```

How to pass the connection string from app to EF context?

答:
Because you are manually creating the instance of the context, the configuration applied at startup is not being injected into the context and instead it is using the OnConfiguring method.

That is why your configuration at start is not being applied.

Refactor the context to remove the default constructor and OnConfiguring

```<code>public partial class ContactDBContext : DbContext {
    public ContactDBContext(DbContextOptions<ContactDBContext> options)
        : base(options) {
    }

    public virtual DbSet<Contacts> Contacts { get; set; }

    }
}
</code>```

Next ensure that the context is injected into the desired dependent class

```<code>public class ContactService : IContactService {
    ContactDBContext db;

    public ContactService (ContactDBContext db) {
        this.db = db
    }

    public async Task<List<ContactModel>> GetContacts() {
        var contacts = db.Contacts;

        //...convert to models

        //...
    }
}
</code>```

The configuration applied at startup should now be included when the container resolves the context for injection.

Reference Configuring a DbContext

Body:
There is the working example:
https://www.codeproject.com/Articles/3132485/CRUD-Operation-using-ASP-NET-CORE-2-2-and-React-Re

I'd like to replace the hardcoded connection string in assembly with string from config. It is in the original example:

public partial class ContactDBContext : DbContext
{
    public ContactDBContext()
    {
    }

    public ContactDBContext(DbContextOptions<ContactDBContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Contacts> Contacts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            //#warning To protect potentially sensitive information
            //in your connection string, you should move it out of source code.
            //See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance
            //on storing connection strings.
            optionsBuilder.UseSqlServer("Server=yourservername ;
                                         Database=ContactDB;Trusted_Connection=True;");
       }
    }
}

I have added the code:

public void ConfigureServices(IServiceCollection services)
{
    //...

    services.AddDbContext<ContactDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString(nameof(ContactDBContext))));//<------?

    //...
}

The string is read ok, but it is not used. The hardcoded string still used (see the first piece of code).

I use the context like

public class ContactService : IContactService
{
    public async Task<List<ContactModel>> GetContacts()
    {
        using (ContactDBContext db = new ContactDBContext())
        {

        //...

How to pass the connection string from app to EF context?

Body:
Because you are manually creating the instance of the context, the configuration applied at startup is not being injected into the context and instead it is using the OnConfiguring method.

That is why your configuration at start is not being applied.

Refactor the context to remove the default constructor and OnConfiguring

public partial class ContactDBContext : DbContext {
    public ContactDBContext(DbContextOptions<ContactDBContext> options)
        : base(options) {
    }

    public virtual DbSet<Contacts> Contacts { get; set; }

    }
}

Next ensure that the context is injected into the desired dependent class

public class ContactService : IContactService {
    ContactDBContext db;

    public ContactService (ContactDBContext db) {
        this.db = db
    }

    public async Task<List<ContactModel>> GetContacts() {
        var contacts = db.Contacts;

        //...convert to models

        //...
    }
}

The configuration applied at startup should now be included when the container resolves the context for injection.

Reference Configuring a DbContext


问:
Guarding resources with Singleton?
I have read quite a few blog posts and answers on SO pointing to Singleton being a bad design. Previously I implemented a singleton CameraControl class. This class controls a camera which is connected to the system. Under the following knowledge:

Under no circumstance will there be more than one camera (the camera API provided by the camera maker control all cameras).

Using the API of the camera maker in multiple places at the same time have caused problems in the past (e.g. one thread trying to grab an image, the other thread trying to set the shutter speed).

My class only provides several extra methods to display the image captured in a UI. Forward the image to a face detector, ... (i.e. it is not memory intensive).

Is my choice of making this class a singleton class a bad decision?

答:
You can read anything, sooner or later.  Regardless of what the
some people say, there's no fundamental reason against using
a singleton in the appropriate cases_.  In your case, I have
serious doubts, at least the way you describe it.  Regardless of
the API of the camera maker (which is probably in C), your
client code will want to treat each individual camera as
a separate object, and there's nothing inherantly unique about
cameras.

Where a singleton probably is appropriate here is if the API of
the camera maker is in C, and you decide to provide
a lightweight C++ wrapper for it, to be used (exclusively) by
your Camera classes.  Such light weight wrappers are one
legitimate use of singletons---there's no way in the world you
can have several instances of the library in your code.
(Usually, however, it's easier to have the Camera class address
the API directly, and skip the intermediate wrapper.)

Title: Guarding resources with Singleton?


问:
What is the use case of Styled-Components' .attrs() function?
I came across the .attrs() function in styled components, but I do not understand what it does, or what it does differently?

I tried to understand the example in their docs, but as far as I am concerned, I can do the exact same thing without the attrs() function.

Could somebody please explain this to me or give a simple example?

答:
The goal is to add new props/modify input props (as an HoC) only to a specific styled component.

Please notice:

As of styled-components v4 the withComponent API is now a candidate
  for deprecation. In all likelihood, you probably want to use the new
  "as" prop to simply switch what element/component being rendered since
  the withComponent API is destructive toward styles if the
  lowest-wrapped component is a StyledComponent.


问:
Why postgres "scan index(btree)" phase of plan returns all rows?
I have some misunderstanding with btree using Postgres 9.6.

I'm using SELECT max(total_amount) FROM bookings;

Total rows count 2111110, total_amount - numeric(10,2)

I have index on this column

```<code>CREATE INDEX ON bookings USING btree (total_amount);
</code>```

When I'm using explain I see:

And as I know Btree is ordered tree, so to find min key value you should go left from root to end, maximum - right

So why postgres gets all rows but not one from scan index node?

答: No it doesn't get all the rows - if you look closely there is a Limit step right above the Index Only Scan Backwards - and that estimates only 1 row. So the index scan stops after the first row that was retrieved from the index.

Body:
I have some misunderstanding with btree using Postgres 9.6.

I'm using SELECT max(total_amount) FROM bookings;

Total rows count 2111110, total_amount - numeric(10,2)

I have index on this column

CREATE INDEX ON bookings USING btree (total_amount);

When I'm using explain I see:

And as I know Btree is ordered tree, so to find min key value you should go left from root to end, maximum - right

So why postgres gets all rows but not one from scan index node?