/* Start a webserver for the Web IDE
963534
function startWebIDEServer(writeCallback) {
  var httpPort = args.ideServer;
  var server = require("http").createServer(function(req, res) {
    res.end(`<html>
<body style="margin:0px">
<iframe id="ideframe" src="https://www.espruino.com/ide/" style="width:100%;height:100%;border:0px;"></iframe>
<script src="https://www.espruino.com/ide/embed.js"></script>
<script>
  var ws = new WebSocket("ws://" + location.host + "/ws", "serial");
  var Espruino = EspruinoIDE(document.getElementById('ideframe'));
  Espruino.onports = function() {
    return [{path:'local', description:'Connected Device', type : "net"}];
  };
  Espruino.onready = function(data) { Espruino.connect("local");};
  Espruino.onwrite = function(data) { ws.send(data); }
  ws.onmessage = function (event) { Espruino.received(event.data); };
  ws.onclose = function (event) { Espruino.disconnect(); };
</script>
</body>
</html>
`);
  });
  server.listen(httpPort);
  log("Web IDE is now available on http://localhost:"+httpPort);
  /* Start the WebSocket relay - allows standard Websocket MQTT communications */
  var WebSocketServer = require('websocket').server;
  var wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
  });
  var ideConnections = [];
  wsServer.on('request', function(request) {
    // request.reject() based on request.origin?
    var connection = request.accept('serial', request.origin);
    ideConnections.push(connection);
    log('Web IDE Connection accepted.');
    connection.on('message', function(message) {
      if (message.type === 'utf8') writeCallback(message.utf8Data);
    });
    connection.on('close', function(reasonCode, description) {
      log('Web IDE Connection closed.');
      var conIdx = ideConnections.indexOf(connection);
      if (conIdx>=0) ideConnections.splice(conIdx,1);
    });
  });

  return {
    write : function(data) {
      ideConnections.forEach(function(connection) { connection.sendUTF(data) });
    }
  };
}
136155
public void start() throws Exception {
		server = new Server();
		ServerConnector connector = new ServerConnector(server);
		if (serverAddress != null) {
			connector.setHost(serverAddress.getHostAddress());
		}
		connector.setPort(serverPort);
		server.addConnector(connector);
		server.setHandler(new JmxWebHandler());
		server.start();
	}
929144
function runWebServerAsWorker(rawConfig, serverConfig, emitter, callback) {
  if (serverConfig.command == 'stop') {
    logger.info('stopping server workers');
    if (netServer) {
      netServer.close();
      netServer = null;
    }    
    
    for (var i=0;i<webservers.length;i++) {
      var webserver = webservers[i];
      webserver.kill();    
    }
    webservers = [];
    
    return;
  }
  
  netServer = require('net').createServer().listen(serverConfig.options.port, function() {
    var numWorkers = require('os').cpus().length;
    var readyCount = 0;
    for (var i=0;i<numWorkers;i++) {
      var webserver = fork(__dirname + '/worker.js', [], {env: process.env});
      webservers.push(webserver);
      webserver.send({message: 'start', rawConfig: rawConfig, serverConfig: serverConfig}, netServer._handle)
      
      webserver.on('message', function(m) {
        if (m == 'ready') {
          //this is a reply from the worker indicating that the server is ready.
          readyCount += 1;
          if (readyCount == numWorkers) {
            //all servers are ready
            logger.info('started server workers');
            if (callback) callback();
          }
          return;
        }
        
        var webserverWorker = this;
        var id = m.id;
        if (m.err) { 
          logger.error("Error: " + m.err);
          if (callback) callback(m.err);
        } else {
          emitter.emit(m.commandName, m.config, function(err, result) {
            webserverWorker.send({message: 'result', err: err, result: result, id: id})
          });
        }
      })
    }
    
    
  });
}
497791
def cli_main():
    """"""
    SearchContext.commit()
    args = parser.parse_args()
    # open up a browser
    firefox_remote = Remote("http://127.0.0.1:4444/wd/hub", DesiredCapabilities.FIREFOX)
    with contextlib.closing(firefox_remote):
        context = SearchContext.from_instances([FastSearch(), Browser(firefox_remote)])
        search = Search(parent=context)

        if args.fast:
            with context.use(FastSearch, Browser):
                main(search, args.query)
        else:
            with context.use(Browser):
                main(search, args.query)
