Run the recordRoute demo. Sends several randomly chosen points from the
pre-generated feature database with a variable delay in between. Prints the
statistics when they are sent from the server.
@param {function} callback Called when this demo is complete
359102
function runRecordRoute(callback) {
  var argv = parseArgs(process.argv, {
    string: 'db_path'
  });
  fs.readFile(path.resolve(argv.db_path), function(err, data) {
    if (err) {
      callback(err);
      return;
    }
    // Transform the loaded features to Feature objects
    var feature_list = _.map(JSON.parse(data), function(value) {
      var feature = new messages.Feature();
      feature.setName(value.name);
      var location = new messages.Point();
      location.setLatitude(value.location.latitude);
      location.setLongitude(value.location.longitude);
      feature.setLocation(location);
      return feature;
    });

    var num_points = 10;
    var call = client.recordRoute(function(error, stats) {
      if (error) {
        callback(error);
        return;
      }
      console.log('Finished trip with', stats.getPointCount(), 'points');
      console.log('Passed', stats.getFeatureCount(), 'features');
      console.log('Travelled', stats.getDistance(), 'meters');
      console.log('It took', stats.getElapsedTime(), 'seconds');
      callback();
    });
    /**
     * Constructs a function that asynchronously sends the given point and then
     * delays sending its callback
     * @param {messages.Point} location The point to send
     * @return {function(function)} The function that sends the point
     */
    function pointSender(location) {
      /**
       * Sends the point, then calls the callback after a delay
       * @param {function} callback Called when complete
       */
      return function(callback) {
        console.log('Visiting point ' + location.getLatitude()/COORD_FACTOR +
            ', ' + location.getLongitude()/COORD_FACTOR);
        call.write(location);
        _.delay(callback, _.random(500, 1500));
      };
    }
    var point_senders = [];
    for (var i = 0; i < num_points; i++) {
      var rand_point = feature_list[_.random(0, feature_list.length - 1)];
      point_senders[i] = pointSender(rand_point.getLocation());
    }
    async.series(point_senders, function() {
      call.end();
    });
  });
}
204117
function(callback){
        for(this._itr; this._itr < this._data.length; this._itr++) {
            this._testFunction.call(this, this._itr);
        }

        callback.call(this, this._res);
	}
705895
async function runSample() {
  const res = await mirror.locations.list({});
  console.log(res.data);
}
903841
function runListFeatures(callback) {
  var rect = new messages.Rectangle();
  var lo = new messages.Point();
  lo.setLatitude(400000000);
  lo.setLongitude(-750000000);
  rect.setLo(lo);
  var hi = new messages.Point();
  hi.setLatitude(420000000);
  hi.setLongitude(-730000000);
  rect.setHi(hi);
  console.log('Looking for features between 40, -75 and 42, -73');
  var call = client.listFeatures(rect);
  call.on('data', function(feature) {
      console.log('Found feature called "' + feature.getName() + '" at ' +
          feature.getLocation().getLatitude()/COORD_FACTOR + ', ' +
          feature.getLocation().getLongitude()/COORD_FACTOR);
  });
  call.on('end', callback);
}
590120
function (data, callback) {
    if (typeof callback !== 'function') {
        this.debug("Registering dummy callback, because a response message is expected");
    } else {
        this.debug("Registering callback");
    }
    this.waitingCallbacks.push(callback);
    send.call(this, data);
}
430981
function(callback) {

      // Detect server errors
      var t = this, server = t.get('server');
      server.on('clientError', function(err){
        console.error('Client error detected on server', err);
        t.trigger('error', err);
      });
      server.on('close', function(err){
        server.hasEmittedClose = true;
        t.stop();
      });

      // Notify that we've started
      t.isListening = true;
      if (callback) {
        callback(null);
      }
      t.trigger('start');
    }
503644
function (baseUrl, callback) {
    callback = callback || function (error, results) {
      if (error) {
        console.error.apply(console,
          error.stack ? [ error.stack ] : [ 'Error:', error ]);
      }
      var total = results.passed.length + results.failed.length;
      console.log('Results: ' + results.passed.length + '/' + total + ' test' +
        (total === 1 ? '' : 's') + ' passed.');
      if (results.failed.length > 0) {
        console.error('Failed:', jsonStringifyWithFunctions(results.failed));
      }
    };

    var results = {
      failed: [],
      passed: []
    };

    this.exportAllTests(baseUrl, function runNextTest (tests) {
      if (tests.length === 0) {
        callback(null, results);
        return;
      }

      var i = Math.floor(Math.random() * tests.length);
      var test = tests.splice(i, 1)[0];
      test(function (error, testResults) {
        if (testResults) {
          results.failed = results.failed.concat(testResults.failed);
          results.passed = results.passed.concat(testResults.passed);
        }
        if (error) {
          callback(error, results);
          return;
        }
        runNextTest(tests);
      });
    });
  }
