If a cdx_server is available, return response from server,
        otherwise empty list
773110
def load_cdx_for_dupe(self, url, timestamp, digest, cdx_loader):
        
        if not cdx_loader:
            return iter([])

        filters = []

        filters.append('!mime:warc/revisit')

        if digest and digest != '-':
            filters.append('digest:' + digest)

        params = dict(url=url,
                      closest=timestamp,
                      filter=filters)

        return cdx_loader(params)
901604
def get_server_alerts(call=None, for_output=True, **kwargs):
    '''
    
    '''
    for key, value in kwargs.items():
        servername = ""
        if key == "servername":
            servername = value
    creds = get_creds()
    clc.v2.SetCredentials(creds["user"], creds["password"])
    alerts = clc.v2.Server(servername).Alerts()
    return alerts
364290
def get_load(jid):
    '''
    
    '''
    serv = _get_serv(ret=None)
    sql = "select load from jids where jid = '{0}'".format(jid)

    log.debug(">> Now in get_load %s", jid)
    data = serv.query(sql)
    log.debug(">> Now Data: %s", data)
    if data:
        return data
    return {}
289152
function (url, method, cb) {

            request({
                url: url,
                method: method
            }, function (error, response, body) {

                if (error) {
                    return cb(error);
                }

                if (response.statusCode == 200 || response.statusCode == 201) {

                    return cb(null, body);

                } else {

                    return cb(new Error('Server responded with error: ' + response.statusCode));

                }

            })

        }
