factory function that returns a proxy object for an owserver at
    host, port.
777588
def proxy(host='localhost', port=4304, flags=0, persistent=False,
          verbose=False, ):
    

    # resolve host name/port
    try:
        gai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM,
                                 socket.IPPROTO_TCP)
    except socket.gaierror as err:
        raise ConnError(*err.args)

    # gai is a (non empty) list of tuples, search for the first working one
    assert gai
    for (family, _type, _proto, _, sockaddr) in gai:
        assert _type is socket.SOCK_STREAM and _proto is socket.IPPROTO_TCP
        owp = _Proxy(family, sockaddr, flags, verbose)
        try:
            # check if there is an owserver listening
            owp.ping()
        except ConnError as err:
            # no connection, go over to next sockaddr
            lasterr = err.args
            continue
        else:
            # ok, live owserver found, stop searching
            break
    else:
        # no server listening on (family, sockaddr) found:
        raise ConnError(*lasterr)

    # init errno to errmessage mapping
    # FIXME: should this be only optional?
    owp._init_errcodes()

    if persistent:
        owp = clone(owp, persistent=True)

    # here we should have all connections closed
    assert not isinstance(owp, _PersistentProxy) or owp.conn is None

    return owp
1371028
def factory(cls, endpoint, timeout, *args, **kwargs):
        
        start = time.time()
        kwargs['connect_timeout'] = timeout
        conn = cls(endpoint, *args, **kwargs)
        elapsed = time.time() - start
        conn.connected_event.wait(timeout - elapsed)
        if conn.last_error:
            if conn.is_unsupported_proto_version:
                raise ProtocolVersionUnsupported(endpoint, conn.protocol_version)
            raise conn.last_error
        elif not conn.connected_event.is_set():
            conn.close()
            raise OperationTimedOut("Timed out creating connection (%s seconds)" % timeout)
        else:
            return conn
776973
def _make_serverproxy_handler(name, command, environment, timeout, absolute_url, port):
    
    # FIXME: Set 'name' properly
    class _Proxy(SuperviseAndProxyHandler):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.name = name
            self.proxy_base = name
            self.absolute_url = absolute_url
            self.requested_port = port

        @property
        def process_args(self):
            return {
                'port': self.port,
                'base_url': self.base_url,
            }

        def _render_template(self, value):
            args = self.process_args
            if type(value) is str:
                return value.format(**args)
            elif type(value) is list:
                return [self._render_template(v) for v in value]
            elif type(value) is dict:
                return {
                    self._render_template(k): self._render_template(v)
                    for k, v in value.items()
                }
            else:
                raise ValueError('Value of unrecognized type {}'.format(type(value)))

        def get_cmd(self):
            if callable(command):
                return self._render_template(call_with_asked_args(command, self.process_args))
            else:
                return self._render_template(command)

        def get_env(self):
            if callable(environment):
                return self._render_template(call_with_asked_args(environment, self.process_args))
            else:
                return self._render_template(environment)

        def get_timeout(self):
            return timeout

    return _Proxy
124625
def web(host, port):
    """"""
    from .webserver.web import get_app
    get_app().run(host=host, port=port)
203324
function (host, port, onError) {
	
	var proxy = undefined;
	
	var options = {target: 'ws://' + host, ws: true};
	LOG.warn('create new ws proxy at port: ' + port + ' options: ', 'SR.Proxy');
	LOG.warn(options, 'SR.Proxy');
	
	proxy = httpProxy.createServer(options);
		
	// install error handler (NOTE: very imporant for stability)
	proxy.on('error', function (err, req, res) {
		UTIL.safeCall(onError, err);
	});
	
	// be notified when closed
	// ref: https://github.com/nodejitsu/node-http-proxy
	proxy.on('close', function (req, socket, head) {
  		// view disconnected websocket connections
  		console.log('Client disconnected');
	});	

	// store proxy for later uses
	// NOTE: not used directly
	l_proxies[host] = proxy;

	// record local port for future references
	// NOTE: this is an important step for future queries of the proxy
	// and may need to be performed before setting the on('xx') handler(s) 
	// BUG: seems like 'local_port' info will disappear under certain circumstances
	// (after entries are shutdown & restart many times)
	l_proxies[host].local_port = port;
		
	// start to listen for requests	
	// NOTE: listen may fail or cause errors that could trigger this proxy be removed from list
	proxy.listen(port);	

	return proxy;
	
	/* 2nd version
	proxy = httpProxy.createProxyServer(options);
	
	proxy.on('error', function (e) {
		UTIL.safeCall(onError, e);
	});
	
	// start a new HTTP server just for websocket connections
	var proxyServer = http.createServer(function (req, res) {
		LOG.warn('incoming request to standalone HTTP ws proxy', 'SR.Proxy');
		proxy.web(req, res);
	});

	//
	// Listen to the `upgrade` event and proxy the
	// WebSocket requests as well.
	//
	proxyServer.on('upgrade', function (req, socket, head) {
		try {
			proxy.ws(req, socket, head);
		}
	    catch (e) {
			LOG.error('websocket error:', 'SR.Proxy');
			LOG.error(e, 'SR.Proxy');
		}
			
	});

	// TODO: may need to provide a unique port for it
	// TODO: record this http server?
	LOG.warn('starting ws proxy at port: ' + port, 'SR.Proxy');
	proxyServer.listen(port);
	
	return proxy;
	*/
}
831810
def make_server(
        server_class, handler_class, authorizer_class, filesystem_class,
        host_port, file_access_user=None, **handler_options):
    
    from . import compat
    if isinstance(handler_class, compat.string_type):
        handler_class = import_class(handler_class)

    if isinstance(authorizer_class, compat.string_type):
        authorizer_class = import_class(authorizer_class)

    if isinstance(filesystem_class, compat.string_type):
        filesystem_class = import_class(filesystem_class)

    authorizer = authorizer_class(file_access_user)
    handler = handler_class
    for key, value in handler_options.items():
        setattr(handler, key, value)
    handler.authorizer = authorizer
    if filesystem_class is not None:
        handler.abstracted_fs = filesystem_class
    return server_class(host_port, handler)