1353717
function (filename, callbackFn) {
                    var self = this,
                        url = self.options.hostAndPort + '/page/functions/render';

                    self.options.debug && console.log('calling url: %s', url);
                    request.post(url, {form:{ args:JSON.stringify(
                            [
                                filename
                            ], null, 4)}},
                        function (error, response, body) {
                            error && console.error(error);
                            if (response && response.statusCode === 200) {
                                callbackFn && callbackFn.call(self, !!body);
                            }
                            else {
                                console.error(body);
                                callbackFn && callbackFn.call(self, body);
                            }
                        }
                    );
                }
70642
function runRouteChat(callback) {
  var call = client.routeChat();
  call.on('data', function(note) {
    console.log('Got message "' + note.getMessage() + '" at ' +
        note.getLocation().getLatitude() + ', ' +
        note.getLocation().getLongitude());
  });

  call.on('end', callback);

  var notes = [{
    location: {
      latitude: 0,
      longitude: 0
    },
    message: 'First message'
  }, {
    location: {
      latitude: 0,
      longitude: 1
    },
    message: 'Second message'
  }, {
    location: {
      latitude: 1,
      longitude: 0
    },
    message: 'Third message'
  }, {
    location: {
      latitude: 0,
      longitude: 0
    },
    message: 'Fourth message'
  }];
  for (var i = 0; i < notes.length; i++) {
    var note = notes[i];
    console.log('Sending message "' + note.message + '" at ' +
        note.location.latitude + ', ' + note.location.longitude);
    var noteMsg = new messages.RouteNote();
    noteMsg.setMessage(note.message);
    var location = new messages.Point();
    location.setLatitude(note.location.latitude);
    location.setLongitude(note.location.longitude);
    noteMsg.setLocation(location);
    call.write(noteMsg);
  }
  call.end();
}
916800
function (callback) {
    var self = this;

    function initDispatcher() {
      debug('init event dispatcher');
      self.dispatcher = new EventDispatcher(self.publisher, self);
      self.dispatcher.start(callback);
    }

    this.store.on('connect', function () {
      self.emit('connect');
    });

    this.store.on('disconnect', function () {
      self.emit('disconnect');
    });

    process.nextTick(function() {
      tolerate(function(callback) {
        self.store.connect(callback);
      }, self.options.timeout || 0, function (err) {
        if (err) {
          debug(err);
          if (callback) callback(err);
          return;
        }
        if (!self.publisher) {
          debug('no publisher defined');
          if (callback) callback(null);
          return;
        }
        initDispatcher();
      });
    });
  }
707412
function runGetFeature(callback) {
  var next = _.after(2, callback);
  function featureCallback(error, feature) {
    if (error) {
      callback(error);
      return;
    }
    var latitude = feature.getLocation().getLatitude();
    var longitude = feature.getLocation().getLongitude();
    if (feature.getName() === '') {
      console.log('Found no feature at ' +
          latitude/COORD_FACTOR + ', ' + longitude/COORD_FACTOR);
    } else {
      console.log('Found feature called "' + feature.getName() + '" at ' +
          latitude/COORD_FACTOR + ', ' + longitude/COORD_FACTOR);
    }
    next();
  }
  var point1 = new messages.Point();
  point1.setLatitude(409146138);
  point1.setLongitude(-746188906);
  var point2 = new messages.Point();
  point2.setLatitude(0);
  point2.setLongitude(0);
  client.getFeature(point1, featureCallback);
  client.getFeature(point2, featureCallback);
}
363959
function(callback){
        var cursor = db.db(dbName).collection(collectionName).find({}).toArray(function(err,result){
            if(result.length!=0){
                roadmapNum = roadMapIdTemp = parseInt(result[result.length-1]['roadMapId'])+1;
            }
            else{
                roadmapNum = roadMapIdTemp = 1;
            }
            db.db(dbName).collection(collectionName).insertOne({
                "roadMapId" : roadMapIdTemp.toString(),
                "clientId" : source['clientId'],
                "orderNode" : source['orderNode'],
                "initNode" : source['initNode'],
                "lastNode" : source['lastNode'],
                "incomingNode" : source['incomingNode'],
                "outingNode" : source['outingNode'],
                "isInput" : source['isInput'],
                "isOutput" : source['isOutput'],
                "nodeIds" : source['nodeIds']
            },function(err, result){
                response.send(roadmapNum.toString());
            });
        });

    }
