Sorts a list of servers by http round-trip time

    Params:
        servers: sequence of http server urls
    Returns:
        sequence of pairs of url,rtt in seconds, sorted by rtt, excluding failed servers
        (possibly empty)
519652
def sort_servers_closest(servers: Sequence[str]) -> Sequence[Tuple[str, float]]:
    
    if not {urlparse(url).scheme for url in servers}.issubset({'http', 'https'}):
        raise TransportError('Invalid server urls')

    get_rtt_jobs = set(
        gevent.spawn(lambda url: (url, get_http_rtt(url)), server_url)
        for server_url
        in servers
    )
    # these tasks should never raise, returns None on errors
    gevent.joinall(get_rtt_jobs, raise_error=False)  # block and wait tasks
    sorted_servers: List[Tuple[str, float]] = sorted(
        (job.value for job in get_rtt_jobs if job.value[1] is not None),
        key=itemgetter(1),
    )
    log.debug('Matrix homeserver RTT times', rtt_times=sorted_servers)
    return sorted_servers
1253087
def _async_requests(urls):
    
    session = FuturesSession(max_workers=30)
    futures = [
        session.get(url)
        for url in urls
    ]
    return [ future.result() for future in futures ]
573797
def _sort_to_str(self):
        

        params_list = []
        timestamp = ""

        for k, v in self._solr_params['sort'].items():
            if k != "timestamp":
                params_list.append(" ".join([k, v]))
            else:
                timestamp = v

        params_list.append(" ".join(['timestamp', timestamp]))

        self._solr_params['sort'] = ", ".join(params_list)
1108386
def end_time(self):
        
        resource_list = self.traffic_incident()
        end_time = namedtuple('end_time', 'end_time')
        if len(resource_list) == 1 and resource_list[0] is None:
            return None
        else:
            try:
                return [end_time(resource['end'])
                        for resource in resource_list]
            except (KeyError, TypeError):
                return [end_time(resource['EndTimeUTC'])
                        for resource in resource_list]
1249209
def servers(self, server='api.telldus.com', port=http.HTTPS_PORT):
        
        logging.debug("Fetching server list from %s:%d", server, port)

        conn = http.HTTPSConnection(server, port, context=self.ssl_context())
        conn.request('GET', "/server/assign?protocolVersion=2")

        response = conn.getresponse()
        if response.status != http.OK:
            raise RuntimeError("Could not connect to {}:{}: {} {}".format(
                server, port, response.status, response.reason))

        servers = []

        def extract_servers(name, attributes):
            if name == "server":
                servers.append((attributes['address'],
                                int(attributes['port'])))

        parser = expat.ParserCreate()
        parser.StartElementHandler = extract_servers
        parser.ParseFile(response)

        logging.debug("Found %d available servers", len(servers))
        return servers
1369627
private List<T> randomChoose(List<T> servers, int toChoose) {
        int size = servers.size();
        if (toChoose >= size || toChoose < 0) {
            return servers;
        } 
        for (int i = 0; i < toChoose; i++) {
            int index = random.nextInt(size);
            T tmp = servers.get(index);
            servers.set(index, servers.get(i));
            servers.set(i, tmp);
        }
        return servers.subList(0, toChoose);        
    }
732301
def servers(self):
        """"""
        url = "%s/servers" % self.root
        return Servers(url=url,
                       securityHandler=self._securityHandler,
                       proxy_url=self._proxy_url,
                       proxy_port=self._proxy_port)
192551
function filterAndSortAvailableServers (serverArray) {
        var copyOfServerArray = JSON.parse(JSON.stringify(serverArray));
        copyOfServerArray.sort(function (itemOne, itemTwo) {
            return sortValue(itemOne) - sortValue(itemTwo);
        });

        // Filter servers we've too-recently disconnected from
        return copyOfServerArray.filter(haveNotDisconnectedFromRecently);
    }
1352453
def _clean_servers(self):
        
        if len(self._telnet_servers) > 0:
            for telnet_server in self._telnet_servers:
                telnet_server.close()
                yield from telnet_server.wait_closed()
            self._telnet_servers = []
