function testCase(seriesNext) {
   //3 hosts alive
   assert.strictEqual(Object.keys(hosts).length, 3);
   var counter = 0;
   var issued = 0;
   var killed = false;
   async.times(500, function (n, next) {
     if (n === 10) {
       //kill a node when there are some outstanding requests
       helper.ccmHelper.exec(['node2', 'stop', '--not-gently'], function (err) {
         killed = true;
         assert.ifError(err);
         next();
       });
       return;
     }
     if (killed) {
       //Don't issue more requests
       return next();
     }
     issued++;
     client.execute('SELECT * FROM system.schema_keyspaces', function (err, result) {
       assert.ifError(err);
       counter++;
       next();
     });
   }, function (err) {
     assert.ifError(err);
     //Only 2 hosts alive at the end
     assert.strictEqual(
       client.hosts.slice(0).reduce(function (val, h) {
         return val + (h.isUp() ? 1 : 0);
       }, 0),
       2);
     seriesNext();
   });
 }
Example #2
0
  post: function(done){
    function _addUser(user_id, cb){

      var postdata = JSON.stringify({'user_id': user_id}),
      opts = {
        hostname: hostname,
        port: port,
        path: '/users/create',
        method: 'POST',
        headers: {
          'Content-Length': postdata.length
        }
      };

      var req = http.request(opts, function(res){
        res.on('data', function(chunk){})

        res.on('end', function(){
          cb();
        });
      });

      req.on('error', cb);

      req.write(postdata);
      req.end();
    }

    async.times(5, function(n, next){
      _addUser(++n, function(err){
        next(err);
      });
    }, function(err){
      if (err) return done(err);
      done(null, 'saved');
    });
  },
Example #3
0
exports.createPlayfields = function(user, request, orientation, times, type, done) {

	if (_.isFunction(type)) {
		done = type;
		type = null;
	}
	var fileType = type || 'playfield-' + orientation;
	var mimeType = 'image/png';

	var isFS = orientation == 'fs';

	async.times(times, function(n, next) {
		var name = 'playfield-' + n + '.png';

		gm(isFS ? 1080 : 1920, isFS ? 1920 : 1080, pleasejs.make_color()).toBuffer('PNG', function(err, data) {
			if (err) {
				throw err;
			}
			request
				.post('/storage/v1/files')
				.query({ type: fileType })
				.type(mimeType)
				.set('Content-Disposition', 'attachment; filename="' + name + '"')
				.set('Content-Length', data.length)
				.send(data)
				.as(user)
				.end(function(err, res) {
					expect(err).to.not.be.ok();
					expect(res.status).to.be(201);
					next(null, res.body);
				});
		});

	}, function(err, playfields) {
		done(playfields);
	});
};
Example #4
0
    it("allows requests after the interval has passed", function(done) {
      var counter = RateLimitedCounter({
        redis: redis.createClient(),
        interval: 150,
        maxInInterval: 30
      });

      async.times(100, function(n, next) {
        counter.increment(n % 3, next);
      }, function(err) {
        if (err) throw err;
        setTimeout(function() {
          async.times(100, function(n, next) {
            counter.increment(n % 3, next);
          }, function(err, results) {
            if (err) throw err;
            expect(counter.getCount(0)).to.equal(60);
            expect(counter.getCount(1)).to.equal(60);
            expect(counter.getCount(2)).to.equal(60);
            done();
          });
        }, 150);
      });
    });
Example #5
0
  it('tests the all function, specific cache', function(done){

    serviceInstance.clear('specific');
    var specific = serviceInstance.new('specific');

    async.times(5, function(time, timeCB){

      var key = "sync_key_" + time;
      var opts = {};

      if (time == 4) opts.ttl = 2000;

      specific.set(key, {"val":key}, opts, timeCB);

    }, function(e){

      if (e) return done(e);

      expect(Object.keys(specific.__cache).length).to.be(5);

      specific.all(function(e, items){

        if (e) return done(e);
        expect(items.length).to.be(5);

        expect(items[0].val).to.be("sync_key_" + 0);
        expect(items[1].val).to.be("sync_key_" + 1);
        expect(items[2].val).to.be("sync_key_" + 2);
        expect(items[3].val).to.be("sync_key_" + 3);
        expect(items[4].val).to.be("sync_key_" + 4);

        done();

      });
    });
  });
