问:
Extracting data from nested json document using tidyjson in R
I am querying a research publication database. Articles have different number of authors (ranging from 1 to more than 20). My goal is to create an edge list of co-authors for social network analysis using iGraph. Below is a snippet of json

```<code>{
"format": "linked-data-api",
"version": "0.2",
"result": {
"_about": "http://network.csiro.au:9500/standalone/publications.json?_pageSize=5&_page=1",
"definition": "http://network.csiro.au:9500/standalone/meta/publications.json",
"extendedMetadataVersion": "http://network.csiro.au:9500/standalone/publications.json?_pageSize=5&_page=1&_metadata=all",
"first": "http://network.csiro.au:9500/standalone/publications.json?_page=0",
"isPartOf": {
"_about": "http://network.csiro.au:9500/standalone/publications.json",
"definition": "http://network.csiro.au:9500/standalone/meta/publications.json",
"hasPart": "http://network.csiro.au:9500/standalone/publications.json?_pageSize=5&_page=1",
"type": [
"http://purl.org/linked-data/api/vocab#ListEndpoint"
]
},
"items": [
{
"_about": "http://network.csiro.au/data/pub_EP1312922",
"access": "Public",
"author": {
"_about": "http://network.csiro.au/data/aimee.slangen",
"hasName": {
"_about": "http://network.csiro.au/data/aimee.slangen_name",
"firstName": "Aimee",
"lastName": "Slangen",
"title": "Ms"
}
},
"authorSeq": {
"_about": "http://network.csiro.au/data/pub_EP1312922_author_0",
"author": {
"_about": "http://network.csiro.au/data/aimee.slangen",
"hasName": {
"_about": "http://network.csiro.au/data/aimee.slangen_name",
"firstName": "Aimee",
"lastName": "Slangen",
"title": "Ms"
}
},
"sequenceNumber": 0
},
"classification": {
"_about": "http://network.csiro.au/data/classification_code_040104",
"name": "Climate Change Processes"
},
"classificationLevel": "http://network.csiro.au/data/unclassified",
"journalTitle": "Journal of Geophysical Research-Oceans",
"keyword": " ",
"outcome": "Approved",
"pages": "156-164",
"project": "http://network.csiro.au/data/project_PD00003609",
"publicationVolume": "119",
"publishedDate": "9-Jan-2014",
"publisher": "American Geophysical Union",
"title": "Regional Differences of Relative Sea Level Changes in the Northwest Atlantic: Historical Trends and Future Projections",
"wbscode": "R-03426-01-003",
"yearOfPublication": "2014"
},
{
"_about": "http://network.csiro.au/data/pub_EP112347",
"access": "Public",
"author": {
"_about": "http://network.csiro.au/data/roland.pitcher",
"hasName": {
"_about": "http://network.csiro.au/data/roland.pitcher_name",
"firstName": "Roland",
"lastName": "Pitcher",
"title": "Dr"
}
},
"authorSeq": {
"_about": "http://network.csiro.au/data/pub_EP112347_author_0",
"author": {
"_about": "http://network.csiro.au/data/roland.pitcher",
"hasName": {
"_about": "http://network.csiro.au/data/roland.pitcher_name",
"firstName": "Roland",
"lastName": "Pitcher",
"title": "Dr"
}
},
"sequenceNumber": 0
},
"classification": {
"_about": "http://network.csiro.au/data/classification_code_050209",
"name": "Natural Resource Management"
},
"classificationLevel": "http://network.csiro.au/data/unclassified",
"keyword": " ",
"outcome": "Approved",
"project": "http://network.csiro.au/data/project_PD00000752",
"publisher": "Queensland Department of Environment and Resource Management",
"title": "Understanding and Managing the Effects of Trawling on the Seabed in the Great Barrier Reef",
"wbscode": "R-00654-03-003",
"yearOfPublication": " "
},
{
"_about": "http://network.csiro.au/data/pub_EP148991",
"access": "CSIRO Only",
"author": {
"_about": "http://network.csiro.au/data/rob.bramley",
"hasName": {
"_about": "http://network.csiro.au/data/rob.bramley_name",
"firstName": "Rob",
"lastName": "Bramley",
"title": "Dr"
}
},
"authorSeq": {
"_about": "http://network.csiro.au/data/pub_EP148991_author_0",
"author": {
"_about": "http://network.csiro.au/data/rob.bramley",
"hasName": {
"_about": "http://network.csiro.au/data/rob.bramley_name",
"firstName": "Rob",
"lastName": "Bramley",
"title": "Dr"
}
},
"sequenceNumber": 0
},
"classification": {
"_about": "http://network.csiro.au/data/classification_code_070107",
"name": "Farming Systems Research"
},
"classificationLevel": "http://network.csiro.au/data/unclassified",
"keyword": " ",
"outcome": "Approved",
"pages": "26 + appendices",
"project": "http://network.csiro.au/data/project_PD00002886",
"publishedDate": "17-Sep-2014",
"publisher": "SRA",
"title": "A collaborative approach to Precision Agriculture RDE for the Australian Sugar Industry",
"wbscode": "R-02709-01",
"yearOfPublication": "2014"
},
{
"_about": "http://network.csiro.au/data/pub_EP151976",
"access": "Public",
"author": {
"_about": "http://network.csiro.au/data/paul.krummel",
"hasName": {
"_about": "http://network.csiro.au/data/paul.krummel_name",
"firstName": "Paul",
"lastName": "Krummel",
"title": "Mr"
}
},
"authorSeq": {
"_about": "http://network.csiro.au/data/pub_EP151976_author_0",
"author": {
"_about": "http://network.csiro.au/data/paul.krummel",
"hasName": {
"_about": "http://network.csiro.au/data/paul.krummel_name",
"firstName": "Paul",
"lastName": "Krummel",
"title": "Mr"
}
},
"sequenceNumber": 0
},
"classification": [
{
"_about": "http://network.csiro.au/data/classification_code_040104",
"name": "Climate Change Processes"
},
{
"_about": "http://network.csiro.au/data/classification_code_040199",
"name": "Atmospheric Sciences not elsewhere classified"
}
],
"classificationLevel": "http://network.csiro.au/data/unclassified",
"journalTitle": "Atmospheric Chemistry and Physics",
"keyword": [
"CH4",
"OH",
"hydroxyl radical",
"methane"
],
"outcome": "Approved",
"pages": "7943\u20137956",
"project": "http://network.csiro.au/data/project_PD00009165",
"publicationVolume": "16",
"publishedDate": "30-Jun-2016",
"publisher": "Copernicus GmbH",
"title": "Role of OH variability in the stalling of the global atmospheric CH4 growth rate from 1999 to 2006",
"wbscode": "R-07848; R-06420; R-07768",
"yearOfPublication": "2016"
},
{
"_about": "http://network.csiro.au/data/pub_EP152677",
"access": "CSIRO Only",
"author": [
{
"_about": "http://network.csiro.au/data/andrew.george",
"hasName": {
"_about": "http://network.csiro.au/data/andrew.george_name",
"firstName": "Andrew",
"lastName": "George",
"title": "Dr"
}
},
{
"_about": "http://network.csiro.au/data/sigrid.lehnert",
"hasName": {
"_about": "http://network.csiro.au/data/sigrid.lehnert_name",
"firstName": "Sigrid",
"lastName": "Lehnert",
"title": "Dr"
}
},
{
"_about": "http://network.csiro.au/data/toni.reverter-gomez",
"hasName": {
"_about": "http://network.csiro.au/data/toni.reverter-gomez_name",
"firstName": "Toni",
"lastName": "Reverter-Gomez",
"title": "Dr"
}
},
{
"_about": "http://network.csiro.au/data/yutao.li",
"hasName": {
"_about": "http://network.csiro.au/data/yutao.li_name",
"firstName": "Yutao",
"lastName": "Li",
"title": "Dr"
}
}
],
"authorSeq": [
{
"_about": "http://network.csiro.au/data/pub_EP152677_author_0",
"author": {
"_about": "http://network.csiro.au/data/yutao.li",
"hasName": {
"_about": "http://network.csiro.au/data/yutao.li_name",
"firstName": "Yutao",
"lastName": "Li",
"title": "Dr"
}
},
"sequenceNumber": 0
},
{
"_about": "http://network.csiro.au/data/pub_EP152677_author_1",
"author": {
"_about": "http://network.csiro.au/data/andrew.george",
"hasName": {
"_about": "http://network.csiro.au/data/andrew.george_name",
"firstName": "Andrew",
"lastName": "George",
"title": "Dr"
}
},
"sequenceNumber": 1
},
{
"_about": "http://network.csiro.au/data/pub_EP152677_author_2",
"author": {
"_about": "http://network.csiro.au/data/sigrid.lehnert",
"hasName": {
"_about": "http://network.csiro.au/data/sigrid.lehnert_name",
"firstName": "Sigrid",
"lastName": "Lehnert",
"title": "Dr"
}
},
"sequenceNumber": 2
},
{
"_about": "http://network.csiro.au/data/pub_EP152677_author_3",
"author": {
"_about": "http://network.csiro.au/data/toni.reverter-gomez",
"hasName": {
"_about": "http://network.csiro.au/data/toni.reverter-gomez_name",
"firstName": "Toni",
"lastName": "Reverter-Gomez",
"title": "Dr"
}
},
"sequenceNumber": 3
}
],
"classification": {
"_about": "http://network.csiro.au/data/classification_code_070201",
"name": "Animal Breeding"
},
"classificationLevel": "http://network.csiro.au/data/unclassified",
"conferenceDate": "28th-30th September 2015",
"conferenceLocation": "Lorne, Victoria",
"conferenceName": "21st AAABG",
"keyword": " ",
"outcome": "Approved",
"pages": "433-436",
"project": "http://network.csiro.au/data/project_PD00005603",
"publicationVolume": "21",
"publishedDate": "25-Sep-2015",
"publisher": "Association for the Advancement of Animal Breeding and Genetics",
"title": "Using Random Forests to Identify SNP Associated With Leg Defect in Broiler Chicken: Impact of Correcting For Population Structures",
"wbscode": "R-05156",
"yearOfPublication": "2015"
}
],
"itemsPerPage": 5,
"next": "http://network.csiro.au:9500/standalone/publications.json?_page=2",
"page": 1,
"prev": "http://network.csiro.au:9500/standalone/publications.json?_page=0",
"startIndex": 6,
"totalResults": 47023,
"type": [
"http://purl.org/linked-data/api/vocab#Page"
]
}
}
</code>```