510491
def url_permutations(url):
        
        def url_host_permutations(host):
            if re.match(r'\d+\.\d+\.\d+\.\d+', host):
                yield host
                return
            parts = host.split('.')
            l = min(len(parts), 5)
            if l > 4:
                yield host
            for i in range(l - 1):
                yield '.'.join(parts[i - l:])

        def url_path_permutations(path):
            yield path
            query = None
            if '?' in path:
                path, query = path.split('?', 1)
            if query is not None:
                yield path
            path_parts = path.split('/')[0:-1]
            curr_path = ''
            for i in range(min(4, len(path_parts))):
                curr_path = curr_path + path_parts[i] + '/'
                yield curr_path

        protocol, address_str = urllib.splittype(url)
        host, path = urllib.splithost(address_str)
        user, host = urllib.splituser(host)
        host, port = urllib.splitport(host)
        host = host.strip('/')
        seen_permutations = set()
        for h in url_host_permutations(host):
            for p in url_path_permutations(path):
                u = '{}{}'.format(h, p)
                if u not in seen_permutations:
                    yield u
                    seen_permutations.add(u)
1007751
def get_list(
        self,
        search='',
        start=0,
        limit=0,
        order_by='',
        order_by_dir='ASC',
        published_only=False,
        minimal=False
    ):
        

        parameters = {}
        args = ['search', 'start', 'limit', 'minimal']
        for arg in args:
            if arg in locals() and locals()[arg]:
                parameters[arg] = locals()[arg]
        if order_by:
            parameters['orderBy'] = order_by
        if order_by_dir:
            parameters['orderByDir'] = order_by_dir
        if published_only:
            parameters['publishedOnly'] = 'true'
        response = self._client.session.get(
            self.endpoint_url, params=parameters
        )
        return self.process_response(response)
497549
async def asynchronous(urls=None, re_filter=None):
    
    class _URLBase(str):
        """ Convenient access to hostname (ip) portion of the URL """
        @property
        def hostname(self):
            return urlsplit(self).hostname

    http_devices = {}
    qualified_devices = []
    connection = aiohttp.TCPConnector(limit=0)
    async with aiohttp.ClientSession(connector=connection, 
        conn_timeout=5, raise_for_status=True) as session:
        
        futures = [fetch_page(session, url) for url in urls]

        for future in asyncio.as_completed(futures):
            response = await future
            if 'found' in response[1]:
                http_devices[response[0]] = response[2]
                logger.debug('Processed %s', response[0])
                if re_filter.search(response[2]):
                    qualified_devices.append(_URLBase(response[0]))

    # print('The following responded to HTTP:')
    # for x in http_devices.keys():
    #     print(x)

    return qualified_devices
599760
def _get_sorted(self, resources):
        
        tmp = []
        for resource in resources:
            path = resource._path
            # Each slash counts as 10 priority, each variable takes one away
            priority = path.count('/') * 10 - path.count('{')
            tmp.append((priority, resource))
        return [resource for prio, resource in reversed(sorted(tmp))]
1212583
public List<ThriftServerInfo> getThriftServers() {
		List<ThriftServerInfo> servers = new ArrayList<>();
		servers.addAll(thriftServers);
		return servers;
	}
1306257
def Servers(self):
		

		return(clc.v2.Servers(
			alias=self.alias,
			servers_lst=[obj['id'] for obj in self.data['links'] if obj['rel']=='server'],
			session=self.session))
363911
def _get_server(self):
        
        with self._lock:
            inactive_server_count = len(self._inactive_servers)
            for i in range(inactive_server_count):
                try:
                    ts, server, message = heapq.heappop(self._inactive_servers)
                except IndexError:
                    pass
                else:
                    if (ts + self.retry_interval) > time():
                        # Not yet, put it back
                        heapq.heappush(self._inactive_servers,
                                       (ts, server, message))
                    else:
                        self._active_servers.append(server)
                        logger.warn("Restored server %s into active pool",
                                    server)

            # if none is old enough, use oldest
            if not self._active_servers:
                ts, server, message = heapq.heappop(self._inactive_servers)
                self._active_servers.append(server)
                logger.info("Restored server %s into active pool", server)

            server = self._active_servers[0]
            self._roundrobin()

            return server
861408
def _serve_runs(self, request):
    
    if self._db_connection_provider:
      db = self._db_connection_provider()
      cursor = db.execute('''
        SELECT
          run_name,
          started_time IS NULL as started_time_nulls_last,
          started_time
        FROM Runs
        ORDER BY started_time_nulls_last, started_time, run_name
      ''')
      run_names = [row[0] for row in cursor]
    else:
      # Python's list.sort is stable, so to order by started time and
      # then by name, we can just do the sorts in the reverse order.
      run_names = sorted(self._multiplexer.Runs())
      def get_first_event_timestamp(run_name):
        try:
          return self._multiplexer.FirstEventTimestamp(run_name)
        except ValueError as e:
          logger.warn(
              'Unable to get first event timestamp for run %s: %s', run_name, e)
          # Put runs without a timestamp at the end.
          return float('inf')
      run_names.sort(key=get_first_event_timestamp)
    return http_util.Respond(request, run_names, 'application/json')