Start a development web server on app
346697
function serve(app, couch) {
  var url = require('url');
  var port = 3000,
      staticDir = 'attachments',
      tmpDir = '/tmp/couchapp-compile-' + process.pid,
      logDbRewrites = false;
  var arg;
  while(arg = process.argv.shift()){
    if(arg == '-p'){
      port = parseInt(process.argv.shift());
    }
    if(arg == '-d'){
      staticDir = process.argv.shift();
    }
    if(arg == '-l'){
      logDbRewrites = true;
    }
  }
  var dbUrlObj = url.parse(couch);

  var proxyPaths = {}
  var dbPrefix = '../../';
  for (var i in app.doc.rewrites){
    var rw = app.doc.rewrites[i];
    // Rewrites starting with '../../' are proxied to the database
    if (rw.to.indexOf(dbPrefix) == 0){
      var proxyPath = rw.from;
      if(proxyPath[proxyPath.length -1] == '*') {
        proxyPath = proxyPath.substring(0,proxyPath.length-1)
      }
      var dbPath = rw.to.substring(dbPrefix.length);
      if(dbPath[dbPath.length - 1] == '*'){
        dbPath = dbPath.substring(0,dbPath.length-1)
      }
      if(dbPath.indexOf('*') >=0 ){
        if(logDbRewrites){
          console.log("Don't know how to proxy '" + rw.from + "' to CouchDB at " + rw.from );
        }
      } else {
        proxyPaths[proxyPath] =
          dbUrlObj.protocol + '//' + dbUrlObj.host +
          path.normalize(dbUrlObj.pathname + dbPath);
          if(logDbRewrites){
            console.log("Proxying rewrite '" + proxyPath + "' to CouchDB at " + proxyPaths[proxyPath] );
          }
      }
    }
  }

  var connect = require('connect');
  var httpProxy = require('http-proxy'),
      connect   = require('connect'),
      logger = require('morgan'),
      serveStatic = require('serve-static'),
      errorHandler = require('errorhandler'),
      connectCompiler;
  try{
      connectCompiler = require('connect-compiler');
  } catch(e) {}


  var proxy = httpProxy.createProxyServer({
    target: {
      host: dbUrlObj.host,
      hostname: dbUrlObj.hostname,
      port: dbUrlObj.port,
      https: dbUrlObj.protocol == 'https:',
    }
  });
  var app = connect()
    .use(logger('dev'))
    .use(serveStatic(staticDir));
  if(connectCompiler){
    console.log('Will compile assets with connect-assets.');
    var ignore = [];
    var quote = function(str) {
      return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    }
    for(var prefix in proxyPaths){
      ignore.push(quote(prefix));
    }
    if(ignore.length){
      //console.log("Asset compile ignore paths:", '^(' +  ignore.join('|') + ')');
      ignore  = new RegExp('^(' +  ignore.join('|') + ')');
    } else {
      ignore = null;
    }
    app.use(connectCompiler({
      enabled: ['coffee'] ,
      src: staticDir,
      dest: tmpDir,
      ignore :  ignore,
    }))
    .use(serveStatic(tmpDir));
  }
  app.use(function(req, res, next) {
      for(var prefix in proxyPaths){
        var dbPath = proxyPaths[prefix];
        if (req.url.indexOf(prefix) === 0) {
          var dbURL = req.url.replace(prefix,dbPath);
          if(logDbRewrites){
            console.log("*** ", req.url , ' -> ', dbURL);
          }
          req.url = dbURL;
          req.headers['host'] = dbUrlObj.host;
          proxy.proxyRequest(req, res);
          return;
        }
      }
      var body = '404 Not found.\nNo static file or db route matched.';
      res.statusCode = 404;
      res.setHeader('Content-Length', body.length);
      res.end(body);
     })
    .use(errorHandler())
    .listen(port);
  console.log("Serving couchapp at: http://0.0.0.0:" + port +"/");

  //Cleanup the temp directory on exit
  var cleanup = function(){
    var rmDir = function(dirPath) {
      try { var files = fs.readdirSync(dirPath); }
      catch(e) { return; }
      if (files.length > 0)
        for (var i = 0; i < files.length; i++) {
          var filePath = dirPath + '/' + files[i];
          if (fs.statSync(filePath).isFile())
            fs.unlinkSync(filePath);
          else
            rmDir(filePath);
        }
      fs.rmdirSync(dirPath);
    };
    rmDir(tmpDir);
  };
  process.on('exit',cleanup);
  process.on('SIGINT',function(){
    cleanup()
    process.exit();
  });
}
632212
function startBrowserSync() {
    if (args.nosync || browserSync.active) {
        return;
    }

    helper.log('Starting BrowserSync on port ' + port);

    var serverRoot = config.baseDirs;

    gulp.watch([].concat(config.src), ['watch-all']);


    var options = {
        //proxy: 'localhost:' + port,
        port: 8010,
        ws: true,
        server: {
            baseDir: serverRoot
        },
        reloadDelay: config.browserReloadDelay
    };

    browserSync.init(options);

}
1276506
async function start () {
  let exitCode = 0
  const port = process.env.PORT || 3000
  console.log(chalk`{magenta creating app bundle}`)

  /**
   * Creating rollup bundle by bundling `test/qunit/index.js` file.
   */
  const bundle = await rollup.rollup({
    input: path.join(__dirname, '../test', 'qunit', 'index'),
    plugins: require('../rollupPlugins')
  })

  const { code } = await bundle.generate({
    file: path.join(__dirname, '../tmp', 'qunit.js'),
    format: 'umd',
    name: 'indicativeSpec'
  })

  const server = await sauceLabs.serve(qUnitTemplate(code), port)
  console.log(chalk`started app server on {green http://localhost:${port}}`)

  /**
   * Starting the HTTP server. If `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY`
   * env variables exists, we will run tests on sauce, otherwise
   * we will run them on user machine.
   */
  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.log(chalk`{yellow pass SAUCE_USERNAME & SAUCE_ACCESS_KEY to run tests on saucelabs}`)
    opn(`http://localhost:${port}`)
    return
  }

  const ngrok = require('ngrok')
  try {
    /**
     * Ngrok url
     */
    const publicUrl = await sauceLabs.getPublicUrl(port)
    console.log(chalk`started ngrok tunnel on {green ${publicUrl}}`)

    /**
     * Creating jobs with sauce labs
     */
    const jobs = await sauceLabs.createTestsJob(browsers, publicUrl)
    console.log(chalk`created {green ${jobs.length} jobs}`)

    /**
     * Monitoring jobs for results
     */
    console.log(chalk`{magenta monitoring jobs}`)
    const results = await sauceLabs.getJobsResult(jobs)

    /**
     * Got some results
     */
    results.forEach((result) => {
      console.log('')
      console.log(chalk`{bold ${result.platform.join(' ')}}`)
      console.log(chalk`  {green Passed ${result.result.passed}}`)
      console.log(chalk`  {red Failed ${result.result.failed}}`)
      console.log(`  Total ${result.result.total}`)
    })

    /**
     * Creating a new build to be annotated
     */
    const buildId = `build-${new Date().getTime()}`

    console.log('annotating jobs result')
    for (let result of results) {
      await sauceLabs.annotateJob(result.job_id, buildId, result.result.failed === 0)
    }
    console.log(chalk`{green done}`)
  } catch (error) {
    console.log(chalk`  {red Reaceived error}`)
    console.log(error)
    exitCode = 1
  }

  /**
   * Cleanup
   */
  ngrok.kill()
  server.close()
  process.exit(exitCode)
}
1249290
def start(debug=False, host='127.0.0.1'):
    
    if debug:
        debug = True
    nago.protocols.httpserver.app.run(debug=debug, host=host)
