问:
Nodejs 502 Bad Gateway Deploying Express on Elastic Beanstalk AWS
I deployed node js application to AWS EBS. When I run the app, i get the error " 502 Bad Gateway " nginx/1.6.2 . This is what i found out in the log.

2016/08/13 08:46:03 [warn] 14418#0: duplicate MIME type "text/html" in /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf:42
2016/08/13 09:22:25 [error] 14421#0: *2 connect() failed (111: Connection refused) while connecting to upstream, client: 118.36.218.138, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8081/", host: "cider-1.siwrszgawk.ap-northeast-1.elasticbeanstalk.com"
2016/08/13 09:22:25 [error] 14421#0: *2 connect() failed (111: Connection refused) while connecting to upstream, client: 118.36.218.138, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8081/favicon.ico", host: "cider-1.siwrszgawk.ap-northeast-1.elasticbeanstalk.com", referrer: "http://cider-1.siwrszgawk.ap-northeast-1.elasticbeanstalk.com/"```
</div>
</div>
</p>

<p>I spend my day for this. and i found some good solution.
enter link description here (it's same problem)
but it's not working on my code.( I tried the rename solution which most chosen )
While I have read other resources on StackOverflow, which suggest I rename my main file from app.js to main.js and set the port in a bin/www folder, I feel like this isn't the solution for my app.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
  "name": "cidermics",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node main.js"
  },
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "ejs": "~2.3.3",
    "express": "~4.13.1",
    "file-system": "^2.2.1",
    "formidable": "^1.0.17",
    "morgan": "~1.6.1",
    "multer": "^1.1.0",
    "node-dir": "^0.1.11",
    "serve-favicon": "~2.3.0",
    "xhr": "^2.2.0",
    "passport" : "*",
    "passport-local" : "*",
    "connect-flash" : "*",
    "express-session" : "*",
    "req-flash" : "*"
  }
}</code>```

It's main.js I changed the name from app.js to main.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var debug = require('debug')('cidermics:server');
var http = require('http');
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
var mysql = require("./routes/model/mysql");
var flash = require('req-flash');
var session = require('express-session');

var routes = require('./routes/index');
var users = require('./routes/users');
var admin = require('./routes/admin');

//route add
var about = require('./routes/about');
var cmn = require('./routes/cmn');
var consulting = require('./routes/consulting');
var contents = require('./routes/contents');
var member = require('./routes/member');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ secret: 'fortt', resave: true, saveUninitialized: true }))

app.use(passport.initialize());
app.use(passport.session());

//express.static ADD
app.use('/cid_about', express.static(__dirname + '/views/cid_about'));
app.use('/cid_cmn', express.static(__dirname + '/views/cid_cmn'));
app.use('/cid_consulting', express.static(__dirname + '/views/cid_consulting'));
app.use('/cid_contents', express.static(__dirname + '/views/cid_contents'));
app.use('/cid_member', express.static(__dirname + '/views/cid_member'));
app.use(flash());

app.use('/', routes);
app.use('/users', users);
app.use('/adm', admin);

//app.get
app.use('/',about);
app.use('/',cmn);
app.use('/',consulting);
app.use('/',contents);
app.use('/',member);

passport.use('local', new LocalStrategy({

    usernameField : 'email',
    passwordField : 'pw',
    passReqToCallback : true
}

,function(req, email, pw, done) {

 mysql.select('select * from cider.cid_user where user_email ="'+email+'" and user_password = "'+pw+'"', function (err, data){
  console.log("data");
  console.log(data.length);
  if(data.length < 1){
   console.log('fail');
   return done(null, false);
  }else {
   console.log('success');
   return done(null, data);
  }
  if(err){
   res.redirect('back');
  }

    });

}
));

passport.serializeUser(function(user, done) {
    done(null, user);
    // if you use Model.id as your idAttribute maybe you'd want
    // done(null, user.id);
});

passport.deserializeUser(function(user, done) {
    done(null, user);
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

app.set('port', process.env.PORT || 80);

var server = app.listen(app.get('port'), function() {
//http.createServer(app).listen(app.get('port'), function(){
// console.log('Express server listening on port ' + app.get('port'));

  debug('Express server listening on port ' + server.address().port);
});```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>/var/log/nodejs/nodejs.log
-------------------------------------
npm ERR! Linux 4.4.14-24.50.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/npm" "start"
npm ERR! node v4.4.6
npm ERR! npm  v2.15.5
npm ERR! code ELIFECYCLE
npm ERR! cidermics@0.0.1 start: `node app.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cidermics@0.0.1 start script 'node app.js'.
npm ERR! This is most likely a problem with the cidermics package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node app.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs cidermics
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!
npm ERR!     npm owner ls cidermics
npm ERR! There is likely additional logging output above.
npm ERR! Linux 4.4.14-24.50.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/npm" "start"
npm ERR! node v4.4.6
npm ERR! npm  v2.15.5
npm ERR! path npm-debug.log.3664877195
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall open

npm ERR! Error: EACCES: permission denied, open 'npm-debug.log.3664877195'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES: permission denied, open 'npm-debug.log.3664877195']
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'open',
npm ERR!   path: 'npm-debug.log.3664877195' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
npm ERR!     /var/app/current/npm-debug.log

> cidermics@0.0.1 start /var/app/current
> node app.js

/var/app/current/node_modules/multer/node_modules/mkdirp/index.js:90
                    throw err0;
                    ^

Error: EACCES: permission denied, mkdir '/var/app/public'
    at Error (native)
    at Object.fs.mkdirSync (fs.js:794:18)
    at sync (/var/app/current/node_modules/multer/node_modules/mkdirp/index.js:71:13)
    at Function.sync (/var/app/current/node_modules/multer/node_modules/mkdirp/index.js:77:24)
    at new DiskStorage (/var/app/current/node_modules/multer/storage/disk.js:21:12)
    at module.exports (/var/app/current/node_modules/multer/storage/disk.js:65:10)
    at new Multer (/var/app/current/node_modules/multer/index.js:15:20)
    at multer (/var/app/current/node_modules/multer/index.js:88:12)
    at Object.<anonymous> (/var/app/current/routes/admin.js:8:14)
    at Module._compile (module.js:409:26)

npm ERR! Linux 4.4.14-24.50.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/npm" "start"
npm ERR! node v4.4.6
npm ERR! npm  v2.15.5
npm ERR! code ELIFECYCLE
npm ERR! cidermics@0.0.1 start: `node app.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cidermics@0.0.1 start script 'node app.js'.
npm ERR! This is most likely a problem with the cidermics package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node app.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs cidermics
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!
npm ERR!     npm owner ls cidermics
npm ERR! There is likely additional logging output above.
npm ERR! Linux 4.4.14-24.50.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/npm" "start"
npm ERR! node v4.4.6
npm ERR! npm  v2.15.5
npm ERR! path npm-debug.log.1654992227
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall open