1250754
def instance(host=None, port=None):
        

        if not hasattr(WebServer, "_instance") or WebServer._instance is None:
            assert host is not None
            assert port is not None
            WebServer._instance = WebServer(host, port)
        return WebServer._instance
908742
def proxy(request):
    """"""

    # TODO: don't hardcode http
    uri = "http://" + HOST + request.META['PATH_INFO']
    if request.META['QUERY_STRING']:
        uri += '?' + request.META['QUERY_STRING']

    headers = {}
    for name, val in six.iteritems(request.environ):
        if name.startswith('HTTP_'):
            name = header_name(name)
            headers[name] = val

    # TODO: try/except
    http = Http()
    http.follow_redirects = False
    logger.debug("GET for: %s" % uri)
    info, content = http.request(uri, 'GET', headers=headers)
    response = HttpResponse(content, status=info.pop('status'))

    for name, val in info.items():
        if not is_hop_by_hop(name):
            response[name] = val
    logger.info("PROXY to: %s" % uri)
    return response
752119
def get_environ_proxies():
    """"""

    proxy_keys = [
        'all',
        'http',
        'https',
        'ftp',
        'socks',
        'ws',
        'wss',
        'no'
    ]

    def get_proxy(k):
        return os.environ.get(k) or os.environ.get(k.upper())

    proxies = [(key, get_proxy(key + '_proxy')) for key in proxy_keys]
    return dict([(key, val) for (key, val) in proxies if val])
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
437847
function createServer(port, f) {
  f = f || noop;
  http.createServer(handler).listen(port, f);
  return statusHelper.changeStatus;
}
992854
def proxy_it(request, port):
    """"""

    # Check if we have websocket proxy configured
    websocket_proxy = request.registry.settings.get("pyramid_notebook.websocket_proxy", "")
    if websocket_proxy.strip():
        r = DottedNameResolver()
        websocket_proxy = r.maybe_resolve(websocket_proxy)

    if "upgrade" in request.headers.get("connection", "").lower():
        if websocket_proxy:
            return websocket_proxy(request, port)
        else:
            # If we run on localhost on pserve, we should never hit here as requests go directly to IPython Notebook kernel, not us
            raise RuntimeError("Websocket proxy support is not configured.")

    proxy_app = WSGIProxyApplication(port)

    return request.get_response(proxy_app)
771356
def get_proxy():
    """"""
    proxies = _config['proxies']

    return proxies[
        random.randint(0, len(proxies) - 1)
    ] if len(proxies) > 0 else None
1032031
private Proxy lookupProxy(String hostKey, String portKey, Proxy.Type type, int defaultPort) {
        String host = System.getProperty(hostKey);
        if (host == null || host.isEmpty()) {
            return null;
        }

        int port = getSystemPropertyInt(portKey, defaultPort);
        return new Proxy(type, InetSocketAddress.createUnresolved(host, port));
    }
1294433
def wsgi_proxyfix(factory=None):
    
    def create_wsgi(app, **kwargs):
        wsgi_app = factory(app, **kwargs) if factory else app.wsgi_app
        if app.config.get('WSGI_PROXIES'):
            return ProxyFix(wsgi_app, num_proxies=app.config['WSGI_PROXIES'])
        return wsgi_app
    return create_wsgi
921406
function getPort (port, callback) {
  const server = net.createServer()

  server.on('error', () => {
    getPort(++port, callback)
  })

  // Explicitly listen on 0.0.0.0 to detect ports used by Docker
  // See: https://github.com/nodejs/node/issues/14034
  server.listen(port, '0.0.0.0', () => {
    server.once('close', () => {
      callback(port)
    })
    server.close()
  })
}
85185
def weakref_proxy(obj):
    """"""
    if type(obj) in weakref.ProxyTypes:
        return obj
    else:
        return weakref.proxy(obj)