问:
Merge multiple dataframes into a single column
Hello guys I'm here again to ask  you some questions.

I've "n" separated csv with only two columns temperature and date in format dmy HM, these documents are from a single digital Thermometer which only can store 4 months at time.
I would like to read all these documents and put their variable temperature into a new df (Union)just in a single column.

In order to make a single document,  I created a df named "date" with a date-time sequence bigger than any other csv to union this "n" documents with the column "Date" to paste the value when the dates are the same.

My inputs are like this:

```<code>Date<- seq(as.POSIXlt("2017-01-01 00:00:00", tz="UTC"),
     as.POSIXlt("2017-03-01 00:00:00", tz="UTC"),
     by="60 min")
temp = runif(1417, min = 32, max = 100)
df1 <- data.frame(Date,temp)

Date<- seq(as.POSIXlt("2017-03-01 00:00:00", tz="UTC"),
     as.POSIXlt("2017-06-01 00:00:00", tz="UTC"),
     by="60 min")
temp = runif(2209, min = 32, max = 100)
df2 <- data.frame(Date,temp)
</code>```

So, it's the big sequence which I made to union my df's with.

```<code>Date <- seq(as.POSIXlt("2017-01-01 00:00:00", tz="UTC"),
       as.POSIXlt("2017-07-01 00:00:00", tz="UTC"),
       by="60 min")
date <- data.frame(Date)
</code>```

I was trying with the library data.table as follow:

```<code>setDT(date)
setDT(df1)
Union<-df1[date, on="Date"])
</code>```

This worked just with 1 df, but, How can I  get a way to automate the multiple merge from my 2 df just into that single column which was made in Union.

I hope you can help me.
Thanks

答:
I'm going to generate some sample data to show how to use Reduce and merge. I'm assuming you want a 'wide' format, with a column for each location.

```<code>set.seed(123)

# list of 10 data.tables with columns date and temp

ldat <- lapply(1:10, function(x) data.table(date = sample(seq(as.Date('2016/01/01'), as.Date('2016/01/31'), by="day"), 12),
                                            temp = runif(12, min = 32, max = 100)))

# right now, each table in the list has the same column name
# change the 'temp' column name to the location it was collected

loc_vect <- c("Alabama", "Alaska", "Arizona", "Arkansas", "California",
              "Colorado", "Connecticut", "Indiana", "Iowa", "Kansas")

ldat <- lapply(1:10, function(x) setnames(ldat[[x]], c("date", "temp"), c("date", loc_vect[x])))
</code>```

That's the sample data. Now to put it together using merge.

```<code># now merge all of them within Reduce

dat <- Reduce(function(x, y) merge(x,
                                   y,
                                   all = TRUE,
                                   by = "date"),
              ldat,
              accumulate = FALSE)
</code>```

The output is:

```<code>          date  Alabama   Alaska  Arizona Arkansas California Colorado Connecticut  Indiana     Iowa   Kansas
 1: 2016-01-01       NA 47.84632       NA 61.57271         NA       NA          NA       NA       NA       NA
 2: 2016-01-02 34.86005       NA 58.10994       NA         NA       NA          NA       NA       NA 45.44664
 3: 2016-01-03       NA       NA 86.01528 76.41093   42.00244 61.88134    46.82337       NA       NA       NA
 4: 2016-01-04       NA 60.18915 62.49911       NA         NA 98.62789          NA       NA 64.77890       NA
 5: 2016-01-05       NA       NA 87.24249       NA         NA       NA          NA       NA       NA       NA
 6: 2016-01-06       NA       NA       NA 55.35912         NA       NA    68.29078 50.02121 46.70533       NA
 7: 2016-01-07       NA       NA       NA 92.72748         NA 76.86901    46.74871       NA       NA       NA
 8: 2016-01-08       NA 41.71040 74.78704       NA         NA       NA    47.03500 53.24648       NA 68.86146
 9: 2016-01-09 78.07480       NA 77.22783 40.88731   96.44543 67.43723    56.17029 94.09680       NA 88.57107
10: 2016-01-10 99.61034 63.68545       NA       NA         NA 82.12129          NA       NA       NA       NA
11: 2016-01-11 79.11063       NA       NA 92.27990         NA       NA          NA       NA 43.60388 79.48179
12: 2016-01-12 38.99888       NA       NA       NA   69.35136       NA    57.48055 93.32746       NA 86.63246
13: 2016-01-13 92.48867       NA 50.65809       NA   81.00055       NA          NA 89.10421 35.24113 94.26648
14: 2016-01-14 54.29861       NA       NA 98.97707   95.60039 32.71176          NA       NA 51.60027       NA
15: 2016-01-15       NA       NA 87.08438 76.65955   52.48357       NA          NA 70.39215       NA       NA
16: 2016-01-16       NA 53.63631       NA 43.90358         NA 59.84430          NA       NA       NA       NA
17: 2016-01-17       NA 47.75055 61.90855       NA   36.12900       NA          NA 50.02223       NA 59.00633
18: 2016-01-18       NA 41.43881       NA       NA         NA 44.50177          NA       NA 43.70768       NA
19: 2016-01-19       NA       NA 83.30431       NA         NA       NA          NA 80.16374 91.85676 49.73827
20: 2016-01-20       NA       NA       NA       NA   96.87820       NA    56.06551 64.72771       NA       NA
21: 2016-01-21 75.55446 83.57525       NA       NA         NA 77.76394          NA       NA       NA       NA
22: 2016-01-22 96.90625 46.71574 87.39552       NA   71.81287       NA    76.19899 53.86083 77.85759       NA
23: 2016-01-23       NA       NA       NA 38.99480   41.67601       NA          NA       NA       NA       NA
24: 2016-01-24 70.93907       NA       NA       NA         NA       NA          NA 72.41534       NA 74.04788
25: 2016-01-25 93.18810 60.13325       NA 53.78538   59.92690 53.19575          NA       NA       NA 35.97654
26: 2016-01-26 48.73397       NA 38.44916 44.76300         NA 85.46715          NA       NA       NA 61.13266
27: 2016-01-27       NA       NA       NA       NA         NA       NA    70.89160       NA 79.65801       NA
28: 2016-01-28       NA       NA       NA       NA         NA       NA    82.34274       NA 56.75825       NA
29: 2016-01-29       NA 42.36624       NA       NA         NA       NA    66.15637 50.64333 49.20162       NA
30: 2016-01-30       NA 57.08149       NA       NA         NA 87.88277    62.24422       NA       NA       NA
31: 2016-01-31       NA       NA       NA       NA   59.50670       NA          NA       NA 59.37499 42.39633
          date  Alabama   Alaska  Arizona Arkansas California Colorado Connecticut  Indiana     Iowa   Kansas
</code>```

If you want it in a 'tall' format (only two columns for date, temp, and possibly a third for location), that would be even easier by adding a 'location' column and using rbindlist(dat). But, going from the current table, you can use melt.

```<code>melt(dat,
     id.vars = "date",
     variable.name = "Location",
     value.name = "Temp")[!is.na(Temp)]
</code>```

Resulting in:

```<code>           date Location     Temp
  1: 2016-01-02  Alabama 34.86005
  2: 2016-01-09  Alabama 78.07480
  3: 2016-01-10  Alabama 99.61034
  4: 2016-01-11  Alabama 79.11063
  5: 2016-01-12  Alabama 38.99888
 ---
116: 2016-01-19   Kansas 49.73827
117: 2016-01-24   Kansas 74.04788
118: 2016-01-25   Kansas 35.97654
119: 2016-01-26   Kansas 61.13266
120: 2016-01-31   Kansas 42.39633
</code>```

Body:
Hello guys I'm here again to ask  you some questions.

I've "n" separated csv with only two columns temperature and date in format dmy HM, these documents are from a single digital Thermometer which only can store 4 months at time.
I would like to read all these documents and put their variable temperature into a new df (Union)just in a single column.

In order to make a single document,  I created a df named "date" with a date-time sequence bigger than any other csv to union this "n" documents with the column "Date" to paste the value when the dates are the same.

My inputs are like this:

Date<- seq(as.POSIXlt("2017-01-01 00:00:00", tz="UTC"),
     as.POSIXlt("2017-03-01 00:00:00", tz="UTC"),
     by="60 min")
temp = runif(1417, min = 32, max = 100)
df1 <- data.frame(Date,temp)

Date<- seq(as.POSIXlt("2017-03-01 00:00:00", tz="UTC"),
     as.POSIXlt("2017-06-01 00:00:00", tz="UTC"),
     by="60 min")
temp = runif(2209, min = 32, max = 100)
df2 <- data.frame(Date,temp)

So, it's the big sequence which I made to union my df's with.

Date <- seq(as.POSIXlt("2017-01-01 00:00:00", tz="UTC"),
       as.POSIXlt("2017-07-01 00:00:00", tz="UTC"),
       by="60 min")
date <- data.frame(Date)

I was trying with the library data.table as follow:

setDT(date)
setDT(df1)
Union<-df1[date, on="Date"])

This worked just with 1 df, but, How can I  get a way to automate the multiple merge from my 2 df just into that single column which was made in Union.

I hope you can help me.
Thanks

Body:
I'm going to generate some sample data to show how to use Reduce and merge. I'm assuming you want a 'wide' format, with a column for each location.

set.seed(123)

# list of 10 data.tables with columns date and temp

ldat <- lapply(1:10, function(x) data.table(date = sample(seq(as.Date('2016/01/01'), as.Date('2016/01/31'), by="day"), 12),
                                            temp = runif(12, min = 32, max = 100)))

# right now, each table in the list has the same column name
# change the 'temp' column name to the location it was collected

loc_vect <- c("Alabama", "Alaska", "Arizona", "Arkansas", "California",
              "Colorado", "Connecticut", "Indiana", "Iowa", "Kansas")

ldat <- lapply(1:10, function(x) setnames(ldat[[x]], c("date", "temp"), c("date", loc_vect[x])))

That's the sample data. Now to put it together using merge.

# now merge all of them within Reduce

dat <- Reduce(function(x, y) merge(x,
                                   y,
                                   all = TRUE,
                                   by = "date"),
              ldat,
              accumulate = FALSE)

The output is:

          date  Alabama   Alaska  Arizona Arkansas California Colorado Connecticut  Indiana     Iowa   Kansas
 1: 2016-01-01       NA 47.84632       NA 61.57271         NA       NA          NA       NA       NA       NA
 2: 2016-01-02 34.86005       NA 58.10994       NA         NA       NA          NA       NA       NA 45.44664
 3: 2016-01-03       NA       NA 86.01528 76.41093   42.00244 61.88134    46.82337       NA       NA       NA
 4: 2016-01-04       NA 60.18915 62.49911       NA         NA 98.62789          NA       NA 64.77890       NA
 5: 2016-01-05       NA       NA 87.24249       NA         NA       NA          NA       NA       NA       NA
 6: 2016-01-06       NA       NA       NA 55.35912         NA       NA    68.29078 50.02121 46.70533       NA
 7: 2016-01-07       NA       NA       NA 92.72748         NA 76.86901    46.74871       NA       NA       NA
 8: 2016-01-08       NA 41.71040 74.78704       NA         NA       NA    47.03500 53.24648       NA 68.86146
 9: 2016-01-09 78.07480       NA 77.22783 40.88731   96.44543 67.43723    56.17029 94.09680       NA 88.57107