npm ERR! Error: EACCES: permission denied, open 'npm-debug.log.1654992227'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES: permission denied, open 'npm-debug.log.1654992227']
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'open',
npm ERR!   path: 'npm-debug.log.1654992227' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
npm ERR!     /var/app/current/npm-debug.log</code>```

答:
Your dependency multer is running the command mkdir. But since it is the node process invoking this, and the node process doesn't have permission to run shell commands, it is throwing an error.

How important is multer? Your code snippets don't show you using it. Maybe you can remove it?

Here is a related question.

Body:
I deployed node js application to AWS EBS. When I run the app, i get the error " 502 Bad Gateway " nginx/1.6.2 . This is what i found out in the log.

2016/08/13 08:46:03 [warn] 14418#0: duplicate MIME type "text/html" in /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf:42
2016/08/13 09:22:25 [error] 14421#0: *2 connect() failed (111: Connection refused) while connecting to upstream, client: 118.36.218.138, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8081/", host: "cider-1.siwrszgawk.ap-northeast-1.elasticbeanstalk.com"
2016/08/13 09:22:25 [error] 14421#0: *2 connect() failed (111: Connection refused) while connecting to upstream, client: 118.36.218.138, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8081/favicon.ico", host: "cider-1.siwrszgawk.ap-northeast-1.elasticbeanstalk.com", referrer: "http://cider-1.siwrszgawk.ap-northeast-1.elasticbeanstalk.com/"

I spend my day for this. and i found some good solution.
enter link description here (it's same problem)
but it's not working on my code.( I tried the rename solution which most chosen )
While I have read other resources on StackOverflow, which suggest I rename my main file from app.js to main.js and set the port in a bin/www folder, I feel like this isn't the solution for my app.

{
  "name": "cidermics",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node main.js"
  },
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "ejs": "~2.3.3",
    "express": "~4.13.1",
    "file-system": "^2.2.1",
    "formidable": "^1.0.17",
    "morgan": "~1.6.1",
    "multer": "^1.1.0",
    "node-dir": "^0.1.11",
    "serve-favicon": "~2.3.0",
    "xhr": "^2.2.0",
    "passport" : "*",
    "passport-local" : "*",
    "connect-flash" : "*",
    "express-session" : "*",
    "req-flash" : "*"
  }
}

It's main.js I changed the name from app.js to main.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var debug = require('debug')('cidermics:server');
var http = require('http');
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
var mysql = require("./routes/model/mysql");
var flash = require('req-flash');
var session = require('express-session');

var routes = require('./routes/index');
var users = require('./routes/users');
var admin = require('./routes/admin');

//route add
var about = require('./routes/about');
var cmn = require('./routes/cmn');
var consulting = require('./routes/consulting');
var contents = require('./routes/contents');
var member = require('./routes/member');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ secret: 'fortt', resave: true, saveUninitialized: true }))

app.use(passport.initialize());
app.use(passport.session());

//express.static ADD
app.use('/cid_about', express.static(__dirname + '/views/cid_about'));
app.use('/cid_cmn', express.static(__dirname + '/views/cid_cmn'));
app.use('/cid_consulting', express.static(__dirname + '/views/cid_consulting'));
app.use('/cid_contents', express.static(__dirname + '/views/cid_contents'));
app.use('/cid_member', express.static(__dirname + '/views/cid_member'));
app.use(flash());

app.use('/', routes);
app.use('/users', users);
app.use('/adm', admin);

//app.get
app.use('/',about);
app.use('/',cmn);
app.use('/',consulting);
app.use('/',contents);
app.use('/',member);

passport.use('local', new LocalStrategy({

    usernameField : 'email',
    passwordField : 'pw',
    passReqToCallback : true
}

,function(req, email, pw, done) {

 mysql.select('select * from cider.cid_user where user_email ="'+email+'" and user_password = "'+pw+'"', function (err, data){
  console.log("data");
  console.log(data.length);
  if(data.length < 1){
   console.log('fail');
   return done(null, false);
  }else {
   console.log('success');
   return done(null, data);
  }
  if(err){
   res.redirect('back');
  }

    });

}
));

passport.serializeUser(function(user, done) {
    done(null, user);
    // if you use Model.id as your idAttribute maybe you'd want
    // done(null, user.id);
});

passport.deserializeUser(function(user, done) {
    done(null, user);
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

app.set('port', process.env.PORT || 80);

var server = app.listen(app.get('port'), function() {
//http.createServer(app).listen(app.get('port'), function(){
// console.log('Express server listening on port ' + app.get('port'));

  debug('Express server listening on port ' + server.address().port);
});

/var/log/nodejs/nodejs.log
-------------------------------------
npm ERR! Linux 4.4.14-24.50.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/npm" "start"
npm ERR! node v4.4.6
npm ERR! npm  v2.15.5
npm ERR! code ELIFECYCLE
npm ERR! cidermics@0.0.1 start: `node app.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cidermics@0.0.1 start script 'node app.js'.
npm ERR! This is most likely a problem with the cidermics package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node app.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs cidermics
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!
npm ERR!     npm owner ls cidermics
npm ERR! There is likely additional logging output above.
npm ERR! Linux 4.4.14-24.50.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/npm" "start"
npm ERR! node v4.4.6
npm ERR! npm  v2.15.5
npm ERR! path npm-debug.log.3664877195
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall open

npm ERR! Error: EACCES: permission denied, open 'npm-debug.log.3664877195'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES: permission denied, open 'npm-debug.log.3664877195']
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'open',
npm ERR!   path: 'npm-debug.log.3664877195' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
npm ERR!     /var/app/current/npm-debug.log

> cidermics@0.0.1 start /var/app/current
> node app.js

/var/app/current/node_modules/multer/node_modules/mkdirp/index.js:90
                    throw err0;
                    ^

Error: EACCES: permission denied, mkdir '/var/app/public'
    at Error (native)
    at Object.fs.mkdirSync (fs.js:794:18)
    at sync (/var/app/current/node_modules/multer/node_modules/mkdirp/index.js:71:13)
    at Function.sync (/var/app/current/node_modules/multer/node_modules/mkdirp/index.js:77:24)
    at new DiskStorage (/var/app/current/node_modules/multer/storage/disk.js:21:12)
    at module.exports (/var/app/current/node_modules/multer/storage/disk.js:65:10)
    at new Multer (/var/app/current/node_modules/multer/index.js:15:20)
    at multer (/var/app/current/node_modules/multer/index.js:88:12)
    at Object.<anonymous> (/var/app/current/routes/admin.js:8:14)
    at Module._compile (module.js:409:26)