Example #6
0
function measureCluster(samples, callback) {
  var start = process.hrtime();
  var latencies = [];

  async.times(samples, function(n, next) {
    var socket = net.connect('/tmp/hive.sock');
    var buffer = '';
    socket.on('data', function(data) {
      buffer += data.toString();
    });
    socket.on('end', function() {
      var data = buffer.split('\0');
      assert.equal('2', data[0]);
      latencies.push(+data[1]);
      next();
    });
    socket.end('1 + 1;');
  }, function(err) {
    var diff = process.hrtime(start);
    var elapsed = (diff[0] * 1e9 + diff[1]) / 1000000;
    var avgLatency = utils.avg(latencies);
    callback(null, elapsed, avgLatency);
  });
}
Example #7
0
 notificationproxy.getNotificationsByMasterId(req.session.user._id, function(err, docs) {
     if (err) return next(err);
     var count = docs.length;
     async.times(count, function(n, cb) {
         docs[n].friendly_create_time = formatfun.formatDate(docs[n].createtime, true);
         if (docs[n].type === 'follow') {
             authproxy.getUserById(docs[n].authorid, function(err, author) {
                 if (err) return next(err);
                 docs[n].author = author;
                 return cb(null, docs[n]);
             });
         } else if (docs[n].type === 'comment') {
             commentproxy.getCommentsByQuery({_id: docs[n].commentid}, {}, function(err, comment) {
                 if (err) return next(err);
                 docs[n].comment = comment[0];
                 return cb(null, docs[n]);
             });
         }
     }, function(err, result) {
         if (err) return next(err);
         //console.log(result);
         return res.render('user/notifications', {notifications: result});
     });
 });
Example #8
0
Pool.prototype.initialize = function(callback) {
  var self = this;

  // If a drivername is supplied, initialize the via the old method,
  // Class.forName()
  if (this._drivername) {
    java.newInstance(this._drivername, function(err, driver) {
      if (err) {
        return callback(err);
      } else {
        dm.registerDriver(driver, function(err) {
          if (err) {
            return callback(err);
          }
        });
      }
    });
  }

  asyncjs.times(self._minpoolsize, function(n, next){
    addConnection(self._url, self._props, function(err, conn) {
      next(err, conn);
    });
  }, function(err, conns) {
    if (err) {
      return callback(err);
    } else {
      _.each(conns, function(conn) {
        self._pool.push(conn);
      });
      return callback(null);
    }
  });

  jinst.events.emit('initialized');
};
      it('counts api keys differently', function(done) {
        var options = {
          headers: headers({
            'X-Forwarded-For': this.ipAddress,
            'X-Api-Key': this.apiKey,
          }, headerOverrides),
        };

        async.times(limit, function(index, asyncCallback) {
          request.get('http://localhost:9333' + path, options, function(error, response) {
            response.statusCode.should.eql(200);
            asyncCallback(null);
          });
        }.bind(this), function() {
          Factory.create('api_user', function(user) {
            options.headers['X-Api-Key'] = user.api_key;

            request.get('http://localhost:9333' + path, options, function(error, response) {
              response.statusCode.should.eql(200);
              done();
            });
          });
        });
      });
Example #10
0
var loadSeedData = function (callback) {
  callback = callback || _.noop;

  async.times(10, function(n, next) {
    var director = { firstName : 'Steven', lastName : 'Spielberg the ' + n, titles : ['Producer', 'Writer', 'Director']};
    var actors = [
      { firstName : 'Tom', lastName : 'Hanks', titles : ['Producer', 'Actor', 'Soundtrack']}
    ];

    var tags = ['tag ' + n];

    if(n %3 === 0) {
      actors.push({ firstName : 'Rex', lastName : 'Ryan', titles : ['Actor', 'Head Coach']});
      tags.push('Action');
    }

    if(n %5 === 0) {
      actors.push({ firstName : 'Tom', lastName : 'Coughlin', titles : ['Writer', 'Head Coach']});
      tags.push('Comedy');
    }

    Movie.create({title : 'Movie ' + n, releaseYear : 2001 + n, actors : actors, director : director, tags: tags}, next);
  }, callback);
};
Example #11
0
    Comment.find(query, {}, option, function(err, docs) {
        if (err) return callback(err);
        if (!docs || docs.length === 0) {
            return callback(null, []);
        }
        var count = docs.length;
        async.times(count, function(n, cb) {
            authproxy.getUserById(docs[n].authorid, function(err, user) {
             if (err) return cb(err);
             var author = {
                 _id: user._id,
                 name: user.name,
                 profile: user.profile,
                 gravatar: user.gravatar

             };
             docs[n].author = author;
             cb(null, docs[n]);
            });
        }, function(err, comments) {
            if (err) return callback(err);
            return callback(null, comments);
        });
    });