I am read the data in as follows:

```<code>library(jsonlite)
library(tidyjson)
pubs <- fromJSON("http://network.csiro.au:9500/standalone/publications.json?_page=1&_pageSize=5")
</code>```

When trying to extract meaningful data using tidyjson, I get this error:

```<code>pubs %>%
  as.tbl_json %>%
  enter_object("items")

Error in UseMethod("as.tbl_json") :
  no applicable method for 'as.tbl_json' applied to an object of class "list"
</code>```

I am not an expert in R or JSON so would appreciate some guidance. Using the above example, I want to create for each publication an edge list of co-authors like this:

```<code>_about                                    yearOfPublication from            to
http://network.url.com/data/pub_EP16079   2011              Colin Jackson   Holly Trueman
http://network.url.com/data/pub_EP16079   2011              Colin Jackson   Tara Sutherland
http://network.url.com/data/pub_EP16079   2011              Colin Jackson   Trevor Rapson
http://network.url.com/data/pub_EP16079   2011              Holly Trueman   Tara Sutherland
http://network.url.com/data/pub_EP16079   2011              Holly Trueman   Trevor Rapson
http://network.url.com/data/pub_EP16079   2011              Tara Sutherland Trevor Rapson
</code>```

I hope someone can help me! Thanks in advance.

答:
This is a bit of a tricky example.  See this issue for discussion on how to improve how tidyjson handles objects that are sometimes arrays.

While not the cleanest solution, I think this does get the job done - you could probably functionalize some of these groups of steps to optimize code-reuse.

The basic aim is to parse enough of the object to get to the authors, then use a separate work-flow for objects and arrays.  The arrays require tidyr::expand to complete the combinations of all authors (since those combinations are not represented in the data)

```<code>json <- paste(readLines("ex.json"), collapse = " ")

library(dplyr)
library(tidyjson)
library(tidyr)

## parse the objects.  Notice some publications have objects representing a
## single author, others have an array of many authors
prep <- json %>%
 enter_object("result") %>%
 enter_object("items") %>%
 gather_array() %>%
 spread_values(
   about = jstring("_about")
   , yearOfPublication = jstring(yearOfPublication)
 ) %>%
 enter_object("author") %>%
 json_types()

## parse object types
authorobj <- prep %>%
filter(as.character(type) == "object") %>%
spread_values(
 authorFirst = jstring(hasName, firstName)
 , authorLast = jstring(hasName, lastName)
) %>%
mutate(from = paste(authorFirst, authorLast), to = from) %>%
select(-authorFirst, -authorLast) %>%
tbl_df()

## parse array types - get 'from' authors
authorarr <- prep %>%
filter(as.character(type) == "array") %>%
gather_array("authorid") %>%
spread_values(
 authorFirst = jstring(hasName, firstName)
 , authorLast = jstring(hasName, lastName)
) %>%
mutate(from = paste(authorFirst, authorLast)) %>%
select(-authorFirst, -authorLast)

## use tidyr::expand to complete combinations of from/to
authorarr <- authorarr %>%
tbl_df() %>%
left_join(
  authorarr %>%
   group_by(array.index) %>%
   expand(from = authorarr$from, to = authorarr$from) %>%
   ungroup()
  , by = c("array.index", "from"))

## stack (select only a few columns for display)
dplyr::bind_rows(authorobj, authorarr) %>%
 select(array.index, from, to)
#> # A tibble: 20 x 3
#>    array.index                from                  to
#>          <int>               <chr>               <chr>
#>  1           1       Aimee Slangen       Aimee Slangen
#>  2           2      Roland Pitcher      Roland Pitcher
#>  3           3         Rob Bramley         Rob Bramley
#>  4           4        Paul Krummel        Paul Krummel
#>  5           5       Andrew George       Andrew George
#>  6           5       Andrew George      Sigrid Lehnert
#>  7           5       Andrew George Toni Reverter-Gomez
#>  8           5       Andrew George            Yutao Li
#>  9           5      Sigrid Lehnert       Andrew George
#> 10           5      Sigrid Lehnert      Sigrid Lehnert
#> 11           5      Sigrid Lehnert Toni Reverter-Gomez
#> 12           5      Sigrid Lehnert            Yutao Li
#> 13           5 Toni Reverter-Gomez       Andrew George
#> 14           5 Toni Reverter-Gomez      Sigrid Lehnert
#> 15           5 Toni Reverter-Gomez Toni Reverter-Gomez
#> 16           5 Toni Reverter-Gomez            Yutao Li
#> 17           5            Yutao Li       Andrew George
#> 18           5            Yutao Li      Sigrid Lehnert
#> 19           5            Yutao Li Toni Reverter-Gomez
#> 20           5            Yutao Li            Yutao Li
</code>```

Body:
I am querying a research publication database. Articles have different number of authors (ranging from 1 to more than 20). My goal is to create an edge list of co-authors for social network analysis using iGraph. Below is a snippet of json

{
"format": "linked-data-api",
"version": "0.2",
"result": {
"_about": "http://network.csiro.au:9500/standalone/publications.json?_pageSize=5&_page=1",
"definition": "http://network.csiro.au:9500/standalone/meta/publications.json",
"extendedMetadataVersion": "http://network.csiro.au:9500/standalone/publications.json?_pageSize=5&_page=1&_metadata=all",
"first": "http://network.csiro.au:9500/standalone/publications.json?_page=0",
"isPartOf": {
"_about": "http://network.csiro.au:9500/standalone/publications.json",
"definition": "http://network.csiro.au:9500/standalone/meta/publications.json",
"hasPart": "http://network.csiro.au:9500/standalone/publications.json?_pageSize=5&_page=1",
"type": [
"http://purl.org/linked-data/api/vocab#ListEndpoint"
]
},
"items": [
{
"_about": "http://network.csiro.au/data/pub_EP1312922",
"access": "Public",
"author": {
"_about": "http://network.csiro.au/data/aimee.slangen",
"hasName": {
"_about": "http://network.csiro.au/data/aimee.slangen_name",
"firstName": "Aimee",
"lastName": "Slangen",
"title": "Ms"
}
},
"authorSeq": {
"_about": "http://network.csiro.au/data/pub_EP1312922_author_0",
"author": {
"_about": "http://network.csiro.au/data/aimee.slangen",
"hasName": {
"_about": "http://network.csiro.au/data/aimee.slangen_name",
"firstName": "Aimee",
"lastName": "Slangen",
"title": "Ms"
}
},
"sequenceNumber": 0
},
"classification": {
"_about": "http://network.csiro.au/data/classification_code_040104",
"name": "Climate Change Processes"
},
"classificationLevel": "http://network.csiro.au/data/unclassified",
"journalTitle": "Journal of Geophysical Research-Oceans",
"keyword": " ",
"outcome": "Approved",
"pages": "156-164",
"project": "http://network.csiro.au/data/project_PD00003609",
"publicationVolume": "119",
"publishedDate": "9-Jan-2014",
"publisher": "American Geophysical Union",
"title": "Regional Differences of Relative Sea Level Changes in the Northwest Atlantic: Historical Trends and Future Projections",
"wbscode": "R-03426-01-003",
"yearOfPublication": "2014"
},
{
"_about": "http://network.csiro.au/data/pub_EP112347",
"access": "Public",
"author": {
"_about": "http://network.csiro.au/data/roland.pitcher",
"hasName": {
"_about": "http://network.csiro.au/data/roland.pitcher_name",
"firstName": "Roland",
"lastName": "Pitcher",
"title": "Dr"
}
},
"authorSeq": {
"_about": "http://network.csiro.au/data/pub_EP112347_author_0",
"author": {
"_about": "http://network.csiro.au/data/roland.pitcher",
"hasName": {
"_about": "http://network.csiro.au/data/roland.pitcher_name",
"firstName": "Roland",
"lastName": "Pitcher",
"title": "Dr"
}
},
"sequenceNumber": 0
},
"classification": {
"_about": "http://network.csiro.au/data/classification_code_050209",
"name": "Natural Resource Management"
},
"classificationLevel": "http://network.csiro.au/data/unclassified",
"keyword": " ",
"outcome": "Approved",
"project": "http://network.csiro.au/data/project_PD00000752",
"publisher": "Queensland Department of Environment and Resource Management",
"title": "Understanding and Managing the Effects of Trawling on the Seabed in the Great Barrier Reef",
"wbscode": "R-00654-03-003",
"yearOfPublication": " "
},
{
"_about": "http://network.csiro.au/data/pub_EP148991",
"access": "CSIRO Only",
"author": {
"_about": "http://network.csiro.au/data/rob.bramley",
"hasName": {
"_about": "http://network.csiro.au/data/rob.bramley_name",
"firstName": "Rob",
"lastName": "Bramley",
"title": "Dr"
}
},
"authorSeq": {
"_about": "http://network.csiro.au/data/pub_EP148991_author_0",
"author": {
"_about": "http://network.csiro.au/data/rob.bramley",
"hasName": {
"_about": "http://network.csiro.au/data/rob.bramley_name",
"firstName": "Rob",
"lastName": "Bramley",
"title": "Dr"
}
},
"sequenceNumber": 0
},
"classification": {
"_about": "http://network.csiro.au/data/classification_code_070107",
"name": "Farming Systems Research"
},
"classificationLevel": "http://network.csiro.au/data/unclassified",
"keyword": " ",
"outcome": "Approved",
"pages": "26 + appendices",
"project": "http://network.csiro.au/data/project_PD00002886",
"publishedDate": "17-Sep-2014",
"publisher": "SRA",
"title": "A collaborative approach to Precision Agriculture RDE for the Australian Sugar Industry",
"wbscode": "R-02709-01",
"yearOfPublication": "2014"
},
{
"_about": "http://network.csiro.au/data/pub_EP151976",
"access": "Public",
"author": {
"_about": "http://network.csiro.au/data/paul.krummel",
"hasName": {
"_about": "http://network.csiro.au/data/paul.krummel_name",
"firstName": "Paul",
"lastName": "Krummel",
"title": "Mr"
}
},
"authorSeq": {
"_about": "http://network.csiro.au/data/pub_EP151976_author_0",
"author": {
"_about": "http://network.csiro.au/data/paul.krummel",
"hasName": {
"_about": "http://network.csiro.au/data/paul.krummel_name",
"firstName": "Paul",
"lastName": "Krummel",
"title": "Mr"
}
},
"sequenceNumber": 0
},
"classification": [
{
"_about": "http://network.csiro.au/data/classification_code_040104",
"name": "Climate Change Processes"
},
{
"_about": "http://network.csiro.au/data/classification_code_040199",
"name": "Atmospheric Sciences not elsewhere classified"
}
],
"classificationLevel": "http://network.csiro.au/data/unclassified",
"journalTitle": "Atmospheric Chemistry and Physics",
"keyword": [
"CH4",
"OH",
"hydroxyl radical",
"methane"
],
"outcome": "Approved",
"pages": "7943\u20137956",
"project": "http://network.csiro.au/data/project_PD00009165",
"publicationVolume": "16",
"publishedDate": "30-Jun-2016",
"publisher": "Copernicus GmbH",
"title": "Role of OH variability in the stalling of the global atmospheric CH4 growth rate from 1999 to 2006",
"wbscode": "R-07848; R-06420; R-07768",
"yearOfPublication": "2016"
},
{
"_about": "http://network.csiro.au/data/pub_EP152677",
"access": "CSIRO Only",
"author": [
{
"_about": "http://network.csiro.au/data/andrew.george",
"hasName": {
"_about": "http://network.csiro.au/data/andrew.george_name",
"firstName": "Andrew",
"lastName": "George",
"title": "Dr"
}
},
{
"_about": "http://network.csiro.au/data/sigrid.lehnert",
"hasName": {
"_about": "http://network.csiro.au/data/sigrid.lehnert_name",
"firstName": "Sigrid",
"lastName": "Lehnert",
"title": "Dr"
}
},
{
"_about": "http://network.csiro.au/data/toni.reverter-gomez",
"hasName": {
"_about": "http://network.csiro.au/data/toni.reverter-gomez_name",
"firstName": "Toni",
"lastName": "Reverter-Gomez",
"title": "Dr"
}
},
{
"_about": "http://network.csiro.au/data/yutao.li",
"hasName": {
"_about": "http://network.csiro.au/data/yutao.li_name",
"firstName": "Yutao",
"lastName": "Li",
"title": "Dr"
}
}
],
"authorSeq": [
{
"_about": "http://network.csiro.au/data/pub_EP152677_author_0",
"author": {
"_about": "http://network.csiro.au/data/yutao.li",
"hasName": {
"_about": "http://network.csiro.au/data/yutao.li_name",
"firstName": "Yutao",
"lastName": "Li",
"title": "Dr"
}
},
"sequenceNumber": 0
},
{
"_about": "http://network.csiro.au/data/pub_EP152677_author_1",
"author": {
"_about": "http://network.csiro.au/data/andrew.george",
"hasName": {
"_about": "http://network.csiro.au/data/andrew.george_name",
"firstName": "Andrew",
"lastName": "George",
"title": "Dr"
}
},
"sequenceNumber": 1
},
{
"_about": "http://network.csiro.au/data/pub_EP152677_author_2",
"author": {
"_about": "http://network.csiro.au/data/sigrid.lehnert",
"hasName": {
"_about": "http://network.csiro.au/data/sigrid.lehnert_name",
"firstName": "Sigrid",
"lastName": "Lehnert",
"title": "Dr"
}
},
"sequenceNumber": 2
},
{
"_about": "http://network.csiro.au/data/pub_EP152677_author_3",
"author": {
"_about": "http://network.csiro.au/data/toni.reverter-gomez",
"hasName": {
"_about": "http://network.csiro.au/data/toni.reverter-gomez_name",
"firstName": "Toni",
"lastName": "Reverter-Gomez",
"title": "Dr"
}
},
"sequenceNumber": 3
}
],
"classification": {
"_about": "http://network.csiro.au/data/classification_code_070201",
"name": "Animal Breeding"
},
"classificationLevel": "http://network.csiro.au/data/unclassified",
"conferenceDate": "28th-30th September 2015",
"conferenceLocation": "Lorne, Victoria",
"conferenceName": "21st AAABG",
"keyword": " ",
"outcome": "Approved",
"pages": "433-436",
"project": "http://network.csiro.au/data/project_PD00005603",
"publicationVolume": "21",
"publishedDate": "25-Sep-2015",
"publisher": "Association for the Advancement of Animal Breeding and Genetics",
"title": "Using Random Forests to Identify SNP Associated With Leg Defect in Broiler Chicken: Impact of Correcting For Population Structures",
"wbscode": "R-05156",
"yearOfPublication": "2015"
}
],
"itemsPerPage": 5,
"next": "http://network.csiro.au:9500/standalone/publications.json?_page=2",
"page": 1,
"prev": "http://network.csiro.au:9500/standalone/publications.json?_page=0",
"startIndex": 6,
"totalResults": 47023,
"type": [
"http://purl.org/linked-data/api/vocab#Page"
]
}
}