npm ERR! Linux 4.4.14-24.50.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/npm" "start"
npm ERR! node v4.4.6
npm ERR! npm  v2.15.5
npm ERR! code ELIFECYCLE
npm ERR! cidermics@0.0.1 start: `node app.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cidermics@0.0.1 start script 'node app.js'.
npm ERR! This is most likely a problem with the cidermics package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node app.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs cidermics
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!
npm ERR!     npm owner ls cidermics
npm ERR! There is likely additional logging output above.
npm ERR! Linux 4.4.14-24.50.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v4.4.6-linux-x64/bin/npm" "start"
npm ERR! node v4.4.6
npm ERR! npm  v2.15.5
npm ERR! path npm-debug.log.1654992227
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall open

npm ERR! Error: EACCES: permission denied, open 'npm-debug.log.1654992227'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES: permission denied, open 'npm-debug.log.1654992227']
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'open',
npm ERR!   path: 'npm-debug.log.1654992227' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
npm ERR!     /var/app/current/npm-debug.log


来源: stackexchange

问:
iOS - Load cells one by one
I want to load the cell of a collection view one by one using the API collectionView.insertItems(at:). There are many answers online which accomplish this by animating the alpha of the cell inside of willDisplayCell and other methods, for example here - link. However, nothing works perfectly. The reason for using collectionView.insertItems(at:) is that the animation is already built in and no hacks needed.

However using collectionView.insertItems(at:), I get error such as:

*** Terminating app due to uncaught exception  'NSInternalInconsistencyException', reason: 'Invalid update: invalid
  number of items in section 0.  The number of items contained in an
  existing section after the update (5) must be equal to the number of
  items contained in that section before the update (5), plus or minus
  the number of items inserted or deleted from that section (1 inserted,
  0 deleted) and plus or minus the number of items moved into or out of
  that section (0 moved in, 0 moved out).

This is an example of what I have, it's crashing as shown above, but it's a start I think in the right direction (hopefully):

```<code>class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    /// This array is populated from a network call.
    let images = [Image]()

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        animateCells()
    }

    func animateCells() {
        let indexPaths = [IndexPath(item: 0, section: 0),
                          IndexPath(item: 1, section: 0),
                          IndexPath(item: 2, section: 0),
                          IndexPath(item: 3, section: 0),
                          IndexPath(item: 4, section: 0)]

        for indexPath in indexPaths {
            let delayTime = 0.1 + Double(indexPath.row) * 0.3

            delay(delayTime) {
                self.collectionView.performBatchUpdates({
                    self.collectionView.insertItems(at: [indexPath])
                }, completion: nil)
            }
        }
    }

    func delay(_ delay: TimeInterval, closure: @escaping () -> Void) {
        let when = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
    }
}

// MARK: - UICollectionViewDataSource

extension ViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

        return cell
    }
}
</code>```

One of the main problems I see is that I do return images.count inside of numberOfItemsInSection.

Any thoughts?

答:
I made one demo with your code and found your mistake

When you are inserting items in your collection view there are already 5 items in your collection view in that position so you can not insert new cells there because your images array has only 5 items which are already been displayed.

Please find below working code ->

```<code>    class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    //Array for collectionView
    var images :[UIImage] = []

    //This array will populate from network call
    var arrAllImagesFromNetwork : [UIImage] = Array(repeating: UIImage(named: "img1")!, count: 5)

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        animateCells()

    }

    func animateCells() {
        let indexPaths = [IndexPath(item: 0, section: 0),
                          IndexPath(item: 1, section: 0),
                          IndexPath(item: 2, section: 0),
                          IndexPath(item: 3, section: 0),
                          IndexPath(item: 4, section: 0)]

        for indexPath in indexPaths {
            let delayTime = 0.1 + Double(indexPath.row) * 0.3

            delay(delayTime) {

                self.images.append(self.arrAllImagesFromNetwork[indexPath.row])

                self.collectionView.performBatchUpdates({
                    self.collectionView.insertItems(at: [indexPath])
                }, completion: nil)
            }
        }
    }

    func delay(_ delay: TimeInterval, closure: @escaping () -> Void) {
        let when = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
    }
}

// MARK: - UICollectionViewDataSource

extension ViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

        return cell
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: iOS - Load cells one by one

Body:
I want to load the cell of a collection view one by one using the API collectionView.insertItems(at:). There are many answers online which accomplish this by animating the alpha of the cell inside of willDisplayCell and other methods, for example here - link. However, nothing works perfectly. The reason for using collectionView.insertItems(at:) is that the animation is already built in and no hacks needed.

However using collectionView.insertItems(at:), I get error such as:

*** Terminating app due to uncaught exception  'NSInternalInconsistencyException', reason: 'Invalid update: invalid
  number of items in section 0.  The number of items contained in an
  existing section after the update (5) must be equal to the number of
  items contained in that section before the update (5), plus or minus
  the number of items inserted or deleted from that section (1 inserted,
  0 deleted) and plus or minus the number of items moved into or out of
  that section (0 moved in, 0 moved out).

This is an example of what I have, it's crashing as shown above, but it's a start I think in the right direction (hopefully):

class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    /// This array is populated from a network call.
    let images = [Image]()

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        animateCells()
    }

    func animateCells() {
        let indexPaths = [IndexPath(item: 0, section: 0),
                          IndexPath(item: 1, section: 0),
                          IndexPath(item: 2, section: 0),
                          IndexPath(item: 3, section: 0),
                          IndexPath(item: 4, section: 0)]

        for indexPath in indexPaths {
            let delayTime = 0.1 + Double(indexPath.row) * 0.3

            delay(delayTime) {
                self.collectionView.performBatchUpdates({
                    self.collectionView.insertItems(at: [indexPath])
                }, completion: nil)
            }
        }
    }

    func delay(_ delay: TimeInterval, closure: @escaping () -> Void) {
        let when = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
    }
}

// MARK: - UICollectionViewDataSource

extension ViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

        return cell
    }
}

One of the main problems I see is that I do return images.count inside of numberOfItemsInSection.

Any thoughts?

Body:
I made one demo with your code and found your mistake

When you are inserting items in your collection view there are already 5 items in your collection view in that position so you can not insert new cells there because your images array has only 5 items which are already been displayed.

Please find below working code ->

    class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    //Array for collectionView
    var images :[UIImage] = []

    //This array will populate from network call
    var arrAllImagesFromNetwork : [UIImage] = Array(repeating: UIImage(named: "img1")!, count: 5)

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        animateCells()

    }

    func animateCells() {
        let indexPaths = [IndexPath(item: 0, section: 0),
                          IndexPath(item: 1, section: 0),
                          IndexPath(item: 2, section: 0),
                          IndexPath(item: 3, section: 0),
                          IndexPath(item: 4, section: 0)]

        for indexPath in indexPaths {
            let delayTime = 0.1 + Double(indexPath.row) * 0.3

            delay(delayTime) {

                self.images.append(self.arrAllImagesFromNetwork[indexPath.row])

                self.collectionView.performBatchUpdates({
                    self.collectionView.insertItems(at: [indexPath])
                }, completion: nil)
            }
        }
    }

    func delay(_ delay: TimeInterval, closure: @escaping () -> Void) {
        let when = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
    }
}

// MARK: - UICollectionViewDataSource

extension ViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

        return cell
    }
}


问:
How to access to an object data php cakephp 3.1
this is a cakephp 3.1 query result, I whant to access directly to $data->items but I get an error saying the key item is not found and I don't whant to use the funtcion toArray() because if I do that it will return only the 'items' => ... and I lost all 'query' => ... informations.
can you help me with the right syntaxe to get $data->items or $data->{'items'} ...
.</p>

