Beispiel #1
0
var payments = function (remote, balances, callback) {
  assert(3 === arguments.length);

  var sends = [];

  for (var src in balances) {
    var values_src  = balances[src];
    var values      = 'string' === typeof values_src ? [ values_src ] : values_src;

    for (var index in values) {
      var amount_json = values[index];
      var amount      = Amount.from_json(amount_json);

      sends.push( { "source" : src, "destination" : amount.issuer().to_json(), "amount" : amount_json } );
    }
  }

  async.every(sends,
    function (send, callback) {
      payment(remote, send.source, send.destination, send.amount,
        function (mismatch) { callback(!mismatch); });
    },
    function (every) {
      callback(!every);
    });
};
Beispiel #2
0
task("build-tools", function (callback) {
	async.every(["./build/typescript/typescript.d.ts", "./build/typescript/index.js", "./build/doc.js"], fs.exists.bind(fs), function (allExist) {
		if (allExist) {
			callback();
			return;
		}

		var typescriptPath = path.join(require.resolve("typescript"), "..", "..");

		async.waterfall([
			async.parallel.bind(async, [
				fs.readFile.bind(fs, path.join(typescriptPath, "lib", "typescript.d.ts"), "utf8"),
				fs.readFile.bind(fs, "./build/typescript/extras.d.ts", "utf8")
			]),
			function (results, callback) {
				var newDts = results[0] + "\n\n" + results[1];
				fs.writeFile("./build/typescript/typescript.d.ts", newDts, "utf8", callback);
			},
			function (callback) {
				npm.load(function () {
					npm.commands["run-script"](["build"], callback);
				});
			}
		], callback);
	});
});
Beispiel #3
0
  it('should ignore dumb stuff', (done) => {
    const dumbStuff = [
      '1',
      'e',
      'E',
      "i'm g",
      '9/10',
      '10/10',
      '11/10',
      '10/100',
      '4:20',
      '(1)',
      '.2 bytes / second',
      '3 #comment',
      '"3" #comment',
      'not 5',
      'not []',
      // "W 0 B S C A L E", // One can dream
    ];

    async.every(dumbStuff, (el, callback) => {
      assertNoResponse(el, () => { callback(true); });
    }, (err) => {
      assert.isOk(err);
      done();
    });
  });
Beispiel #4
0
  self._doGetRequest('/v1/txproposals/', function(err, txps) {
    if (err) return cb(err);

    API._processTxps(txps, self.credentials.sharedEncryptingKey);
    async.every(txps,
      function(txp, acb) {
        if (opts.doNotVerify) return acb(true);

        Verifier.checkTxProposal(self.credentials, txp, {
          payProGetter: self.payProGetter
        }, function(err, isLegit) {
          if (err)
            return cb(new Error('Cannot check transaction now:' + err));

          return acb(isLegit);
        });
      },
      function(isLegit) {
        if (!isLegit)
          return cb(new ServerCompromisedError('Server sent fake transaction proposal'));

        var result;
        if (opts.forAirGapped) {
          result = {
            txps: JSON.parse(JSON.stringify(txps)),
            encryptedPkr: WalletUtils.encryptMessage(JSON.stringify(self.credentials.publicKeyRing), self.credentials.personalEncryptingKey),
            m: self.credentials.m,
            n: self.credentials.n,
          };
        } else {
          result = txps;
        }
        return cb(null, result);
      });
  });
    }, function(err) {
        if (err) {
            log.error('operational-sync-endpoint-handler.initialOPDSync(): Not starting initial operational data sync because of a communication error with JDS: ' + err);
            return setTimeout(handlerCallback, 0, err);
        } else if (_.isEmpty(sitesToSubscribeOPD)) {
            log.debug('operational-sync-endpoint-handler.initialOPDSync(): Operational data has already been synced for all primary sites.');
            return setTimeout(handlerCallback, 0);
        } else {
            log.debug('operational-sync-endpoint-handler.initialOPDSync(): Beginning initial operational data sync for sites ' + sitesToSubscribeOPD.toString());

            async.every(sitesToSubscribeOPD, function(site, callback) {
                var job = jobUtil.createOperationalSyncRequest(site);
                log.debug('operational-sync-endpoint-handler.initialOPDSync() : build operational job');
                log.debug(job);

                environment.publisherRouter.publish(job, config, function(error) {
                    if (error) {
                        log.error('operational-sync-endpoint-handler.initialOPDSync() : operational-sync-endpoint' + error);
                    } else {
                        log.debug('operational-sync-endpoint-handler.initialOPDSync() : operational sync job accepted');
                    }
                    callback(!(!!error));
                });
            }, function(result) {
                if (result) {
                    log.debug('operational-sync-endpoint-handler.initialOPDSync(): initial operational sync successfully started');
                    return setTimeout(handlerCallback, 0);
                } else {
                    log.error('operational-sync-endpoint-handler.initialOPDSync(): Unable to send operational sync to all sites');
                    return setTimeout(handlerCallback, 0, 'FailedJobsNotPublished');
                }
            });

        }
    });
