detect whether a url is a Service type that HHypermap supports
969014
def detect_metadata_url_scheme(url):
    """"""

    scheme = None
    url_lower = url.lower()

    if any(x in url_lower for x in ['wms', 'service=wms']):
        scheme = 'OGC:WMS'
    if any(x in url_lower for x in ['wmts', 'service=wmts']):
        scheme = 'OGC:WMTS'
    elif all(x in url for x in ['/MapServer', 'f=json']):
        scheme = 'ESRI:ArcGIS:MapServer'
    elif all(x in url for x in ['/ImageServer', 'f=json']):
        scheme = 'ESRI:ArcGIS:ImageServer'

    return scheme
848543
def is_json(mimetype):
    
    if not mimetype:
        return False
    if ";" in mimetype:  # Allow Content-Type header to be passed
        mimetype = get_mimetype(mimetype)
    if mimetype == "application/json":
        return True
    if mimetype.startswith("application/") and mimetype.endswith("+json"):
        return True
    return False
171343
def is_url_for(cls, _action, _endpoint=None, _app=None, _external=None, **paramattrs):
        
        def decorator(f):
            if 'url_for_endpoints' not in cls.__dict__:
                cls.url_for_endpoints = {None: {}}  # Stick it into the class with the first endpoint
            cls.url_for_endpoints.setdefault(_app, {})

            for keyword in paramattrs:
                if isinstance(paramattrs[keyword], six.string_types) and '.' in paramattrs[keyword]:
                    paramattrs[keyword] = tuple(paramattrs[keyword].split('.'))
            cls.url_for_endpoints[_app][_action] = _endpoint or f.__name__, paramattrs, _external
            return f
        return decorator
797285
public boolean hasValidKey(HttpRequestHeader reqHeader, JSONObject params) {
		try {
			String apiPath;
			try {
				apiPath = reqHeader.getURI().getPath();
			} catch (URIException e) {
				logger.error(e.getMessage(), e);
				return false;
			}
			String nonceParam = reqHeader.getHeader(HttpHeader.X_ZAP_API_NONCE);
			if (nonceParam == null && params.has(API_NONCE_PARAM)) {
				nonceParam = params.getString(API_NONCE_PARAM);
			}
			
			if (nonceParam != null) {
				Nonce nonce = nonces.get(nonceParam);
				if (nonce == null) {
					logger.warn("API nonce " + nonceParam + " not found in request from " + reqHeader.getSenderAddress().getHostAddress());
					return false;
				} else if (nonce.isOneTime()) {
					nonces.remove(nonceParam);
				}
				if (! nonce.isValid()) {
					logger.warn("API nonce " + nonce.getNonceKey() + " expired at " + nonce.getExpires().toString() +
							" in request from " + reqHeader.getSenderAddress().getHostAddress());
					return false;
				}
				
				if (! apiPath.equals(nonce.getApiPath())) {
					logger.warn("API nonce path was " + nonce.getApiPath() + " but call was for " + apiPath + 
						" in request from " + reqHeader.getSenderAddress().getHostAddress());
					return false;
				}
			} else {
				String keyParam = reqHeader.getHeader(HttpHeader.X_ZAP_API_KEY);
				if (keyParam == null && params.has(API_KEY_PARAM)) {
					keyParam = params.getString(API_KEY_PARAM);
				}
				if (!getOptionsParamApi().getKey().equals(keyParam)) {
					logger.warn("API key incorrect or not supplied: " + keyParam +
							" in request from " + reqHeader.getSenderAddress().getHostAddress());
					return false;
				}
			}
			
			return true;
		} finally {
			synchronized (nonces) {
				for (Entry<String, Nonce> entry : nonces.entrySet()) {
					if (! entry.getValue().isValid()) {
						nonces.remove(entry.getKey());
					}
				}
			}
		}
	}
482473
def _get_content_type(url):
        """"""
        scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
        if not scheme in ('http', 'https', 'ftp', 'ftps'):
            ## FIXME: some warning or something?
            ## assertion error?
            return ''
        req = Urllib2HeadRequest(url, headers={'Host': netloc})
        resp = urlopen(req)
        try:
            if hasattr(resp, 'code') and resp.code != 200 and scheme not in ('ftp', 'ftps'):
                ## FIXME: doesn't handle redirects
                return ''
            return resp.info().get('content-type', '')
        finally:
            resp.close()
644626
private boolean checkRequestHeaders(HeaderMap headers) {
        // :method pseudo-header must be present always exactly one time;
        // HTTP2 request MUST NOT contain 'connection' header
        if (headers.count(METHOD) != 1 || headers.contains(Headers.CONNECTION)) {
            return false;
        }

        // if CONNECT type is used, then we expect :method and :authority to be present only;
        // :scheme and :path must not be present
        if (headers.get(METHOD).contains(Methods.CONNECT_STRING)) {
            if (headers.contains(SCHEME) || headers.contains(PATH) || headers.count(AUTHORITY) != 1) {
                return false;
            }
        // For other HTTP methods we expect that :scheme, :method, and :path pseudo-headers are
        // present exactly one time.
        } else if (headers.count(SCHEME) != 1 || headers.count(PATH) != 1) {
            return false;
        }

        // HTTP2 request MAY contain TE header but if so, then only with 'trailers' value.
        if (headers.contains(Headers.TE)) {
            for (String value : headers.get(Headers.TE)) {
                if (!value.equals("trailers")) {
                    return false;
                }
            }
        }

        return true;
    }