```<code>$data = object(Cake\ORM\ResultSet) {

    'query' => object(Cake\ORM\Query) {

        '(help)' => 'This is a Query object, to get the results execute or iterate it.',
        'sql' => 'SELECT Posts_types.id AS `Posts_types__id`, Posts_types.name AS `Posts_types__name` FROM posts_types Posts_types ORDER BY id ASC',
        'params' => [],
        'defaultTypes' => [
            'Posts_types.id' => 'integer',
            'id' => 'integer',
            'Posts_types.name' => 'string',
            'name' => 'string'
        ],
        'decorators' => (int) 0,
        'executed' => true,
        'hydrate' => true,
        'buffered' => true,
        'formatters' => (int) 0,
        'mapReducers' => (int) 0,
        'contain' => [],
        'matching' => [],
        'extraOptions' => [],
        'repository' => object(Cake\ORM\Table) {

            'registryAlias' => 'Posts_types',
            'table' => 'posts_types',
            'alias' => 'Posts_types',
            'entityClass' => '\Cake\ORM\Entity',
            'associations' => [],
            'behaviors' => [],
            'defaultConnection' => 'default',
            'connectionName' => 'default'

        }

    },
    'items' => [
        (int) 0 => object(Cake\ORM\Entity) {

            'id' => (int) 1,
            'name' => 'Descriptif de la formation',
            '[new]' => false,
            '[accessible]' => [
                '*' => true
            ],
            '[dirty]' => [],
            '[original]' => [],
            '[virtual]' => [],
            '[errors]' => [],
            '[repository]' => 'Posts_types'

        },
        (int) 1 => object(Cake\ORM\Entity) {

            'id' => (int) 2,
            'name' => 'Cours',
            '[new]' => false,
            '[accessible]' => [
                '*' => true
            ],
            '[dirty]' => [],
            '[original]' => [],
            '[virtual]' => [],
            '[errors]' => [],
            '[repository]' => 'Posts_types'

        },
        (int) 2 => object(Cake\ORM\Entity) {

            'id' => (int) 3,
            'name' => 'Evénements',
            '[new]' => false,
            '[accessible]' => [
                '*' => true
            ],
            '[dirty]' => [],
            '[original]' => [],
            '[virtual]' => [],
            '[errors]' => [],
            '[repository]' => 'Posts_types'

        }
    ]

}
</code>```

答:
By default queries and result sets will return Entities objects. You can retrieve basic arrays by disabling hydration:

add this to your query
->hydrate(false)

Body:
this is a cakephp 3.1 query result, I whant to access directly to $data->items but I get an error saying the key item is not found and I don't whant to use the funtcion toArray() because if I do that it will return only the 'items' => ... and I lost all 'query' => ... informations.
can you help me with the right syntaxe to get $data->items or $data->{'items'} ...
.

$data = object(Cake\ORM\ResultSet) {

    'query' => object(Cake\ORM\Query) {

        '(help)' => 'This is a Query object, to get the results execute or iterate it.',
        'sql' => 'SELECT Posts_types.id AS `Posts_types__id`, Posts_types.name AS `Posts_types__name` FROM posts_types Posts_types ORDER BY id ASC',
        'params' => [],
        'defaultTypes' => [
            'Posts_types.id' => 'integer',
            'id' => 'integer',
            'Posts_types.name' => 'string',
            'name' => 'string'
        ],
        'decorators' => (int) 0,
        'executed' => true,
        'hydrate' => true,
        'buffered' => true,
        'formatters' => (int) 0,
        'mapReducers' => (int) 0,
        'contain' => [],
        'matching' => [],
        'extraOptions' => [],
        'repository' => object(Cake\ORM\Table) {

            'registryAlias' => 'Posts_types',
            'table' => 'posts_types',
            'alias' => 'Posts_types',
            'entityClass' => '\Cake\ORM\Entity',
            'associations' => [],
            'behaviors' => [],
            'defaultConnection' => 'default',
            'connectionName' => 'default'

        }

    },
    'items' => [
        (int) 0 => object(Cake\ORM\Entity) {

            'id' => (int) 1,
            'name' => 'Descriptif de la formation',
            '[new]' => false,
            '[accessible]' => [
                '*' => true
            ],
            '[dirty]' => [],
            '[original]' => [],
            '[virtual]' => [],
            '[errors]' => [],
            '[repository]' => 'Posts_types'

        },
        (int) 1 => object(Cake\ORM\Entity) {

            'id' => (int) 2,
            'name' => 'Cours',
            '[new]' => false,
            '[accessible]' => [
                '*' => true
            ],
            '[dirty]' => [],
            '[original]' => [],
            '[virtual]' => [],
            '[errors]' => [],
            '[repository]' => 'Posts_types'

        },
        (int) 2 => object(Cake\ORM\Entity) {

            'id' => (int) 3,
            'name' => 'Evénements',
            '[new]' => false,
            '[accessible]' => [
                '*' => true
            ],
            '[dirty]' => [],
            '[original]' => [],
            '[virtual]' => [],
            '[errors]' => [],
            '[repository]' => 'Posts_types'

        }
    ]

}


问:
Swap two variables in Lolcode
What command do I need to swap two variables's values in one line using Lolcode? I've tried looking at Specification, but failed to find any info about it.</p>

答:
Well, i thnk thts right
a,a R b,b R IT

Title: Swap two variables in Lolcode

Body:
Well, i thnk thts right
a,a R b,b R IT


问:
Metro configuration is inaccessible in Java SE 8
I have a Java desktop app that uses JAX-WS to call some web services using the default Metro JAX-WS implementation in Java SE -- it's an SWT app that's launched via Java Web Start (.jnlp). The web services haven't had any problems until recently, when several instances started having errors when the web service calls are initialized:

```<code>WARNING: MASM0010: Unable to unmarshall metro config file from location [ jar:file:/C:/Program%20Files%20(x86)/Java/jre1.8.0_31/lib/resources.jar!/com/sun/xml/internal/ws/assembler/jaxws-tubes-default.xml ]
java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")
</code>```

Which ultimately leads to:

```<code>SEVERE: MASM0003: Default [ jaxws-tubes-default.xml ] configuration file was not loaded.
</code>```

All of the clients experiencing this issue are on Windows using the JRE 1.8.31-45, both x86 and x86_64.  I've been scouring this site and google, but haven't been able to find any information about this issue.

Thanks for any insight to this problem!

答:
I think you meet the same issue as me.

```<code>private static JAXBContext createJAXBContext() throws Exception {
        return isJDKInternal()?(JAXBContext)AccessController.doPrivileged(new PrivilegedExceptionAction<JAXBContext>() {
            public JAXBContext run() throws Exception {
                return JAXBContext.newInstance(MetroConfig.class.getPackage().getName());
            }
        }, createSecurityContext()):JAXBContext.newInstance(MetroConfig.class.getPackage().getName());
}

private static AccessControlContext createSecurityContext() {
    PermissionCollection perms = new Permissions();
    perms.add(new RuntimePermission("accessClassInPackage.com.sun.xml.internal.ws.runtime.config"));
    perms.add(new ReflectPermission("suppressAccessChecks"));
    return new AccessControlContext(new ProtectionDomain[]{new ProtectionDomain((CodeSource)null, perms)});
}
</code>```