10: 2016-01-10 99.61034 63.68545       NA       NA         NA 82.12129          NA       NA       NA       NA
11: 2016-01-11 79.11063       NA       NA 92.27990         NA       NA          NA       NA 43.60388 79.48179
12: 2016-01-12 38.99888       NA       NA       NA   69.35136       NA    57.48055 93.32746       NA 86.63246
13: 2016-01-13 92.48867       NA 50.65809       NA   81.00055       NA          NA 89.10421 35.24113 94.26648
14: 2016-01-14 54.29861       NA       NA 98.97707   95.60039 32.71176          NA       NA 51.60027       NA
15: 2016-01-15       NA       NA 87.08438 76.65955   52.48357       NA          NA 70.39215       NA       NA
16: 2016-01-16       NA 53.63631       NA 43.90358         NA 59.84430          NA       NA       NA       NA
17: 2016-01-17       NA 47.75055 61.90855       NA   36.12900       NA          NA 50.02223       NA 59.00633
18: 2016-01-18       NA 41.43881       NA       NA         NA 44.50177          NA       NA 43.70768       NA
19: 2016-01-19       NA       NA 83.30431       NA         NA       NA          NA 80.16374 91.85676 49.73827
20: 2016-01-20       NA       NA       NA       NA   96.87820       NA    56.06551 64.72771       NA       NA
21: 2016-01-21 75.55446 83.57525       NA       NA         NA 77.76394          NA       NA       NA       NA
22: 2016-01-22 96.90625 46.71574 87.39552       NA   71.81287       NA    76.19899 53.86083 77.85759       NA
23: 2016-01-23       NA       NA       NA 38.99480   41.67601       NA          NA       NA       NA       NA
24: 2016-01-24 70.93907       NA       NA       NA         NA       NA          NA 72.41534       NA 74.04788
25: 2016-01-25 93.18810 60.13325       NA 53.78538   59.92690 53.19575          NA       NA       NA 35.97654
26: 2016-01-26 48.73397       NA 38.44916 44.76300         NA 85.46715          NA       NA       NA 61.13266
27: 2016-01-27       NA       NA       NA       NA         NA       NA    70.89160       NA 79.65801       NA
28: 2016-01-28       NA       NA       NA       NA         NA       NA    82.34274       NA 56.75825       NA
29: 2016-01-29       NA 42.36624       NA       NA         NA       NA    66.15637 50.64333 49.20162       NA
30: 2016-01-30       NA 57.08149       NA       NA         NA 87.88277    62.24422       NA       NA       NA
31: 2016-01-31       NA       NA       NA       NA   59.50670       NA          NA       NA 59.37499 42.39633
          date  Alabama   Alaska  Arizona Arkansas California Colorado Connecticut  Indiana     Iowa   Kansas

If you want it in a 'tall' format (only two columns for date, temp, and possibly a third for location), that would be even easier by adding a 'location' column and using rbindlist(dat). But, going from the current table, you can use melt.

melt(dat,
     id.vars = "date",
     variable.name = "Location",
     value.name = "Temp")[!is.na(Temp)]

Resulting in:

           date Location     Temp
  1: 2016-01-02  Alabama 34.86005
  2: 2016-01-09  Alabama 78.07480
  3: 2016-01-10  Alabama 99.61034
  4: 2016-01-11  Alabama 79.11063
  5: 2016-01-12  Alabama 38.99888
 ---
116: 2016-01-19   Kansas 49.73827
117: 2016-01-24   Kansas 74.04788
118: 2016-01-25   Kansas 35.97654
119: 2016-01-26   Kansas 61.13266
120: 2016-01-31   Kansas 42.39633


来源: stackexchange

问:
React-Native and WebPack Hello World. Web Build not working
I have cloned this github project: github project
I've installed webpack globally. "I'm not sure if this is the issue, because I tried with a local version of webpack and it still didn't work"

I can't run the project. I am under the impression that if you download everything from a project, your package.json, and all configuration files should provide all the details for what npm needs to do to "install", and run a project. Am I missing something else?

I tried to run the project using

npm run web-dev

Here is the output npm-debug.log

```<code> info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'web-dev' ]
2 info using npm@3.10.10
3 info using node@v6.11.0
4 verbose run-script [ 'preweb-dev', 'web-dev', 'postweb-dev' ]
5 info lifecycle ClubApp@0.0.1~preweb-dev: ClubApp@0.0.1
6 silly lifecycle ClubApp@0.0.1~preweb-dev: no script for preweb-dev, continuing
7 info lifecycle ClubApp@0.0.1~web-dev: ClubApp@0.0.1
8 verbose lifecycle ClubApp@0.0.1~web-dev: unsafe-perm in lifecycle true
9 verbose lifecycle ClubApp@0.0.1~web-dev: PATH: C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin;C:\Users\clark\Documents\Test\ClubApp\node_modules\.bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\130\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;C:\Users\clark\AppData\Local\Microsoft\WindowsApps;C:\Users\clark\AppData\Roaming\npm;C:\Program Files (x86)\Microsoft VS Code\bin
10 verbose lifecycle ClubApp@0.0.1~web-dev: CWD: C:\Users\clark\Documents\Test\ClubApp
11 silly lifecycle ClubApp@0.0.1~web-dev: Args: [ '/d /s /c',
11 silly lifecycle   'webpack-dev-server --content-base web/public/ --config web/webpack/web.dev.config.js --port 3001 --inline --hot --colors' ]
12 silly lifecycle ClubApp@0.0.1~web-dev: Returned: code: 1  signal: null
13 info lifecycle ClubApp@0.0.1~web-dev: Failed to exec web-dev script
14 verbose stack Error: ClubApp@0.0.1 web-dev: `webpack-dev-server --content-base web/public/ --config web/webpack/web.dev.config.js --port 3001 --inline --hot --colors`
14 verbose stack Exit status 1
14 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\lib\utils\lifecycle.js:255:16)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at EventEmitter.emit (events.js:191:7)
14 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\lib\utils\spawn.js:40:14)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at ChildProcess.emit (events.js:191:7)
14 verbose stack     at maybeClose (internal/child_process.js:891:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid ClubApp@0.0.1
16 verbose cwd C:\Users\clark\Documents\Test\ClubApp
17 error Windows_NT 10.0.15063
18 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "web-dev"
19 error node v6.11.0
20 error npm  v3.10.10
21 error code ELIFECYCLE
22 error ClubApp@0.0.1 web-dev: `webpack-dev-server --content-base web/public/ --config web/webpack/web.dev.config.js --port 3001 --inline --hot --colors`
22 error Exit status 1
23 error Failed at the ClubApp@0.0.1 web-dev script 'webpack-dev-server --content-base web/public/ --config web/webpack/web.dev.config.js --port 3001 --inline --hot --colors'.
23 error Make sure you have the latest version of node.js and npm installed.
23 error If you do, this is most likely a problem with the ClubApp package,
23 error not with npm itself.
23 error Tell the author that this fails on your system:
23 error     webpack-dev-server --content-base web/public/ --config web/webpack/web.dev.config.js --port 3001 --inline --hot --colors
23 error You can get information on how to open an issue for this project with:
23 error     npm bugs ClubApp
23 error Or if that isn't available, you can get their info via:
23 error     npm owner ls ClubApp
23 error There is likely additional logging output above.
24 verbose exit [ 1, true ]
</code>```

答: Please run npm install before you try to run npm run web-dev

ContentLicense: CC BY-SA 3.0

Body:
I have cloned this github project: github project
I've installed webpack globally. "I'm not sure if this is the issue, because I tried with a local version of webpack and it still didn't work"

I can't run the project. I am under the impression that if you download everything from a project, your package.json, and all configuration files should provide all the details for what npm needs to do to "install", and run a project. Am I missing something else?

I tried to run the project using

npm run web-dev

Here is the output npm-debug.log

 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'web-dev' ]
2 info using npm@3.10.10
3 info using node@v6.11.0
4 verbose run-script [ 'preweb-dev', 'web-dev', 'postweb-dev' ]
5 info lifecycle ClubApp@0.0.1~preweb-dev: ClubApp@0.0.1
6 silly lifecycle ClubApp@0.0.1~preweb-dev: no script for preweb-dev, continuing
7 info lifecycle ClubApp@0.0.1~web-dev: ClubApp@0.0.1
8 verbose lifecycle ClubApp@0.0.1~web-dev: unsafe-perm in lifecycle true
9 verbose lifecycle ClubApp@0.0.1~web-dev: PATH: C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin;C:\Users\clark\Documents\Test\ClubApp\node_modules\.bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\130\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;C:\Users\clark\AppData\Local\Microsoft\WindowsApps;C:\Users\clark\AppData\Roaming\npm;C:\Program Files (x86)\Microsoft VS Code\bin
10 verbose lifecycle ClubApp@0.0.1~web-dev: CWD: C:\Users\clark\Documents\Test\ClubApp
11 silly lifecycle ClubApp@0.0.1~web-dev: Args: [ '/d /s /c',
11 silly lifecycle   'webpack-dev-server --content-base web/public/ --config web/webpack/web.dev.config.js --port 3001 --inline --hot --colors' ]
12 silly lifecycle ClubApp@0.0.1~web-dev: Returned: code: 1  signal: null
13 info lifecycle ClubApp@0.0.1~web-dev: Failed to exec web-dev script
14 verbose stack Error: ClubApp@0.0.1 web-dev: `webpack-dev-server --content-base web/public/ --config web/webpack/web.dev.config.js --port 3001 --inline --hot --colors`
14 verbose stack Exit status 1
14 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\lib\utils\lifecycle.js:255:16)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at EventEmitter.emit (events.js:191:7)
14 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\lib\utils\spawn.js:40:14)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at ChildProcess.emit (events.js:191:7)
14 verbose stack     at maybeClose (internal/child_process.js:891:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid ClubApp@0.0.1
16 verbose cwd C:\Users\clark\Documents\Test\ClubApp
17 error Windows_NT 10.0.15063
18 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "web-dev"
19 error node v6.11.0
20 error npm  v3.10.10
21 error code ELIFECYCLE
22 error ClubApp@0.0.1 web-dev: `webpack-dev-server --content-base web/public/ --config web/webpack/web.dev.config.js --port 3001 --inline --hot --colors`
22 error Exit status 1
23 error Failed at the ClubApp@0.0.1 web-dev script 'webpack-dev-server --content-base web/public/ --config web/webpack/web.dev.config.js --port 3001 --inline --hot --colors'.
23 error Make sure you have the latest version of node.js and npm installed.
23 error If you do, this is most likely a problem with the ClubApp package,
23 error not with npm itself.
23 error Tell the author that this fails on your system:
23 error     webpack-dev-server --content-base web/public/ --config web/webpack/web.dev.config.js --port 3001 --inline --hot --colors
23 error You can get information on how to open an issue for this project with:
23 error     npm bugs ClubApp
23 error Or if that isn't available, you can get their info via:
23 error     npm owner ls ClubApp
23 error There is likely additional logging output above.
24 verbose exit [ 1, true ]


问:
Styling divs to align correctly
I think I don't perfectly understand inline, block, float, etc. and was hoping for some help. I'm trying to achieve this setup:

The idea is to display the most common languages our clients use. I want to have a block that has the top 5 most common, with the most common getting a spotlight section. Then just list the rest of the languages underneath.

However, my code just pushes everything to the left, and the lets the rest of the page (like the footer) next to it. I want the top language and the next 4 to be next to each other, in the center of the screen, without affecting the page below it.

body {
    font-family: Arial;
    transition: all ease .5s;
    text-align: center;
    color: rgb(58,58,58);
}

#footer ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 100%;
    background-color: #666;
}

