Create and configure server instance
174674
function createServer () {

    // Create server

    var server = express.createServer();

    // Configure Server

    server.configure(function () {

        // Built-in

        server.use(express.methodOverride());                           // Allow method override using _method form parameter
        server.use(express.bodyDecoder()); 	                            // Parse application/x-www-form-urlencoded
        server.use(express.staticProvider(__dirname + '/files'));       // Serve client documents in local directory

        // Local

        server.use(setResponseHeader());                                // Set default response headers for CORS
        server.use(logConsole());                                       // Display incoming requests

        // Authentication

        server.use(auth([auth.Mac({ realm: "Example",                   // Set realm, typically a domain name or application name
                                    getTokenAttributes: getToken,       // Function used to fetch the access token record, typically from a database
                                    // hostHeader: 'x-forwarded-host',  // Needed when running behind a proxy such as Apache2
                                    // isHTTPS: true,                   // Uncomment for HTTPS
                                    checkNonce: nonceCheck,             // Optional nonce checking function
                                    bodyHashMode: "require" })]));      // Require body hash validation for all non GET/HEAD/OPTIONS requests
    });

    // Setup generic OPTIONS route

    server.options(/.+/, function (req, res) {

        res.send(' ');
    });

    return server;
}
23865
def run(self):
        
        self.configure()
        self.setup()
        self.update_dir()
        db.init_db(drop_all=True)
        self.out.log("Starting up the server...")
        config = get_config()
        with HerokuLocalWrapper(config, self.out, verbose=self.verbose) as wrapper:
            try:
                self.execute(wrapper)
            except KeyboardInterrupt:
                pass
            finally:
                os.chdir(self.original_dir)
                self.cleanup()
759245
def launch_server():
    
    print(os.path.dirname(os.path.abspath(__file__)))
    cur_dir = os.getcwd()
    path = os.path.dirname(os.path.abspath(__file__))
    run = True
    os.chdir(path)
    os.system('python manage.py runserver --nostatic')
    os.chdir(cur_dir)
345803
def configure
      @web_server.mount('/alive', Alive)
      @web_server.mount('/tasks/new', NewTask, self)
      @web_server.mount('/shutdown', Shutdown)
      @web_server.mount('/response_from_device', ResponseFromDevice, self)
      @web_server.mount('/auto_update_pid', AutoUpdatePID, self)
    end
982877
public void start() {
        config.serverConfigs().forEach((key, serverConfig) -> servers.put(key, EbeanServerFactory.create(serverConfig)));
    }
983715
def Initialize(config=None,
               external_hostname = None,
               admin_password = None,
               redownload_templates = False,
               repack_templates = True,
               token = None):
  """"""

  print("Checking write access on config %s" % config["Config.writeback"])
  if not os.access(config.parser.filename, os.W_OK):
    raise IOError("Config not writeable (need sudo?)")

  print("\nStep 0: Importing Configuration from previous installation.")
  options_imported = 0
  prev_config_file = config.Get("ConfigUpdater.old_config", default=None)
  if prev_config_file and os.access(prev_config_file, os.R_OK):
    print("Found config file %s." % prev_config_file)
    # pytype: disable=wrong-arg-count
    if builtins.input("Do you want to import this configuration? "
                      "[yN]: ").upper() == "Y":
      options_imported = ImportConfig(prev_config_file, config)
    # pytype: enable=wrong-arg-count
  else:
    print("No old config file found.")

  print("\nStep 1: Setting Basic Configuration Parameters")
  print("We are now going to configure the server using a bunch of questions.")
  ConfigureDatastore(config)
  ConfigureUrls(config, external_hostname=external_hostname)
  ConfigureEmails(config)

  print("\nStep 2: Key Generation")
  if config.Get("PrivateKeys.server_key", default=None):
    if options_imported > 0:
      print("Since you have imported keys from another installation in the "
            "last step,\nyou probably do not want to generate new keys now.")
    # pytype: disable=wrong-arg-count
    if (builtins.input("You already have keys in your config, do you want to"
                       " overwrite them? [yN]: ").upper() or "N") == "Y":
      config_updater_keys_util.GenerateKeys(config, overwrite_keys=True)
    # pytype: enable=wrong-arg-count
  else:
    config_updater_keys_util.GenerateKeys(config)

  FinalizeConfigInit(
      config,
      token,
      admin_password=admin_password,
      redownload_templates=redownload_templates,
      repack_templates=repack_templates,
      prompt=True)
703552
def settings(instance):
    """"""
    with open(instance.root_dir + '/Config/config.yml') as config:
        config = yaml.load(config)
        instance.name = config['name']
        instance.port = config['web']['port']
        # default host
        instance.host = "http://localhost"
        if 'host' in config['web']:
            instance.host = config['web']['host']
        instance.debug = config['debug']
    return instance