that's code in JDK MetroConfigLoader, it will load the resource with specific privilege, and that's the root cause, so you can use jaxws-rt which is a third part lib to implement it,

Or you can load your resource in your class loader with AccessController.doPrivileged, so that's you can access your resource.

Body:
I have a Java desktop app that uses JAX-WS to call some web services using the default Metro JAX-WS implementation in Java SE -- it's an SWT app that's launched via Java Web Start (.jnlp). The web services haven't had any problems until recently, when several instances started having errors when the web service calls are initialized:

WARNING: MASM0010: Unable to unmarshall metro config file from location [ jar:file:/C:/Program%20Files%20(x86)/Java/jre1.8.0_31/lib/resources.jar!/com/sun/xml/internal/ws/assembler/jaxws-tubes-default.xml ]
java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "accessDeclaredMembers")

Which ultimately leads to:

SEVERE: MASM0003: Default [ jaxws-tubes-default.xml ] configuration file was not loaded.

All of the clients experiencing this issue are on Windows using the JRE 1.8.31-45, both x86 and x86_64.  I've been scouring this site and google, but haven't been able to find any information about this issue.

Thanks for any insight to this problem!

Body:
I think you meet the same issue as me.

private static JAXBContext createJAXBContext() throws Exception {
        return isJDKInternal()?(JAXBContext)AccessController.doPrivileged(new PrivilegedExceptionAction<JAXBContext>() {
            public JAXBContext run() throws Exception {
                return JAXBContext.newInstance(MetroConfig.class.getPackage().getName());
            }
        }, createSecurityContext()):JAXBContext.newInstance(MetroConfig.class.getPackage().getName());
}

private static AccessControlContext createSecurityContext() {
    PermissionCollection perms = new Permissions();
    perms.add(new RuntimePermission("accessClassInPackage.com.sun.xml.internal.ws.runtime.config"));
    perms.add(new ReflectPermission("suppressAccessChecks"));
    return new AccessControlContext(new ProtectionDomain[]{new ProtectionDomain((CodeSource)null, perms)});
}

that's code in JDK MetroConfigLoader, it will load the resource with specific privilege, and that's the root cause, so you can use jaxws-rt which is a third part lib to implement it,

Or you can load your resource in your class loader with AccessController.doPrivileged, so that's you can access your resource.


问:
Specifying name, description and refresh interval in iCal (ics) format
I'm creating a iCal subscription calendar which is all working as expected; except I can't seem to specify seemingly basic things such as a default name to suggest to the client for the calendar, a description, and how often it should refresh.

I did find this specification revision: https://datatracker.ietf.org/doc/html/draft-daboo-icalendar-extensions-06

It does suggest that I can simply pass in the fields I want.  Having done this and with the top of the ics file looking like this:

```<code>BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//My Company//NONSGML Event Calendar//EN
URL:http://my.calendar/url
NAME:My Calendar Name
DESCRIPTION:A description of my calendar
TIMEZONE-ID:Europe/London
REFRESH-INTERVAL;VALUE=DURATION:P1D
COLOR:34:50:105
CALSCALE:GREGORIAN
METHOD:PUBLISH
</code>```

I'm simply finding that whilst no device/app that I've tried rejects the calendar, they are all ignoring the properties.  I've used Outlook 2010, an iPhone on iOS 6, and Google Calendar.  Outlook claims to respect some sort of refresh interval in the file, but when I subscribe my calendar - it says it's unspecified.

So the question is are these properties supported, or do I need to specify them as something else for each different client, or am I just plain out of luck?

答:
Another option with the icalendar Ruby gem:

```<code>calendar = Icalendar::Calendar.new
calendar.x_wr_calname = 'Calendar Name'
</code>```

Body:
I'm creating a iCal subscription calendar which is all working as expected; except I can't seem to specify seemingly basic things such as a default name to suggest to the client for the calendar, a description, and how often it should refresh.

I did find this specification revision: https://datatracker.ietf.org/doc/html/draft-daboo-icalendar-extensions-06

It does suggest that I can simply pass in the fields I want.  Having done this and with the top of the ics file looking like this:

BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//My Company//NONSGML Event Calendar//EN
URL:http://my.calendar/url
NAME:My Calendar Name
DESCRIPTION:A description of my calendar
TIMEZONE-ID:Europe/London
REFRESH-INTERVAL;VALUE=DURATION:P1D
COLOR:34:50:105
CALSCALE:GREGORIAN
METHOD:PUBLISH

I'm simply finding that whilst no device/app that I've tried rejects the calendar, they are all ignoring the properties.  I've used Outlook 2010, an iPhone on iOS 6, and Google Calendar.  Outlook claims to respect some sort of refresh interval in the file, but when I subscribe my calendar - it says it's unspecified.

So the question is are these properties supported, or do I need to specify them as something else for each different client, or am I just plain out of luck?

Body:
Another option with the icalendar Ruby gem:

calendar = Icalendar::Calendar.new
calendar.x_wr_calname = 'Calendar Name'


问:
Redux-form FieldArray, handleSubmit' is not defined
I'm working to use a redux-form FieldArray. I'm having challenges connecting the form w the actual react component. When I try to submit the form, I get the following error: error    'handleSubmit' is not defined

The file is below. Am I building this form correctly in my React component? Any idea why handleSubmit is erroring?

```<code>import React from 'react';
import {Field, FieldArray, reduxForm} from 'redux-form'
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as inviteActions from '../../actions/inviteActions';

let renderEmailField = ({input, label, type, meta: {touched, error}}) =>
  <div>
    <label>{label}</label>
    <div>
      <input {...input} name="email" type="email"/>
      {touched && error && <span>{error}</span>}
    </div>
  </div>

let renderEmails = ({fields, meta: {submitFailed, error}}) =>
  <ul>
    <li>
      <button type="button" onClick={() => fields.push()}>Add Email</button>
    </li>
    {fields.map((email, index) =>
      <li key={index}>
        {index > 2 && <button
          type="button"
          title="Remove Email"
          onClick={() => fields.remove(index)}
        />}
        <Field
          name={email}
          component={renderEmailField}
          label={`Email #${index + 1}`}
        />
      </li>
    )}
    {submitFailed && error && <li className="error">{error}</li>}
  </ul>

let EmailsForm = ({handleSubmit, pristine, reset, submitting}) =>
  <form onSubmit={handleSubmit}>
    <FieldArray name="emails" component={renderEmails} />
    <div>
      <button type="submit" disabled={submitting}>Submit</button>
      <button type="button" disabled={pristine || submitting} onClick={reset}>
        Clear Values
      </button>
    </div>
  </form>

class InvitePage extends React.Component {