683565
function run(desc, data, callback) {
    if (callback.length === 2) {
        callItAsync(desc, data, callback)
    } else {
        callItSync(desc, data, callback)
    }
}
492738
function (bin, data, statsRequest) {
    var id = bin.id,
        delayTrigger = 500;

    if (!pending[id]) {
      pending[id] = {};
    }

    pending[id].bin = bin;
    pending[id][data.panelId] = utils.process(data, bin.settings);

    // Clear the previous ping
    clearTimeout(pending[id].timer);

    // NOTE: this will only fire once per jsbin session -
    // not for every panel sent - because we clear the timer
    pending[id].timer = setTimeout(function () {
      var session = utils.sessionForBin(bin),
          data = null,
          ping = pending[id];


      if (!ping) { return; }

      // Javascript and HTML cause reloads. CSS is injected.
      data = ping.javascript || ping.html || ping.css || (statsRequest ? {} : false);

      // Forget this ping, it's done with now
      delete pending[id];

      if (!data) { return; }
      if (!session) { return; }

      // Send the update to all connected sessions in original and raw flavours
      session.res.forEach(function (res) {
        var raw = data.raw || data.content;
        if (!res.req.stats) {
          res.write(utils.makeEvent(data.panelId, raw));
          res.write(utils.makeEvent(data.panelId + ':processed', data.content));
        }
        res.write(utils.makeEvent('stats', { connections: session.res.filter(function (res) {
          return !res.req.stats;
        }).length }));
        if (res.ajax && !statsRequest) {
          res.end(); // lets older browsers finish their xhr request
          res.req.emit('close');
        }
      });

    }, delayTrigger);
  }
888264
function (server, callback) {
            var self = this;

            this.$server = server;
            this._start(function(err) {
                self.$started = true;
                callback(err);
            });
        }
881463
function doSyncBench(fn, callback) {

		var start,
		    fnOverhead,
		    pretotal,
		    result,
		    runs,
		    name;

		runs = 0;

		// For the initial test, to determine how many iterations we should
		// test later, we just use Date.now()
		start = Date.now();

		// See how many times we can get it to run for 50ms
		// This doesn't need to be precise yet. We don't use these results
		// for the ops count because Date.now() takes time, too
		do {
			fn();
			runs++;
			pretotal = Date.now() - start;
		} while (pretotal < 50);

		// See how long it takes to run an empty function
		fnOverhead = getFunctionOverhead(runs);

		result = syncTest(fn, runs, fnOverhead);

		if (callback) {
			result.name = fn.name || '';
			callback(null, result);
		} else {
			name = fn.name || '';
			if (name) name = 'for "' + name + '" ';

			console.log('Benchmark ' + name + 'did ' + Bound.Number.humanize(result.ops) + '/s (' + Bound.Number.humanize(result.iterations) + ' iterations)');
		}

		return result;
	}
241274
function start(callback) {
        var serverDeferred = Q.defer();

        if (typeof callback !== 'function') {
            callback = function () {
            };
        }

        if (self.isRunning) {
            // FIXME: should this be an error?
            callback();
            return;
        }

        sockets = {};

        __httpServer = Http.createServer(__app);

        if (gmeConfig.server.timeout > -1) {
            __httpServer.timeout = gmeConfig.server.timeout;
        }

        function handleNewConnection(socket) {
            var socketId = socket.remoteAddress + ':' + socket.remotePort;

            if (socket.encrypted) { // https://nodejs.org/api/tls.html#tls_tlssocket_encrypted
                socketId += ':encrypted';
            }

            sockets[socketId] = socket;
            logger.debug('socket connected (added to list) ' + socketId);

            socket.on('close', function () {
                if (sockets.hasOwnProperty(socketId)) {
                    logger.debug('socket closed (removed from list) ' + socketId);
                    delete sockets[socketId];
                }
            });
        }

        __httpServer.on('connection', handleNewConnection);
        __httpServer.on('secureConnection', handleNewConnection);

        __httpServer.on('clientError', function (err/*, socket*/) {
            logger.debug('clientError', err);
        });

        __httpServer.on('error', function (err) {
            if (err.code === 'EADDRINUSE') {
                logger.error('Failed to start server', {metadata: {port: gmeConfig.server.port, error: err}});
                serverDeferred.reject(err);
            } else {
                logger.error('Server raised an error', {metadata: {port: gmeConfig.server.port, error: err}});
            }
        });

        logger.debug('starting server');

        __gmeAuth.connect()
            .then(function (db) {
                var promises = [];

                logger.debug('gmeAuth connected');

                promises.push(Q.ninvoke(__workerManager, 'start'));
                promises.push(__storage.openDatabase());

                if (__executorServer) {
                    promises.push(__executorServer.start({mongoClient: db}));
                }

                return Q.all(promises);
            })
            .then(function () {
                var promises = [];
                __webSocket.start(__httpServer);

                promises.push(apiReady);

                routeComponents.forEach(function (component) {
                    promises.push(Q.ninvoke(component, 'start'));
                });

                return Q.all(promises);
            })
            .then(function () {
                // Finally start listening to the server port.
                __httpServer.listen(gmeConfig.server.handle || gmeConfig.server.port, function () {
                    logger.info('Server is listening ...');
                    serverDeferred.resolve();
                });

                return serverDeferred.promise;
            })
            .then(function () {
                return webgmeUtils.createStartUpProjects(gmeConfig, __gmeAuth, __storage, logger, getUrl());
            })
            .nodeify(function (err) {
                self.isRunning = true;
                if (err) {
                    logger.error('Error at server start', err);
                }

                callback(err);
            });
    }