489051
async function setupServer() {
  return new Promise(async (resolve, reject) => {
    config = config || (await getConfig());
    config.components.individual = [];
    config.prod = true;
    config.enableCache = true;
    config.mode = 'server';
    config.env = 'pwa';
    config.sourceMaps = false;
    config.copy = [];
    config.webpackDevServer = false;
    config.buildDir = path.join(config.wwwDir, 'build-ssr');
    config.dataDir = path.join(config.wwwDir, 'build-ssr', 'data');

    app.use(express.static(path.relative(process.cwd(), config.wwwDir)));

    // generate a fresh webpack build + pass along asset data to dynamic HTML template rendered
    server = await app.listen(port);

    app.get('/ssr', function(req, res) {
      res.send(template(html || '', port, webpackStatsGenerated || []));
    });

    // handle cleaning up + shutting down the server instance
    process.on('SIGTERM', shutDownSSRServer);
    process.on('SIGINT', shutDownSSRServer);

    server.on('connection', connection => {
      connections.push(connection);
      connection.on(
        'close',
        // eslint-disable-next-line no-return-assign
        () => (connections = connections.filter(curr => curr !== connection)),
      );
    });

    resolve();
  });
}
238176
private WebServer loadWebServer() {
        WebServer webServer = null;
        if (!Utils.isEmpty(getParamString("webserver_class"))) {
            try {
                Class<?> serviceClass = Class.forName(getParamString("webserver_class"));
                Method instanceMethod = serviceClass.getMethod("instance", (Class<?>[])null);
                webServer = (WebServer)instanceMethod.invoke(null, (Object[])null);
                webServer.init(RESTServlet.class.getName());
            } catch (Exception e) {
                throw new RuntimeException("Error initializing WebServer: " + getParamString("webserver_class"), e);
            }
        }
        return webServer;
    }
204426
async function start() {
  await run(clean);
  await run(copy.bind(undefined, { watch: true }));
  await new Promise(resolve => {
    // Patch the client-side bundle configurations
    // to enable Hot Module Replacement (HMR) and React Transform
    webpackConfig.filter(x => x.target !== 'node').forEach(config => {
      /* eslint-disable no-param-reassign */
      if (Array.isArray(config.entry)) {
        config.entry.unshift('webpack-hot-middleware/client');
      } else {
        config.entry = ['webpack-hot-middleware/client', config.entry];
      }

      config.output.filename = config.output.filename.replace('[chunkhash]', '[hash]');
      config.output.chunkFilename = config.output.chunkFilename.replace('[chunkhash]', '[hash]');
      config.plugins.push(new webpack.HotModuleReplacementPlugin());
      config.plugins.push(new webpack.NoErrorsPlugin());
      config
        .module
        .loaders
        .filter(x => x.loader === 'babel-loader')
        .forEach(x => (x.query = {
          ...x.query,

          // Wraps all React components into arbitrary transforms
          // https://github.com/gaearon/babel-plugin-react-transform
          plugins: [
            ...(x.query ? x.query.plugins : []),
            ['react-transform', {
              transforms: [
                {
                  transform: 'react-transform-hmr',
                  imports: ['react'],
                  locals: ['module'],
                }, {
                  transform: 'react-transform-catch-errors',
                  imports: ['react', 'redbox-react'],
                },
              ],
            },
            ],
          ],
        }));
      /* eslint-enable no-param-reassign */
    });

    const bundler = webpack(webpackConfig);
    const wpMiddleware = webpackMiddleware(bundler, {

      // IMPORTANT: webpack middleware can't access config,
      // so we should provide publicPath by ourselves
      publicPath: webpackConfig[0].output.publicPath,

      // Pretty colored output
      stats: webpackConfig[0].stats,

      // For other settings see
      // https://webpack.github.io/docs/webpack-dev-middleware
    });
    const hotMiddlewares = bundler
      .compilers
      .filter(compiler => compiler.options.target !== 'node')
      .map(compiler => webpackHotMiddleware(compiler));

    let handleServerBundleComplete = () => {
      runServer((err, host) => {
        if (!err) {
          const bs = Browsersync.create();
          bs.init({
            ...(DEBUG ? {} : { notify: false, ui: false }),

            proxy: {
              target: host,
              middleware: [wpMiddleware, ...hotMiddlewares],
            },

            // no need to watch '*.js' here, webpack will take care of it for us,
            // including full page reloads if HMR won't work
            files: ['build/content/**/*.*'],
          }, resolve);
          handleServerBundleComplete = runServer;
        }
      });
    };

    bundler.plugin('done', () => handleServerBundleComplete());
  });
}
1330837
async def start(self, **kwargs):
        """"""
        zeroconf = kwargs['zeroconf']
        self._name = kwargs['name']
        self._pairing_guid = kwargs.get('pairing_guid', None) or \
            self._generate_random_guid()

        self._web_server = web.Server(self.handle_request, loop=self._loop)
        self._server = await self._loop.create_server(
            self._web_server, '0.0.0.0')

        # Get the allocated (random port) and include it in zeroconf service
        allocated_port = self._server.sockets[0].getsockname()[1]
        _LOGGER.debug('Started pairing web server at port %d', allocated_port)

        self._setup_zeroconf(zeroconf, allocated_port)