  handleSubmit(data) {
    console.log(data)
    this.props.actions.createInvites(data);
  }

  render() {

    return (
      <div>
        <h1>Invites</h1>
        <EmailsForm onSubmit={handleSubmit}/>
      </div>
    );
  }

}

EmailsForm = reduxForm({
  form: 'emailsForm',
  initialValues: {
    emails: ['', '', '']
  },
  validate(values) {
    const errors = {}
    if (!values.emails || !values.emails.length) {
      errors.emails = {_error: 'At least one email must be entered'}
    }
    else {
      let emailsArrayErrors = []
      values.emails.forEach((email, emailIndex) => {
        const emailErrors = {}
        if (email == null || !email.trim()) {
          emailsArrayErrors[emailIndex] = 'Required'
        }
      })
      if (emailsArrayErrors.length) {
        errors.emails = emailsArrayErrors
      }
    }
    return errors
  }
})(EmailsForm)

const mapStateToProps = state => {
  return {
    currentUser: state.currentUser
  };
};

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(inviteActions, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(InvitePage);
</code>```

答:
You have to explicitly pass a callback function to handleSubmit like this.

```<code>render() {
    const { handleSubmit } = this.props;

    return (
      <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
          <Field name="firstName" component={this.renderField} type="text" className="curvedBorder" label="First Name" />
          ...
          <button type="submit" className="btn btn-primary">Submit</button>
      </form>
    );
}

onSubmit(values) {
    // handle form submission here.
    console.log(values);
}
</code>```

Hope this helps. Happy coding!

ContentLicense: CC BY-SA 4.0

Body:
I'm working to use a redux-form FieldArray. I'm having challenges connecting the form w the actual react component. When I try to submit the form, I get the following error: error    'handleSubmit' is not defined

The file is below. Am I building this form correctly in my React component? Any idea why handleSubmit is erroring?

import React from 'react';
import {Field, FieldArray, reduxForm} from 'redux-form'
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as inviteActions from '../../actions/inviteActions';

let renderEmailField = ({input, label, type, meta: {touched, error}}) =>

    {label}

      <input {...input} name="email" type="email"/>
      {touched && error && {error}}

let renderEmails = ({fields, meta: {submitFailed, error}}) =>

      <button type="button" onClick={() => fields.push()}>Add Email</button>

    {fields.map((email, index) =>

        {index > 2 && <button
          type="button"
          title="Remove Email"
          onClick={() => fields.remove(index)}
        />}
        <Field
          name={email}
          component={renderEmailField}
          label={`Email #${index + 1}`}
        />

    )}
    {submitFailed && error &&
{error}
}

let EmailsForm = ({handleSubmit, pristine, reset, submitting}) =>
  <form onSubmit={handleSubmit}>
    <FieldArray name="emails" component={renderEmails} />

      <button type="submit" disabled={submitting}>Submit</button>
      <button type="button" disabled={pristine || submitting} onClick={reset}>
        Clear Values
      </button>

  </form>

class InvitePage extends React.Component {

  handleSubmit(data) {
    console.log(data)
    this.props.actions.createInvites(data);
  }

  render() {

    return (

Invites

        <EmailsForm onSubmit={handleSubmit}/>

    );
  }

}

EmailsForm = reduxForm({
  form: 'emailsForm',
  initialValues: {
    emails: ['', '', '']
  },
  validate(values) {
    const errors = {}
    if (!values.emails || !values.emails.length) {
      errors.emails = {_error: 'At least one email must be entered'}
    }
    else {
      let emailsArrayErrors = []
      values.emails.forEach((email, emailIndex) => {
        const emailErrors = {}
        if (email == null || !email.trim()) {
          emailsArrayErrors[emailIndex] = 'Required'
        }
      })
      if (emailsArrayErrors.length) {
        errors.emails = emailsArrayErrors
      }
    }
    return errors
  }
})(EmailsForm)

const mapStateToProps = state => {
  return {
    currentUser: state.currentUser
  };
};

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(inviteActions, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(InvitePage);

Body:
You have to explicitly pass a callback function to handleSubmit like this.

render() {
    const { handleSubmit } = this.props;

    return (
      <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
          <Field name="firstName" component={this.renderField} type="text" className="curvedBorder" label="First Name" />
          ...
          <button type="submit" className="btn btn-primary">Submit</button>
      </form>
    );
}

onSubmit(values) {
    // handle form submission here.
    console.log(values);
}

Hope this helps. Happy coding!


问:
Snap to center of a cell when scrolling UICollectionView horizontally
I know some people have asked this question before but they were all about UITableViews or UIScrollViews and I couldn't get the accepted solution to work for me. What I would like is the snapping effect when scrolling through my UICollectionView horizontally - much like what happens in the iOS AppStore. iOS 9+ is my target build so please look at the UIKit changes before answering this.

Thanks.

答:
Here is my implementation

```<code>func snapToNearestCell(scrollView: UIScrollView) {
     let middlePoint = Int(scrollView.contentOffset.x + UIScreen.main.bounds.width / 2)
     if let indexPath = self.cvCollectionView.indexPathForItem(at: CGPoint(x: middlePoint, y: 0)) {
          self.cvCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
     }
}
</code>```

Implement your scroll view delegates like this

```<code>func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    self.snapToNearestCell(scrollView: scrollView)
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    self.snapToNearestCell(scrollView: scrollView)
}
</code>```

Also, for better snapping

```<code>self.cvCollectionView.decelerationRate = UIScrollViewDecelerationRateFast
</code>```

Works like a charm

Body:
Here is my implementation

func snapToNearestCell(scrollView: UIScrollView) {
     let middlePoint = Int(scrollView.contentOffset.x + UIScreen.main.bounds.width / 2)
     if let indexPath = self.cvCollectionView.indexPathForItem(at: CGPoint(x: middlePoint, y: 0)) {
          self.cvCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
     }
}

Implement your scroll view delegates like this

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    self.snapToNearestCell(scrollView: scrollView)
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    self.snapToNearestCell(scrollView: scrollView)
}

Also, for better snapping

self.cvCollectionView.decelerationRate = UIScrollViewDecelerationRateFast

Works like a charm


问:
While using the YouTube api, the loadvideo function wont work unless I alert the video id first
```<code>function playPlaylist(trackstemp) {
    trackstemp = trackstemp.split(' ');
    for (i=0; i < trackstemp.length; i++){
        tracks[i] = trackstemp[i];
    }
    numoftracks = tracks.length - 1;
    currenttrack = 0;
    loadNewVideo(tracks[currenttrack])
}

function loadNewVideo(id) {
ytplayerid.loadVideoById(id, 0);
}
</code>```

I have a prev() and next() function that work just fine by calling loadNewVideo(tracks[currenttrack]), but the initial video only works if I alert(id) within the loadNewVideo() function.

Any clue to why this is happening?

答:
Mostly likely the effect of the alert is to delay the execution of ytplayerid.loadVideoById(id, 0); so that it satisfies a race condition in your code - for example, the function doesn't exist yet, or some dependency in the function is not yet settled.