Example #12
0
  it('caches concurrent requests to the appropriate file', function(done) {
    // Fire off 20 concurrent requests and ensure that all the cached responses
    // end up in the appropriate place.
    async.times(20, function(index, next) {
      var randomInput = Math.random().toString();
      var url = '/echo_chunked?input=' + randomInput;

      var cacheKey = ['GET', 'localhost:9333', url].join('');
      var cacheBase = crypto.createHash('sha256').update(cacheKey).digest('hex');

      request.get('http://localhost:9333' + url, function(error, response, body) {
        next(null, {
          url: url,
          input: randomInput,
          output: body,
          cacheBase: cacheBase,
        });
      });
    }, function(error, requests) {
      setTimeout(function() {
        for(var i = 0; i < requests.length; i++) {
          var request = requests[i];
          var cacheBase = request.cacheBase;

          var cachedMeta = fs.readFileSync(path.join(process.env.PROXY_CACHE_DIR, cacheBase + '.meta'));
          var cachedBody = fs.readFileSync(path.join(process.env.PROXY_CACHE_DIR, cacheBase + '.body'));

          JSON.parse(cachedMeta).request.url.should.eql(request.url);
          request.input.should.eql(request.output);
          cachedBody.toString().should.eql(request.output);
        }

        done();
      }, 50);
    });
  });
 it('should allow multiple parallel calls to connect', function (done) {
   var client = newInstance();
   async.times(100, function (n, next) {
     client.connect(next);
   }, done);
 });
 function executeABunchOfTimes(next) {
   async.times(10, function (n, timesNext) {
     client.execute('SELECT * FROM system.local', timesNext);
   }, next);
 },
Example #15
0
 function shutDownMultiple(seriesNext) {
   async.times(10, function(n, next) {
     client.shutdown(next);
   }, seriesNext);
 }
 iotAgentLib.clearAll(function() {
     async.times(10, createDeviceRequest, function(error, results) {
         done();
     });
 });
Example #17
0
    scraperjs = require('scraperjs');

low.load();

var scrapeBan = function(id, callback) {
    scraperjs.StaticScraper.create('http://www.archeometrie.mom.fr/banadora/echantillon.php?num=' + id)
	.scrape(function($) {
            return $("tr").map(function() {
		return $(this).text();
            }).get().filter(function(labcode) {
		return labcode.lastIndexOf('  Code', 0) === 0;
	    })[0];
	}, function(labcode) {
	    // console.log(id);
	    low('c14').insert({source: 'BANADORA', labcode: labcode});
	    callback(null, {
		labcode: labcode
	    });
	});
};

// example from caolan/async
// upper limit is 39625
async.times(25, function(n, next){
    scrapeBan(n, function(err, user) {
      next(err, user);
    });
}, function(err, users) {
    console.log(users);
});
 it('should handle 500 parallel queries', function (done) {
   var client = newInstance();
   async.times(500, function (n, next) {
     client.execute(helper.queries.basic, [], next);
   }, done)
 });
Example #19
0
 before(function(done) {
   async.times(10, function(n, next) {
     makeFakeEntity(path, next);
   }, done);
 });
 function insertData(seriesNext) {
   var query = util.format('INSERT INTO %s (id, text_sample) VALUES (?, ?)', table);
   async.times(100, function (n, next) {
     client.execute(query, [types.Uuid.random(), n.toString()], next);
   }, seriesNext);
 },
Example #21
0
			mayCauseLength = 0
			// console.log(util.inspect(body.response, {depth: null}))
		}

		return cb(null, {
			id: id,
			mayCauseLength: mayCauseLength,
			fullObject: body.response
		})
	})
}

async.times(limit, countMayCause, function(err, result){
	if (err){ console.log('Error:', err)}

	result = result.filter(function(v){ return v })

	var fullResult = result.map(function(v){ return v.fullObject })

	var trimmedResult = result.map(function(v){ return {id: v.id, mayCauseLength: v.mayCauseLength} })
	var activeIds = result.map(function(v){ return v.id })

	// console.log(util.inspect(result, {depth: 1}))
	
	// write output to file
	fs.writeFile('full-result.json', JSON.stringify(fullResult, null, 4))
	fs.writeFile('trimmed-result.json', JSON.stringify(trimmedResult, null, 4))
	fs.writeFile('active-ids.json', JSON.stringify(activeIds, null, 4))

	console.log('all done!', 'sent', sent, 'requests')
})
 function makeSomeQueries(next) {
   //to ensure that the pool is all up!
   async.times(100, function (n, timesNext) {
     client.execute('SELECT * FROM system.schema_keyspaces', timesNext);
   }, next);
 },
