register express with spawnpoint
480834
function(err){
			if(!err){
				var address = app[serverNS].address();

				if(config.port){
					app.info('Server online at %s:%s', address.address, address.port);
				}else if(config.file){
					app.info('Server online via %s', config.file);
				}else{
					app.info('Server online!');
				}
			}
			app.emit('app.register', 'express');
			return callback(err);
		}
1074788
def register_plugin(self):
        """"""
        self.redirect_stdio.connect(self.main.redirect_internalshell_stdio)
        self.main.console.shell.refresh.connect(self.refresh_plugin)
        iconsize = 24 
        self.toolbar.setIconSize(QSize(iconsize, iconsize))
        self.main.addToolBar(self.toolbar)
643138
function startServer(argv, httpPort, httpsPort, certs) {
  console.log('Launching proxy server...');
  console.log('   http: ' + httpPort);
  console.log('  https: ' + httpsPort);

  // Injects a node stream by buffering all data, transforming it, and writing
  // it back out.
  // Module IDs are assigned on demand and rotate 0-126.
  var nextModuleId = 0;
  function injectStream(url, source, target) {
    var moduleId = nextModuleId++;
    if (nextModuleId >= 127) {
      nextModuleId = 0;
    }
    var sourceCode = '';
    source.on('data', function(chunk) {
      sourceCode += chunk;
    });
    source.on('end', function() {
      try {
        var targetCode = transformCode(moduleId, url, sourceCode, argv);
        target.end(targetCode);
      } catch (e) {
        console.log('Error during transformation, writing through.');
        console.log(e);
        target.end(sourceCode);
      }
    });
  };

  // Handles both HTTP and HTTPS requests.
  function handler(req, res) {
    // Support both the ?url= mode and the X-WTF-URL header.
    var targetUrl;
    if (req.headers['x-wtf-url']) {
      targetUrl = req.headers['x-wtf-url'];
    } else {
      var parsedUrl = url.parse(req.url, true);
      var query = parsedUrl.query;
      targetUrl = query.url;
    }
    if (!targetUrl || targetUrl.indexOf('http') != 0) {
      res.writeHead(404, ['Content-Type', 'text/plain']);
      res.end();
      return;
    }

    res.on('error', function(e) {
      console.log('ERROR (source): ' + e);
    });

    var targetModule = targetUrl.indexOf('https') == 0 ? https : http;
    targetModule.get(targetUrl, function(originalRes) {
      // Eat errors, otherwise the app will die.
      originalRes.on('error', function(e) {
        console.log('ERROR (target): ' + e);
      });

      // Pull out content type to see if we are interested in it.
      var supportedContentType = false;
      var contentType = originalRes.headers['content-type'];
      if (contentType && contentType.indexOf(';') != 0) {
        contentType = contentType.substr(0, contentType.indexOf(';'));
      }
      switch (contentType) {
        case 'text/javascript':
        case 'application/javascript':
          supportedContentType = true;
          break;
      }

      // Also parse the URL - some servers don't return content type for some
      // reason.
      var supportedPath = false;
      var contentUrl = url.parse(targetUrl);
      if (path.extname(contentUrl.pathname) == '.js') {
        supportedPath = true;
      }

      if (supportedContentType || supportedPath) {
        var headers = [];
        for (var key in originalRes.headers) {
          if (key == 'content-length') {
            continue;
          }
          headers.push([key, originalRes.headers[key]]);
        }
        res.writeHead(originalRes.statusCode, headers);
        injectStream(targetUrl, originalRes, res);
      } else {
        console.log('Pass-through: ' + targetUrl, contentType);
        res.writeHead(originalRes.statusCode, originalRes.headers);
        originalRes.pipe(res);
      }
    }).on('error', function(e) {
      console.log(e);
      res.writeHead(404, ['Content-Type', 'text/plain']);
      res.end(e.message);
    });
  };

  // HTTP server.
  var httpServer = http.createServer(handler);
  httpServer.listen(httpPort);

  // HTTPS server.
  var httpsServer = https.createServer({
    key: certs.privateKey,
    cert: certs.certificate
  }, handler);
  httpsServer.listen(httpsPort);

  console.log('Server ready, use ctrl-c to exit...');
  console.log('');
}
798060
function spawn() {
  if(this.ps && this.ps.connected) return;
  this.ps = fork(
    runner, [], {execPath: path.basename(process.execPath)});
  this.ps.send({event: 'loglevel', level: log.level()});
}
270153
function register(server, options, next) {
	Schema.validate(options, function (error, config) {
		if (error) {
			next(error);
		} else {
			let methodsAsync = {};
			const dirs = config.methods;
			_.each(dirs, (dir) => {
				const relativePath = path.relative(__dirname, process.cwd() + '/' + dir);
				importDirectory(module, relativePath, {
					visit: function (obj) {
						if (!_.isUndefined(obj)) {
							let methods = _.isArray(obj) ? obj : [obj]; 
							_.each(methods, (method) => {
								if (_.isObject(method) && _.isFunction(method.method)) {
									const instance = _.clone(method);
									// store the oringial method
									const asyncMethod = method.method;
									// convert async function to normal thunky function
									instance.method = function (...args) {
										// the handler after function is called
										const after = args[args.length - 1];
										// call the async method, since asyn function return promise, use then and catch to handle result and error by handler
										asyncMethod.apply(this, args).then((result) => after(null, result)).catch((err) => after(err));
									};
									server.method(instance);
								}
							});
						}
					}
				});
			});
			_.each(server.methods, (method, name) => {
				methodsAsync[name] = function (...args) {
					// async function is a function return promise
					// convert back the async function
					return new Promise((resolve, reject) => {
						// call the thunky function
						server.methods[name].apply(server.methods, args.concat([(err, result) => {
							// reject if error exists, resolve if error not exists
							if (err) {
								reject(err);
							} else {
								resolve(result);
							}
						}]));
					});
				};
				// drop cache should also support async
				if (method.cache) {
					methodsAsync[name].cache = Promise.promisifyAll(method.cache);
				}
			});
			server.decorate('server', config.name, methodsAsync);
			next();
		}
	});
}
888488
function spawn() {
    startInterval();
    var args = Array.prototype.slice.call(arguments);
    if (currentCount < limitCount) {
        currentCount++;
        if (monitorCallback) {
            monitorCallback("start", remainedTasks);
        }
        return new Promise(function (resolved) {
            var process = originalSpawn.apply(null, args);
            process.on("close", function (code) {
                if (monitorCallback) {
                    monitorCallback("close", remainedTasks, code);
                }
                currentCount--;
                if (currentCount === 0 && remainedTasks.length === 0) {
                    callWaitAllCallbacks();
                }
            });
            resolved(process);
        });
    } else {
        var id = taskId++;
        remainedTasks.push([args, id]);
        if (monitorCallback) {
            monitorCallback("added", remainedTasks);
        }
        return new Promise(function (resolved) {
            remainedTaskCallbacks[id] = resolved;
        });
    }
}
1210574
async function start() {
  if (server) return server;
  server = express();
  server.use(errorOverlayMiddleware());
  server.use(express.static(path.resolve(__dirname, '../public')));

  // Configure client-side hot module replacement
  const clientConfig = webpackConfig.find(config => config.name === 'client');
  clientConfig.entry.client = ['./tools/lib/webpackHotDevClient']
    .concat(clientConfig.entry.client)
    .sort((a, b) => b.includes('polyfill') - a.includes('polyfill'));
  clientConfig.output.filename = clientConfig.output.filename.replace(
    'chunkhash',
    'hash',
  );
  clientConfig.output.chunkFilename = clientConfig.output.chunkFilename.replace(
    'chunkhash',
    'hash',
  );
  clientConfig.module.rules = clientConfig.module.rules.filter(
    x => x.loader !== 'null-loader',
  );
  clientConfig.plugins.push(new webpack.HotModuleReplacementPlugin());

  // Configure server-side hot module replacement
  const serverConfig = webpackConfig.find(config => config.name === 'server');
  serverConfig.output.hotUpdateMainFilename = 'updates/[hash].hot-update.json';
  serverConfig.output.hotUpdateChunkFilename =
    'updates/[id].[hash].hot-update.js';
  serverConfig.module.rules = serverConfig.module.rules.filter(
    x => x.loader !== 'null-loader',
  );
  serverConfig.plugins.push(new webpack.HotModuleReplacementPlugin());

  // Configure compilation
  await run(clean);
  const multiCompiler = webpack(webpackConfig);
  const clientCompiler = multiCompiler.compilers.find(
    compiler => compiler.name === 'client',
  );
  const serverCompiler = multiCompiler.compilers.find(
    compiler => compiler.name === 'server',
  );
  const clientPromise = createCompilationPromise(
    'client',
    clientCompiler,
    clientConfig,
  );
  const serverPromise = createCompilationPromise(
    'server',
    serverCompiler,
    serverConfig,
  );

  // https://github.com/webpack/webpack-dev-middleware
  server.use(
    webpackDevMiddleware(clientCompiler, {
      publicPath: clientConfig.output.publicPath,
      logLevel: 'silent',
      watchOptions,
    }),
  );

  // https://github.com/glenjamin/webpack-hot-middleware
  server.use(webpackHotMiddleware(clientCompiler, { log: false }));

  let appPromise;
  let appPromiseResolve;
  let appPromiseIsResolved = true;
  serverCompiler.hooks.compile.tap('server', () => {
    if (!appPromiseIsResolved) return;
    appPromiseIsResolved = false;
    // eslint-disable-next-line no-return-assign
    appPromise = new Promise(resolve => (appPromiseResolve = resolve));
  });

  let app;
  server.use((req, res) => {
    appPromise
      .then(() => app.handle(req, res))
      .catch(error => console.error(error));
  });

  function checkForUpdate(fromUpdate) {
    const hmrPrefix = '[\x1b[35mHMR\x1b[0m] ';
    if (!app.hot) {
      throw new Error(`${hmrPrefix}Hot Module Replacement is disabled.`);
    }
    if (app.hot.status() !== 'idle') {
      return Promise.resolve();
    }
    return app.hot
      .check(true)
      .then(updatedModules => {
        if (!updatedModules) {
          if (fromUpdate) {
            console.info(`${hmrPrefix}Update applied.`);
          }
          return;
        }
        if (updatedModules.length === 0) {
          console.info(`${hmrPrefix}Nothing hot updated.`);
        } else {
          console.info(`${hmrPrefix}Updated modules:`);
          updatedModules.forEach(moduleId =>
            console.info(`${hmrPrefix} - ${moduleId}`),
          );
          checkForUpdate(true);
        }
      })
      .catch(error => {
        if (['abort', 'fail'].includes(app.hot.status())) {
          console.warn(`${hmrPrefix}Cannot apply update.`);
          delete require.cache[require.resolve('../build/server')];
          // eslint-disable-next-line global-require, import/no-unresolved
          app = require('../build/server').default;
          console.warn(`${hmrPrefix}App has been reloaded.`);
        } else {
          console.warn(
            `${hmrPrefix}Update failed: ${error.stack || error.message}`,
          );
        }
      });
  }

  serverCompiler.watch(watchOptions, (error, stats) => {
    if (app && !error && !stats.hasErrors()) {
      checkForUpdate().then(() => {
        appPromiseIsResolved = true;
        appPromiseResolve();
      });
    }
  });

  // Wait until both client-side and server-side bundles are ready
  await clientPromise;
  await serverPromise;

  const timeStart = new Date();
  console.info(`[${format(timeStart)}] Launching server...`);

  // Load compiled src/server.js as a middleware
  // eslint-disable-next-line global-require, import/no-unresolved
  app = require('../build/server').default;
  appPromiseIsResolved = true;
  appPromiseResolve();

  // Launch the development server with Browsersync and HMR
  await new Promise((resolve, reject) =>
    browserSync.create().init(
      {
        // https://www.browsersync.io/docs/options
        server: 'src/server.js',
        middleware: [server],
        open: !process.argv.includes('--silent'),
        ...(isDebug ? {} : { notify: false, ui: false }),
      },
      (error, bs) => (error ? reject(error) : resolve(bs)),
    ),
  );

  const timeEnd = new Date();
  const time = timeEnd.getTime() - timeStart.getTime();
  console.info(`[${format(timeEnd)}] Server launched after ${time} ms`);
  return server;
}
843914
function loadAndServe() {
  ip2co.dbLoad();
  ip2co.listenHTTP({hostname: appConfig.listenOpt.http.hostname, port: appConfig.listenOpt.http.port});
}
733045
function createServer() {
  function app(req, res, next){ app.handle(req, res, function(){
    res.end("", 'utf8');
  }); }
  merge(app, proto);
  merge(app, EventEmitter.prototype);
  app.route = '/';
  app.stack = [];
  return app;
}
1157507
function onRegistered(client, url) {
  let server
  return new Promise(resolve => {
    server = http.createServer((request, response) => {
      if (request.url.indexOf('/do_access') === 0) {
        log('debug', request.url, 'url received')
        resolve(request.url)
        response.end(
          'Authorization registered, you can close this page and go back to the cli'
        )
      }
    })
    server.listen(3333, () => {
      require('opn')(url, { wait: false })
      console.log(
        'A new tab just opened in your browser to require the right authorizations for this connector in your cozy. Waiting for it...'
      )
      console.log(
        'If your browser does not open (maybe your are in a headless virtual machine...), then paste this url in your browser'
      )
      console.log(url)
    })
  }).then(
    url => {
      server.close()
      return url
    },
    err => {
      server.close()
      log('error', err, 'registration error')
      throw err
    }
  )
}
735890
function createEntryPoint(paths, subPath, name) {
      var outputPath = path.join(packageDir, subPath || '', (name || 'index') + '.js'), requires;
      requires = Array.isArray(paths) ? getRequiresForArray(paths) : getRequiresForGroup(paths);
      var exports = "module.exports = require('sugar-core');";
      var outputBody = [STRICT, requires, exports].join('\n\n');
      writeFile(outputPath, outputBody);
    }