Make sure that the first loadNewVideo happens after all other scripts are loaded and the DOM is ready (ie, by attaching the function to the window.load event).

ContentLicense: CC BY-SA 2.5

Body:
function playPlaylist(trackstemp) {
    trackstemp = trackstemp.split(' ');
    for (i=0; i < trackstemp.length; i++){
        tracks[i] = trackstemp[i];
    }
    numoftracks = tracks.length - 1;
    currenttrack = 0;
    loadNewVideo(tracks[currenttrack])
}

function loadNewVideo(id) {
ytplayerid.loadVideoById(id, 0);
}

I have a prev() and next() function that work just fine by calling loadNewVideo(tracks[currenttrack]), but the initial video only works if I alert(id) within the loadNewVideo() function.

Any clue to why this is happening?


问:
Celery: Which are the queues consumed if the -Q option is not specified
According to the Celery documentation, the -Q/--queues command line option can be used for:

-Q, --queues

List of queues to enable for this worker, separated by comma. By default all configured queues are enabled. Example: -Q video,image

However I don't understand what does it mean with configured queues here. Does this mean all queues known to Celery, including the default one? Or only the ones defined in the  task_queues config option? Does the task_create_missing_queues option affect this?

答:
If you haven't configured anything, it will consume from celery queue and you can as you can see from logs

```<code>celery worker -A t

 -------------- celery@pavilion v4.0.2 (latentcall)
---- **** -----
--- * ***  * -- Linux-4.4.0-79-generic-x86_64-with-Ubuntu-16.04-xenial 2017-06-09 10:39:14
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app:         tasks:0x7f15cf9cdfd0
- ** ---------- .> transport:   amqp://guest:**@localhost:5672//
- ** ---------- .> results:     rpc://
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery
</code>```

You can also configure celery to consume a set of queues by default like this

```<code>from celery import Celery
from kombu import Queue

app = Celery(broker='amqp://guest@localhost//', backend='rpc')
app.conf.task_queues = (Queue('foo'), Queue('bar'))
</code>```

Now all workers will consume foo, bar queues by default.

```<code>-------------- [queues]
               .> bar              exchange=celery(direct) key=celery
               .> foo              exchange=celery(direct) key=celery
</code>```

Body:
If you haven't configured anything, it will consume from celery queue and you can as you can see from logs

celery worker -A t

 -------------- celery@pavilion v4.0.2 (latentcall)
---- **** -----
--- * ***  * -- Linux-4.4.0-79-generic-x86_64-with-Ubuntu-16.04-xenial 2017-06-09 10:39:14
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app:         tasks:0x7f15cf9cdfd0
- ** ---------- .> transport:   amqp://guest:**@localhost:5672//
- ** ---------- .> results:     rpc://
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

You can also configure celery to consume a set of queues by default like this

from celery import Celery
from kombu import Queue

app = Celery(broker='amqp://guest@localhost//', backend='rpc')
app.conf.task_queues = (Queue('foo'), Queue('bar'))

Now all workers will consume foo, bar queues by default.

-------------- [queues]
               .> bar              exchange=celery(direct) key=celery
               .> foo              exchange=celery(direct) key=celery


问:
Sum of powers of prime factors
Given an array of integers (each <=10^6) what is the fastest way to find the sum of powers of prime factors of  each integer?</p>

```<code>Ex:-
    array: 4 6 12 7
    4 -> 2^2 -> 2
    6 -> 2^1 * 3^1 -> 1+1 -> 2
    12 -> 2^2 * 3^1 -> 2+1 -> 3
    7 -> 7^1 -> 1
    Answer: 2+2+3+1 = 8
</code>```

答:
You can reduce the time for finding the prime-factors of a number using sieve algorithm. For your question, some modification in the sieve algorithm will work.

You can do this,

```<code>// For Globally storing the sum of power of prime factors
public static int powerSum[] = new int[1000001];

// For Identifying the factor is prime or not
public static boolean prime[] = new boolean[1000001];

public static void sieve()
{
    powerSum[0] = 0;
    powerSum[1] = 1;

    Arrays.fill(prime , true);

    prime[0] = false;
    prime[1] = false;

    for(int i = 2 ; i <= 1000000 ; i++)     // sieve algorithm
    {
        if(prime[i])   // Consider the factor for calculation only if it is prime
        {
            for(int j = i ; j <= 1000000 ; j += i)
            {
                int tempJ = j;

                while(tempJ != 0 && tempJ%i == 0)// Counting number of occurance of the factor
                {
                    powerSum[j]++;

                    tempJ /= i;
                }

                prime[j] = false;
            }
        }
    }
}
</code>```

In the sieve method, I'm pre calculating the sum of powers of prime factors of every number between given range. I use the simple sieve method for considering  only prime factors, and for counting the occurrence of that factor, I apply while loop.

Now you can use this method for finding the sum of power of prime factors for any number in given range by this way,

```<code>public static void main(String args[])
{
    sieve();

    int ans = powerSum[4] + powerSum[6] + powerSum[7] + powerSum[12];

    System.out.println(ans);
}
</code>```

Title: Sum of powers of prime factors

Body:
Given an array of integers (each <=10^6) what is the fastest way to find the sum of powers of prime factors of  each integer?

Ex:-
    array: 4 6 12 7
    4 -> 2^2 -> 2
    6 -> 2^1 * 3^1 -> 1+1 -> 2
    12 -> 2^2 * 3^1 -> 2+1 -> 3
    7 -> 7^1 -> 1
    Answer: 2+2+3+1 = 8

Body:
You can reduce the time for finding the prime-factors of a number using sieve algorithm. For your question, some modification in the sieve algorithm will work.

You can do this,

// For Globally storing the sum of power of prime factors
public static int powerSum[] = new int[1000001];

// For Identifying the factor is prime or not
public static boolean prime[] = new boolean[1000001];

public static void sieve()
{
    powerSum[0] = 0;
    powerSum[1] = 1;

    Arrays.fill(prime , true);

    prime[0] = false;
    prime[1] = false;

    for(int i = 2 ; i <= 1000000 ; i++)     // sieve algorithm
    {
        if(prime[i])   // Consider the factor for calculation only if it is prime
        {
            for(int j = i ; j <= 1000000 ; j += i)
            {
                int tempJ = j;

                while(tempJ != 0 && tempJ%i == 0)// Counting number of occurance of the factor
                {
                    powerSum[j]++;

                    tempJ /= i;
                }

                prime[j] = false;
            }
        }
    }
}

In the sieve method, I'm pre calculating the sum of powers of prime factors of every number between given range. I use the simple sieve method for considering  only prime factors, and for counting the occurrence of that factor, I apply while loop.

Now you can use this method for finding the sum of power of prime factors for any number in given range by this way,

public static void main(String args[])
{
    sieve();

    int ans = powerSum[4] + powerSum[6] + powerSum[7] + powerSum[12];

    System.out.println(ans);
}


问:
Why does these 2 similar for loop have different results when adding ActionListener into JButton?
Originally I have a JFrame have 3 buttons: which button 0 prints 0 when clicked, button 1 prints 1 and so on:

```<code>JFrame jframe=new JFrame();
jframe.getContentPane().setLayout(new GridLayout(3,1));
for(int i=0;i<3;i++){
    final int j=i;
    JButton jbutton=new JButton(""+j);
    jframe.getContentPane().add(jbutton);
    jbutton.setPreferredSize(new Dimension(100,100));
    jbutton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            System.out.println(""+j);
        }
    });
}
jframe.setVisible(true);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
</code>```

I want to reduce 1 line due to the final variable, and hence refactor the for-loop as this:

```<code>JFrame jframe=new JFrame();
jframe.getContentPane().setLayout(new GridLayout(3,1));
for(final int[] arr={0};arr[0]<3;arr[0]++){
    JButton jbutton=new JButton(""+arr[0]);
    jframe.getContentPane().add(jbutton);
    jbutton.setPreferredSize(new Dimension(100,100));
    jbutton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            System.out.println(""+arr[0]);
        }
    });
}
jframe.setVisible(true);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
</code>```

but this time all buttons print 3 even the button index is still 0,1,2, what is the reason?

答:
In the second program, you are passing the same variable to all three buttons. And then you increment the value of the variable with each iteration. So the value gets updated for all three buttons.

Let me give you a simple example,

```<code>class Resource{
    int a = 10;
}
class A{
    Resource r;
}
class B{
    public static void main(String args[]){
        Resource r = new Resource();

        A o1 = new A();
        o1.r = r;

        A o2 = new A();
        o2.r = r;

        o1.r.a = 20;

        System.out.println(o1.r.a);  // prints 20
        System.out.println(o2.r.a);  // prints 20 too
    }
}
</code>```

Body:
Originally I have a JFrame have 3 buttons: which button 0 prints 0 when clicked, button 1 prints 1 and so on:

JFrame jframe=new JFrame();
jframe.getContentPane().setLayout(new GridLayout(3,1));
for(int i=0;i<3;i++){
    final int j=i;
    JButton jbutton=new JButton(""+j);
    jframe.getContentPane().add(jbutton);
    jbutton.setPreferredSize(new Dimension(100,100));
    jbutton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            System.out.println(""+j);
        }
    });
}
jframe.setVisible(true);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

I want to reduce 1 line due to the final variable, and hence refactor the for-loop as this:

JFrame jframe=new JFrame();
jframe.getContentPane().setLayout(new GridLayout(3,1));
for(final int[] arr={0};arr[0]<3;arr[0]++){
    JButton jbutton=new JButton(""+arr[0]);
    jframe.getContentPane().add(jbutton);
    jbutton.setPreferredSize(new Dimension(100,100));
    jbutton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            System.out.println(""+arr[0]);
        }
    });
}
jframe.setVisible(true);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

but this time all buttons print 3 even the button index is still 0,1,2, what is the reason?

Body:
In the second program, you are passing the same variable to all three buttons. And then you increment the value of the variable with each iteration. So the value gets updated for all three buttons.

Let me give you a simple example,

class Resource{
    int a = 10;
}
class A{
    Resource r;
}
class B{
    public static void main(String args[]){
        Resource r = new Resource();

        A o1 = new A();
        o1.r = r;

        A o2 = new A();
        o2.r = r;

        o1.r.a = 20;

        System.out.println(o1.r.a);  // prints 20
        System.out.println(o2.r.a);  // prints 20 too
    }
}


问:
document.getElementById giving Null by JS not by HTML
When I am defining my input tag in html and accessing in JS by id then I am getting my tag.

HTML Code:

```<code><input class="easyui-combobox" name="language" style="width:30%;" id= "XX">
</code>```

JS Code:

```<code>var cc = document.getElementById("XX");
</code>```

Here things are fine.

But When I am creating from javascript and trying to access I am getting. I want dynamic So I need to create from JS.

JS Code:

```<code>var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
</code>```

Here I am getting null after applying this:

```<code>var cc = document.getElementById("XX");
</code>```

答:
You have to append your created element into the document using document.body.appendChild(input);

var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);
console.log(document.getElementById("XX"));```

Body:
When I am defining my input tag in html and accessing in JS by id then I am getting my tag.

HTML Code:

<input class="easyui-combobox" name="language" style="width:30%;" id= "XX">

JS Code:

var cc = document.getElementById("XX");

Here things are fine.

But When I am creating from javascript and trying to access I am getting. I want dynamic So I need to create from JS.

JS Code:

var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";

Here I am getting null after applying this:

var cc = document.getElementById("XX");


问:
RouterLink- angular2, child route and a query string
angular2,

How do I add a query query to a nested route in this format?

This works in ts file:

```<code>routerLink = ['/output', {outlets: {'output': ['details']}}]

http://localhost:4200/#/output/(output:details)
</code>```

How do I modify to add a query parm?
URL should like like this:

```<code>    http://localhost:4200/#/output/(output:details;id=1)
</code>```

答:
You can pass parameters as objects to URL segments like this:

```<code>router.navigate([
     '/inbox', 33, {details: true}, 'messages', 44, {mode: 'preview'}
])
</code>```

So in your case it will like this:

```<code>routerLink = ['/output', {outlets: {'output': ['details', {id: 1}]}}]
                                                           ^^^^^
</code>```

this will generate the URL:

```<code>/output/(output:details;id=1)
</code>```

Body:
angular2,

How do I add a query query to a nested route in this format?

This works in ts file:

routerLink = ['/output', {outlets: {'output': ['details']}}]

http://localhost:4200/#/output/(output:details)

How do I modify to add a query parm?
URL should like like this:

    http://localhost:4200/#/output/(output:details;id=1)

Body:
You can pass parameters as objects to URL segments like this:

router.navigate([
     '/inbox', 33, {details: true}, 'messages', 44, {mode: 'preview'}
])

So in your case it will like this:

routerLink = ['/output', {outlets: {'output': ['details', {id: 1}]}}]
                                                           ^^^^^

this will generate the URL:

/output/(output:details;id=1)


问:
Compare two date fields in MongoDB
in my collection each document has 2 dates, modified and sync. I would like to find those which modified > sync, or sync does not exist.

I tried

```<code>{'modified': { $gt : 'sync' }}
</code>```

but it's not showing what I expected. Any ideas?

Thanks

答:
Use Javascript, use foreach And convert Date To toDateString() </p>

```<code>db.ledgers.find({}).forEach(function(item){

    if(item.fromdate.toDateString() == item.todate.toDateString())
    {
        printjson(item)
    }
})
</code>```

Title: Compare two date fields in MongoDB

Body:
in my collection each document has 2 dates, modified and sync. I would like to find those which modified > sync, or sync does not exist.

I tried

{'modified': { $gt : 'sync' }}

but it's not showing what I expected. Any ideas?

Thanks

Body:
Use Javascript, use foreach And convert Date To toDateString()

db.ledgers.find({}).forEach(function(item){

    if(item.fromdate.toDateString() == item.todate.toDateString())
    {
        printjson(item)
    }
})