Beispiel #6
0
		async.every(tasks, function(task, done){
			var specHandler = task.handler;
			/* Iterate All Results */
			async.every(task.results, function(result, dealt){
				try {
					handlers[specHandler](result, function(err, newTasks, fin){
						// Call By Client or Which Calls ack()
						if( {}.toString.call(newTasks) === '[object Array]' ) {
							newTasks.forEach(function(job){
								if(job.urls && job.urls.length != 0) {
									var rto = { handler: specHandler, urls: job.urls };
									if( job.category !== undefined ) rto.category = job.category;
									_self.push( rto );
								}
							});
						}
						console.log('[ACK] accept a job');
						if( fin ) fin();
					}, function(){ dealt(true); });
				} catch(err) {
					// There is something wrong here, about Err
					console.log(err);
					dealt(true);
				}
			}, function(truthValue){ done(true); }); // End of Iterating All Results

		}, function(truthValue){ callback(null, 'ack'); }); // End of Iterating All Tasks
Beispiel #7
0
	Meta.dependencies.check = function(callback) {
		var modules = Object.keys(pkg.dependencies);
		winston.verbose('Checking dependencies for outdated modules');

		async.every(modules, function(module, next) {
			fs.readFile(path.join(__dirname, '../../node_modules/', module, 'package.json'), {
				encoding: 'utf-8'
			}, function(err, pkgData) {
				// If a bundled plugin/theme is not present, skip the dep check (#3384)
				if (err && err.code === 'ENOENT' && (module.startsWith('nodebb-plugin') || module.startsWith('nodebb-theme'))) {
					winston.warn('[meta/dependencies] Bundled plugin ' + module + ' not found, skipping dependency check.');
					return next(true);
				}

				try {
					pkgData = JSON.parse(pkgData);
					var ok = !semver.validRange(pkg.dependencies[module]) || semver.satisfies(pkgData.version, pkg.dependencies[module]);

					if (ok || (pkgData._resolved && pkgData._resolved.indexOf('//github.com') !== -1)) {
						next(true);
					} else {
						process.stdout.write('[' + 'outdated'.yellow + '] ' + module.bold + ' installed v' + pkgData.version + ', package.json requires ' + pkg.dependencies[module] + '\n');
						next(false);
					}
				} catch(e) {
					winston.error('[meta/dependencies] Could not read: ' + module);
					process.exit();
				}
			});
		}, function(ok) {
			callback(!ok && global.env !== 'development' ? new Error('dependencies-out-of-date') : null);
		});
	};
 utils.getItems('Test Table', function(err, data) {
     if(err) {
         assert.fail("Failed to get items using name");
         done();
     } else {
         if(data.length === 0) {
             return done();
         }
         async.every(data, function(item, callback) {
             utils.makeRestCall({method: 'GET'}, '/items/' + item._id, null, function(err, resp, body) {
                 //console.log(JSON.stringify(body, null, 4));
                 if(resp.statusCode === 200) {
                     return callback(true);
                 } else {
                     return callback(false);
                 }
             });
         }, function(result) {
             if(result === false) {
                 assert("failed while getting the items");
             }
             done();
         });
     }
 });