842484
def server(port):
    

    header("Serving application in development mode ... ")
    print("")
    print("- Port: %s" % port)
    print("")
    cwd_to_sys_path()
    application.app.run(debug=True, host='0.0.0.0', port=port)
103083
def serve(project, port, no_watch):
    

    header("Serving application in development mode ... ")
    print("- Project: %s " % project)
    print("")
    print("- Port: %s" % port)
    print("")

    module = import_module(project, True)

    extra_files = []
    if not no_watch:
        extra_dirs = [CWD,]
        extra_files = extra_dirs[:]
        for extra_dir in extra_dirs:
            for dirname, dirs, files in os.walk(extra_dir):
                for filename in files:
                    filename = os.path.join(dirname, filename)
                    if os.path.isfile(filename):
                        extra_files.append(filename)

    module.app.run(debug=True,
                   host='0.0.0.0',
                   port=port,
                   extra_files=extra_files)
891262
async function start () {
    var config = this.immutableApp
    var module = this
    // initialize app if not yet initialized
    if (!config.initialized) {
        try {
            await this.init()
        }
        catch (err) {
            throw err
        }
    }
    // run any start functions for modules
    await Promise.each(_.values(config.modules), subModule => {
        // if onStart is function run it
        if (typeof subModule.onStart === 'function') {
            return subModule.onStart(config)
        }
    })
    debug('start Promise')
    // create new promise that will be resolved when server started
    return new Promise(function (resolve, reject) {
        // create HTTP server
        config.server = http.createServer(config.express)
        // create error handler
        config.server.on('error', function (err) {
            // only deal with listen errors
            if (err.syscall !== 'listen') {
                throw err
            }
            // log error if logging enable
            if (config.log) {
                // error msg detail
                var msg
                // get specific errors
                if (err.code === 'EACCES') {
                    msg = 'permission denied'
                }
                else if (err.code === 'EADDRINUSE') {
                    msg = 'address in use'
                }
                else {
                    msg = err.code
                }
                // log error
                console.error('listen on port '+config.port+' failed '+msg)
            }
            // if exit on error is set then exit
            if (config.exit) {
                process.exit(1)
            }
            // reject promise with error
            reject(err)
        })
        debug('start listen')
        // listen on provided port, on all network interfaces.
        config.server.listen(config.port, function () {
            // log start if logging enabled
            if (config.log) {
                console.log(module.name+' listening on port '+config.port)
            }
            // set started to true
            config.started = true
            // resolve promise
            resolve()
        })
    })
    // after starting check the START_TEST_ONLY flag and shut back down if it
    // is set - this flag is used to validate app config and sync models
    .then(() => {
        if (process.env.START_TEST_ONLY) {
            return this.stop().then(() => {
                if (config.log) {
                    console.log('START_TEST_ONLY success - server stopped')
                }
                process.exit()
            })
        }
    })
}
457173
function (options, callback) {
    var log = this.log;

    log('starting app server');
    if (this.startAppServerFunc) {
      // manual starting of app server
      this.startAppServerFunc(options, callback);
    } else {
      // let smocks-magellan-nightwatch automatically handle the work
      var appServer = this.appServer = new Hapi.Server();
      appServer.connection({ port: this.appPort });
      appServer.route([{
        method: 'GET',
        path: '/{path*}',
        handler: function (req, reply) {
          log('request made: ' + req.path);
          var requestPath = req.path;
          var artifactPath = Path.join(options.distPath, requestPath);
          if (requestPath.match(/\/[^\.]*$/i)) {
            log('handling response as container html file');
            // it's the main index file.  In order to re-use the transpiled files, we need to
            // ensure that the container html file represents the correct mock port so
            // we will replace that out when returning the file contents
            replyWithIndexFile(options, reply);
          } else {
            log('handling response: ' + requestPath);

            fs.exists(artifactPath, function (exists) {
              if (exists) {
                var mimeType = mimeTypes.lookup(artifactPath);
                fs.readFile(artifactPath, function (err, buffer) {
                  if (err) {
                    log('error loading file: ' + artifactPath + ': ' + e.message);
                    reply(err);
                  } else {
                    log('responding with ' + artifactPath);
                    reply(buffer).type(mimeType);
                  }
                });
              } else {
                log(artifactPath + ' does not exist... 404');
                reply({message: artifactPath + ' does not exist'}).code(404);
              }
            });
          }
        }
      }]);
      appServer.start(callback);
    }
  }