I am read the data in as follows:

library(jsonlite)
library(tidyjson)
pubs <- fromJSON("http://network.csiro.au:9500/standalone/publications.json?_page=1&_pageSize=5")

When trying to extract meaningful data using tidyjson, I get this error:

pubs %>%
  as.tbl_json %>%
  enter_object("items")

Error in UseMethod("as.tbl_json") :
  no applicable method for 'as.tbl_json' applied to an object of class "list"

I am not an expert in R or JSON so would appreciate some guidance. Using the above example, I want to create for each publication an edge list of co-authors like this:

_about                                    yearOfPublication from            to
http://network.url.com/data/pub_EP16079   2011              Colin Jackson   Holly Trueman
http://network.url.com/data/pub_EP16079   2011              Colin Jackson   Tara Sutherland
http://network.url.com/data/pub_EP16079   2011              Colin Jackson   Trevor Rapson
http://network.url.com/data/pub_EP16079   2011              Holly Trueman   Tara Sutherland
http://network.url.com/data/pub_EP16079   2011              Holly Trueman   Trevor Rapson
http://network.url.com/data/pub_EP16079   2011              Tara Sutherland Trevor Rapson

I hope someone can help me! Thanks in advance.

Body:
This is a bit of a tricky example.  See this issue for discussion on how to improve how tidyjson handles objects that are sometimes arrays.

While not the cleanest solution, I think this does get the job done - you could probably functionalize some of these groups of steps to optimize code-reuse.

The basic aim is to parse enough of the object to get to the authors, then use a separate work-flow for objects and arrays.  The arrays require tidyr::expand to complete the combinations of all authors (since those combinations are not represented in the data)

json <- paste(readLines("ex.json"), collapse = " ")

library(dplyr)
library(tidyjson)
library(tidyr)

## parse the objects.  Notice some publications have objects representing a
## single author, others have an array of many authors
prep <- json %>%
 enter_object("result") %>%
 enter_object("items") %>%
 gather_array() %>%
 spread_values(
   about = jstring("_about")
   , yearOfPublication = jstring(yearOfPublication)
 ) %>%
 enter_object("author") %>%
 json_types()

## parse object types
authorobj <- prep %>%
filter(as.character(type) == "object") %>%
spread_values(
 authorFirst = jstring(hasName, firstName)
 , authorLast = jstring(hasName, lastName)
) %>%
mutate(from = paste(authorFirst, authorLast), to = from) %>%
select(-authorFirst, -authorLast) %>%
tbl_df()

## parse array types - get 'from' authors
authorarr <- prep %>%
filter(as.character(type) == "array") %>%
gather_array("authorid") %>%
spread_values(
 authorFirst = jstring(hasName, firstName)
 , authorLast = jstring(hasName, lastName)
) %>%
mutate(from = paste(authorFirst, authorLast)) %>%
select(-authorFirst, -authorLast)

## use tidyr::expand to complete combinations of from/to
authorarr <- authorarr %>%
tbl_df() %>%
left_join(
  authorarr %>%
   group_by(array.index) %>%
   expand(from = authorarr$from, to = authorarr$from) %>%
   ungroup()
  , by = c("array.index", "from"))

## stack (select only a few columns for display)
dplyr::bind_rows(authorobj, authorarr) %>%
 select(array.index, from, to)
#> # A tibble: 20 x 3
#>    array.index                from                  to
#>          <int>               <chr>               <chr>
#>  1           1       Aimee Slangen       Aimee Slangen
#>  2           2      Roland Pitcher      Roland Pitcher
#>  3           3         Rob Bramley         Rob Bramley
#>  4           4        Paul Krummel        Paul Krummel
#>  5           5       Andrew George       Andrew George
#>  6           5       Andrew George      Sigrid Lehnert
#>  7           5       Andrew George Toni Reverter-Gomez
#>  8           5       Andrew George            Yutao Li
#>  9           5      Sigrid Lehnert       Andrew George
#> 10           5      Sigrid Lehnert      Sigrid Lehnert
#> 11           5      Sigrid Lehnert Toni Reverter-Gomez
#> 12           5      Sigrid Lehnert            Yutao Li
#> 13           5 Toni Reverter-Gomez       Andrew George
#> 14           5 Toni Reverter-Gomez      Sigrid Lehnert
#> 15           5 Toni Reverter-Gomez Toni Reverter-Gomez
#> 16           5 Toni Reverter-Gomez            Yutao Li
#> 17           5            Yutao Li       Andrew George
#> 18           5            Yutao Li      Sigrid Lehnert
#> 19           5            Yutao Li Toni Reverter-Gomez
#> 20           5            Yutao Li            Yutao Li


来源: stackexchange

答:
Just throwing my attempt in the mix:

```<code>list1 = [["a","b"],["c","d"]]
list2 = [["a","1"],["c","2"]]
list3 = [(sub + [list2[i][-1]]) for i, sub in enumerate(list1)]
#[['a', 'b', '1'], ['c', 'd', '2']]
</code>```

This is pretty close to @A-B-B's though if zip uses enumerate.

ContentLicense: CC BY-SA 3.0

Title: Merge two multidimensional lists into one list in Python

Body:
I have two lists:

a_list =
[['2017-06-03 23:01:49', 0], ['2017-06-03 23:02:49', 712.32], ['2017-06-03 23:03:49', 501.21].......]