293465
private static void launchServer(final String url,
                                     final CloseableHttpClient client) {
        try {
            final JDialog dialog = new JDialog();
            dialog.setSize(new java.awt.Dimension(400, 75));
            dialog.setModalityType(ModalityType.MODELESS);
            dialog.setTitle("DuraCloud Sync");
            dialog.setLocationRelativeTo(null);

            JPanel panel = new JPanel();
            final JLabel label = new JLabel("Loading...");
            final JProgressBar progress = new JProgressBar();
            progress.setStringPainted(true);

            panel.add(label);
            panel.add(progress);
            dialog.add(panel);
            dialog.setVisible(true);

            port = SyncUIConfig.getPort();
            contextPath = SyncUIConfig.getContextPath();
            Server srv = new Server(port);

            // Setup JMX
            MBeanContainer mbContainer = new MBeanContainer(
                    ManagementFactory.getPlatformMBeanServer() );
            srv.addBean( mbContainer );

            ProtectionDomain protectionDomain =
                org.duracloud.syncui.SyncUIDriver.class.getProtectionDomain();
            String warFile =
                protectionDomain.getCodeSource().getLocation().toExternalForm();

            log.debug("warfile: {}", warFile);
            WebAppContext context = new WebAppContext();
            context.setContextPath(contextPath);
            context.setWar(warFile);
            context.setExtractWAR(Boolean.TRUE);

            Configuration.ClassList classlist = Configuration.ClassList
                    .setServerDefault( srv );
            classlist.addBefore(
                    "org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
                    "org.eclipse.jetty.annotations.AnnotationConfiguration" );

            context.setAttribute(
                    "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                    ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );

            srv.setHandler(context);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    createSysTray(url, srv);

                    while (true) {
                        if (progress.getValue() < 100) {
                            progress.setValue(progress.getValue() + 3);
                        }

                        sleep(2000);
                        if (isAppRunning(url, client)) {
                            break;
                        }
                    }

                    progress.setValue(100);

                    label.setText("Launching browser...");
                    launchBrowser(url);
                    dialog.setVisible(false);
                }
            }).start();

            srv.start();

            srv.join();
        } catch (Exception e) {
            log.error("Error launching server: " + e.getMessage(), e);
        }
    }
1370106
protected void startServerImpl() {
        SelendroidLogger.info("*** ServerInstrumentation#startServerImpl() ***");
        if (serverThread != null && serverThread.isAlive()) {
            return;
        }

        if (serverThread != null) {
            stopServer();
        }

        serverThread = new HttpdThread(this, serverPort);
        serverThread.startServer();
    }
589821
function HyperServer($){

    //setup
    $ = Object.assign( defaults, $ ); 

    //injection
    let gx   = $.generator;
    let hx   = $.handler;

    //prototype
    let $ns, $n = proto();
    let dev  = ( 'development' == $n.get('env') || process.env.NODE_ENV  == 'development' );
    let port = (( dev ? $.LOCAL_PORT : $.APP_PORT ) || process.env.NODE_PORT );
 
    //config mapping
    $n.set( 'port', port );
    $n.set( 'view engine', $.VIEW_ENGINE );

    //middleware in out next
    if( dev ) $n.use( errorHandler({ dumpExceptions: true, showStack: true }) );
    $n.use( bodyParser.json() );
    $n.use( bodyParser.urlencoded({ extended:true }) );
    $n.use( override() );
    $n.use( cookieParser() );
    $n.use( sss({secret: 'secret', key:$.SESSION_ID, resave:true, saveUninitialized:true }));
    $n.use( ( i, o, n ) => { o.set('X-Powered-By', $.SERVER_ID ); n(); });
    $n.use( ( i, o, n ) => { i.baseUrl = i.originalUrl.split("?").shift(); n(); });
    $n.use( ( i, o, n ) => { console.info( `[${i.method} ${i.baseUrl}]`) || n(); }); //| q:${k(i.query)} \t | c:${k(i.cookies)}` ) || n(); });
    $n.use( favicon( $.PUBLIC_WWW + '/favicon.ico') );
    $n.use( proto.static( $.PUBLIC_WWW, {  
        setHeaders: ( res, path, stat ) => res.set('X-Timestamp', Date.now())
    }));

    //route stubs
    $.router.route( $n );

    //boot
    $ns = http.createServer($n)
          .on( 'close', ()=> {
            console.error( $.SERVER_ID + " - Shutting Down..");
          })
          .listen( port, data => {
            console.info( `Env  : [ ${( dev ? "DEV" : "UAT" )} ] \nPort : [ ${port} ]` );
            console.info( `URL  :  http://localhost:${port}` );
          });

    //termsigs
    process.once( 'SIGUSR2', ()=> {
            console.warn( 'Attempting to graceful kill...' );
            process.kill( process.pid, 'SIGUSR2');
          })
          .once( 'EADDRINUSE', ()=> {
            console.warn( 'Required port unavailable' );
            process.exit(1);
          });

    return $n;
  }
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);

}
586163
public static void main(String[] args) {
		if (args == null || args.length == 0) {
			server = com.jfinal.server.jetty.ServerFactory.getServer();
			server.start();
			return ;
		}
		
		// for Eclipse
		if (args.length == 4) {
			String webAppDir = args[0];
			int port = Integer.parseInt(args[1]);
			String context = args[2];
			int scanIntervalSeconds = Integer.parseInt(args[3]);
			server = com.jfinal.server.jetty.ServerFactory.getServer(webAppDir, port, context, scanIntervalSeconds);
			server.start();
			return ;
		}
		
		// for IDEA
		if (args.length == 3) {
			start(args[0], Integer.parseInt(args[1]), args[2]);
			return ;
		}
		
		throw new RuntimeException("Boot parameter error. The right parameter like this: src/main/webapp 80 / 5");
	}