1276157
function devserver(yargs) {
  var requirements = pathRequiredUsage(
    'Path to a staticbuild.json file or directory to find one.\n' +
    '                 If no path is supplied, the current directory is used.');
  
  yargs = configureYargs(yargs)
  .usage(commandUsage('dev', '[options] <path>' + requirements, 
    'Development server.\n\n' + 
    '    Runs a local http server to dynamically render static content ' + 
    'during development.'))
  .option('b', {
    alias: 'bundling',
    description: 'Enable bundling.',
    type: 'boolean',
    // jscs: disable
    'default': false
    // jscs: enable
  })
  .option('r', {
    alias: 'restart',
    description: 'Number of seconds to delay nodemon restarts. -1 to disable nodemon.',
    type: 'number',
    // jscs: disable
    'default': 1
    // jscs: enable
  })
  .help('h', 'Show help.').alias('h', 'help');
  yargs = configureVerbosity(yargs);

  var args = processYargs(yargs, 'dev');
  parseDevserverRestart(args);
  pathRequired(args, 1002);
  return args;
}
379805
public function start()
  {
    try
    {
        $host    = $this->getOption('host');
        $port    = intval($this->getOption('port'));
        $binary  = ProcessUtils::escapeArgument((new PhpExecutableFinder)->find(false));
        $docroot = ProcessUtils::escapeArgument($this->getOption('docroot'));
        $output  = $this->output;

        $this->writeln([
          sprintf('Codeigniter development server started at %s', date(DATE_RFC2822)),
          sprintf('Listening on http://%s:%s', $host, $port),
          sprintf('Document root is %s', getcwd()),
          'Press Ctrl-C to quit.'
        ]);

        $process = new Process(sprintf('%s -S %s:%s -t %s', $binary, $host, $port, $docroot));

        $process
            // ->setWorkingDirectory(getcwd())
            ->setTimeout(0)
            ->setPTY(true)
            ->run(function ($type, $buffer) use($output) {
                if (Process::ERR === $type && $output instanceof ConsoleOutputInterface) {
                    $output = $output->getErrorOutput();
                }
                $output->write($buffer, false, OutputInterface::OUTPUT_RAW);
            });
    }
    catch (Exception $e)
    {
        $this->error(sprintf(
            'Error starting the server: %s', $e->getMessage()
        ));
    }
  }