#footer li {
    float: left;
}

#footer li p {
    display: block;
    color: #555;
    text-align: center;
    padding: 7px 16px;
}

br {
    display: block;
}

#footer li a {
    display: block;
    color: #555;
    text-align: center;
    text-decoration: none;
}

#footer li a:hover {
    display: block;
    color: #555;
    text-align: center;
    text-decoration: underline;
}

#language-stats li {
    display: inline-block;
    padding: 13px;
    margin: 6px;
    border-radius: 5px;
    color: rgb(58,58,58);
    background-color: rgb(210,210,210);
    font-weight: bold;
}

#top-5 {
  width: 600px;
}

#top-1 {
  float: left;
  width: 250px;
  height: 300px;
  background-color: #fff;
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
  text-align: center;
}

#next-4 {
  float: left;
  width: 350px;
  height: 300px;
  background-color: #f5f5f5;
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Test</title>
</head>

  <div id="languages">

    <div id="top-5">
      <h3>Top Languages</h3>

      <div id="top-1">
        <svg height="70" width="60">
          <circle cx="30" cy="40" r="30" fill="#CECECE" />
          <text x="18" y="53" style="font-size: 40;
                                     stroke: #fff;
                                     fill: #fff">1</text>
        </svg>
      </div>
      <div id="next-4">
        <ul>
          <li>2: Example</li>
          <li>3: Example</li>
          <li>4: Example</li>
          <li>5: Example</li>
        </ul>
      </div>
    </div>

    <div id="language-stats">
      <h3>Language Stats</h3>
      <ul id="language-stats-list">
        <li>Languages Represented: 37</li>
        <li>Coolest Language: Example</li>
      </ul>
    </div>

  </div>
  <br />
  <hr />
  <div id="footer">
    <ul>
        <li><p>Download CSV</p></li>
        <li><p>Link to dictionary</p></li>
    </ul>
  </div>
</body>
</html></code>```

(You have to see the snippet in full page to witness the issue.)

What am I missing to have the cleaner layout I desire?

答:
In your example, if you'd like the language-stats div to appear under your floated top-1 and next-4 elements, you'll just need to add the style clear: left to language-stats.  This will effectively line-break it below the other two elements.

Additionally, you'll want to add margin: 0px auto to the styles of the top-5 div- this will equally space the left and right margins of your 600px-wide element and center it on the page.

Title: Styling divs to align correctly

Body:
I think I don't perfectly understand inline, block, float, etc. and was hoping for some help. I'm trying to achieve this setup:

The idea is to display the most common languages our clients use. I want to have a block that has the top 5 most common, with the most common getting a spotlight section. Then just list the rest of the languages underneath.

However, my code just pushes everything to the left, and the lets the rest of the page (like the footer) next to it. I want the top language and the next 4 to be next to each other, in the center of the screen, without affecting the page below it.

body {
    font-family: Arial;
    transition: all ease .5s;
    text-align: center;
    color: rgb(58,58,58);
}

#footer ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 100%;
    background-color: #666;
}

#footer li {
    float: left;
}

#footer li p {
    display: block;
    color: #555;
    text-align: center;
    padding: 7px 16px;
}

br {
    display: block;
}

#footer li a {
    display: block;
    color: #555;
    text-align: center;
    text-decoration: none;
}

#footer li a:hover {
    display: block;
    color: #555;
    text-align: center;
    text-decoration: underline;
}

#language-stats li {
    display: inline-block;
    padding: 13px;
    margin: 6px;
    border-radius: 5px;
    color: rgb(58,58,58);
    background-color: rgb(210,210,210);
    font-weight: bold;
}

#top-5 {
  width: 600px;
}

#top-1 {
  float: left;
  width: 250px;
  height: 300px;
  background-color: #fff;
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
  text-align: center;
}

#next-4 {
  float: left;
  width: 350px;
  height: 300px;
  background-color: #f5f5f5;
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Test</title>

Top Languages

        <svg height="70" width="60">
          <circle cx="30" cy="40" r="30" fill="#CECECE" />
          <text x="18" y="53" style="font-size: 40;
                                     stroke: #fff;
                                     fill: #fff">1</text>
        </svg>

2: Example

3: Example

4: Example

5: Example

Language Stats

Languages Represented: 37

Coolest Language: Example

Download CSV

Link to dictionary

(You have to see the snippet in full page to witness the issue.)

What am I missing to have the cleaner layout I desire?


问:
jQuery if button is not pressed
I want to check wether a button is pressed in jQuery. If the button is pressed the page has to scroll down. If the button it not pressed the page shows an animation and once this is finished it has to scroll down.

Now I have this:

```<code>$('#btmmdl').click(function(){
    $(this).data('clicked', true);
});

if($('#btmmdl').data('clicked')){
    // Scroll down
} else {
    // Show animation and scroll down after 9 seconds
}
</code>```

Am I doing something wrong?

答:
I tried a lot of solutions below but finally (through another question) found a solution that worked for me.

```<code>var scroll = setTimeout(function(){
  // Show animation and scroll down after 9 seconds
}, 9000);

$('#btmmdl').click(function(){
      // Scroll down
        clearTimeout(scroll);
    });
</code>```

The clearTimeout function with the Timeout as a var did it for me, but I was nog aware of this functionality.

Thanks for the answers!

Title: jQuery if button is not pressed

Body:
I want to check wether a button is pressed in jQuery. If the button is pressed the page has to scroll down. If the button it not pressed the page shows an animation and once this is finished it has to scroll down.

Now I have this:

$('#btmmdl').click(function(){
    $(this).data('clicked', true);
});

if($('#btmmdl').data('clicked')){
    // Scroll down
} else {
    // Show animation and scroll down after 9 seconds
}

Am I doing something wrong?

Body:
I tried a lot of solutions below but finally (through another question) found a solution that worked for me.

var scroll = setTimeout(function(){
  // Show animation and scroll down after 9 seconds
}, 9000);

$('#btmmdl').click(function(){
      // Scroll down
        clearTimeout(scroll);
    });

The clearTimeout function with the Timeout as a var did it for me, but I was nog aware of this functionality.

Thanks for the answers!


问:
How do I get Devise's Rememberable module to use http_only for the remember me cookie?
The rails session cookie is HttpOnly by default but the remember_user_token cookie set by Devise's Rememberable module is not.

As I understand it that cookie when sent will result in the user being issued a new session cookie, so surely it's as vulnerable to XSS.

So is there any way to set it to HttpOnly?

答:
With the help of @camonz on #rubyonrails I came up with this monkey patch:
https://gist.github.com/749289

In Devise 1.1.3 the cookie options are hardcoded so a monkey patch is all I could think would work.

However, Devise 1.2rc looks like it will allow configuration because it pulls in resource.cookie_options (e.g. pulling cookie_options from the User model, so you should be able to set it there somehow - haven't figured that out yet).

P.S. I haven't figured out how to test this yet. To test manually in Chrome switch to the tab the cookie is set in, open Developer Tools with Alt + Cmd + I, switch to the Storage tab, click the item under 'Cookies' (localhost in my case), and look at the HTTP column. There'll be a tick if the cookie is HttpOnly. For reference the rails session cookie, called _session_id by default, is HttpOnly by default.

ContentLicense: CC BY-SA 2.5


问:
In Qt how can I delay a member function's return until a signal is received?
I want to use a recursive procedure to iterate through a large number of images in Qt: essentially the image is repeatedly quartered (up to a limit) and the user is asked whether the image passes or fails - ie if the image passes at large dimensions we call our function again with smaller dimensions (until we reach the limit), if it fails we return and so pass back up the hierarchy.

This approach seems to run into a roadblock with Qt's event-driven approach - I cannot see how I can pause the loop while waiting for the user input - ie there is nothing like a "wait_for_button_press" method.

I know that this sort of approach is regarded as an anti-pattern in event driven programming, but what is the alternative way that doesn't involve holding lots and lots of state on the heap (as opposed to getting it held for 'free' on the stack)?

答:
QEventLoop maybe could help you. I start a http connection aside a timer with a timeout, all inside a thread. Then a wait for one of those had finish and return.</p>

```<code>void MyThread::run(){
  QNetworkAccessManager qnaManager;
  bool isPost = false;

  QUrl url(myUrl);
  QNetworkRequest req(url);
  QNetworkReply *reply;

  req.setHeader(QNetworkRequest::ContentTypeHeader,
            "application/json");
  req.setHeader(QNetworkRequest::ContentLengthHeader,
            QVariant(postData.size()).toString());

  reply = qnaManager.get(req);

  QEventLoop eventLoop;
  QTimer timer;
  timer.setSingleShot(true);
  const int timeout = 400;
  timer.start(timeout);

  connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
  connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
  eventLoop.exec();

  if (timer.isActive()){
    //everything is ok
  }else{
    //timer elapsed, no replay
    return;
  }

}
</code>```

Body:
QEventLoop maybe could help you. I start a http connection aside a timer with a timeout, all inside a thread. Then a wait for one of those had finish and return.

void MyThread::run(){
  QNetworkAccessManager qnaManager;
  bool isPost = false;

  QUrl url(myUrl);
  QNetworkRequest req(url);
  QNetworkReply *reply;

  req.setHeader(QNetworkRequest::ContentTypeHeader,
            "application/json");
  req.setHeader(QNetworkRequest::ContentLengthHeader,
            QVariant(postData.size()).toString());

  reply = qnaManager.get(req);

  QEventLoop eventLoop;
  QTimer timer;
  timer.setSingleShot(true);
  const int timeout = 400;
  timer.start(timeout);

  connect(&timer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
  connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
  eventLoop.exec();

  if (timer.isActive()){
    //everything is ok
  }else{
    //timer elapsed, no replay
    return;
  }

}


问:
Remove undefined properties from object
I would like to recursively clean any fields which are undefined, or have an empty object as parent like this following:

Example:

```<code>{
  "a": {
    "b": {
      "c": undefined,
    }
  },
  "d": undefined,
  "e": {
    f: undefined,
  },
  "g": {
     "h": 'I',
     "j": undefined,
  },
  "k": "L",
  "m": {
     "n": {
       "o": {
         "z": undefined,
       }
     },
    "p": 'toto'
   }
}
</code>```

I am expecting the following result :

```<code>{
  "g": {
    "h": 'I',
  },
  "k": 'L',
  "m": {
    "p": 'toto'
  }
}
</code>```

Thank you for your help

答:
function cleanArray(actual) {
  var newArray = new Object();
 newArray=JSON.parse(JSON.stringify(actual));
  return newArray;
}
var obj={
  "a": {
    "b": {
      "c": undefined,
    }
  },
  "d": undefined,
  "e": {
    f: undefined,
  },
  "g": {
     "h": 'I',
     "j": undefined,
  },
  "k": "L",
  "m": {
     "n": {
       "o": {
         "z": undefined,
       }
     },
    "p": 'toto'
   }
};
console.log(cleanArray(obj));```

Title: Remove undefined properties from object

Body:
I would like to recursively clean any fields which are undefined, or have an empty object as parent like this following:

Example:

{
  "a": {
    "b": {
      "c": undefined,
    }
  },
  "d": undefined,
  "e": {
    f: undefined,
  },
  "g": {
     "h": 'I',
     "j": undefined,
  },
  "k": "L",
  "m": {
     "n": {
       "o": {
         "z": undefined,
       }
     },
    "p": 'toto'
   }
}

I am expecting the following result :

{
  "g": {
    "h": 'I',
  },
  "k": 'L',
  "m": {
    "p": 'toto'
  }
}