1250605
def create(provider, count=1, name=None, **kwargs):
    
    '''
    count = int(count)
    provider = provider_by_name(provider)
    options = provider.create_server_defaults
    options.update(kwargs)
    names = [name] * count
    provider.validate_create_options(**options)
    return provider.create_servers(count, names, **options)
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;
}
772438
private function createServer()
    {
        $server = new SoapServer(null, $this->soapServerOptions);
        $server->SetClass($this->wsdlclassname);
        $server->handle();
    }
690693
def _create_server(host, port):
    

    exc = socket.error("getaddrinfo returns an empty list")
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            # Create the listening socket
            sock = socket.socket(af, socktype, proto)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind(sa)
            sock.listen(1024)
            return sock

        except socket.error as exc:
            # Clean up after ourselves
            if sock is not None:
                sock.close()

    # Couldn't create a listening socket
    raise exc
260652
def create_server(host_name, service_name, template_name, disk_name=nil, zone_name=nil, network_names=[], extra_params)

      if host_name then
        if get_server(host_name) then
          puts "\nError: Server '#{host_name}' already exists."
          exit 1
        end
      end

      service = get_service_offering(service_name)
      if !service then
        puts "\nError: Service offering '#{service_name}' is invalid"
        exit 1
      end

      template = get_template(template_name, zone_name)
      template = get_iso(template_name, zone_name) unless template

      if !template then
        puts "\nError: Template / ISO name: '#{template_name}' is invalid"
        exit 1
      end

      if disk_name then
        disk = get_disk_offering(disk_name)
        if !disk then
          puts "\nError: Disk offering '#{disk_name}' is invalid"
          exit 1
        end
      end

      zone = zone_name ? get_zone(zone_name) : get_default_zone
      if !zone then
        msg = zone_name ? "Zone '#{zone_name}' is invalid" : "No default zone found"
        puts "\nError: #{msg}"
        exit 1
      end

      if zone['networktype'] != 'Basic' then
      # If this is a Basic zone no networkids are needed in the params

        networks = []
        if network_names.nil? then
          networks << get_default_network(zone['id'])
        else
          network_names.each do |name|
            network = get_network(name)
            if !network then
              puts "\nError: Network '#{name}' not found"
            end
            networks << get_network(name)
          end
        end

        if networks.empty? then
          networks << get_default_network(zone['id'])
        end
        if networks.empty? then
          puts "\nError: No default network found"
          exit 1
        end
        network_ids = networks.map { |network|
          network['id']
        }

        params = {
            'command' => 'deployVirtualMachine',
            'serviceOfferingId' => service['id'],
            'templateId' => template['id'],
            'zoneId' => zone['id'],
            'networkids' => network_ids.join(',')
        }

      else

        params = {
            'command' => 'deployVirtualMachine',
            'serviceOfferingId' => service['id'],
            'templateId' => template['id'],
            'zoneId' => zone['id']
        }

      end

      params.merge!(extra_params) if extra_params

      params['name'] = host_name if host_name
      params['diskOfferingId'] = disk['id'] if disk

      json = send_async_request(params)
      json['virtualmachine']
    end
343940
function createServer(listen, opt) {

  if (!listen) {
    throw new TypeError('listen required');
  }
  var options = opt || Object.create(null);
  var my = {
    keepalive: Number(options.keepalive) || 2000,
    callback: typeof options.callback === 'function' ? options.callback : false,
    http: false,
    https: false
  };
  if (typeof options.http === 'object') {
    my.http = {
      port: Number(options.http.port) || 3000,
      host: String(options.http.host || '127.0.0.1')
    };
  }
  if (typeof options.https === 'object') {
    my.https = options.https;
    my.https.port = Number(options.https.port) || 3000;
    my.https.host = String(options.https.host || '127.0.0.1');
  }

  var hosts = Object.create(null);
  var server = net.createServer(function(sock) {

    sock.setKeepAlive(true, my.keepalive); // https://en.wikipedia.org/wiki/Keepalive
    sock.on('data', function(buff) {

      if (sock._id) {
        hosts[sock._id] = {
          state: sock.readyState,
          beat: Date.now()
        };
      } else if (buff.length > 1) { // set client id
        var _id = String(buff);
        hosts[_id] = {
          state: sock.readyState,
          beat: Date.now()
        };
        sock._id = _id;
      }
      return;

    }).on('close', function(had_error) {

      if (sock._id) {
        hosts[sock._id] = {
          state: sock.readyState,
          beat: Date.now()
        };
      }
      // error hook [with client id]
      return my.callback !== false ? my.callback(had_error, sock._id) : null;
    });
  });

  if (options.host && typeof listen === 'number') { // tpc only
    server.listen(listen, options.host);
  } else {
    server.listen(listen);
  }

  if (my.http || my.https) {
    var web = function(req, res) {

      var out = '';
      res.setHeader('Content-Type', 'application/json; charset=utf-8');
      var url = decodeURI(req.url);
      url = url.substr(1, url.length);
      if (url === '') {
        out = JSON.stringify(hosts);
      } else if (hosts[url] !== undefined) {
        out = JSON.stringify(hosts[url]);
      } else {
        res.statusCode = 404;
      }
      return res.end(out);
    };
    if (my.http) {
      require('http').createServer(web).listen(my.http.port, my.http.host);
    }
    if (my.https) {
      require('https').createServer(my.https, web).listen(my.https.port,
        my.https.host);
    }
  }

  server._hosts = hosts; // hosts reference
  return server;
}
530404
def add_server(self, name, ip, port):
        """"""
        new_server = {
            'key': name,  # Zeroconf name with both hostname and port
            'name': name.split(':')[0],  # Short name
            'ip': ip,  # IP address seen by the client
            'port': port,  # TCP port
            'username': 'glances',  # Default username
            'password': '',  # Default password
            'status': 'UNKNOWN',  # Server status: 'UNKNOWN', 'OFFLINE', 'ONLINE', 'PROTECTED'
            'type': 'DYNAMIC'}  # Server type: 'STATIC' or 'DYNAMIC'
        self._server_list.append(new_server)
        logger.debug("Updated servers list (%s servers): %s" %
                     (len(self._server_list), self._server_list))
900441
function Server(config) {
        RED.nodes.createNode(this, config);

        // Start a DLPA server.
        // Options:
        //   --port PORT           Listening port number.
        //   --clients CLIENTS     The number of clicents.
        //   --max-workers MAX_WORKERS
        //                         The maximum number of workiers (default: 10).
        const proc = spawn("python3", [
            "-m", "dlpa.server",
            "--port", config.port,
            "--clients", config.nclient,
            "--key-length", "128",
            "--time-span", config.span ? config.span : "300"
        ], {
            cwd: __dirname,
        });
        let exited = false;
        proc.on("exit", (code, signal) => {
            this.log(`DLPA server is closed: ${signal}`);
            exited = true;
        })
        const logger = readline.createInterface({
            input: proc.stderr
        });
        logger.on("line", (line) => {
            this.log(line);
        })

        // Wait results which should be outputted into stderr; and then
        // post a message based on each output.
        const rl = readline.createInterface({
            input: proc.stdout
        });
        rl.on("line", (line) => {
            const payload = JSON.parse(line);
            this.send({
                "topic": config.topic,
                "payload": matrix(
                    parseInt(config.rows, 10),
                    parseInt(config.columns, 10),
                    payload.value.map(v => (v / MAG) - MAG))
            });
        });

        // Stop the server.
        this.on("close", (done) => {
            if (exited) {
                done();
                return;
            }

            // Wait the server is closed.
            proc.on("exit", () => {
                done();
            });

            // Send a signal.
            this.log("DLPA server is closing");
            proc.stdin.close();
            rl.close();
            logger.close();
            proc.kill();

        });

    }
1191400
def __make_server(self):
        ""
        notice('Making server, getting listening socket', self.color)
        self.mode = 's'
        sock = utils.get_server_sock()
        self.__s = sock
        with self.__client_list_lock:
            self.clients = deque()
        self.threads = deque()
        notice('Making beacon', self.color)
        b = Thread(target=self.__beacon_thread, name='beacon')
        b.start()
        self.threads.append(b)
        l = Thread(target=self.__listen_thread, name='listen')
        notice('Starting listen thread', self.color)
        l.start()
        self.threads.append(l)
210212
def CreateServer(frontend=None):
  """"""
  max_port = config.CONFIG.Get("Frontend.port_max",
                               config.CONFIG["Frontend.bind_port"])

  for port in range(config.CONFIG["Frontend.bind_port"], max_port + 1):

    server_address = (config.CONFIG["Frontend.bind_address"], port)
    try:
      httpd = GRRHTTPServer(
          server_address, GRRHTTPServerHandler, frontend=frontend)
      break
    except socket.error as e:
      if e.errno == socket.errno.EADDRINUSE and port < max_port:
        logging.info("Port %s in use, trying %s", port, port + 1)
      else:
        raise

  sa = httpd.socket.getsockname()
  logging.info("Serving HTTP on %s port %d ...", sa[0], sa[1])
  return httpd