908687
function spawnProtractor(configPath, chunks, port, skyPagesConfig) {
  logger.info('Running Protractor');
  protractorLauncher.init(configPath, {
    params: {
      localUrl: `https://localhost:${port}`,
      chunks: chunks,
      skyPagesConfig: skyPagesConfig
    }
  });
  process.on('exit', killServers);
}
1093121
function Init(appGlobal, pathsList) {
            debug("Initializing Boot");
            loadFinder = new Finder();
            loadProvider = new Provider();
            loadNamespace = new Namespace();
            global = appGlobal;
            global.App = {};
            global.Modules = {};
            global.Config = {};
            this.initProviders(sortProvider);
            this.initApplication();
            this.initModules();
            var mainApp = require("../express");
            this.boot(mainApp);
            mainApp.boot = function (nameProvider, userApp) {
                debug("Booting Manual Provider");
                loadProvider.bootProvider(nameProvider, userApp ? userApp : mainApp);
            };
            mainApp.provider = function (nameProvider) {
                debug("Getting " + nameProvider + " Provider");
                return loadProvider.providerByName(nameProvider).instance;
            };
            return mainApp;
        }
471296
def register_app(app):
    "  "

    from .views import urls
    app.register_blueprint(urls)

    from .ext import admin
    admin.init_app(app)

    from flask_bootstrap import Bootstrap
    bootstrap = Bootstrap()
    bootstrap.init_app(app)

    from flask import render_template
    app.errorhandler(404)(lambda e: (render_template('core/404.html'), 404))