Thank you for your help


问:
Install OpenWhisk CLI on mac
I am unable to install OpenWhisk command line for some reason. I download the CLI and double click to run it. I see a terminal window saying </p>

```<code>[Process Complete]
</code>```

<p>But then it says </p>

```<code>-bash: wsk: command not found
</code>```

答:
Download wsk cli from here.

Go to downloads folder and modify permissions for wsk file using terminal

$ chmod +x ./wsk

Move wsk to use/local/bin folder using terminal. This will add wsk to the PATH

$ sudo mv wsk /usr/local/bin

Test this using following command:

$ wsk --help

ContentLicense: CC BY-SA 4.0

Title: Install OpenWhisk CLI on mac

Body:
I am unable to install OpenWhisk command line for some reason. I download the CLI and double click to run it. I see a terminal window saying

[Process Complete]

But then it says

-bash: wsk: command not found


问:
FFMPEG: how to wrap h264 stream into FLV container?
What I want is straightforward: wrap H.264 video stream into a FLV container. However, ffmpeg just decode the input stream and pack raw video stream into FLV. The details are described below:

The input stream is captured from a hardware-encoder video camera, and the FLV will be sent to some video server. Firstly I used following command:

```<code>$ ffmpeg -framerate 15 -s 320x240 -i /dev/video1 -f flv "rtmp://some.website.com/receive/path"
</code>```

However, the resultant stream is suspicious. The watching side don't get any H.264 thing. Then I made a test by writing output to local files.

1: Read raw stream, encode by h264_omx, write to FLV file:

```<code>$ ffmpeg -framerate 15 -s 320x240 -i /dev/video0 -codec h264_omx -f flv raw_input_h264_omx.flv

......
Input #0, video4linux2,v4l2, from '/dev/video0':
  Duration: N/A, start: 194017.870905, bitrate: 18432 kb/s
    Stream #0:0: Video: rawvideo (YUY2 / 0x32595559), yuyv422, 320x240, 18432 kb/s, 15 fps, 15 tbr, 1000k tbn, 1000k tbc
Stream mapping:
  Stream #0:0 -> #0:0 (rawvideo (native) -> h264 (h264_omx))
......
</code>```

2: Read H264 stream, write to FLV file:

```<code>$ ffmpeg -framerate 15 -s 320x240 -i /dev/video1  -f flv h264_input.flv

......
Input #0, video4linux2,v4l2, from '/dev/video1':
  Duration: N/A, start: 194610.307096, bitrate: N/A
    Stream #0:0: Video: h264 (Main), yuv420p(progressive), 320x240, 15 fps, 15 tbr, 1000k tbn, 2000k tbc
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> flv1 (flv))
......
</code>```

Then read the two files correspondingly:

```<code>$ ffmpeg -i raw_input_h264_omx.flv
......
    Stream #0:0: Video: h264 (High), yuv420p(progressive), 320x240, 200 kb/s, 15 fps, 15 tbr, 1k tbn

$ ffmpeg -i h264_input.flv
......
    Stream #0:0: Video: flv1, yuv420p, 320x240, 200 kb/s, 15 fps, 15 tbr, 1k tbn
</code>```

It is clear when I give a H.264 stream, ffmpeg firstly decodes it, then pack the raw video into FLV. How to avoid that happen, and have the H.264 stream packed directly?

Supplement: I will eventually pushing multiple video streams, so don't ask me to allow ffmpeg's silent decoding, and encode the stream again.

答:
Unless told otherwise, ffmpeg will transcode streams.

Use

```<code>ffmpeg -framerate 15 -s 320x240 -i /dev/video1 -c copy -f flv "rtmp://website/receive/path"
</code>```

Body:
What I want is straightforward: wrap H.264 video stream into a FLV container. However, ffmpeg just decode the input stream and pack raw video stream into FLV. The details are described below:

The input stream is captured from a hardware-encoder video camera, and the FLV will be sent to some video server. Firstly I used following command:

$ ffmpeg -framerate 15 -s 320x240 -i /dev/video1 -f flv "rtmp://some.website.com/receive/path"

However, the resultant stream is suspicious. The watching side don't get any H.264 thing. Then I made a test by writing output to local files.

1: Read raw stream, encode by h264_omx, write to FLV file:

$ ffmpeg -framerate 15 -s 320x240 -i /dev/video0 -codec h264_omx -f flv raw_input_h264_omx.flv

......
Input #0, video4linux2,v4l2, from '/dev/video0':
  Duration: N/A, start: 194017.870905, bitrate: 18432 kb/s
    Stream #0:0: Video: rawvideo (YUY2 / 0x32595559), yuyv422, 320x240, 18432 kb/s, 15 fps, 15 tbr, 1000k tbn, 1000k tbc
Stream mapping:
  Stream #0:0 -> #0:0 (rawvideo (native) -> h264 (h264_omx))
......

2: Read H264 stream, write to FLV file:

$ ffmpeg -framerate 15 -s 320x240 -i /dev/video1  -f flv h264_input.flv

......
Input #0, video4linux2,v4l2, from '/dev/video1':
  Duration: N/A, start: 194610.307096, bitrate: N/A
    Stream #0:0: Video: h264 (Main), yuv420p(progressive), 320x240, 15 fps, 15 tbr, 1000k tbn, 2000k tbc
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> flv1 (flv))
......

Then read the two files correspondingly:

$ ffmpeg -i raw_input_h264_omx.flv
......
    Stream #0:0: Video: h264 (High), yuv420p(progressive), 320x240, 200 kb/s, 15 fps, 15 tbr, 1k tbn

$ ffmpeg -i h264_input.flv
......
    Stream #0:0: Video: flv1, yuv420p, 320x240, 200 kb/s, 15 fps, 15 tbr, 1k tbn

It is clear when I give a H.264 stream, ffmpeg firstly decodes it, then pack the raw video into FLV. How to avoid that happen, and have the H.264 stream packed directly?

Supplement: I will eventually pushing multiple video streams, so don't ask me to allow ffmpeg's silent decoding, and encode the stream again.

Body:
Unless told otherwise, ffmpeg will transcode streams.

Use

ffmpeg -framerate 15 -s 320x240 -i /dev/video1 -c copy -f flv "rtmp://website/receive/path"


问:
Error deploying meteor app
I get the following error during the verifying deployment stage of deploying a meteor app

The full log is a long list of similar errors of fetch failed ending with

答:
I fixed it by restarting the docker service

thanks to this answer

restarting docker with this command fixes it for me but I don't know why

sudo service docker restart

I too, have no idea why that worked

Title: Error deploying meteor app


问:
Use sed/awk to remove the last portion of a delimited-text column
I have a file with rows of values. The first column, a PacBio read ID, is a forward-slash-delimited value. I would like to modify the column by removing the final slash and values beyond it. Ideally the result would be stream-able (sed/awk, etc.) and would not rely on the number of forward slashes (i.e. the solution should work whether there is a single forward slash, or three, as below.) </p>

```<code># example row
m54151_170617_100137/4194626/10117_11723/0_1606 1257    1606

# desired row
m54151_170617_100137/4194626/10117_11723    1257    1606
</code>```

答:
If you don't mind slightly modifying the whitespace:

```<code>awk '{sub("/[^/]*$","",$1)}1' input
</code>```

If whitespace matters:

```<code>sed 's@^\([^ ]*\)/[^ /]* @\1 @' input
</code>```

Body:
I have a file with rows of values. The first column, a PacBio read ID, is a forward-slash-delimited value. I would like to modify the column by removing the final slash and values beyond it. Ideally the result would be stream-able (sed/awk, etc.) and would not rely on the number of forward slashes (i.e. the solution should work whether there is a single forward slash, or three, as below.)

# example row
m54151_170617_100137/4194626/10117_11723/0_1606 1257    1606

# desired row
m54151_170617_100137/4194626/10117_11723    1257    1606

Body:
If you don't mind slightly modifying the whitespace:

awk '{sub("/[^/]*$","",$1)}1' input

If whitespace matters:

sed 's@^\([^ ]*\)/[^ /]* @\1 @' input


问:
Returning a Mongoose Aggregate Function to Angular
I'm trying to figure out how to return an aggregate function to Angular but I keep getting errors. I'm really stuck on this and would appreciate some help on what I'm doing wrong. I get an error telling me Cannot read property 'aggregate' of undefined.

 This is my route that the angular connects to:

```<code>router.get('/enrolledin', function(req, res) {
    var isEnrolled = Enrolled.findDetails(); //Enrolled.studentIsTaking(student);
       isEnrolled.then((user) => {
        res.json(user);
    })
        .catch((err) => {
        res.send("error found");
    });

});
</code>```

Here's the Enrolled.findDetails():

```<code> module.exports.findDetails = function() {
    var x = db.enrolleds.aggregate(
        { $lookup:
         {
             from:'classstores',
             localField:'classID',
             foreignField: 'classKey',
             as: 'matching'
         }
        }

    );
    return x;
}
</code>```

答:
I believe aggregate (scroll to example) expects an array not an object.

Aside: I'm not sure why people love to use then and catch with mongoose. IMO it seems unnecessary and makes your code longer.

I would simply rewrite it your code like this:

```<code>router.get('/enrolledin', (req, res) => {
    Enrolled.findDetails((err, users) => {
        if (err)
            return res.send('error found', err);
        res.json(users);
    });
});

module.exports.findDetails = (callback) => {
    db.enrolleds.aggregate([
        {
            $lookup: {
                from: 'classstores',
                localField: 'classID',
                foreignField: 'classKey',
                as: 'matching'
            }
        }
    ], callback);
};
</code>```

Body:
I'm trying to figure out how to return an aggregate function to Angular but I keep getting errors. I'm really stuck on this and would appreciate some help on what I'm doing wrong. I get an error telling me Cannot read property 'aggregate' of undefined.

 This is my route that the angular connects to:

router.get('/enrolledin', function(req, res) {
    var isEnrolled = Enrolled.findDetails(); //Enrolled.studentIsTaking(student);
       isEnrolled.then((user) => {
        res.json(user);
    })
        .catch((err) => {
        res.send("error found");
    });

});

Here's the Enrolled.findDetails():

 module.exports.findDetails = function() {
    var x = db.enrolleds.aggregate(
        { $lookup:
         {
             from:'classstores',
             localField:'classID',
             foreignField: 'classKey',
             as: 'matching'
         }
        }

    );
    return x;
}

Body:
I believe aggregate (scroll to example) expects an array not an object.

Aside: I'm not sure why people love to use then and catch with mongoose. IMO it seems unnecessary and makes your code longer.

I would simply rewrite it your code like this:

router.get('/enrolledin', (req, res) => {
    Enrolled.findDetails((err, users) => {
        if (err)
            return res.send('error found', err);
        res.json(users);
    });
});

module.exports.findDetails = (callback) => {
    db.enrolleds.aggregate([
        {
            $lookup: {
                from: 'classstores',
                localField: 'classID',
                foreignField: 'classKey',
                as: 'matching'
            }
        }
    ], callback);
};


问:
PHP Header in CRON Job not working
I am using this code header('Location: http://example.com/test.php?number='.$requestsDone.'');

But looks like it is not working, what is wrong here?

Let me know, if you need more information.

答:
Producing a header in a command line script doesn't make any sense. The header is part of the HTTP protocol, there is no HTTP involved when the script is executed using the CLI version of PHP.

Accordingly, the header() function is not implemented in the CLI version of PHP. It exists, but it doesn't produce any output.