733658
function startApplication(appName, appDirectory, appList, configStore, sessionStore) {

    let path = appDirectory + '/' + appList[appName] + '/';
    let commonPath = appDirectory + '/apps/common/';
    let config = configStore[appName].get();
    let commonJsDir = commonPath + '/js/';
    let controllerJsDir = path + '/public/js/';

    if (config.isDaemon || config.serverMode === 'api') {
        controllerJsDir = path + '/js/';
    }

    let schema = JSON.parse((readFile(path + '/schema.json') || readFile(commonPath + '/schema.json')).toString());

    let controllerPath = (config.controller || 'controller.js');
    let matches = controllerPath.match(/(.*?)([0-9A-Za-z_]*)\.js$/);
    let prefix = matches[1];
    let prop = matches[2];

    // TODO: Completely change how we do configurations
    config.nconf = configStore[appName]; // Global config
    config.configStore = configStore;

    return setUpInjectObjectTemplate(appName, config, schema)
        .then(buildAppConfigAndLoadTemplates.bind(this, appName, config, controllerJsDir, commonJsDir, sessionStore))
        .spread(finishDaemonIfNeeded.bind(this, config, prop, prefix, appName));
}
65163
function start(root, distPath) {
  return new Promise((resolve, reject) => {

    const dist = path.resolve(process.cwd(), distPath || 'dist');

    logger.info('Creating web server');
    app.use(cors());

    logger.info(`Exposing static directory: ${dist}`);
    app.use(express.static(dist));
    if (root) {
      logger.info(`Mapping server requests from ${root} to ${dist}`);
      app.use(root, express.static(dist));
    }

    const options = {
      cert: fs.readFileSync(path.resolve(__dirname, '../../ssl/server.crt')),
      key: fs.readFileSync(path.resolve(__dirname, '../../ssl/server.key'))
    };

    server = https.createServer(options, app);
    server.on('error', reject);

    logger.info('Requesting open port...');
    portfinder
      .getPortPromise()
      .then(port => {
        logger.info(`Open port found: ${port}`);
        logger.info('Starting web server...');
        server.listen(port, 'localhost', () => {
          logger.info('Web server running.');
          resolve(port);
        });
      })
      .catch(reject);
  });
}
581094
async function startApp(middlewareConfig, config) {
  const {
    port = DEFAULT_PORT,
    host = DEFAULT_HOST,
  } = config

  // close all connections when running nodemon
  const sigListener = async () => {
    await app.destroy()
    process.kill(process.pid, 'SIGUSR2')
  }
  process.once('SIGUSR2', sigListener)

  const appMeta = await createApp(middlewareConfig, config)
  const { app } = appMeta

  const server = await listen(app, port, host)

  enableDestroy(server)
  app.destroy = async () => {
    await destroy(server)
    process.removeListener('SIGUSR2', sigListener)
  }
  const { port: p } = server.address()

  const url = `http://localhost:${p}`

  const router = new Router()

  return { ...appMeta, router, url, server }
}
878888
def dev():
    """"""
    env.roledefs = {
        'web': ['192.168.1.2'],
        'lb': ['192.168.1.2'],
    }
    env.user = 'vagrant'
    env.backends = env.roledefs['web']
    env.server_name = 'django_search_model-dev.net'
    env.short_server_name = 'django_search_model-dev'
    env.static_folder = '/site_media/'
    env.server_ip = '192.168.1.2'
    env.no_shared_sessions = False
    env.server_ssl_on = False
    env.goal = 'dev'
    env.socket_port = '8001'
    env.map_settings = {}
    execute(build_env)
949886
function startServer(alerts, params, port, resources) {
    const compiledAlerts = compileMarkdown(alerts);
    const app = http.createServer((req, res) =>
        res.end(resources[req.url] || resources['/index.html']));
    const io = listen(app);
    io.on('connection', socket => {
        emitInfo(`new session for ${socket.handshake.address}`);
        socket.emit('update', compiledAlerts);
        socket.on('disconnect', () => {
            emitInfo(`disconnected session ${socket.handshake.address}`);
        });
    });

    return new Promise(resolve => app.listen(port, emitRungEmoji & resolve))
        .then(~watchChanges(io, params));
}
1190944
function startBrowserSync(serverRoot) {

    helper.log('Starting BrowserSync on port ' + 8080 + ' for ' + serverRoot);

    var options = {
        //proxy: 'localhost:' + port,
        port: 8080,
        ws: true,
        server: {
            baseDir: serverRoot
        },
        reloadDelay: config.browserReloadDelay
    };

    browserSync.init(options);

}
1037336
def start_simple_server():
	""
	args = _get_args()
	addr = ('', args.port)
	DebuggingServer(addr, None)
	asyncore.loop()