b_list =
[['2017-06-03 23:01:49', 100.01], ['2017-06-03 23:02:49', 50.01], ['2017-06-03 23:03:49', 521.79].......]

I need to merge a_list with b_list so it becomes:

combined_list =
[['2017-06-03 23:01:49', 0, 100,01], ['2017-06-03 23:02:49', 712.32, 50.01], ['2017-06-03 23:03:49', 501.21, 521.79].......]

How would I achieve this?

Body:
Just throwing my attempt in the mix:

list1 = [["a","b"],["c","d"]]
list2 = [["a","1"],["c","2"]]
list3 = [(sub + [list2[i][-1]]) for i, sub in enumerate(list1)]
#[['a', 'b', '1'], ['c', 'd', '2']]

This is pretty close to @A-B-B's though if zip uses enumerate.


问:
rethinkdb check if record exists
Here is an example:

```<code>r.db('my_db').table('my_table').get('my_record_id_123')
</code>```

The above code works fine, but returns the record. The records in this table are huge. Is there a way to check if the record with that specific id exists or not without returning the record itself?

答:
returns number</p>

```<code>r.db('my_db')
  .table('my_table')
  .count(function(user){
    return user('id').eq(1121)
  })
</code>```

Title: rethinkdb check if record exists

Body:
Here is an example:

r.db('my_db').table('my_table').get('my_record_id_123')

The above code works fine, but returns the record. The records in this table are huge. Is there a way to check if the record with that specific id exists or not without returning the record itself?

Body:
returns number

r.db('my_db')
  .table('my_table')
  .count(function(user){
    return user('id').eq(1121)
  })


问:
perl: sort arrayref inside a hashref
I have the following structure:

```<code>my $hsh = {
  arr => [
    1,
    3,
    6,
    4,
    2
  ]
}
</code>```

I want to sort $hsh->{arr}, but I can't figure out how.  sort $h->{arr} doesn't work.

Title: perl: sort arrayref inside a hashref

Body:
I have the following structure:

my $hsh = {
  arr => [
    1,
    3,
    6,
    4,
    2
  ]
}

I want to sort $hsh->{arr}, but I can't figure out how.  sort $h->{arr} doesn't work.

Body: $hsh->{arr} = [sort @{$hsh->{arr}}];


问:
Make TypeScript produce prototypes for ES6
Is it possible within the latest TypeScript to make specific class methods to be prototypes, even though the general target is ES6?

And as a side question - to have a specific class produce prototypes only.

Example of a TypeScript class:

```<code>class Test {
    constructor() {
    }

    methodName() {
    }
}
</code>```

For ES6 as the general target it produces the same JavaScript code, while I want it to be:

```<code>class Test {
    constructor() {
    }
}

Test.prototype.methodName = function () {
}
</code>```

i.e. either for a specific method or for all methods within the class I want to get prototypes instead, despite using ES6 as the general target.

The main reason for asking is as follows. I have a module that needs to create a very large number of such class instances, and after reading many posts here it seems the consensus is that prototypes will perform better in such a case:

Javascript prototype operator performance

Defining methods via prototype vs using this in the constructor

P.S. I'm mostly interested in the server-side of things, i.e. Node.js 4-8.

答:
When this code

```<code>class Test {
    constructor() {
    }

    methodName() {
    }
}
</code>```

is executed in es6-capable runtime, methodName is defined on the prototype:

```<code>console.log(typeof Test.prototype.methodName)
VM153:1 function
</code>```

UPDATE

I created very simple test to compare performance of method defined in the class vs. assigned on the prototype. If jsperf results are to be believed, calling class method is 5% slower in Chrome 58, but prototype is 14 % slower in Firefox.

I'd suggest running actual performance tests with real data from your use cases, then filing appropriate bugs for Chrome and/or Firefox.

Body:
Is it possible within the latest TypeScript to make specific class methods to be prototypes, even though the general target is ES6?

And as a side question - to have a specific class produce prototypes only.

Example of a TypeScript class:

class Test {
    constructor() {
    }

    methodName() {
    }
}

For ES6 as the general target it produces the same JavaScript code, while I want it to be:

class Test {
    constructor() {
    }
}

Test.prototype.methodName = function () {
}

i.e. either for a specific method or for all methods within the class I want to get prototypes instead, despite using ES6 as the general target.

The main reason for asking is as follows. I have a module that needs to create a very large number of such class instances, and after reading many posts here it seems the consensus is that prototypes will perform better in such a case:

Javascript prototype operator performance

Defining methods via prototype vs using this in the constructor

P.S. I'm mostly interested in the server-side of things, i.e. Node.js 4-8.

Body:
When this code

class Test {
    constructor() {
    }

    methodName() {
    }
}

is executed in es6-capable runtime, methodName is defined on the prototype:

console.log(typeof Test.prototype.methodName)
VM153:1 function

UPDATE

I created very simple test to compare performance of method defined in the class vs. assigned on the prototype. If jsperf results are to be believed, calling class method is 5% slower in Chrome 58, but prototype is 14 % slower in Firefox.

I'd suggest running actual performance tests with real data from your use cases, then filing appropriate bugs for Chrome and/or Firefox.


问:
C# Is it possible to replace my dictionary class with the contents of a text file?
For example, in a file of my project I have Dictionaries.cs containing:

```<code> public DictionaryInit() {

        public Dictionary<int, DictionaryCheckup> H = new Dictionary<int, DictionaryCheckup>()
        {
            {180000, new DictionaryCheckup {theGrouping="H"}},
            {180001, new DictionaryCheckup {theGrouping="H"}},
            {180303, new DictionaryCheckup {theGrouping="H"}},
        };

     public Dictionary<int, DictionaryCheckup> C = new Dictionary<int, DictionaryCheckup>()
        {
            {180700, new DictionaryCheckup {theGrouping="C"}},
            {180201, new DictionaryCheckup {theGrouping="C"}},
            {180503, new DictionaryCheckup {theGrouping="C"}},
        };

      Etc.
     }
</code>```

(DictionaryCheckup is a class that get;set; the string theGrouping)

The idea is that I wanted to allow my end user to hot swap a criteria, which is the dictionary class in question. Should he need to add a Dictionary U, he will simply need to copy the structure in the text file, replace the Key or Value where necessary, and then select it from the program. This loads it and replaces my dictionary class at runtime. Is this possible?

After some research, I found that Json and serialization is a method of doing this, but I'm not so  familiar with it, or if there's any difference from reading a text file. Here is a thread I found: How do I read and write a C# string Dictionary to a file?.

In these examples, i'm not sure how they differentiate a key from a value. Furthermore, I don't think I will be able to access my DictionaryCheckup class through this, which is the criteria the Key is valued to.

So, my question is whether I can, for simplicity, write my dictionary class, perhaps as-is, to a text file of some sort, and then load it up at runtime? Or would I have to create a var dictionary, and then add keys and values to it based on the external file? I'll probably look into the Json method anyway of seralization, I'm just worried about implementing a web function when my program has nothing to do with it.

答:
how they differentiate a key from a value

From the format. If you try any of those steps, the resulting file clearly differentiate between the keys & values.

I don't think I will be able to access my DictionaryCheckup class through this

You will be able to. If you use JavaScriptSerializer, just make sure you follow the requirement, similar requirement exist for JSON.NET. Of course, the Linq to XML answer have to be modified if you have complex type.

write my dictionary class, perhaps as-is, to a text file of some sort, and then load it up at runtime?

Yes, you can just deserialize the collection at once, no need to create the empty collection and fill it one by one. This is true for all serialization method.

Body:
For example, in a file of my project I have Dictionaries.cs containing:

 public DictionaryInit() {

        public Dictionary<int, DictionaryCheckup> H = new Dictionary<int, DictionaryCheckup>()
        {
            {180000, new DictionaryCheckup {theGrouping="H"}},
            {180001, new DictionaryCheckup {theGrouping="H"}},
            {180303, new DictionaryCheckup {theGrouping="H"}},
        };

     public Dictionary<int, DictionaryCheckup> C = new Dictionary<int, DictionaryCheckup>()
        {
            {180700, new DictionaryCheckup {theGrouping="C"}},
            {180201, new DictionaryCheckup {theGrouping="C"}},
            {180503, new DictionaryCheckup {theGrouping="C"}},
        };

      Etc.
     }

(DictionaryCheckup is a class that get;set; the string theGrouping)

The idea is that I wanted to allow my end user to hot swap a criteria, which is the dictionary class in question. Should he need to add a Dictionary U, he will simply need to copy the structure in the text file, replace the Key or Value where necessary, and then select it from the program. This loads it and replaces my dictionary class at runtime. Is this possible?

After some research, I found that Json and serialization is a method of doing this, but I'm not so  familiar with it, or if there's any difference from reading a text file. Here is a thread I found: How do I read and write a C# string Dictionary to a file?.

In these examples, i'm not sure how they differentiate a key from a value. Furthermore, I don't think I will be able to access my DictionaryCheckup class through this, which is the criteria the Key is valued to.

So, my question is whether I can, for simplicity, write my dictionary class, perhaps as-is, to a text file of some sort, and then load it up at runtime? Or would I have to create a var dictionary, and then add keys and values to it based on the external file? I'll probably look into the Json method anyway of seralization, I'm just worried about implementing a web function when my program has nothing to do with it.


问:
echo 'the character - (dash) in the unix command line
This is an extremely simple question that had absolutely nothing related on the internet no matter what.
How do I print a single dash with the echo command? I tried escaping it with '\', '/', '-', '%' and even '#', but it seemed it refused to print a simple, single dash character nonetheless. I tried it with a single quote, double quote or no quote at all, but it seems that this simply isn't possible with echo. Nothing on the man page nor anywhere else, for that matter, can someone please tell me how to do this?
To make things absolutely clear: I want to use echo '-' (or anything like this ) and get a single dash - as output</p>

答:
echo - works on my system.
Linux and bash.


问:
Changing $row values to integer decimals on PHP
I'm trying to recreate something like this: http://www.coincap.io/

It's working so far, but I'm having trouble to display the numbers as decimals (.0000). If I try to do it inside a cell (<?= $row->price; ?>	, for example), it messes with my table layout. Is there a way to set individual objects to display decimals differently?
Such as that price: .0000, volume: .00, and so on.