Beispiel #9
0
      async.eachSeries(action, function(act, done) {

        //
        // 6. Abort if 'act' is not an object.
        //
        if(typeof act !== "object" || util.isArray(act))
          return done()

        //
        // 7. Use action's pin temporarily, if one is specified
        //
        var p = act.pin
        if(typeof p === "undefined") p = pin

        //
        // 8. If no pin is specified, abort.
        //
        if(typeof p === "undefined")
          return done()

        // 9. Exececute each supported verb in parallel
        async.every(verbs, function(verb, done) {
          var value = act[verb]
          if(typeof value === "number") {
            // If it's a number, then execute it.
            execVerb[verb].apply(self, [p, value, done])
          } else done()
        }, function(err) {
          //
          // Finished with verbs
          //
          done()
        }) 
      }, function(err) {
Beispiel #10
0
    'Compile ES6 JavaScript to ES5 JavaScript', function() {
      var options = this.options({
        sourceMaps: true
      });
      grunt.log.debug('using options: ' + JSON.stringify(options));
      var done = this.async();
      var server, compile;

      if (options.spawn) {
        server = compiler.server();
        compile = server.compile;
      } else {
        compile = asyncCompile;
      }
      delete options.spawn;

      // We don't terminate immediately on errors to log all error messages
      // before terminating.
      async.every(this.files, function(group, callback) {
        compileAll(grunt, compile, group.src, group.dest, options, callback);
      }, function(success) {
        if (server) server.stop();
        done(success);
      });
    });
Beispiel #11
0
Crawler.prototype.ack = function(tasks,callback){
	var _self = this;
	async.every(tasks,function(task,done){
		var handler = _self.handlers[task.handler];
		async.every(task.results,function(data,done){
			try{
				data.extra = task.extra;
				handler(data
					,function(err,nexts,done){
						nexts.forEach(function(job){
							if(job.urls.length!=0){
       								if(job.handler == '__self__') job.handler = task.handler;
								_self.push(job)
							}
						});
						done();
					}
					,function(){
						done(true);
					}
				);
			}catch(exe){logger.error(exe); done(true);}
		},function(all){done(true);});
	},function(all){callback();});
}
Beispiel #12
0
 this.getSeasonEpisodes(function (err, ids, show) {
   if (err) {
     callback('Failed to get season episodes.');
   } else {
     async.every(ids, function (id, next) {
       if (id === self.id) {
         next(true);
       } else {
         var episode = nohm.factory('Episode');
         episode.id = id;
         episode.getSeen(user, function (err, seen) {
           next(!err && seen);
         });
       }
     }, function (result) {
       user.link(self, 'seen');
       if (result) {
         user.link(show, 'seen_season_'+self.p('season'));
       }
       user.save(function (err) {
         if (err) {
           callback('Failed to set Episode as unseen.');
         } else {
           user.checkSeenChangesNextUp(true, self.id, function (err) {
             callback(err, {episode: true, season: result});
           });
         }
       });
     });
   }
 });
 utils.getItems('Test Table', function(err, data) {
     if(err) {
         assert.fail("Failed to get items using name");
         done();
     } else {
         if(data.length === 0) {
             return done();
         }
         async.every(data, function(item, callback) {
             item.additional = "Something new";
             utils.makeRestCall({method: 'PUT', body: item}, '/items/' + item._id, null, function(err, resp, body) {
                 //console.log(JSON.stringify(body, null, 4));
                 if( (resp.statusCode === 200) && (body.additional === 'Something new') ) {
                     return callback(true);
                 } else {
                     return callback(false);
                 }
             });
         }, function(result) {
             if(result === false) {
                 assert("failed to update an item");
             }
             done();
         });
     }
 });
Beispiel #14
0
  fs.readdir(dir, function (err, files) {
    if (err) {
      return cb(err);
    }

    var stats = {};

    // This function is passed to async.every below.
    var iterator = function (file, cb) {
      // Skip hidden files (start with a period).
      if (/^\./.test(file)) {
        return cb(true);
      }

      // Skip Vim backup files (end with a tilde).
      if (/~$/.test(file)) {
        return cb(true);
      }

      fs.stat(file, function (statErr, stat) {
        if (statErr) {
          err = statErr;
        } else {
          stats[file] = stat;
        }

        cb(!err); // stops async.every when there is an error
      });
    };

    async.every(files, iterator, function (result) {
      cb(err, stats);
    });
  });
Beispiel #15
0
      data.data.tumblog.photo({limit: 10, offset: data.offset}, function(err, response){
        if(err && response && response.posts){
          console.log('starting the log --------');
          console.log(err);
          console.log(response);
          console.log('error: ending the log <check_tumblr> --------');
        } else {
          async.every(response.posts, does_item_exist, function(result){
            if(!result){ // not all of those 10 posts are new, fetch further.

              // process the current batch of 10 posts.
              for(i = 0; i < response.posts.length; i++){
                that.emit('process_image', {
                  data: data.data,
                  post: response.posts[i]
                });
              }

              setTimeout(function(){
                that.emit('check_tumblr', {data: data.data, offset: data.offset + 10});
              }, 10000);
            }
          });
        }
      });
function pingConnection(service, callback) {
  async.every(service.connections, function (socket, done) {
    socket.write('ping');
    socket.once('data', function (chunk) {
      return done(chunk.toString() === 'pong');
    });
  }, callback);
}
Beispiel #17
0
/*
 * When validate is called, it will call the callback with true or false
 * depending on whether the object is considered valid. This defaults to
 * simply clear the error and then callback true.
 */
function validateMethod(attrs, callback) {
  var obj = this, ctor = this.constructor;
  obj.errors = [];
  //console.log("validate: " + obj + " => " + util.inspect(attrs));
  async.every(ctor.validations,
              function (validation, cb) { validation.call(obj, attrs, cb); },
              callback);
}
Beispiel #18
0
module.exports["async every timing"] = function(test){
	async.every([1,2,3], function(x, cb){
		setTimeout(function(){cb(true)}, x*10);
	}, function(result){
		test.equals(result, true);
		test.done();
	});
}
Beispiel #19
0
exports['every false'] = function(test){
    async.every([1,2,3], function(x, callback){
        setTimeout(function(){callback(x % 2);}, 0);
    }, function(result){
        test.equals(result, false);
        test.done();
    });
};
Beispiel #20
0
exports['every false'] = function(test){
    async.every([1,2,3], function(x, callback){
        process.nextTick(function(){callback(x % 2);});
    }, function(result){
        test.equals(result, false);
        test.done();
    });
};
Beispiel #21
0
										arr.forEach(function(job) {
											async.every(job.tasks, function(item, done) {
												_self.push(item);
												done();
											}, function(tasks) {
												coll.remove({'_id': job._id}, function(err, res) {
													if(err) prevCallback(err);
													else prevCallback(null, job);
												});
											});
										});
function everyExample( callback ) {
	console.log("async.every");
	async.every( items, greaterThanFiveDetector, function(result) {
		console.log("Every greater than five:", result);

		setTimeout(function(){
			console.log();
			callback(null);
		}, 1000);
	});
}
function isProject(root, callback) {
  var cls = this;

  async.every([
    root,
    path.join(root, 'package.json'),
    path.join(root, 'app.js')
  ], fs.exists, callback);

  return cls;
}
Beispiel #24
0
function verify_owner_counts(remote, counts, callback) {
  var tests = prepare_tests(counts, function(account) {
    return { account: account, count: counts[account] };
  });

  function iterator(test, callback) {
    verify_owner_count(remote, test.account, test.count, callback)
  }

  async.every(tests, iterator, callback);
};
Beispiel #25
0
		client.collection(_self.config.collectionName,function(err,collection){
			if(err)	do_callback(err);
			else{
				async.every(items,function(item,done){
						collection.insert(item,function(err){
							if(err) do_callback(err);
							else done(true);
						});	
					},function(all){do_callback();}
				);
			}	
		});
  function save(current_user_id, data, callback) {
    if (data._id) return callback('not allowed to specify _id');
    if (data.system) return callback('not allowed to use system area');
    if (data.created_time) return callback('not allowed to specify created_time');
    if (data.owner) return callback('not allowed to specify owner');

    async.every(data.scope || [{
      public: true
    }],

    function(item, cb) {
      var permission_name = 'UNKNOWN';
      var target_id = null;
      if (item.public) {
        permission_name = 'CREATE_OBJECT_TO_PUBLIC';
      } else if (item.group_id) {
        permission_name = 'CREATE_OBJECT_TO_GROUP';
        target_id = item.group_id;
      } else if (item.user_id) {
        permission_name = 'CREATE_OBJECT_TO_USER';
        target_id = item.user_id;
      }
      authorization_manager.hasPermission(current_user_id, permission_name, object_type, target_id, function(err, ok) {
        //ignore err
        cb(ok);
      });
    }, function(ok) {
      if (!ok) return callback('no permission to create object');

      data.created_time = new Date();
      data.owner = {
        user_id: current_user_id
      };
      mongodb_manager.createPrimaryKey(object_type, function(err, primary_key) {
        if (err) return callback(err);

        data._id = primary_key;
        mongodb_manager.getCollection(object_type, function(err, collection) {
          if (err) return callback(err);

          collection.insert(data, {
            w: 1
          }, function(err, result) {
            if (err) return callback(err);

            callback(null, result.length ? result[0] : result);
            processDestination(data);
          });
        });
      });
    });

  }
Beispiel #27
0
		function filter(data, trigger, menu) {
			async.every(trigger.filters, function(filter, cb) {
				fireNsChild(filter, data, Filters.getNamespaces(), cb);
			}, function(result) {
				if (result) {
					Log.info('It looks like this menu is up to your standards, sir. I\'ll handle it from here.');
					Brain.serve(menu, query);
				} else {
					Log.info('This menu isn\'t up to your expectations, sir. I\'ll ignore it.');
				}
			});
		}
function isModule(root, callback) {
  var cls = this;

  debug('Checking module-ness of %s...', root);

  async.every([
    root,
    path.join(root, 'module.json')
  ], fs.exists, callback);

  return cls;
}
Beispiel #29
0
    function(next){
      async.every(['Procfile', 'app.js'], function(item, next){
        fs.exists(baseDir + item, function(exist){
          next(null, exist);
        });
      }, function(result){
        if (result && !setup) return next();

        console.log('Setting up.');

        async.parallel([
          function(next){
            file.write(baseDir + 'Procfile', 'web: node app', next);
          },
          function(next){
            file.read(baseDir + 'package.json', function(err, content){
              if (err) throw new Error('Failed to read file: ' + baseDir + 'package.json');
              var pkg = JSON.parse(content);
              if (_.isObject(pkg.dependencies)){
                pkg.dependencies = _.extend(pkg.dependencies, {connect: '*'});
              } else {
                pkg.dependencies = {connect: '*'};
              }

              file.write(baseDir + 'package.json', JSON.stringify(pkg, null, '  ') + '\n', next);
            });
          },
          function(next){
            var content = [
              'var connect = require("connect"),',
              '  app = connect.createServer(),',
              '  port = process.env.PORT;',
              '',
              'app.use(connect.static(__dirname + "/public"));',
              'app.use(connect.compress());',
              '',
              'app.listen(port, function(){',
              '  console.log("Hexo is running on port %d.", port);',
              '});'
            ];

            file.write(baseDir + 'app.js', content.join('\n'), next);
          },
          function(next){
            command('git', ['init'], function(){
              command('git', ['remote', 'add', 'heroku', config.repository], next);
            });
          }
        ], function(){
          if (!setup) next();
        });
      });
    },
Beispiel #30
0
	client.open(function(err){
		async.every(items,function(item,done){
			client.collection(item.collection,function(err,collection){
				delete item.collection;
				collection.insert(item,function(err){
					done(!err);
				});		
			});		
		},function(result){
			client.close();
			done();
		});
	});