Also, the superglobals that contain information extracted from the HTTP request ($_GET[], $_POST[], $_REQUEST[], $_FILES[], $_COOKIE[] etc) exist but they are empty.

In order to pass arguments to a script using the command line, use the $argc and $argv[] variables.

Title: PHP Header in CRON Job not working


问:
How can I get the length of the longest string in a column (Excel)?
I have an Excel spreadsheet that I am writing out to a file.  I am currently using the following method to reproduce the contents of each cell:

```<code>cell_contents = Right(Space(10) & Trim(Cells(iRow, iColumn)), 10)
</code>```

However, if the contents of the cell are longer than 10 characters long (or however long I choose to specify), then I loose parts of the data.  Is there a way to quickly and easily get the length of the longest string in a range of cells?

I have seen people suggest using the following loop, but I was hoping that I might be able to do it without having to loop over all the cells:

```<code>For Each c In SourceRange.Cells
   if len(c) > b then b = len(c)
Next c
</code>```

答:
Suppose that the data is in column A and there is a heading row for your spreadsheet.

Create a new column next to it and enter in the formula: =LEN(A2)

Autofill down that formula.

Turn on filtering for that column and the click the drop-down box on the column heading cell.

Scroll down to the bottom of the list where the largest summarized value is.

That will be the largest value in the column.

Body:
I have an Excel spreadsheet that I am writing out to a file.  I am currently using the following method to reproduce the contents of each cell:

cell_contents = Right(Space(10) & Trim(Cells(iRow, iColumn)), 10)

However, if the contents of the cell are longer than 10 characters long (or however long I choose to specify), then I loose parts of the data.  Is there a way to quickly and easily get the length of the longest string in a range of cells?

I have seen people suggest using the following loop, but I was hoping that I might be able to do it without having to loop over all the cells:

For Each c In SourceRange.Cells
   if len(c) > b then b = len(c)
Next c


问:
Is is possible to proxy a COM interface using Spring.Net?
I am trying to create a dynamic proxy using Spring.NET and C# for a COM interface.  I am currently experimenting using code, not config files.
I have code similar to the following:

```<code>Type comInterfaceType = typeof(ICOMInterface);
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.AddInterface(comInterfaceType);
proxyFactory.GetProxy();
</code>```

It blows up at the GetProxy() call with the following exception:

```<code>System.InvalidOperationException: The property with name ArraySubType can't be found
    in the type System.Runtime.InteropServices.MarshalAsAttribute, but is present as
    a named property on the attributeData
[System.Runtime.InteropServices.MarshalAsAttribute(
    (System.Runtime.InteropServices.UnmanagedType)28, ArraySubType = 0, SizeParamIndex
    = 0, SizeConst = 0, IidParameterIndex = 0, SafeArraySubType = 0)]
</code>```

Is this simply not possible?  I am still using Spring.NET 1.1, is this possible in the newer versions (which we will finally be moving to soon)?

UPDATE: After experimenting, I got this same error with slightly different parameters (ie. UnmanagedType 44) when proxying the Form class as well.

答: It seems this was a result of a bug in Spring.NET 1.1 when generating attributes for proxied methods: https://issues.springsource.org/browse/SPRNET-852?page=com.atlassian.streams.streams-jira-plugin%3Aactivity-stream-issue-tab.  We have a solution to test migrating to the latest Spring version, and so I tested this there.  It worked.</p>

Body:
I am trying to create a dynamic proxy using Spring.NET and C# for a COM interface.  I am currently experimenting using code, not config files.
I have code similar to the following:

Type comInterfaceType = typeof(ICOMInterface);
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.AddInterface(comInterfaceType);
proxyFactory.GetProxy();

It blows up at the GetProxy() call with the following exception:

System.InvalidOperationException: The property with name ArraySubType can't be found
    in the type System.Runtime.InteropServices.MarshalAsAttribute, but is present as
    a named property on the attributeData
[System.Runtime.InteropServices.MarshalAsAttribute(
    (System.Runtime.InteropServices.UnmanagedType)28, ArraySubType = 0, SizeParamIndex
    = 0, SizeConst = 0, IidParameterIndex = 0, SafeArraySubType = 0)]

Is this simply not possible?  I am still using Spring.NET 1.1, is this possible in the newer versions (which we will finally be moving to soon)?

UPDATE: After experimenting, I got this same error with slightly different parameters (ie. UnmanagedType 44) when proxying the Form class as well.


问:
EmberJS - throw error on `firebase` implementation
In my emberjs - i am implementing the firebase data base. for that I have changed the environment settings like this: ( please see my comments )

```<code>module.exports = function(environment) {
    var ENV = {
        modulePrefix: 'ember-simple-blog-eee6c',
        environment: environment,
        rootURL: '/',
        contentSecurityPolicy: {
            'script-src': "'self' 'unsafe-eval' apis.google.com",
            'frame-src': "'self' https://*.firebaseapp.com",
            'connect-src': "'self' wss://*.firebaseio.com https://*.googleapis.com"
        },
        firebase: {
            authDomain: 'ember-simple-blog-eee6c.firebaseapp.com',
            databaseURL: 'https://ember-simple-blog-eee6c.firebaseio.com/',
            projectId: "ember-simple-blog-eee6c",
            storageBucket: "",
            messagingSenderId: "731960884482" //note sure taken from previous app
        },
        locationType: 'auto',
        EmberENV: {
            FEATURES: {
                // Here you can enable experimental features on an ember canary build
                // e.g. 'with-controller': true
            },
            EXTEND_PROTOTYPES: {
                // Prevent Ember Data from overriding Date.parse.
                Date: false
            }
        },

        APP: {
            // Here you can pass flags/options to your application instance
            // when it is created
        },

        contentSecurityPolicy: {
            'font-src': "'self' data: fonts.gstatic.com",
            'style-src': "'self' 'unsafe-inline' fonts.googleapis.com"
        }
    };

    if (environment === 'development') {
        // ENV.APP.LOG_RESOLVER = true;
        // ENV.APP.LOG_ACTIVE_GENERATION = true;
        // ENV.APP.LOG_TRANSITIONS = true;
        // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
        // ENV.APP.LOG_VIEW_LOOKUPS = true;
    }

    if (environment === 'test') {
        // Testem prefers this...
        ENV.locationType = 'none';

        // keep test console output quieter
        ENV.APP.LOG_ACTIVE_GENERATION = false;
        ENV.APP.LOG_VIEW_LOOKUPS = false;

        ENV.APP.rootElement = '#ember-testing';
    }

    if (environment === 'production') {

    }

    return ENV;
};
</code>```

After implemented this config, I am getting error as :

```<code>Uncaught Error: Could not find module `ember-simple-blog-eee6c/app` imported from `(require)`
</code>```

What is wrong here? how to solve this? any one please help me .

Thanks in advance.

答: I suspect that your firebase has nothing to do with your error. I'm able to recreate your error on my own app by giving module-prefix an incorrect name. Is it possible you are naming your module-prefix after your firebase project instead of your ember Project? If so, I think that might be the reason. I think you need your modulePrefix to have the same name as the folder your Ember project is inside of.

Body:
In my emberjs - i am implementing the firebase data base. for that I have changed the environment settings like this: ( please see my comments )

module.exports = function(environment) {
    var ENV = {
        modulePrefix: 'ember-simple-blog-eee6c',
        environment: environment,
        rootURL: '/',
        contentSecurityPolicy: {
            'script-src': "'self' 'unsafe-eval' apis.google.com",
            'frame-src': "'self' https://*.firebaseapp.com",
            'connect-src': "'self' wss://*.firebaseio.com https://*.googleapis.com"
        },
        firebase: {
            authDomain: 'ember-simple-blog-eee6c.firebaseapp.com',
            databaseURL: 'https://ember-simple-blog-eee6c.firebaseio.com/',
            projectId: "ember-simple-blog-eee6c",
            storageBucket: "",
            messagingSenderId: "731960884482" //note sure taken from previous app
        },
        locationType: 'auto',
        EmberENV: {
            FEATURES: {
                // Here you can enable experimental features on an ember canary build
                // e.g. 'with-controller': true
            },
            EXTEND_PROTOTYPES: {
                // Prevent Ember Data from overriding Date.parse.
                Date: false
            }
        },

        APP: {
            // Here you can pass flags/options to your application instance
            // when it is created
        },

        contentSecurityPolicy: {
            'font-src': "'self' data: fonts.gstatic.com",
            'style-src': "'self' 'unsafe-inline' fonts.googleapis.com"
        }
    };

    if (environment === 'development') {
        // ENV.APP.LOG_RESOLVER = true;
        // ENV.APP.LOG_ACTIVE_GENERATION = true;
        // ENV.APP.LOG_TRANSITIONS = true;
        // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
        // ENV.APP.LOG_VIEW_LOOKUPS = true;
    }

    if (environment === 'test') {
        // Testem prefers this...
        ENV.locationType = 'none';

        // keep test console output quieter
        ENV.APP.LOG_ACTIVE_GENERATION = false;
        ENV.APP.LOG_VIEW_LOOKUPS = false;

        ENV.APP.rootElement = '#ember-testing';
    }

    if (environment === 'production') {

    }

    return ENV;
};

After implemented this config, I am getting error as :

Uncaught Error: Could not find module `ember-simple-blog-eee6c/app` imported from `(require)`

What is wrong here? how to solve this? any one please help me .

Thanks in advance.


问:
Swift - Array to TableView in macOS
I have some data form a JSON file which I have converted into:

```<code>var tempArray = [NSDictionary]()
</code>```

Here is what a sample of this data looks like:

```<code>(
    {
        active = y;
        "campaign_id" = "Sample ID 1";
        description = "Sample Text";
        "end_date_time" = "2017-10-01 00:00:00";
        "on_expiry" = ignore;
        "on_invalid_user" = reject;
        "start_date_time" = "2017-07-01 00:00:00";
        "voucher_code" = SAMPLEON1;
        "voucher_code_id" = "Sample ID 4";
    },
    {
        active = y;
        "campaign_id" = "Sample ID 2";
        description = "Sample Text";
        "end_date_time" = "2017-10-01 00:00:00";
        "on_expiry" = ignore;
        "on_invalid_user" = reject;
        "start_date_time" = "2017-06-02 00:00:00";
        "voucher_code" = SAMPLEOFF1;
        "voucher_code_id" = "Sample ID 5";
    }
)
</code>```

I have a NSTableView outlet set up, and it has columns with identifiers relative to the dictionary above:

```<code>@IBOutlet var voucherTableView: NSTableView!
</code>```

Once I run the voucherTableView.reloadData(); code in my Controller the table populates with the right amount of rows, but the data in the columns is all the same:

Here is my tableView func:

```<code>private func tableView(tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {

        let cellView = voucherTableView.make(withIdentifier: "cell", owner: self) as! NSTableCellView

        cellView.textField!.stringValue = self.values.object(at: row) as! String

        return cellView
    }
</code>```

Does anyone have any insight into how to get the data from my Array into the tableView on the reload command?

答:
I recommend to use Cocoa Bindings

Connect datasource of the table view in Interface Builder to the target class

Implement these two methods (viewForColumn:row is not needed)

```<code>func numberOfRows(in tableView: NSTableView) -> Int
{
    return tempArray.count
}

func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any?
{
   return tempArray[row]
}
</code>```

In Interface Builder Bindings Inspector bind the value of the text field to Table Cell View > objectValue.[property] for example

Note: It's highly recommended to map the dictionaries to a custom class (a class inherited from NSObject is mandatory)