1053025
def identify_hosting_service(repo_url, hosting_services=HOSTING_SERVICES):
    
    repo_url = unicode(repo_url)

    for service in hosting_services:
        if service in repo_url:
            return service

    raise UnknownHostingService
506553
public static Service identify(String url) {
    Service answer = Service.UNSUPPORTED;
    int index = url.indexOf(COMPOSUM_URL);
    if (index > 0) {
      answer = Service.COMPOSUM;
    }
    else {
      index = url.indexOf(CRX_URL);
      if (index > 0) {
        answer = Service.CRX;
      }
    }
    return answer;
  }
1095501
def identify(self, req, resp, resource, uri_kwargs):
        """"""
        try:
            return req.get_header('X-Api-Key', True)
        except (KeyError, HTTPMissingHeader):
            pass
373991
def has_service_of_type(self, service_type):
        
        summary = self.get_space_summary()
        for instance in summary['services']:
            if 'service_plan' in instance:
                if service_type == instance['service_plan']['service']['label']:
                    return True

        return False
176883
function isDataTagForUniversalLinks(data) {
  // can have only 1 data tag in the intent-filter
  if (data == null || data.length != 1) {
    return false;
  }

  var dataHost = data[0]['$']['android:host'];
  var dataScheme = data[0]['$']['android:scheme'];
  var hostIsSet = dataHost != null && dataHost.length > 0;
  var schemeIsSet = dataScheme != null && dataScheme.length > 0;

  return hostIsSet && schemeIsSet;
}
677181
def get_service_url(region, endpoint_list, lookup):
    

    for endpoint in endpoint_list:
        region_get = endpoint.get('region', '')
        if region.lower() == region_get.lower():
            return http.parse_url(url=endpoint.get(lookup))
    else:
        raise exceptions.AuthenticationProblem(
            'Region "%s" was not found in your Service Catalog.',
            region
        )
573475
def api_url(self):
        ''''''
        return pathjoin(Bin.path, self.name, url=self.service.url)
183989
private static ServiceType serviceTypeFor(final CouchbaseRequest request) {
        if (request instanceof BinaryRequest) {
            return ServiceType.BINARY;
        } else if (request instanceof ConfigRequest) {
            return ServiceType.CONFIG;
        } else if (request instanceof ViewRequest) {
            return ServiceType.VIEW;
        } else if (request instanceof QueryRequest) {
            return ServiceType.QUERY;
        } else if (request instanceof SearchRequest) {
            return ServiceType.SEARCH;
        } else if (request instanceof AnalyticsRequest) {
            return ServiceType.ANALYTICS;
        } else {
            throw new IllegalStateException("Unknown Request: " + request);
        }
    }
901639
def validate_v2_endpoint_data(self, endpoints, admin_port, internal_port,
                                  public_port, expected):
        
        self.log.debug('Validating endpoint data...')
        self.log.debug('actual: {}'.format(repr(endpoints)))
        found = False
        for ep in endpoints:
            self.log.debug('endpoint: {}'.format(repr(ep)))
            if (admin_port in ep.adminurl and
                    internal_port in ep.internalurl and
                    public_port in ep.publicurl):
                found = True
                actual = {'id': ep.id,
                          'region': ep.region,
                          'adminurl': ep.adminurl,
                          'internalurl': ep.internalurl,
                          'publicurl': ep.publicurl,
                          'service_id': ep.service_id}
                ret = self._validate_dict_data(expected, actual)
                if ret:
                    return 'unexpected endpoint data - {}'.format(ret)

        if not found:
            return 'endpoint not found'
577762
def uri_tree_precode_check(uri_tree, type_host = HOST_REG_NAME):
    
    scheme, authority, path, query, fragment = uri_tree # pylint: disable-msg=W0612
    if scheme:
        if not valid_scheme(scheme):
            raise InvalidSchemeError, "Invalid scheme %r" % (scheme,)
    if authority:
        user, passwd, host, port = authority # pylint: disable-msg=W0612
        if port and not __all_in(port, DIGIT):
            raise InvalidPortError, "Invalid port %r" % (port,)
        if type_host == HOST_IP_LITERAL:
            if host and (not __valid_IPLiteral(host)):
                raise InvalidIPLiteralError, "Invalid IP-literal %r" % (host,)
        elif type_host == HOST_IPV4_ADDRESS:
            if host and (not __valid_IPv4address(host)):
                raise InvalidIPv4addressError, "Invalid IPv4address %r" % (host,)
    if path:
        if authority and path[0] != '/':
            raise InvalidPathError, "Invalid path %r - non-absolute path can't be used with an authority" % (path,)
    return uri_tree
446833
def GetRequestFormatMode(request, method_metadata):
  """"""
  if request.path.startswith("/api/v2/"):
    return JsonMode.PROTO3_JSON_MODE

  if request.args.get("strip_type_info", ""):
    return JsonMode.GRR_TYPE_STRIPPED_JSON_MODE

  for http_method, unused_url, options in method_metadata.http_methods:
    if (http_method == request.method and
        options.get("strip_root_types", False)):
      return JsonMode.GRR_ROOT_TYPES_STRIPPED_JSON_MODE

  return JsonMode.GRR_JSON_MODE