1009961
async def _query(
        self,
        path,
        method="GET",
        *,
        params=None,
        data=None,
        headers=None,
        timeout=None,
        chunked=None
    ):
        
        url = self._canonicalize_url(path)
        if headers and "content-type" not in headers:
            headers["content-type"] = "application/json"
        try:
            response = await self.session.request(
                method,
                url,
                params=httpize(params),
                headers=headers,
                data=data,
                timeout=timeout,
                chunked=chunked,
            )
        except asyncio.TimeoutError:
            raise
        if (response.status // 100) in [4, 5]:
            what = await response.read()
            content_type = response.headers.get("content-type", "")
            response.close()
            if content_type == "application/json":
                raise DockerError(response.status, json.loads(what.decode("utf8")))
            else:
                raise DockerError(response.status, {"message": what.decode("utf8")})
        return response
1264309
def parse_response(self, connection, command_name, **options):
        ""
        try:
            response = connection.read_response()
        except ResponseError:
            if EMPTY_RESPONSE in options:
                return options[EMPTY_RESPONSE]
            raise
        if command_name in self.response_callbacks:
            return self.response_callbacks[command_name](response, **options)
        return response
14692
def build_response(cls, code=Status.SYSTEM_ERROR, errors=None):
        
        errors = [errors] if not isinstance(errors, list) else errors
        return cls(code, errors)
993363
def get_server_session(self):
        """"""
        with self._lock:
            session_timeout = self._description.logical_session_timeout_minutes
            if session_timeout is None:
                # Maybe we need an initial scan? Can raise ServerSelectionError.
                if self._description.topology_type == TOPOLOGY_TYPE.Single:
                    if not self._description.has_known_servers:
                        self._select_servers_loop(
                            any_server_selector,
                            self._settings.server_selection_timeout,
                            None)
                elif not self._description.readable_servers:
                    self._select_servers_loop(
                        readable_server_selector,
                        self._settings.server_selection_timeout,
                        None)

            session_timeout = self._description.logical_session_timeout_minutes
            if session_timeout is None:
                raise ConfigurationError(
                    "Sessions are not supported by this MongoDB deployment")

            return self._session_pool.get_server_session(session_timeout)
1037170
def is_available(self):
        
        # if the availability flag is raised, return True immediately.
        # NOTE: subsequent API failures will lower this flag. we do this here
        # to ensure we don't keep hitting Joe with requests while availability
        # is there.
        if self.server_available:
            return True

        # otherwise, we have to check with the cloud.
        else:

            try:
                self.server_available = self.jbx.server_online()
                return self.server_available
            except jbxapi.JoeException:
                pass

        self.server_available = False
        return False
716212
def _check_available(name):
    '''
    
    '''
    _status = _systemctl_status(name)
    sd_version = salt.utils.systemd.version(__context__)
    if sd_version is not None and sd_version >= 231:
        # systemd 231 changed the output of "systemctl status" for unknown
        # services, and also made it return an exit status of 4. If we are on
        # a new enough version, check the retcode, otherwise fall back to
        # parsing the "systemctl status" output.
        # See: https://github.com/systemd/systemd/pull/3385
        # Also: https://github.com/systemd/systemd/commit/3dced37
        return 0 <= _status['retcode'] < 4

    out = _status['stdout'].lower()
    if 'could not be found' in out:
        # Catch cases where the systemd version is < 231 but the return code
        # and output changes have been backported (e.g. RHEL 7.3).
        return False

    for line in salt.utils.itertools.split(out, '\n'):
        match = re.match(r'\s+loaded:\s+(\S+)', line)
        if match:
            ret = match.group(1) != 'not-found'
            break
    else:
        raise CommandExecutionError(
            'Failed to get information on unit \'%s\'' % name
        )
    return ret
71630
def status(self):
        """"""
        try:
            # -- Check client
            res = self.run(['info'])
            if res[0]['clientName'] == '*unknown*':
                return ConnectionStatus.INVALID_CLIENT
            # -- Trigger an auth error if not logged in
            self.run(['user', '-o'])
        except errors.CommandError as err:
            if 'password (P4PASSWD) invalid or unset' in str(err.args[0]):
                return ConnectionStatus.NO_AUTH
            if 'Connect to server failed' in str(err.args[0]):
                return ConnectionStatus.OFFLINE

        return ConnectionStatus.OK
830889
def has_known_servers(self):
        """"""
        return any(s for s in self._server_descriptions.values()
                   if s.is_server_type_known)
245546
def parse_response(self, response, command_list):
        '''
        
        '''
        # Check for 500 level NX-API Server Errors
        if isinstance(response, collections.Iterable) and 'status' in response:
            if int(response['status']) >= 500:
                raise NxosError('{}'.format(response))
            else:
                raise NxosError('NX-API Request Not Supported: {}'.format(response))

        if isinstance(response, collections.Iterable):
            body = response['dict']
        else:
            body = response

        if self.nxargs['connect_over_uds']:
            body = json.loads(response.read().decode('utf-8'))

        # Proceed with caution.  The JSON may not be complete.
        # Don't just return body['ins_api']['outputs']['output'] directly.
        output = body.get('ins_api')
        if output is None:
            raise NxosClientError('Unexpected JSON output\n{0}'.format(body))
        if output.get('outputs'):
            output = output['outputs']
        if output.get('output'):
            output = output['output']

        # The result list stores results for each command that was sent to
        # nxapi.
        result = []
        # Keep track of successful commands using previous_commands list so
        # they can be displayed if a specific command fails in a chain of
        # commands.
        previous_commands = []

        # Make sure output and command_list lists to be processed in the
        # subesequent loop.
        if not isinstance(output, list):
            output = [output]
        if isinstance(command_list, string_types):
            command_list = [cmd.strip() for cmd in command_list.split(';')]
        if not isinstance(command_list, list):
            command_list = [command_list]

        for cmd_result, cmd in zip(output, command_list):
            code = cmd_result.get('code')
            msg = cmd_result.get('msg')
            log.info('command %s:', cmd)
            log.info('PARSE_RESPONSE: %s %s', code, msg)
            if code == '400':
                raise CommandExecutionError({
                    'rejected_input': cmd,
                    'code': code,
                    'message': msg,
                    'cli_error': cmd_result.get('clierror'),
                    'previous_commands': previous_commands,
                })
            elif code == '413':
                raise NxosRequestNotSupported('Error 413: {}'.format(msg))
            elif code != '200':
                raise NxosError('Unknown Error: {}, Code: {}'.format(msg, code))
            else:
                previous_commands.append(cmd)
                result.append(cmd_result['body'])

        return result
553977
def success(headers = None, data = ''):
    
    passed_headers = {} if headers is None else headers
    if isinstance(data, dict): data = json.dumps(data)
    ret_headers = {'status' : 'ok'}
    ret_headers.update(passed_headers)
    return server_responce(ret_headers, data)
825430
def cmd_server_load(self):
        
        servers = defaultdict(int)
        for line in self._valid_lines:
            servers[line.server_name] += 1
        return servers
654110
function getServerStatus(cb) {
  async.parallel({
      live: (cb) => {
        request('http://live.albiononline.com/status.txt', (error, response, body) => {
          if(error) {
            return cb(error);
          }
          cb(null, JSON.parse(body.trim()));
        });
      },
      staging: (cb) => {
        request('http://staging.albiononline.com/status.txt', (error, response, body) => {
          if(error) {
            return cb(error);
          }
          cb(null, JSON.parse(body.trim()));
        });
      }
    }, (e, rs) => {
      if(e) {
        return cb(e);
      }

      cb(null, {
        live: {
          status: rs.live.status,
          message: rs.live.message,
        },
        staging: {
          status: rs.staging.status,
          message: rs.staging.message,
        }
      });
    });
}
212455
def _list_available_hosts(self, *args):
        '''  '''

        return [ h for h in self.inventory.list_hosts(*args) if (h not in self.stats.failures) and (h not in self.stats.dark)]