171519
function start() {
  const node = process.execPath
  const daemonFile = path.join(__dirname, '../daemon')
  const startupFile = startup.getFile('hotel')

  startup.create('hotel', node, [daemonFile], common.logFile)

  // Save startup file path in ~/.hotel
  // Will be used later by uninstall script
  mkdirp.sync(common.hotelDir)
  fs.writeFileSync(common.startupFile, startupFile)

  console.log(`Started http://localhost:${conf.port}`)
}
875283
private function startServer()
    {
        if ($this->resource !== null) {
            return;
        }

        $this->writeln(PHP_EOL);
        $this->writeln('Starting PhantomJS Server.');

        $command = $this->getCommand();

        if ($this->config['debug']) {
            $this->writeln(PHP_EOL);

            // Output the generated command.
            $this->writeln('Generated PhantomJS Command:');
            $this->writeln($command);
            $this->writeln(PHP_EOL);
        }

        $descriptorSpec = [
            ['pipe', 'r'],
            ['file', $this->getLogDir() . 'phantomjs.output.txt', 'w'],
            ['file', $this->getLogDir() . 'phantomjs.errors.txt', 'a'],
        ];

        $this->resource = proc_open($command, $descriptorSpec, $this->pipes, null, null, ['bypass_shell' => true]);

        if (!is_resource($this->resource) || !proc_get_status($this->resource)['running']) {
            proc_close($this->resource);
            throw new ExtensionException($this, 'Failed to start PhantomJS server.');
        }

        // Wait till the server is reachable before continuing.
        $max_checks = 10;
        $checks = 0;

        $this->write('Waiting for the PhantomJS server to be reachable.');
        while (true) {
            if ($checks >= $max_checks) {
                throw new ExtensionException($this, 'PhantomJS server never became reachable.');
            }

            $fp = @fsockopen('127.0.0.1', $this->config['port'], $errCode, $errStr, 10);
            if ($fp) {
                $this->writeln('');
                $this->writeln('PhantomJS server now accessible.');
                fclose($fp);
                break;
            }

            $this->write('.');
            $checks++;

            // Wait before checking again.
            sleep(1);
        }

        // Clear progress line writing.
        $this->writeln('');
    }
14886
function start(callback) {
  let handle = {close(){server.close()}}
  check(function _check(err, inUse) {
    if (err) throw err
    if (inUse) {
      server = {close(){}}
      init(callback)
    }
    else {
      server = dynalite({
        createTableMs: 0
      }).listen(5000, function _server(err) {
        if (err) {
          // if we err then the db has been started elsewhere..
          // just try to continue
          console.log(err)
        }
        init(callback)
      })
    }
  })
  return handle
}
738073
function main() {
  config = createConfig(process.argv.slice(2));

  if (config.options.help) {
    config.options.showHelp(NODE_DEBUG_MODE);
    process.exit();
  }

  if (config.options.version) {
    config.options.showVersion();
    process.exit();
  }

  process.on('SIGINT', function() {
     process.exit();
  });

  startInspectorProcess(function(error, result) {
    if (error) {
      console.error(formatNodeInspectorError(error));
      process.exit(1);
    }

    var url = result.address.url;
    var isUnixSocket = result.address.isUnixSocket;

    startDebuggedProcess(function(error) {
      if (error) {
        console.error('Cannot start %s: %s', config.subproc.script, error.message || error);
        process.exit(2);
      }

      openBrowserAndPrintInfo(url, isUnixSocket);
    });
  });
}