831352
function Server(configs) {
  var dirs = {};
  var app = express();

  // Check environment vars
  var env = process.env.NODE_ENV || 'development';
  var production = (env === 'production');

  // Merge custom config to default configs.
  var settings = _.extend(_.clone(defaults), configs || {});

  // Check database configs
  if (settings.database) {
    // Check if databse uri is a mongdob uri.
    var database = settings.database = databases.mongodb.isMongodbUri(settings.database) ? 
        databases.mongodb.parseMongodbUri(settings.database) : 
        settings.database;

    // Check if we are going to persist sessions in mongodb
    if (database.type === 'mongodb' && settings.session.store && dependencies['connect-mongo'] && dependencies['express-session']) {
      var storeOptions = {
        db: database.name,
        host: database.host || 'localhost',
        port: database.port || 27017,
        username: settings.database.options.user || '',
        password: settings.database.options.pass || ''
      };

      // Create a mongo session store.
      var mongoStore = dependencies['connect-mongo']({ 
        session: dependencies['express-session']
      });

      // Replace store with a instance.
      settings.session.store = new mongoStore(storeOptions);
    }
  }

  // Find `views` and `public` absolute path
  dirs.views = finder(configs, 'views');
  dirs.publics = finder(configs, 'publics');
  dirs.uploads = finder(configs, 'uploads');

  // Setup express settings
  app.set('env', env);
  app.set('views', dirs.views);
  app.set('view engine', settings['view engine']);
  app.set('port', process.env.PORT || 3000);

  // Disable view chche in dev mode
  if (!production) 
    app.set('view cache', false);

  // Logger handler
  app.use(logger(production ? settings.logformat : 'dev'));

  // Compression handler
  if (dependencies.compression)
    app.use(dependencies.compression());

  // Request body parser
  // Parse `application/x-www-form-urlencoded`
  app.use(bodyParser.urlencoded({ extended: false }));
  // Parse `application/json`
  app.use(bodyParser.json());

  // Upload handler
  if (dependencies.multer)
    app.use(dependencies.multer({ dest: dirs.uploads }));

  if (dependencies['method-override'])
    app.use(dependencies['method-override'](settings['method-override'] || {}));

  app.use(cookieParser(settings.secret || settings.session.secret));

  // Session middleware
  if (dependencies['express-session'])
    app.use(dependencies['express-session'](settings.session));

  // Less and Sass middleware
  if (dependencies['less-middleware'])
    app.use(dependencies['less-middleware'](dirs.publics));
  if (dependencies['node-sass-middleware'])
    app.use(dependencies['node-sass-middleware']({ src: dirs.publics }));

  // Serve static files
  app.use(express.static(dirs.publics));

  // Expose locals to template engine
  app.locals.ENGINE = pkg;
  app.locals.SITE = settings;
  app.locals.SETTINGS = settings;
  app.locals.URL = production ? 
    (settings.url || settings.uri || 'http://127.0.0.1') :
    'http://127.0.0.1:' + app.get('port');
  app.locals.URI = app.locals.URL;

  this.app = app;
  this.deps = new depender();
  this.deps.define('debug', debug(settings.name));
  this.deps.define('express', express);
  this.deps.define('middlewares', middlewares);

  this.settings = settings;

  if (settings.session.store)
    this.deps.define('mongoStore', settings.session.store);

  return this;
}
363927
function init (router) {
  router.use((err, req, res, next) => {
    console.error(err.stack || err.message)

    res.statusCode = err.statusCode || 500
    res.end()
  })
}
731537
function startDevServer (directory, port = 3000) {
  let url
  const app = express()
  const { reload } = reloadServer(app)
  let preview = ''

  app.get('/', (req, res) => res.send(preview))
  app.use(express.static(directory))

  function update ({ html, errors, metadata }) {
    let status = errors.length ? chalk.red('failed') : chalk.green('success')
    preview = errors.length
      ? buildErrorPage(errors)
      : html.replace('</body>', '<script src="/reload/reload.js"></script></body>')

    renderCLI({ url, status, time: metadata.time, size: metadata.size })
    reload()
  }

  return new Promise((resolve, reject) => {
    getPort({ port }).then((availablePort) => {
      url = `http://localhost:${availablePort}`

      app.listen(availablePort, () => resolve({ update, url, app }))
    })

    process.on('uncaughtException', reject)
  })
}