```<code><table>
    <thead>
        <tr>
            <th>#Rank</th>
            <th>Name</th>
            <th>Price</th>
            <th>Market Cap</th>
            <th>Volume</th>
            <th>Supply</th>
            <th>24h(%)</th>
        </tr>
    </thead>
    <tbody>
        <?php function compare($a, $b) {
            return intval($a->position24) - intval($b->position24);
        }

        $json = file_get_contents('http://www.coincap.io/front');
        $data = json_decode($json);
        usort($data, 'compare');
        ?>
        <?php foreach ($data as $row) { ?>
        <tr>
            <td><?= $row->position24; ?></td>
            <td><?= $row->long; ?></td>
            <td><?= $row->price; ?></td>
            <td><?= $row->mktcap; ?></td>
            <td><?= $row->volume; ?></td>
            <td><?= $row->supply; ?></td>
            <td><?= $row->cap24hrChangePercent; ?></td>
        </tr>
        <?php } ?>
    </tbody>
</table>
</code>```

答:
You can use number_format Here is a number_format sample.</p>

```<code>echo number_format(110000,2); // 110,000.00
</code>```

Body:
I'm trying to recreate something like this: http://www.coincap.io/

It's working so far, but I'm having trouble to display the numbers as decimals (.0000). If I try to do it inside a cell (<?= $row->price; ?>	, for example), it messes with my table layout. Is there a way to set individual objects to display decimals differently?
Such as that price: .0000, volume: .00, and so on.

            #Rank
            Name
            Price
            Market Cap
            Volume
            Supply
            24h(%)

        <?php function compare($a, $b) {
            return intval($a->position24) - intval($b->position24);
        }

        $json = file_get_contents('http://www.coincap.io/front');
        $data = json_decode($json);
        usort($data, 'compare');
        ?>
        <?php foreach ($data as $row) { ?>

            <?= $row->position24; ?>
            <?= $row->long; ?>
            <?= $row->price; ?>
            <?= $row->mktcap; ?>
            <?= $row->volume; ?>
            <?= $row->supply; ?>
            <?= $row->cap24hrChangePercent; ?>

        <?php } ?>

Body:
You can use number_format Here is a number_format sample.

echo number_format(110000,2); // 110,000.00


问:
IOS Label Inside Table Cell Only Showing One Letter
Preface: I am very new to swift and my have missed something stupid

Here is the picture of one table cell, as seen in the app's storyboard:

The issue is that when I run my code, in which I tried to simply create five of these same cells, I get this:

When I try to populate the cells programmatically, it cuts off the words after one letter!

I created a table and the screen's view controller implements the proper interfaces:
 UIViewController, UITableViewDelegate, UITableViewDataSource

here is my cellsForRowAt function which I implemented because I am implementing the TableViewDelegate Interface (actually, it was because the tutorial I was following did it)

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentity", for: indexPath) as? YeezyCell{
        let dataObject = videoDatas[indexPath.row]
        cell.updateUI(data: dataObject)

        return cell
    }
</code>```

videoDatas is a class I made which should have no problems. Its use here is that it returns the text for the label.

cellIdentity is what I set the identity of the table cell as, in the identity inspector.

All updateUI() does is this:

```<code>func updateUI(data: MusicVideoData){
    videoTitle.text = data.getTitle()
    print(videoTitle.text)
}
</code>```

and videoTitle is simply an IBOutlet I made connecting the label I am referring to, to the code.

My print statement is printing famous so it looks like for some reason the label is cutting off that text after the first letter?

I'd really appreciate it if someone could explain why.

Thanks a lot for any help.

If more of my files are necessary to answer my question, please let me know and I will post them.

答:
Assuming you're using proper constraints for the image already.

Set the constraints of your label like so in interface builder:

pin leading (left) to image

pin trailing (right) to superview

set vertical constraint to superview

Body:
Preface: I am very new to swift and my have missed something stupid

Here is the picture of one table cell, as seen in the app's storyboard:

The issue is that when I run my code, in which I tried to simply create five of these same cells, I get this:

When I try to populate the cells programmatically, it cuts off the words after one letter!

I created a table and the screen's view controller implements the proper interfaces:
 UIViewController, UITableViewDelegate, UITableViewDataSource

here is my cellsForRowAt function which I implemented because I am implementing the TableViewDelegate Interface (actually, it was because the tutorial I was following did it)

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentity", for: indexPath) as? YeezyCell{
        let dataObject = videoDatas[indexPath.row]
        cell.updateUI(data: dataObject)

        return cell
    }

videoDatas is a class I made which should have no problems. Its use here is that it returns the text for the label.

cellIdentity is what I set the identity of the table cell as, in the identity inspector.

All updateUI() does is this:

func updateUI(data: MusicVideoData){
    videoTitle.text = data.getTitle()
    print(videoTitle.text)
}

and videoTitle is simply an IBOutlet I made connecting the label I am referring to, to the code.

My print statement is printing famous so it looks like for some reason the label is cutting off that text after the first letter?

I'd really appreciate it if someone could explain why.

Thanks a lot for any help.

If more of my files are necessary to answer my question, please let me know and I will post them.


问:
Implement Gmail-like labels in a Rails app
This is more of an application design question then a specific Rails question. I'm trying to implement a system like "labels" within Gmail. So I want a user to be able to apply a label (or many) to a specific post. However, I also want the user to be able to manage labels using standard Rails CRUD.

Let's say I have a model called Post. So a user has many Posts. A user can create labels which is a separate model from Posts, but these can also be applied to posts with the use of checkboxes in the Post new/edit views. If a user deletes a specific label, it simply gets removed from the Post view and doesn't affect the Post in any other way.

This situation shows my lack of knowledge of db relationships, but is this a case for a has_many_and_belongs_to_many relationship?

If so, would the following design be the way to implement this?

User has_many Posts

User has_many Labels

Post has_many_and_belongs_to_many
Labels

Label has_many_and_belongs_to_many
Posts

Maybe I'm over thinking this and my logic is way off.

答: From your question, it seems like you are trying to build a taxonomy system (i.e. tagging model).  You may want to check out Acts As Taggable On as a possible solution (or just an interesting modeling reference) for your problem.</p>

ContentLicense: CC BY-SA 2.5


答:
```<code>sort @{ $hsh->{arr} }
</code>```

See http://perlmonks.org/?node=References+Quick+Reference.

Title: perl: sort arrayref inside a hashref

Body:
sort @{ $hsh->{arr} }

See http://perlmonks.org/?node=References+Quick+Reference.


问:
Populate jcombobox from two different mysql data
I created a jdialog with employee list table with two buttons, the add and details button. The add button will show a blank employee details jdialog for adding new employee while the details button will fill the employee details jdialog based on the selected employee in the list table. The problem is that when I click the details, the jcombobox for department does not show the corresponding data for the selected employee instead it still shows the department list. What I want is that the said jcombobox must show first the department from the selected employee before the department list. How can I achieve that. Here is the code for the jcombobox in question:

```<code>data = new ProcessDB();
        for(int i = 0; i < data.loadDeptCombo().get(0).size();i++){
            cmbDept.addItem(data.loadDeptCombo().get(1).get(i));
        }