Title: Swift - Array to TableView in macOS

Body:
I have some data form a JSON file which I have converted into:

var tempArray = [NSDictionary]()

Here is what a sample of this data looks like:

(
    {
        active = y;
        "campaign_id" = "Sample ID 1";
        description = "Sample Text";
        "end_date_time" = "2017-10-01 00:00:00";
        "on_expiry" = ignore;
        "on_invalid_user" = reject;
        "start_date_time" = "2017-07-01 00:00:00";
        "voucher_code" = SAMPLEON1;
        "voucher_code_id" = "Sample ID 4";
    },
    {
        active = y;
        "campaign_id" = "Sample ID 2";
        description = "Sample Text";
        "end_date_time" = "2017-10-01 00:00:00";
        "on_expiry" = ignore;
        "on_invalid_user" = reject;
        "start_date_time" = "2017-06-02 00:00:00";
        "voucher_code" = SAMPLEOFF1;
        "voucher_code_id" = "Sample ID 5";
    }
)

I have a NSTableView outlet set up, and it has columns with identifiers relative to the dictionary above:

@IBOutlet var voucherTableView: NSTableView!

Once I run the voucherTableView.reloadData(); code in my Controller the table populates with the right amount of rows, but the data in the columns is all the same:

Here is my tableView func:

private func tableView(tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {

        let cellView = voucherTableView.make(withIdentifier: "cell", owner: self) as! NSTableCellView

        cellView.textField!.stringValue = self.values.object(at: row) as! String

        return cellView
    }

Does anyone have any insight into how to get the data from my Array into the tableView on the reload command?

Body:
I recommend to use Cocoa Bindings

Connect datasource of the table view in Interface Builder to the target class

Implement these two methods (viewForColumn:row is not needed)

func numberOfRows(in tableView: NSTableView) -> Int
{
    return tempArray.count
}

func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any?
{
   return tempArray[row]
}

In Interface Builder Bindings Inspector bind the value of the text field to Table Cell View > objectValue.[property] for example

Note: It's highly recommended to map the dictionaries to a custom class (a class inherited from NSObject is mandatory)


问:
Bootstrap Tooltip NOT A FUNCTION when jQuery DataTables is initialized
Maybe the answer's here and I'm just not seeing it, so any assistance would be most welcome.  I have a table, that I'm loading jQuery DataTables onto, plus I'm using Bootstrap, and some of the spans IN the td's have Bootstrap tooltips.  The tooltips work fine, just by themselves, since I have the init script in the footer - but when I add the dataTables basic init script, suddenly I get the error:

Uncaught TypeError: $(...).tooltip is not a function

Here's what I have:

HTML5

```<code><table id="resources" class="hover" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Type</th>
                <th>Title</th>
                <th>Thumbnail</th>
                <th>Instrument</th>
                <th>Share</th>
                <th>Resources</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Type</th>
                <th>Title</th>
                <th>Thumbnail</th>
                <th>Instrument</th>
                <th>Share</th>
                <th>Resources</th>
            </tr>
        </tfoot>
        <tbody>
            <tr>
                <td>Video</td>
                <td><a href="#" class="resource-link" data-toggle="modal" data-target="#videoModal">Title of Video</a></td>
                <td><a href="#" class="resource-link" data-toggle="modal" data-target="#videoModal"><img src="thumbnail.jpg" alt="Title of Video" class="img-responsive img-resource"></a></td>
                <td>Insutrment</td>
                <td><a class="btn btn-default btn-xs" data-toggle="modal" data-target="#shareModal">Share <i class="fa fa-share-alt" aria-hidden="true"></i></a></td>
                <td><span class="fa-stack fa-1x" data-toggle="tooltip" data-placement="top" title="Video Resource"><i class="fa fa-square fa-stack-2x"></i><i class="fa fa-video-camera fa-stack-1x fa-inverse"></i></span></td>
            </tr>
     </tbody>
</table>
</code>```

JS

```<code>$(document).ready(function(){
     $("#resources").DataTable();
     $('[data-toggle="tooltip"]').tooltip({
          container : 'body'
     });
});
</code>```

I'm loading in the following libraries:

jQuery - 3.2.1

Bootstrap - 3.3.7

DataTables - 1.10.15

答:
Seems to be working.

$(document).ready(function() {
  $("#resources").DataTable();
  $('[data-toggle="tooltip"]').tooltip();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

<table id="resources" class="hover" cellspacing="0" width="100%">
  <thead>
    <tr title="Tooltip Test">
      <th>Type</th>
      <th>Title</th>
      <th>Thumbnail</th>
      <th>Instrument</th>
      <th>Share</th>
      <th>Resources</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Type</th>
      <th>Title</th>
      <th>Thumbnail</th>
      <th>Instrument</th>
      <th>Share</th>
      <th>Resources</th>
    </tr>
  </tfoot>
  <tbody>
    <tr>
      <td>Video</td>
      <td>Title of Video</td>
      <td>
        <img src="thumbnail.jpg" alt="Title of Video" class="img-responsive img-resource">
      </td>
      <td>Insutrment</td>
      <td>Share <i class="fa fa-share-alt" aria-hidden="true"></i></td>
      <td><span class="fa-stack fa-1x" data-toggle="tooltip" data-placement="top" title="Video Resource"><i class="fa fa-square fa-stack-2x"></i><i class="fa fa-video-camera fa-stack-1x fa-inverse"></i></span></td>
    </tr>
  </tbody>
</table></code>```

Body:
Maybe the answer's here and I'm just not seeing it, so any assistance would be most welcome.  I have a table, that I'm loading jQuery DataTables onto, plus I'm using Bootstrap, and some of the spans IN the td's have Bootstrap tooltips.  The tooltips work fine, just by themselves, since I have the init script in the footer - but when I add the dataTables basic init script, suddenly I get the error:

Uncaught TypeError: $(...).tooltip is not a function

Here's what I have:

HTML5

                Type
                Title
                Thumbnail
                Instrument
                Share
                Resources

                Type
                Title
                Thumbnail
                Instrument
                Share
                Resources

                Video
                Title of Video

                Insutrment
                Share

JS

$(document).ready(function(){
     $("#resources").DataTable();
     $('[data-toggle="tooltip"]').tooltip({
          container : 'body'
     });
});

I'm loading in the following libraries:

jQuery - 3.2.1

Bootstrap - 3.3.7

DataTables - 1.10.15

Body:
Seems to be working.

$(document).ready(function() {
  $("#resources").DataTable();
  $('[data-toggle="tooltip"]').tooltip();
});

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

<table id="resources" class="hover" cellspacing="0" width="100%">
  <thead>
    <tr title="Tooltip Test">
      <th>Type</th>
      <th>Title</th>
      <th>Thumbnail</th>
      <th>Instrument</th>
      <th>Share</th>
      <th>Resources</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Type</th>
      <th>Title</th>
      <th>Thumbnail</th>
      <th>Instrument</th>
      <th>Share</th>
      <th>Resources</th>
    </tr>
  </tfoot>
  <tbody>
    <tr>
      <td>Video</td>
      <td><a href="#" class="resource-link" data-toggle="modal" data-target="#videoModal">Title of Video</a></td>
      <td>
        <a href="#" class="resource-link" data-toggle="modal" data-target="#videoModal"><img src="thumbnail.jpg" alt="Title of Video" class="img-responsive img-resource"></a>
      </td>
      <td>Insutrment</td>
      <td><a class="btn btn-default btn-xs" data-toggle="modal" data-target="#shareModal">Share <i class="fa fa-share-alt" aria-hidden="true"></i></a></td>
      <td><span class="fa-stack fa-1x" data-toggle="tooltip" data-placement="top" title="Video Resource"><i class="fa fa-square fa-stack-2x"></i><i class="fa fa-video-camera fa-stack-1x fa-inverse"></i></span></td>
    </tr>
  </tbody>
</table>


问:
How to publish Gradle artifacts without using gradle publish command
I have multi module requirement where the model classes are referred by other modules as gradle dependency. I was using gradle publish command manually. But in multicontributer environment, people are forgetting to do that and the artifacts hosted in S3 is not getting new publish.
So, I am thinking of making it getting deployed in CI or by heroku dynos. I know in Maven we specify in the Build phase itself. But I am new to Gradle and don't know much about it.
Can you please suggest me a way of doing that ?
Thank you for your time.</p>

答:
First we need to create a publishing task :

publishing {
    repositories {

```<code>    maven {
        url "s3_url"
        credentials(AwsCredentials) {
            accessKey "acccess_key"
            secretKey "secret_key"
        }
    }
}

publications {
    mavenJava(MavenPublication) {
        groupId 'com.example.common'
        artifactId 'common'
        version '1.0'
        from components.java
    }
}
</code>```

}

Then the following command did the trick :

build.finalizedBy(publish)

So, at the end of the build phase, the artifacts is automatically published to the s3, no matter whether is run from remote or from CI (Heroku in my case).

Body:
First we need to create a publishing task :

publishing {
    repositories {

    maven {
        url "s3_url"
        credentials(AwsCredentials) {
            accessKey "acccess_key"
            secretKey "secret_key"
        }
    }
}

publications {
    mavenJava(MavenPublication) {
        groupId 'com.example.common'
        artifactId 'common'
        version '1.0'
        from components.java
    }
}

}

Then the following command did the trick :

build.finalizedBy(publish)

So, at the end of the build phase, the artifacts is automatically published to the s3, no matter whether is run from remote or from CI (Heroku in my case).


问:
Django infinite scroll goes through all pages at once without actually loading them
I'm implementing infinite scroll for my Django app using this excellent tutorial.

I want the app to load 9 articles then show the "loading..." sign and load 9 more articles.

However, what happens is that when the user hits the bottom, it shows the loading sign and nothing happens. On the terminal I can see that it "GET" requested all the pages at once like this:

[06/Jul/2017 18:22:26] "GET /?page=2 HTTP/1.1" 200 19124 [06/Jul/2017
  18:22:27] "GET /?page=3 HTTP/1.1" 200 18774 [06/Jul/2017 18:22:27]
  "GET /?page=4 HTTP/1.1" 200 18772 [06/Jul/2017 18:22:28] "GET /?page=5
  HTTP/1.1" 200 19031 [06/Jul/2017 18:22:28] "GET /?page=6 HTTP/1.1" 200
  18965 [06/Jul/2017 18:22:28] "GET /?page=7 HTTP/1.1" 200 18676
  [06/Jul/2017 18:22:28] "GET /?page=8 HTTP/1.1" 200 18866 [06/Jul/2017
  18:22:28] "GET /?page=9 HTTP/1.1" 200 19094 [06/Jul/2017 18:22:28]
  "GET /?page=10 HTTP/1.1" 200 18750

This is the code in views:

```<code>def context_generator(request, title, category):
    """made this function because views are very similar"""
    context_dict={}

    if(category == "index"):
        articles_list = Article.objects.order_by('-pub_date')
    else:
        articles_list = Article.objects.filter(category=category).order_by('-pub_date')

    page = request.GET.get('page', 1)
    paginator = Paginator(articles_list, 9)

    try:
        articles = paginator.page(page)
    except PageNotAnInteger:
        articles = paginator.page(1)
    except EmptyPage:
        articles = paginator.page(paginator.articles_list)

    context_dict['articles'] =  articles
    context_dict['title'] = title

    return context_dict

def index(request):
    return render(request, 'app_name/index.html', context_generator(request, "page title", "index"))
</code>```

This is index.html:

```<code>{% block body_block %}

    <div class="container infinite-container">

         {% for article in articles %}
          <!-- render articles -->
         {% endfor %}

    </div>

    {% if articles.has_next %}
        <a class="infinite-more-link" href="?page={{ articles.next_page_number }}">More</a>
    {% endif %}

    <div class="loading" style="display: none;">
      Loading...
    </div>

{% endblock %}
</code>```

This script is in base.html:

```<code><script>
  var infinite = new Waypoint.Infinite({
    element: $('.infinite-container')[0],
    onBeforePageLoad: function () {
    $('.loading').show();
    },
    onAfterPageLoad: function ($items) {
    $('.loading').hide();
    }
  });
</script>
</code>```

These imports are in the base.html header:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="{% static 'js/jquery.waypoints.min.js' %}"></script>
<script src="{% static 'js/infinite.min.js' %}"></script>
</code>```

答:
it was because I forgot to add this class to each article div:

```<code>infinite-item
</code>```

so it has to be like this:

```<code><div class="container infinite-container">

     {% for article in articles %}
          <div class="article col-md-4 col-lg-4 col-xs-12 infinite-item"></div>

     {% endfor %}
</code>```

Body:
I'm implementing infinite scroll for my Django app using this excellent tutorial.

I want the app to load 9 articles then show the "loading..." sign and load 9 more articles.

However, what happens is that when the user hits the bottom, it shows the loading sign and nothing happens. On the terminal I can see that it "GET" requested all the pages at once like this:

[06/Jul/2017 18:22:26] "GET /?page=2 HTTP/1.1" 200 19124 [06/Jul/2017
  18:22:27] "GET /?page=3 HTTP/1.1" 200 18774 [06/Jul/2017 18:22:27]
  "GET /?page=4 HTTP/1.1" 200 18772 [06/Jul/2017 18:22:28] "GET /?page=5
  HTTP/1.1" 200 19031 [06/Jul/2017 18:22:28] "GET /?page=6 HTTP/1.1" 200
  18965 [06/Jul/2017 18:22:28] "GET /?page=7 HTTP/1.1" 200 18676
  [06/Jul/2017 18:22:28] "GET /?page=8 HTTP/1.1" 200 18866 [06/Jul/2017
  18:22:28] "GET /?page=9 HTTP/1.1" 200 19094 [06/Jul/2017 18:22:28]
  "GET /?page=10 HTTP/1.1" 200 18750

This is the code in views:

def context_generator(request, title, category):
    """made this function because views are very similar"""
    context_dict={}

    if(category == "index"):
        articles_list = Article.objects.order_by('-pub_date')
    else:
        articles_list = Article.objects.filter(category=category).order_by('-pub_date')

    page = request.GET.get('page', 1)
    paginator = Paginator(articles_list, 9)

    try:
        articles = paginator.page(page)
    except PageNotAnInteger:
        articles = paginator.page(1)
    except EmptyPage:
        articles = paginator.page(paginator.articles_list)

    context_dict['articles'] =  articles
    context_dict['title'] = title

    return context_dict

def index(request):
    return render(request, 'app_name/index.html', context_generator(request, "page title", "index"))

This is index.html:

{% block body_block %}

         {% for article in articles %}

         {% endfor %}

    {% if articles.has_next %}
        More
    {% endif %}

      Loading...

{% endblock %}

This script is in base.html:

These imports are in the base.html header:

Body:
it was because I forgot to add this class to each article div:

infinite-item

so it has to be like this:

<div class="container infinite-container">

     {% for article in articles %}
          <div class="article col-md-4 col-lg-4 col-xs-12 infinite-item"></div>

     {% endfor %}


问:
Exception Handling Error
When a method throws an exception, it searches through the call stack to find a handler right? In that sense, why is there an error with exep.second();? even though i've caught the exception in method second(). Here's my code:

```<code>public class Exep {
void first()throws IOException{
    throw new IOException("device error");
}
void second()throws IOException{
    try{
        first();
    }catch(Exception e){
        System.out.println(e);
    }
}
public static void main(String args[]){
    Exep exep = new Exep();
    exep.second();
}
</code>```

}

But the error disappears on adding  throws IOException to the main(). Why?

答: If you declare void second() throws IOException and then you call the method in main, you need to catch the exception this method may throw, just like you did with the first() method. In that case you simply don't need the throws clause in second().

Title: Exception Handling Error

Body:
When a method throws an exception, it searches through the call stack to find a handler right? In that sense, why is there an error with exep.second();? even though i've caught the exception in method second(). Here's my code:

public class Exep {
void first()throws IOException{
    throw new IOException("device error");
}
void second()throws IOException{
    try{
        first();
    }catch(Exception e){
        System.out.println(e);
    }
}
public static void main(String args[]){
    Exep exep = new Exep();
    exep.second();
}

}

But the error disappears on adding  throws IOException to the main(). Why?


问:
How to pass time_t or simply its date information over COM
I have a Visual C++ ATL project which exposes a COM interface.

From my interface, I am calling into FlexNet Publisher libraries. I need to return back a date from these libraries, which expose a time_t object I can fetch (yes, I know their libraries are susceptible to the 2038 bug on 32-bit systems).

My IDL file has a method on it which needs to return this date.

Given that I can fetch time_t, how do I pass its date information across the COM interface boundary to a client application consuming my COM object? Should I just cast time_t as __int64 and define it as __int64 in my IDL? What's correct here? What's the standard way?

答:
The correct way is to use the DATE type or a VARIANT. To get there from a time_t requires a few conversions.

Headers for the code below:

```<code>#include <windows.h>
#include <comdef.h>
#include <oleauto.h>
#include <time.h>
#include <exception>
</code>```

First, get the C++ time_t you want to convert.

```<code>// get the time_t to convert
time_t cpp_time = ...;
</code>```

Then, convert the C++ time_t to a Windows FILETIME. (This part was lifted from here).

```<code>// convert C++ time_t to Windows FILETIME
FILETIME windows_file_time;
{
    auto ll = Int32x32To64(cpp_time, 10000000) + 116444736000000000;
    windows_file_time.dwLowDateTime = (DWORD)ll;
    windows_file_time.dwHighDateTime = ll >> 32;
}
</code>```

Then, convert the Windows FILETIME to a Windows SYSTEMTIME.

```<code>// convert Windows FILETIME to Windows SYSTEMTIME
SYSTEMTIME windows_system_time;
if (!FileTimeToSystemTime(&windows_file_time, &windows_system_time))
    throw new std::exception();
</code>```

Finally, convert the Windows SYSTEMTIME to a VARIANT DATE.

```<code>// convert Windows FILETIME to VARIANT DATE
DATE variant_date;
if (SystemTimeToVariantTime(&windows_system_time, &variant_date) != TRUE)
    throw new std::exception();
</code>```

If you want to verify that the above works, you can convert the DATE to a string (BSTR).

```<code>// convert DATE to string (for verification purposes)
bstr_t variant_date_string;
if (FAILED(VarBstrFromDate(variant_date, 0, 0, variant_date_string.GetAddress())))
    throw new std::exception();
OutputDebugStringW(variant_date_string);
</code>```

If you need/want to use a VARIANT instead of a DATE, just wrap the DATE in a VARIANT struct.

```<code>// wrap DATE in a VARIANT
VARIANT v_variant_date;
v_variant_date.date = variant_date;
v_variant_date.vt = VT_DATE;
</code>```

To verify that this part works, you can convert that VARIANT to a string (BSTR).

```<code>// convert VARIANT to string (for verification purposes)
variant_t v_variant_date_string;
v_variant_date_string.ChangeType(VT_BSTR, &v_variant_date);
OutputDebugStringW(v_variant_date_string.bstrVal);
</code>```

Body:
The correct way is to use the DATE type or a VARIANT. To get there from a time_t requires a few conversions.

Headers for the code below:

#include <windows.h>
#include <comdef.h>
#include <oleauto.h>
#include <time.h>
#include <exception>

First, get the C++ time_t you want to convert.

// get the time_t to convert
time_t cpp_time = ...;

Then, convert the C++ time_t to a Windows FILETIME. (This part was lifted from here).

// convert C++ time_t to Windows FILETIME
FILETIME windows_file_time;
{
    auto ll = Int32x32To64(cpp_time, 10000000) + 116444736000000000;
    windows_file_time.dwLowDateTime = (DWORD)ll;
    windows_file_time.dwHighDateTime = ll >> 32;
}

Then, convert the Windows FILETIME to a Windows SYSTEMTIME.

// convert Windows FILETIME to Windows SYSTEMTIME
SYSTEMTIME windows_system_time;
if (!FileTimeToSystemTime(&windows_file_time, &windows_system_time))
    throw new std::exception();

Finally, convert the Windows SYSTEMTIME to a VARIANT DATE.

// convert Windows FILETIME to VARIANT DATE
DATE variant_date;
if (SystemTimeToVariantTime(&windows_system_time, &variant_date) != TRUE)
    throw new std::exception();

If you want to verify that the above works, you can convert the DATE to a string (BSTR).

// convert DATE to string (for verification purposes)
bstr_t variant_date_string;
if (FAILED(VarBstrFromDate(variant_date, 0, 0, variant_date_string.GetAddress())))
    throw new std::exception();
OutputDebugStringW(variant_date_string);

If you need/want to use a VARIANT instead of a DATE, just wrap the DATE in a VARIANT struct.

// wrap DATE in a VARIANT
VARIANT v_variant_date;
v_variant_date.date = variant_date;
v_variant_date.vt = VT_DATE;

To verify that this part works, you can convert that VARIANT to a string (BSTR).

// convert VARIANT to string (for verification purposes)
variant_t v_variant_date_string;
v_variant_date_string.ChangeType(VT_BSTR, &v_variant_date);
OutputDebugStringW(v_variant_date_string.bstrVal);


答: You explicitly declared that method second() throws an exception. Compiler is unaware that exception is actually being caught within a method. Move the catch part into main() and the error will disappear. Or even better, remove the throws statement since you are not throwing anything.

Title: Exception Handling Error


问:
if else nested for loops using python list comprehension
Can anyone help me figure the list comprehension way of producing following output -

Let given list be -

```<code>results = [
    {"id":  1, "name":  "input"},
    {"name": "status", "desc": "Status"},
    {"name": "entity", "fields": [
        {"id": 101, "name": "value"},
        {"id": 102, "name": "address"}]
    }
]
</code>```

And I am looking for output in the form of list.
The code to get the output is:

```<code>output = []
for eachDict in results:
    if "fields" in eachDict:
        for field in eachDict["fields"]:
            output.append(eachDict["name"]+"."+field["name"])
    else:
        output.append(eachDict["name"])
</code>```

Thus the output using above code is -

```<code>['input', 'status', 'entity.value', 'entity.address']
</code>```

Is it possible to get similar output using if else nested for loops in list Comprehension?

I am having trouble trying to get access to that inner for loop in if condition of list Comprehension

My attempt -

```<code>output = [eachDict["name"]+"."+field["name"] for field in eachDict["fields"] if "fields" in eachDict else eachDict["name"] for eachDict in results]
</code>```

答:
A list comprehension has a fixed number of (nested) loops. So must have two loops here, one over the top-level dictionaries, and one over the fields. The trick is to produce one iteration in the nested loop if there are no fields:

```<code>[d['name'] + fieldname
 for d in results
 for fieldname in (
    ('.' + sub['name'] for sub in d['fields']) if 'fields' in d else
    ('',))
]
</code>```

The for fieldname loop loops either over the names of the fields sub-directories (with '.' prefixed), or over a tuple with just a single empty string in it.

Note that this isn't actually all that readable. I'd delegate producing the fieldname loop to a helper generator function to improve that:

```<code>def fieldnames(d):
    if 'fields' in d:
        for sub in d['fields']:
            yield '.' + sub['name']
    else:
        yield ''

[d['name'] + fieldname for d in results for fieldname in fieldnames(d)]
</code>```

Demo:

```<code>>>> def fieldnames(d):
...     if 'fields' in d:
...         for sub in d['fields']:
...             yield '.' + sub['name']
...     else:
...         yield ''
...
>>> [d['name'] + fieldname for d in results for fieldname in fieldnames(d)]
['input', 'status', 'entity.value', 'entity.address']
</code>```

Body:
Can anyone help me figure the list comprehension way of producing following output -

Let given list be -

results = [
    {"id":  1, "name":  "input"},
    {"name": "status", "desc": "Status"},
    {"name": "entity", "fields": [
        {"id": 101, "name": "value"},
        {"id": 102, "name": "address"}]
    }
]

And I am looking for output in the form of list.
The code to get the output is:

output = []
for eachDict in results:
    if "fields" in eachDict:
        for field in eachDict["fields"]:
            output.append(eachDict["name"]+"."+field["name"])
    else:
        output.append(eachDict["name"])

Thus the output using above code is -

['input', 'status', 'entity.value', 'entity.address']

Is it possible to get similar output using if else nested for loops in list Comprehension?

I am having trouble trying to get access to that inner for loop in if condition of list Comprehension

My attempt -

output = [eachDict["name"]+"."+field["name"] for field in eachDict["fields"] if "fields" in eachDict else eachDict["name"] for eachDict in results]

Body:
A list comprehension has a fixed number of (nested) loops. So must have two loops here, one over the top-level dictionaries, and one over the fields. The trick is to produce one iteration in the nested loop if there are no fields:

[d['name'] + fieldname
 for d in results
 for fieldname in (
    ('.' + sub['name'] for sub in d['fields']) if 'fields' in d else
    ('',))
]

The for fieldname loop loops either over the names of the fields sub-directories (with '.' prefixed), or over a tuple with just a single empty string in it.

Note that this isn't actually all that readable. I'd delegate producing the fieldname loop to a helper generator function to improve that:

def fieldnames(d):
    if 'fields' in d:
        for sub in d['fields']:
            yield '.' + sub['name']
    else:
        yield ''

[d['name'] + fieldname for d in results for fieldname in fieldnames(d)]

Demo:

>>> def fieldnames(d):
...     if 'fields' in d:
...         for sub in d['fields']:
...             yield '.' + sub['name']
...     else:
...         yield ''
...
>>> [d['name'] + fieldname for d in results for fieldname in fieldnames(d)]
['input', 'status', 'entity.value', 'entity.address']


问:
Angular2: Sum two Observable<number> values
I have a service with two different functions that get the number of itens inside an array that is watched by an BehaviorSubject.

```<code> private itemsInCartSubject: BehaviorSubject<any[]> = new BehaviorSubject([]);
private itemsInCart: any[] = [];

private packetsInCartSubject: BehaviorSubject<Pacote[]> = new BehaviorSubject([]);
private packetsInCart: Pacote[] = [];

 public getTotalItens(): Observable<number> {

    return this.itemsInCartSubject.map((items: any[]) => {
        return items.reduce((prev, curr: any) => {
                return prev + Number(curr.qtd);
        }, 0);
    });
};

   public getTotalPacotes(): Observable<number> {
    return this.packetsInCartSubject.map((items: any[]) => {
        return items.reduce((prev, curr: any) => {
                return prev + Number(1);
        }, 0);
    });
};
</code>```

Inside my component I have two methods to get these numbers:

```<code> public countItens(): Observable<number> {
    return this.cartService.getTotalItens();
}

public countPacotes(): Observable<number> {
    return this.cartService.getTotalPacotes();
}
</code>```

In my html I can show the values like this:

```<code><p>You have {{countItens() | async}} in your cart</p>
</code>```

It works fine, updating the values when theres is a change on the subject, but I need to sum the two values of the two Observables.

How can I accomplish that?

I've tried

```<code>this.cartService.getTotalItens()+this.cartService.getTotalPacotes();
</code>```

But it generates the error: Operator '+' cannot be applied to types Observable and Observable

答:
You can combine these Observables using combineLatest and then return a new value that is the sum of both. You can add a new function like this:

public getTotal(): Observable<number> {
    return this.countItens()
               .combineLatest(this.countPacotes(), (itens, pacotes) => itens + pacotes);
}
```

<p>And then in the template you can use it like so:</p>

<pre class="lang-html prettyprint-override"><code><p>Total is: {{getTotal() | async}}</p>
</code>```

Demo of combineLatest

Body:
I have a service with two different functions that get the number of itens inside an array that is watched by an BehaviorSubject.

 private itemsInCartSubject: BehaviorSubject<any[]> = new BehaviorSubject([]);
private itemsInCart: any[] = [];

private packetsInCartSubject: BehaviorSubject<Pacote[]> = new BehaviorSubject([]);
private packetsInCart: Pacote[] = [];

 public getTotalItens(): Observable<number> {

    return this.itemsInCartSubject.map((items: any[]) => {
        return items.reduce((prev, curr: any) => {
                return prev + Number(curr.qtd);
        }, 0);
    });
};

   public getTotalPacotes(): Observable<number> {
    return this.packetsInCartSubject.map((items: any[]) => {
        return items.reduce((prev, curr: any) => {
                return prev + Number(1);
        }, 0);
    });
};

Inside my component I have two methods to get these numbers:

 public countItens(): Observable<number> {
    return this.cartService.getTotalItens();
}

public countPacotes(): Observable<number> {
    return this.cartService.getTotalPacotes();
}

In my html I can show the values like this:

You have {{countItens() | async}} in your cart

It works fine, updating the values when theres is a change on the subject, but I need to sum the two values of the two Observables.

How can I accomplish that?

I've tried

this.cartService.getTotalItens()+this.cartService.getTotalPacotes();

But it generates the error: Operator '+' cannot be applied to types Observable and Observable

Body:
You can combine these Observables using combineLatest and then return a new value that is the sum of both. You can add a new function like this:

public getTotal(): Observable<number> {
    return this.countItens()
               .combineLatest(this.countPacotes(), (itens, pacotes) => itens + pacotes);
}

And then in the template you can use it like so:

<p>Total is: {{getTotal() | async}}</p>

Demo of combineLatest


问:
What would be the correct JSON argument to update roll and connections in street view publish API
I am trying to update pose.roll and connections along with other UpdateMasks but only updates heading and pitch, pose.roll remain NULL.

Here is php code

```<code><?php
$ch_a = curl_init();
curl_setopt($ch_a, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_a, CURLOPT_HTTPHEADER, array('Authorization: Bearer '.$_SESSION['access_token'], 'Content-Type: application/json'));
curl_setopt($ch_a, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch_a, CURLOPT_URL, 'https://streetviewpublish.googleapis.com/v1/photo/'.$photoId.'?key='.$config['apikey'].'&updateMask=pose.heading,pose.pitch,pose.roll,connections');
curl_setopt($ch_a, CURLOPT_POSTFIELDS, '{"pose":{"heading": 145.9086485977801, "pitch":3.219209274200196, "roll":"0"}}');
$url = curl_exec($ch_a);
curl_close($ch_a);
echo $url;
?>
</code>```

答:
I think this is an expected behavior.

I've tried this sample request using the Try It! in the documentation.

```<code>{
  "pose": {
    "roll": 0,
    "latLngPair": {
      "longitude": 118.04944440000001,
      "latitude": 12.5343694
    },
    "heading": 90,
    "pitch": 5.0999984741210938
  }
}
</code>```

Then I received this 200 response:

```<code>{
  "photoId": {
    "id": "ID"
  },
  "pose": {
    "latLngPair": {
      "latitude": 12.5343694,
      "longitude": 118.04944440000001
    },
    "heading": 90,
    "pitch": 5.0999984741210938
  }
}
</code>```

If you updated roll to 0, then the value will be null. When the value of roll is >0, it will appear in the response. Example:

```<code>{
  "photoId": {
    "id": "ID"
  },
  "pose": {
    "latLngPair": {
      "latitude": 12.5343694,
      "longitude": 118.04944440000001
    },
    "heading": 90,
    "pitch": 5.0999984741210938,
    "roll": 5
  }
}
</code>```

Body:
I am trying to update pose.roll and connections along with other UpdateMasks but only updates heading and pitch, pose.roll remain NULL.

Here is php code

<?php
$ch_a = curl_init();
curl_setopt($ch_a, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_a, CURLOPT_HTTPHEADER, array('Authorization: Bearer '.$_SESSION['access_token'], 'Content-Type: application/json'));
curl_setopt($ch_a, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch_a, CURLOPT_URL, 'https://streetviewpublish.googleapis.com/v1/photo/'.$photoId.'?key='.$config['apikey'].'&updateMask=pose.heading,pose.pitch,pose.roll,connections');
curl_setopt($ch_a, CURLOPT_POSTFIELDS, '{"pose":{"heading": 145.9086485977801, "pitch":3.219209274200196, "roll":"0"}}');
$url = curl_exec($ch_a);
curl_close($ch_a);
echo $url;
?>

Body:
I think this is an expected behavior.

I've tried this sample request using the Try It! in the documentation.

{
  "pose": {
    "roll": 0,
    "latLngPair": {
      "longitude": 118.04944440000001,
      "latitude": 12.5343694
    },
    "heading": 90,
    "pitch": 5.0999984741210938
  }
}

Then I received this 200 response:

{
  "photoId": {
    "id": "ID"
  },
  "pose": {
    "latLngPair": {
      "latitude": 12.5343694,
      "longitude": 118.04944440000001
    },
    "heading": 90,
    "pitch": 5.0999984741210938
  }
}

If you updated roll to 0, then the value will be null. When the value of roll is >0, it will appear in the response. Example:

{
  "photoId": {
    "id": "ID"
  },
  "pose": {
    "latLngPair": {
      "latitude": 12.5343694,
      "longitude": 118.04944440000001
    },
    "heading": 90,
    "pitch": 5.0999984741210938,
    "roll": 5
  }
}


问:
What does '' as <alias> do?
I have a query which has '' as <alias> multiple times, for example:

```<code>SELECT -- ...
'' as first_name,
'' as last_name,
'' as email_address
-- ...
</code>```

This seems to only return columns with empty values.

Are there any other side effects of this query?

The query is old and I believe there are clients expecting these fields (empty or not).

Does this cause any overhead I would be better off handling in Java?
Is there are better way to return empty columns without this unintuitive clause?

答:
You are correct, it's a placeholder to make the column appear in the output.  It would have no other effect on the query.

The only overhead of note this would cause would be the cost of transferring the extra column data over the network to your Java process.  But as they're empty strings, unless you're talking 100M rows, it's going to be negligible.

If you want confirmation that it's not causing DB overhead, use the MySQL EXPLAIN feature to detail the costs of the query.

Title: What does '' as <alias> do?

Body:
I have a query which has '' as <alias> multiple times, for example:

SELECT -- ...
'' as first_name,
'' as last_name,
'' as email_address
-- ...

This seems to only return columns with empty values.

Are there any other side effects of this query?

The query is old and I believe there are clients expecting these fields (empty or not).

Does this cause any overhead I would be better off handling in Java?
Is there are better way to return empty columns without this unintuitive clause?