Example #23
0
File: time.js Project: allyong/node
/*
* @Author: allyong
* @Date:   2016-12-29 15:49:36
* @Last Modified by:   allyong
* @Last Modified time: 2016-12-29 15:50:39
*/

'use strict';
var async = require('async');
/*
times 异步运行,times可以指定调用几次,并把结果合并到数组中返回;
*/
async.times(5, function(n, next){    
    console.log("n: " + n);    
    next(null, n * 2);    
}, function(err, results){    
    console.log(results);// [0, 2, 4, 6, 8]    
}); 
/*
n: 0
n: 1
n: 2
n: 3
n: 4
[ 0, 2, 4, 6, 8 ]
*/
Example #24
0
 return function (done) {
   async.times(times, writer(root), done);
 };
Example #25
0
 // Create two batches.
 function startBatches() {
   async.times(2, function(n, cb) {
     db.beginBatch(ctx, {}, cb);
   }, addRows);
 }
      row.push(" ");
      for (var j = 0; j < 10; j++) {
        letter = field[(i*10+j)].toString() + " ";
        row.push(letter);
      }
      console.log(row.join(""));
    }
  };



async.times(100000, function(n, done) {

  var placement = RandomPlacement();
  placement(function(ships) {
    ships.forEach(function(ship) {
      ship.asFields().forEach(function(f) {
        field[f]++;
      });
    });
    console.log("Ship placement done, #", n);
    done();
  });
}, function(err, results) {
 // results are empty
  
  console.log("DONE!");
  printPlayingField();
});

 it('should handle 500 parallel queries', function (done) {
   var client = newInstance();
   async.times(500, function (n, next) {
     client.execute('SELECT * FROM system.schema_keyspaces', [], next);
   }, done)
 });
Example #28
0
CouponSchema.statics.generate = function(event, count, callback) {
  async.times(count, function(n,cb){
    mongoose.model('Coupon').create({event: event}, cb);
  }, callback);
}
Example #29
0
    return clsSession.run(function () {
        clsSession.set('beachEventID', beachEventID);
        const groups = [];
        return async.times(maxTeamsAdvance, function (i, next) {
            return clsSession.run(function () {
                clsSession.set('beachEventID', beachEventID);
                const nummer = i + 1;
                logger.verbose('Generating Zwischengruppe ' + nummer);
                const teams = [];

                const gruppenID = mongoose.Types.ObjectId();

                for (let seq = 0; seq < gruppenLength; seq++) {
                    teams.push({
                        _id: mongoose.Types.ObjectId(),
                        rank: ((nummer + seq) % 2 + 1),
                        fromType: 'Gruppe',
                        from: gruppen[seq],
                        isPlaceholder: true,
                        gruppe: gruppenID,
                        jugend: jugendid
                    });
                }

                const gruppe = new Gruppen({
                    _id: gruppenID,
                    name: 'Zwischenrunde Gruppe ' + nummer,
                    type: 'zwischenrunde',
                    jugend: jugendid,
                    teams: teams
                });
                logger.silly('Setting Jugend %s', jugendid);
                gruppe.jugend = jugendid;
                const query = Jugend.findById(gruppe.jugend);

                return clsSession.run(function () {
                    clsSession.set('beachEventID', beachEventID);
                    return query.exec(function (err, jugend) {
                        if (err) {
                            return next(err);
                        }
                        return clsSession.run(function () {
                            clsSession.set('beachEventID', beachEventID);
                            return gruppe.save(function (err, gruppe) {
                                if (err) {
                                    return next(err);
                                }
                                logger.silly('Gruppe saved');

                                return clsSession.run(function () {
                                    clsSession.set('beachEventID', beachEventID);
                                    return jugend.pushGruppe(gruppe, function (err) {
                                        if (err) return next(err);

                                        groups.push(gruppe);

                                        return async.eachSeries(teams, function (team, callback) {
                                            const t = new Team(team);
                                            return clsSession.run(function () {
                                                clsSession.set('beachEventID', beachEventID);
                                                t.save(function (err) {
                                                    if (err) return callback(err);

                                                    return callback();
                                                });
                                            }, function (err) {
                                                if (err) return next(err);

                                                return clsSession.run(function () {
                                                    clsSession.set('beachEventID', beachEventID);
                                                    return gruppe.deepPopulate('teams jugend', function (err, gruppe) {
                                                        if (err) return next(err);

                                                        relevantGruppen.push(gruppe);
                                                        return next();
                                                    });
                                                });
                                            });
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        }, function (err) {
            if (err) return callback(err);

            return callback(null, relevantGruppen);
        });
    });
Example #30
0
 function(cb) {
   async.times(5, postUser, cb);
 },