public void loadInfo(String EmpID) throws ParseException{
    data = new ProcessDB();
    cmbDept.addItem(data.getEmpInfo(EmpID).get(4).get(0));
}
</code>```

this is the processdb:

```<code>public List<List<String>> loadDeptCombo(){
    sql = new String("SELECT * FROM departments ORDER BY Deptname ASC");
    List<List<String>> values =  new ArrayList<>();
    List<String> id = new ArrayList<>();
    List<String> dept = new ArrayList<>();

    try{
        stmt = data.createStatement();
        rs = stmt.executeQuery(sql);

        while(rs.next()){
            id.add(String.valueOf(rs.getInt("DeptID")));
            dept.add(rs.getString("Deptname"));
        }
    }catch(SQLException ex){
        ex.printStackTrace();
    }
    values.add(id);
    values.add(dept);

    return values;
}

 public List<List<String>> getEmpInfo(String EmpID){
    sql = new String("SELECT * FROM workinfo WHERE EmpID = ?");
    List<List<String>> values = new ArrayList<>();
    List<String> empID = new ArrayList<>();
    List<String> lastName = new ArrayList<>();
    List<String> firstName = new ArrayList<>();
    List<String> middleName = new ArrayList<>();
    List<String> department = new ArrayList<>();
    List<String> designation = new ArrayList<>();
    List<String> dateStarted = new ArrayList<>();
    List<String> rate = new ArrayList<>();
    List<String> section = new ArrayList<>();
    List<String> line = new ArrayList<>();
    List<String> admin = new ArrayList<>();

    try{
        pstmt = data.prepareStatement(sql);
        pstmt.setString(1, EmpID);
        rs = pstmt.executeQuery();

        while(rs.next()){
            empID.add(rs.getString("EmpID"));
            lastName.add(rs.getString("Lastname"));
            firstName.add(rs.getString("Firstname"));
            middleName.add(rs.getString("Middlename"));
            department.add(rs.getString("Department"));
            designation.add(rs.getString("Designation"));
            dateStarted.add(String.valueOf(rs.getDate("DateStarted")));
            rate.add(rs.getString("Rate"));
            section.add(rs.getString("Section"));
            line.add(rs.getString("Line"));
            admin.add(rs.getString("Admin"));
        }
    }catch(SQLException ex){
        ex.printStackTrace();
    }
    values.add(empID);
    values.add(lastName);
    values.add(firstName);
    values.add(middleName);
    values.add(department);
    values.add(designation);
    values.add(dateStarted);
    values.add(rate);
    values.add(section);
    values.add(line);
    values.add(admin);

    return values;
}
</code>```

答:
I found my solution by arranging the code like this:

```<code>if(EmpID != ""){
        try {
            data = new ProcessDB();
            loadInfo(EmpID);
            cmbDept.addItem(data.getEmpInfo(EmpID).get(4).get(0));
            cmbRate.addItem(data.getEmpInfo(EmpID).get(7).get(0));

            for(int i = 0; i < data.loadDeptCombo().get(0).size();i++){
                cmbDept.addItem(data.loadDeptCombo().get(1).get(i));
            }

            for(int i = 0;i < data.loadRateCombo().get(0).size();i++){
                cmbRate.addItem(data.loadRateCombo().get(1).get(i));
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }else{
        try{
            data = new ProcessDB();
            for(int i = 0; i < data.loadDeptCombo().get(0).size();i++){
                cmbDept.addItem(data.loadDeptCombo().get(1).get(i));
            }

            for(int i = 0;i < data.loadRateCombo().get(0).size();i++){
                cmbRate.addItem(data.loadRateCombo().get(1).get(i));
            }

        }catch(Exception ex){
            //ex.printStackTrace();
            System.out.println(ex.getMessage());
        }

    }
</code>```

first reload the data from the table if the string EmpID is not empty followed by loading the default department list and if empty, reload only the default department list in the combobox.

Body:
I created a jdialog with employee list table with two buttons, the add and details button. The add button will show a blank employee details jdialog for adding new employee while the details button will fill the employee details jdialog based on the selected employee in the list table. The problem is that when I click the details, the jcombobox for department does not show the corresponding data for the selected employee instead it still shows the department list. What I want is that the said jcombobox must show first the department from the selected employee before the department list. How can I achieve that. Here is the code for the jcombobox in question:

data = new ProcessDB();
        for(int i = 0; i < data.loadDeptCombo().get(0).size();i++){
            cmbDept.addItem(data.loadDeptCombo().get(1).get(i));
        }

public void loadInfo(String EmpID) throws ParseException{
    data = new ProcessDB();
    cmbDept.addItem(data.getEmpInfo(EmpID).get(4).get(0));
}

this is the processdb:

public List<List<String>> loadDeptCombo(){
    sql = new String("SELECT * FROM departments ORDER BY Deptname ASC");
    List<List<String>> values =  new ArrayList<>();
    List<String> id = new ArrayList<>();
    List<String> dept = new ArrayList<>();

    try{
        stmt = data.createStatement();
        rs = stmt.executeQuery(sql);

        while(rs.next()){
            id.add(String.valueOf(rs.getInt("DeptID")));
            dept.add(rs.getString("Deptname"));
        }
    }catch(SQLException ex){
        ex.printStackTrace();
    }
    values.add(id);
    values.add(dept);

    return values;
}

 public List<List<String>> getEmpInfo(String EmpID){
    sql = new String("SELECT * FROM workinfo WHERE EmpID = ?");
    List<List<String>> values = new ArrayList<>();
    List<String> empID = new ArrayList<>();
    List<String> lastName = new ArrayList<>();
    List<String> firstName = new ArrayList<>();
    List<String> middleName = new ArrayList<>();
    List<String> department = new ArrayList<>();
    List<String> designation = new ArrayList<>();
    List<String> dateStarted = new ArrayList<>();
    List<String> rate = new ArrayList<>();
    List<String> section = new ArrayList<>();
    List<String> line = new ArrayList<>();
    List<String> admin = new ArrayList<>();

    try{
        pstmt = data.prepareStatement(sql);
        pstmt.setString(1, EmpID);
        rs = pstmt.executeQuery();

        while(rs.next()){
            empID.add(rs.getString("EmpID"));
            lastName.add(rs.getString("Lastname"));
            firstName.add(rs.getString("Firstname"));
            middleName.add(rs.getString("Middlename"));
            department.add(rs.getString("Department"));
            designation.add(rs.getString("Designation"));
            dateStarted.add(String.valueOf(rs.getDate("DateStarted")));
            rate.add(rs.getString("Rate"));
            section.add(rs.getString("Section"));
            line.add(rs.getString("Line"));
            admin.add(rs.getString("Admin"));
        }
    }catch(SQLException ex){
        ex.printStackTrace();
    }
    values.add(empID);
    values.add(lastName);
    values.add(firstName);
    values.add(middleName);
    values.add(department);
    values.add(designation);
    values.add(dateStarted);
    values.add(rate);
    values.add(section);
    values.add(line);
    values.add(admin);

    return values;
}

Body:
I found my solution by arranging the code like this:

if(EmpID != ""){
        try {
            data = new ProcessDB();
            loadInfo(EmpID);
            cmbDept.addItem(data.getEmpInfo(EmpID).get(4).get(0));
            cmbRate.addItem(data.getEmpInfo(EmpID).get(7).get(0));

            for(int i = 0; i < data.loadDeptCombo().get(0).size();i++){
                cmbDept.addItem(data.loadDeptCombo().get(1).get(i));
            }

            for(int i = 0;i < data.loadRateCombo().get(0).size();i++){
                cmbRate.addItem(data.loadRateCombo().get(1).get(i));
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }else{
        try{
            data = new ProcessDB();
            for(int i = 0; i < data.loadDeptCombo().get(0).size();i++){
                cmbDept.addItem(data.loadDeptCombo().get(1).get(i));
            }

            for(int i = 0;i < data.loadRateCombo().get(0).size();i++){
                cmbRate.addItem(data.loadRateCombo().get(1).get(i));
            }

        }catch(Exception ex){
            //ex.printStackTrace();
            System.out.println(ex.getMessage());
        }

    }

first reload the data from the table if the string EmpID is not empty followed by loading the default department list and if empty, reload only the default department list in the combobox.


问:
JavaScript function can't be run in external file
I have two functions in external file, then I call A and B in HEAD script, and A can be run and B can't, but if I put B into head script, B also can be run. I am not sure why, what can I do?

HTML:

```<code><head>
<script language="JavaScript" type="text/JavaScript">
<!--
function B(id) {
    var selected = document.getElementById(id)
    var arr = selected.options[selected.selectedIndex].text.split(" ");
    var value = ""
    for (var i = 1; i < arr.length; i++) {
        if (value != "") value = value + " ";
        value = value + arr[i];
    }
    return value;
}

function save() {
    A("msg");
    var x = B(id);
}
-->
...
<script type="text/JavaScript" src="js/my.js"></script>
</body>
...
</code>```

my.js:

```<code>function A(msg) {
    scroll(0,0);
    var outerPane = document.getElementById('FreezePane');
    var innerPane = document.getElementById('InnerFreezePane');
    if (outerPane) outerPane.className = 'FreezePaneOn';
    if (innerPane) innerPane.innerHTML = msg;
}

function B(id) {
    var selected = document.getElementById(id)
    var arr = selected.options[selected.selectedIndex].text.split(" ");
    var value = ""
    for (var i = 1; i < arr.length; i++) {
        if (value != "") value = value + " ";
        value = value + arr[i];
    }
    return value;
}
</code>```

答:
Add your external file before the script tag contains your "save" function.</p>

```<code><script language="JavaScript" src = "yourfile.js" type="text/JavaScript">
</script>
<script language="JavaScript" type="text/JavaScript">
   function save(){
           A();
           B();
   }
</script>
</code>```

Body:
I have two functions in external file, then I call A and B in HEAD script, and A can be run and B can't, but if I put B into head script, B also can be run. I am not sure why, what can I do?

HTML:

...

my.js:

function A(msg) {
    scroll(0,0);
    var outerPane = document.getElementById('FreezePane');
    var innerPane = document.getElementById('InnerFreezePane');
    if (outerPane) outerPane.className = 'FreezePaneOn';
    if (innerPane) innerPane.innerHTML = msg;
}

function B(id) {
    var selected = document.getElementById(id)
    var arr = selected.options[selected.selectedIndex].text.split(" ");
    var value = ""
    for (var i = 1; i < arr.length; i++) {
        if (value != "") value = value + " ";
        value = value + arr[i];
    }
    return value;
}

Body:
Add your external file before the script tag contains your "save" function.

<script language="JavaScript" src = "yourfile.js" type="text/JavaScript">
</script>
<script language="JavaScript" type="text/JavaScript">
   function save(){
           A();
           B();
   }
</script>


问:
SQL Server JDBC Error on Java 8: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption
I am getting the following error when connecting to a SQL Server database using version the Microsoft JDBC Driver:

com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "SQL Server returned an incomplete response. The connection has been closed. ClientConnectionId:98d0b6f4-f3ca-4683-939e-7c0a0fca5931".

We recently upgraded our applications from Java 6 & Java 7 to Java 8.  All systems running Java are running SUSE Linux Enterprise Server 11 (x86_64), VERSION = 11, PATCHLEVEL = 3.

Here are the facts I have collected with a Java program that I wrote which simply sequentially opens and closes 1,000 database connections.

Connections are dropped with this error about 5%-10% of the time.  The error DOES NOT occur on every connection.

The problem ONLY occurs with Java 8.  I ran the same program on Java 7 and the problem is not reproducible.  This is consistent with our experience in production prior to upgrading.  We've had zero problems running under Java 7 in production.

The problem DOES NOT occur on all of our Linux servers running Java 8, it only occurs on some of them.  This is perplexing to me, but when I run the same test program on the same version of the Linux JVM (1.8.0_60, 64 bit) on different Linux instances, the problem does not occur on one of the Linux instances, but the problem does occur on others.  The Linux instances are running the same version of SUSE and they are at the same patch level.

The problem occurs when connecting to BOTH SQL Server 2008 and SQL Server 2014 servers/databases.

The problem occurs regardless if I am using the 4.0 version of the SQL Server JDBC driver or the newer 4.1 version of the driver.

The thing that makes my observations unique on this compared to others on the web is that although the problem happens ONLY on Java 8, I cannot get the problem to occur on one of the seemingly identical Linux servers that is running the same Java 8 JVM.  Other folks have seen this problem on earlier versions of Java as well, but that has not been our experience.

Any input, suggestions, or observations you may have are appreciated.

答: I've also hit this issue on Windows Server 2012 R2, using JDBC driver 4.0 & 4.1 with Java 7.  This Microsoft article pins the blame on DHE ciphersuites, and recommends disabling them or reducing their priority if you cannot upgrade to JDBC driver 4.2</p>


问:
JQuery onclick doing nothing
So here is my button:

```<code><div id="calculateButton" style="cursor: pointer;">
    <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/btn_calculate.gif")%>" />
</div>
</code>```

And here is the javascript:

```<code>$('#calculateButton').click(function () {
    alert('Calculating...');
});
</code>```

When I click the button nothing happens. What am I doing wrong?

Edits:

```<code>$(document).ready(function () {

        $("#prepaymentTable").bubble({ width: 400, title: 'Prepayment' });
        $("#exposureTable").bubble({ width: 400, title: 'Exposure' });

        $('#calculateButton').click(function () {
            alert('Calculating...');
        });

    });
</code>```

The bubble plugins both work...but not the button click...

答:
Make sure you're attaching the click handler inside a document.ready handler, after the element has loaded, like this:

```<code>$(function() {
  $('#calculateButton').click(function () {
    alert('Calculating...');
  });
});
</code>```

If it's created later as the result of AJAX, etc, use .live(), for example:

```<code>$('#calculateButton').live('click', function () {
</code>```

Title: JQuery onclick doing nothing

Body:
So here is my button:

    <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/btn_calculate.gif")%>" />

And here is the javascript:

$('#calculateButton').click(function () {
    alert('Calculating...');
});

When I click the button nothing happens. What am I doing wrong?

Edits:

$(document).ready(function () {

        $("#prepaymentTable").bubble({ width: 400, title: 'Prepayment' });
        $("#exposureTable").bubble({ width: 400, title: 'Exposure' });

        $('#calculateButton').click(function () {
            alert('Calculating...');
        });

    });

The bubble plugins both work...but not the button click...

Body:
Make sure you're attaching the click handler inside a document.ready handler, after the element has loaded, like this:

$(function() {
  $('#calculateButton').click(function () {
    alert('Calculating...');
  });
});

If it's created later as the result of AJAX, etc, use .live(), for example:

$('#calculateButton').live('click', function () {


问:
Normalize array subscripts so they start with 1
PostgreSQL can work with array subscripts starting anywhere.

Consider this example that creates an array with 3 elements with subscripts from 5 to 7:

```<code>SELECT '[5:7]={1,2,3}'::int[];
</code>```

Returns:

```<code>[5:7]={1,2,3}
</code>```

We get the first element at subscript 5:

```<code>SELECT ('[5:7]={1,2,3}'::int[])[5];
</code>```

I want to normalize 1-dimensional arrays to start with array subscript 1.

The best I could come up with:

```<code>SELECT ('[5:7]={1,2,3}'::int[])[array_lower('[5:7]={1,2,3}'::int[], 1):array_upper('[5:7]={1,2,3}'::int[], 1)]
</code>```

The same, easier the read:

```<code>WITH   cte(a) AS (SELECT '[5:7]={1,2,3}'::int[])
SELECT a[array_lower(a, 1):array_upper(a, 1)]
FROM   cte;
</code>```

Do you know a simpler / faster or at least more elegant way?

Benchmark with old solutions on Postgres 9.5

db<>fiddle here

Benchmark including new solution on Postgres 14

db<>fiddle here

答:
Eventually, something more elegant popped up with Postgres 9.6. The manual:

It is possible to omit the lower-bound and/or
upper-bound of a slice specifier; the missing bound is replaced by the lower or upper limit of the array's subscripts. For example:

So it's simple now:

```<code>SELECT my_arr<b>[:]</b>;</code>```

With my example array literal you need enclosing parentheses to make the syntax unambiguous:

```<code>SELECT <b>(</b>'[5:7]={1,2,3}'::int[]<b>)[:]</b>;</code>```

About the same performance as Daniel's solution with hard-coded max array subscripts - which is still the way to go with Postgres 9.5 or earlier.

ContentLicense: CC BY-SA 4.0

Body:
PostgreSQL can work with array subscripts starting anywhere.

Consider this example that creates an array with 3 elements with subscripts from 5 to 7:

SELECT '[5:7]={1,2,3}'::int[];

Returns:

[5:7]={1,2,3}

We get the first element at subscript 5:

SELECT ('[5:7]={1,2,3}'::int[])[5];

I want to normalize 1-dimensional arrays to start with array subscript 1.

The best I could come up with:

SELECT ('[5:7]={1,2,3}'::int[])[array_lower('[5:7]={1,2,3}'::int[], 1):array_upper('[5:7]={1,2,3}'::int[], 1)]

The same, easier the read:

WITH   cte(a) AS (SELECT '[5:7]={1,2,3}'::int[])
SELECT a[array_lower(a, 1):array_upper(a, 1)]
FROM   cte;

Do you know a simpler / faster or at least more elegant way?

Benchmark with old solutions on Postgres 9.5

db<>fiddle here

Benchmark including new solution on Postgres 14

db<>fiddle here

Body:
Eventually, something more elegant popped up with Postgres 9.6. The manual:

It is possible to omit the lower-bound and/or
upper-bound of a slice specifier; the missing bound is replaced by the lower or upper limit of the array's subscripts. For example:

So it's simple now:

SELECT my_arr[:];

With my example array literal you need enclosing parentheses to make the syntax unambiguous:

SELECT ('[5:7]={1,2,3}'::int[])[:];

About the same performance as Daniel's solution with hard-coded max array subscripts - which is still the way to go with Postgres 9.5 or earlier.


答:
The safest thing to do is wrap the code in the head in a window.onload handler like this...

```<code><head>
  <script type="text/javascript">
    window.onload = function(){
      // your external files are guaranteed to be loaded now
      // you can call A or B
    }
  </script>
</head>
</code>```

onload is only fired after all external scripts have been loaded.

Here is a full example...

index.html

```<code><!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
<script>
function save() {
  A()
  B()
}

window.onload = function() {
  save()
}
</script>
</head>

<body>
The content of the document......
<script src="./external.js"></script>
</body>

</html>
</code>```

external.js

```<code>function A() {
  alert('A ran')
}

function B() {
  alert('B ran')
}
</code>```

NOTE: This is better than moving the external script to the head, like the other answers suggest, because external resources loaded in the head block the entire page render until they are loaded.

By leaving the external script at the end of the body tag, the page load will seem faster as the css/html will display immediately. Even if the javascript isn't loaded yet.

Title: JavaScript function can't be run in external file

Body:
The safest thing to do is wrap the code in the head in a window.onload handler like this...

<head>
  <script type="text/javascript">
    window.onload = function(){
      // your external files are guaranteed to be loaded now
      // you can call A or B
    }
  </script>
</head>

onload is only fired after all external scripts have been loaded.

Here is a full example...

index.html

<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
<script>
function save() {
  A()
  B()
}

window.onload = function() {
  save()
}
</script>
</head>

<body>
The content of the document......
<script src="./external.js"></script>
</body>

</html>

external.js

function A() {
  alert('A ran')
}

function B() {
  alert('B ran')
}

NOTE: This is better than moving the external script to the head, like the other answers suggest, because external resources loaded in the head block the entire page render until they are loaded.

By leaving the external script at the end of the body tag, the page load will seem faster as the css/html will display immediately. Even if the javascript isn't loaded yet.


问:
CSS: Bootstrap menu item right align
I added a menu item called Registration and am trying to have it right aligned using custom.css. (I can't post a screenshot of it due to lack of reputation as this is my first post here)

The following is what I currently have in custom.css

li.nav-registration {
    text-align: right;
    float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
      Home
    </div>
    <div class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
        <li>About</li>
        <li>Music</li>
        <li>Video</li>
        <li>Contact</li>
        <li class="nav-registration">Registration</li>
      </ul>
    </div>
  </div>
</nav></code>```

The styles in custom.css are being properly styled. However, the 'Registration' menu is still not being right aligned - any help with this would be appreciated.

答:
As I understand you will have to create 2 separate navbar elements. One for About, Music, Video, Contact and one for Registration:

About

Music

Video

Contact

Registration

```

You are not stating if you are using Bootstrap v3 or v4. Either way, the solution is the same that you will have to separate the 2 "navs". It's just the classes that you need that will change based on the bootstrap version.

Bootstrap 3 example:
https://getbootstrap.com/examples/navbar/

Bootstrap 4 navbar code:
https://v4-alpha.getbootstrap.com/components/navbar/#supported-content

Title: CSS: Bootstrap menu item right align

Body:
I added a menu item called Registration and am trying to have it right aligned using custom.css. (I can't post a screenshot of it due to lack of reputation as this is my first post here)

The following is what I currently have in custom.css

li.nav-registration {
    text-align: right;
    float: right;
}

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>
      Home

About

Music

Video

Contact

Registration

The styles in custom.css are being properly styled. However, the 'Registration' menu is still not being right aligned - any help with this would be appreciated.

Body:
As I understand you will have to create 2 separate navbar elements. One for About, Music, Video, Contact and one for Registration:

   <div class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
        <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
        <li><a asp-area="" asp-controller="Music" asp-action="Index">Music</a></li>
        <li><a asp-area="" asp-controller="Home" asp-action="Video">Video</a></li>
        <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li class="nav-registration"><a asp-area="" asp-controller="Home" asp-action="Registration">Registration</a></li>
      </ul>
</div>

You are not stating if you are using Bootstrap v3 or v4. Either way, the solution is the same that you will have to separate the 2 "navs". It's just the classes that you need that will change based on the bootstrap version.

Bootstrap 3 example:
https://getbootstrap.com/examples/navbar/

Bootstrap 4 navbar code:
https://v4-alpha.getbootstrap.com/components/navbar/#supported-content


问:
Combo box value depends on the selection of another combo box
I need to selected item on 1 combobox will show dpending items from this selection in another combobox. I dont use SQL,EXEL, ACCESS or VBA in project. I added items by my self in winforms. it should look sonething like this:
http://imgur.com/BYQNVzd
Thanks a lot for help.</p>

```<code>Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    If ComboBox1.SelectedIndex = 0 Then
        ' Index 0 is BMW
        ComboBox2.Items.Clear()
        ComboBox2.Items.AddRange({"X5", "X6", "7-series", "5-series", "3-series"})
    ElseIf ComboBox1.SelectedIndex = 1 Then
        ' Toyota
        ComboBox2.Items.Clear()
        ComboBox2.Items.AddRange({"Teana", "Camry"})
    ElseIf ComboBox1.SelectedIndex = 2 Then
        ' kia
        ComboBox2.Items.Clear()
        ComboBox2.Items.AddRange({"Rio"})
    End If
End Sub
</code>```

答:
It would look like this</p>

```<code>Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    If ComboBox1.SelectedIndex = 0 Then
        ' Index 0 is BMW
        ComboBox2.Items.Clear()
        ComboBox2.Items.AddRange({"X5", "X6", "7-series", "5-series", "3-series"})
    ElseIf ComboBox1.SelectedIndex = 1 Then
        ' Toyota

    End If
End Sub
</code>```

Body:
I need to selected item on 1 combobox will show dpending items from this selection in another combobox. I dont use SQL,EXEL, ACCESS or VBA in project. I added items by my self in winforms. it should look sonething like this:
http://imgur.com/BYQNVzd
Thanks a lot for help.

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    If ComboBox1.SelectedIndex = 0 Then
        ' Index 0 is BMW
        ComboBox2.Items.Clear()
        ComboBox2.Items.AddRange({"X5", "X6", "7-series", "5-series", "3-series"})
    ElseIf ComboBox1.SelectedIndex = 1 Then
        ' Toyota
        ComboBox2.Items.Clear()
        ComboBox2.Items.AddRange({"Teana", "Camry"})
    ElseIf ComboBox1.SelectedIndex = 2 Then
        ' kia
        ComboBox2.Items.Clear()
        ComboBox2.Items.AddRange({"Rio"})
    End If
End Sub

Body:
It would look like this

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    If ComboBox1.SelectedIndex = 0 Then
        ' Index 0 is BMW
        ComboBox2.Items.Clear()
        ComboBox2.Items.AddRange({"X5", "X6", "7-series", "5-series", "3-series"})
    ElseIf ComboBox1.SelectedIndex = 1 Then
        ' Toyota

    End If
End Sub


问:
Embedded SVG misaligned to element
So I'm trying to move from PNG to SVG, but I'm having some growing pains. I'd like to use embedded SVG so I can change their CSS attributes for their colour as well as having fewer resource loads. Although an issue I'm having is when the SVG is embedded it appears above the box provided, although if I use an img tag with linking to the SVG, the formatting is perfect.

In my picture, the box on the right has the img tag while the left box is embedded.

http://jsfiddle.net/fLWhu/684/

```<code><span>
                            @Html.Raw(File.ReadAllText(Server.MapPath("~/Content/images/icons/1.svg")))

</span>
<span>
<img src="~/Content/images/icons/1.svg" alt="our linked in" />
</span>
</code>```

Update:

After adding the

```<code>     display:inline-block;
     vertical-align:middle;
</code>```

into the span, the result is.

答: The SVG part seems ok, you could try set a display:inline-block and vertical align:middle to the div.header .right p span element

Title: Embedded SVG misaligned to element

Body:
So I'm trying to move from PNG to SVG, but I'm having some growing pains. I'd like to use embedded SVG so I can change their CSS attributes for their colour as well as having fewer resource loads. Although an issue I'm having is when the SVG is embedded it appears above the box provided, although if I use an img tag with linking to the SVG, the formatting is perfect.

In my picture, the box on the right has the img tag while the left box is embedded.

http://jsfiddle.net/fLWhu/684/

                            @Html.Raw(File.ReadAllText(Server.MapPath("~/Content/images/icons/1.svg")))

Update:

After adding the

     display:inline-block;
     vertical-align:middle;

into the span, the result is.


问:
Access a variable of iframe from parent
script of iframe

```<code><script type="text/javascript" >
var a=5;
</script>
</code>```

script of parent window

```<code><script type="text/javascript" >
function close()
{
var check=document.getElementById("iframeid").contentDocument.a;
alert(check)
}
</script>
</code>```

I want to access the variable which is defined inside the iframe from parent. But the above code doesn't work properly can anyone give an idea to implement this.

答:
This is how SharePoint do it when passing argument values from the parent window to the iframe. It's simple, but it works.

```<code><html>
<body>
  <iframe id="iframe1"></iframe>
  <script type="text/javascript">
    var ifr = window.document.getElementById("iframe1");
    ifr.dialogArgs = "Hello from the other side.";
    ifr.src = "iframeContent.html"
  </script>
</body>
</html>
</code>```

Inside iframeContent.html:

```<code><html>
<body>
    <input type="button" value="Click Me!" onclick="alert(window.frameElement.dialogArgs);" />
</body>
</html>
</code>```

The other way around (accessing ifr.dialogArgs from the parent window after having its value modified by the iframe document) also works.

Title: Access a variable of iframe from parent

Body:
script of iframe

script of parent window

I want to access the variable which is defined inside the iframe from parent. But the above code doesn't work properly can anyone give an idea to implement this.

Body:
This is how SharePoint do it when passing argument values from the parent window to the iframe. It's simple, but it works.

<html>
<body>
  <iframe id="iframe1"></iframe>
  <script type="text/javascript">
    var ifr = window.document.getElementById("iframe1");
    ifr.dialogArgs = "Hello from the other side.";
    ifr.src = "iframeContent.html"
  </script>
</body>
</html>

Inside iframeContent.html:

<html>
<body>
    <input type="button" value="Click Me!" onclick="alert(window.frameElement.dialogArgs);" />
</body>
</html>

The other way around (accessing ifr.dialogArgs from the parent window after having its value modified by the iframe document) also works.


问:
How to use DateAdd in C#?
I tried to convert VB to c#, in VB DATEADD Working in C# it gives an Error

```<code>DateTime viewPortStartDate = DateAdd("s", viewer.ViewPortLeft * m_dateRange, m_dtmMinDate);
DateTime  viewPortEndDate = DateAdd("s", viewer.ViewPortWidth * m_dateRange, viewPortStartDate);
</code>```

答:
Its AddDays in C#:

```<code>viewPortStartDate.AddDays(1);
</code>```

If you want a range, you can use duration:

```<code> DateTime today = DateTime.Now;
 TimeSpan duration = new TimeSpan(7, 0, 0, 0); //Adding 7 days from date today
 DateTime result = today.Add(duration);
</code>```

For adding with Hours, Minutes and seconds, you can do:

```<code> today = today.AddDays(1).AddHours(1).AddMinutes(1).AddSeconds(1);
</code>```

Or if specific to seconds only:

```<code>today = today.AddSeconds(1);
</code>```

Title: How to use DateAdd in C#?

Body:
I tried to convert VB to c#, in VB DATEADD Working in C# it gives an Error

DateTime viewPortStartDate = DateAdd("s", viewer.ViewPortLeft * m_dateRange, m_dtmMinDate);
DateTime  viewPortEndDate = DateAdd("s", viewer.ViewPortWidth * m_dateRange, viewPortStartDate);

Body:
Its AddDays in C#:

viewPortStartDate.AddDays(1);

If you want a range, you can use duration:

 DateTime today = DateTime.Now;
 TimeSpan duration = new TimeSpan(7, 0, 0, 0); //Adding 7 days from date today
 DateTime result = today.Add(duration);

For adding with Hours, Minutes and seconds, you can do:

 today = today.AddDays(1).AddHours(1).AddMinutes(1).AddSeconds(1);

Or if specific to seconds only:

today = today.AddSeconds(1);


问:
Any ReSharper equivalent for Xcode?
I'm a complete Xcode/Objective-C/Cocoa newbie but I'm learning fast and really starting to enjoy getting to grips with a new language, platform and paradigm.

One thing is though, having been using Visual Studio with R# for so long I've kind of been spoiled with the coding tools such as refactorings and completion etc and as far as I can tell Xcode has some fairly limited built in support for this stuff.

On that note, does anyone know if any add-ins or whatever are available for the Xcode environment which add coding helpers such as automatically generating implementation skeletons from a class interface definition etc?

I suspect there aren't but I suppose it can't help to ask.

答:
I found some xtmacro files in Xcode.app package:
/Developer/Applications/Xcode.app/Contents/PlugIns/TextMacros.xctxtmacro/Contents/Resources

Installed Xcode ver. 3.2.5.

OwnerDisplayName: Shaun Austin

Title: Any ReSharper equivalent for Xcode?

LastEditorDisplayName: Paul


问:
How to add the tags automatically before started the build creation?
I have setup the build and release definitions for my web application in VSTS. Whenever I commit the code then automatically start the build process, after build succeed I manually add the tags like shown in below figure.

But I want to add the build tags before started the build creation only. So, how can I add the tags automatically before started the build creation?

答:
It seems you are using CI build, so if you want to add tags automatically, you can use pre-push hook in local git repo.

Or if it’s ok for you to add tags after build, you can set in build definition. In Get sources step -> show Advanced settings -> select Always for Tag sources -> specify Tag format -> save.

A sample example for pre-push hook (.git/hooks/pre-push), to add a tag with increment of tag version and the version format is major.minor, the number is not bigger then 9:

```<code>#!/bin/sh

temp1=0
temp2=0

for tag in $(git tag)
do
{
  IFS=. read -r major minor <<< "$tag"
  if [ $((major-temp1)) > 0 ]

  then
  {
    temp1=$major
    temp2=$minor

  }
  elif [ $major == $temp1 ]
  then
  {
    if [ $((minor-temp2)) > 0 ]
    then
    temp2=$minor
    else
    {
      temp1=$temp1
      temp2=$temp2
    }
    fi
  }

  fi
}
done
if [ $temp2 != 9 ]
then
  temp2=$((temp2+1))
else
  temp1=$((temp1+1))
fi
nexttag=$temp1"."$temp2
git tag -a $nexttag -m $nexttag
</code>```

Body:
It seems you are using CI build, so if you want to add tags automatically, you can use pre-push hook in local git repo.

Or if it’s ok for you to add tags after build, you can set in build definition. In Get sources step -> show Advanced settings -> select Always for Tag sources -> specify Tag format -> save.

A sample example for pre-push hook (.git/hooks/pre-push), to add a tag with increment of tag version and the version format is major.minor, the number is not bigger then 9:

#!/bin/sh

temp1=0
temp2=0

for tag in $(git tag)
do
{
  IFS=. read -r major minor <<< "$tag"
  if [ $((major-temp1)) > 0 ]

  then
  {
    temp1=$major
    temp2=$minor

  }
  elif [ $major == $temp1 ]
  then
  {
    if [ $((minor-temp2)) > 0 ]
    then
    temp2=$minor
    else
    {
      temp1=$temp1
      temp2=$temp2
    }
    fi
  }

  fi
}
done
if [ $temp2 != 9 ]
then
  temp2=$((temp2+1))
else
  temp1=$((temp1+1))
fi
nexttag=$temp1"."$temp2
git tag -a $nexttag -m $nexttag