我们从Python开源项目中,提取了以下35个代码示例,用于说明如何使用future.utils.string_types()。
def __init__(self, callback, pass_update_queue=False, pass_job_queue=False, pattern=None, pass_groups=False, pass_groupdict=False, pass_user_data=False, pass_chat_data=False): super(InlineQueryHandler, self).__init__( callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue, pass_user_data=pass_user_data, pass_chat_data=pass_chat_data) if isinstance(pattern, string_types): pattern = re.compile(pattern) self.pattern = pattern self.pass_groups = pass_groups self.pass_groupdict = pass_groupdict
def __init__(self, pattern, callback, pass_groups=False, pass_groupdict=False, pass_update_queue=False, pass_job_queue=False): super(StringRegexHandler, self).__init__( callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue) if isinstance(pattern, string_types): pattern = re.compile(pattern) self.pattern = pattern self.pass_groups = pass_groups self.pass_groupdict = pass_groupdict
def __init__(self, callback, pass_update_queue=False, pass_job_queue=False, pattern=None, pass_groups=False, pass_groupdict=False, pass_user_data=False, pass_chat_data=False): super(CallbackQueryHandler, self).__init__( callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue, pass_user_data=pass_user_data, pass_chat_data=pass_chat_data) if isinstance(pattern, string_types): pattern = re.compile(pattern) self.pattern = pattern self.pass_groups = pass_groups self.pass_groupdict = pass_groupdict
def check_update(self, update): return isinstance(update, string_types) and bool(re.match(self.pattern, update))
def __init__(self, pattern, callback, pass_groups=False, pass_groupdict=False, pass_update_queue=False, pass_job_queue=False, pass_user_data=False, pass_chat_data=False, allow_edited=False, message_updates=True, channel_post_updates=False): super(RegexHandler, self).__init__( callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue, pass_user_data=pass_user_data, pass_chat_data=pass_chat_data) if isinstance(pattern, string_types): pattern = re.compile(pattern) self.pattern = pattern self.pass_groups = pass_groups self.pass_groupdict = pass_groupdict self.allow_edited = allow_edited self.message_updates = message_updates self.channel_post_updates = channel_post_updates
def sub_regions(regions, region): """ Get regions from a list the overlap with another region. :param regions: List of :class:`~GenomicRegion` :param region: :class:`~GenomicRegion` used for overlap calculation """ if isinstance(region, string_types): region = GenomicRegion.from_string(region) sr = [] start_ix = None end_ix = None for i, r in enumerate(regions): if r.chromosome == region.chromosome and r.start <= region.end and r.end >= region.start: if start_ix is None: start_ix = i end_ix = i sr.append(r.copy()) else: if end_ix is not None: break if start_ix is None or end_ix is None: raise ValueError("Region not found in dataset! {}:{}-{}".format(region.chromosome, region.start, region.end)) return sr, start_ix, end_ix
def plot(self, region=None, ax=None, **kwargs): if isinstance(region, string_types): region = GenomicRegion.from_string(region) if ax: self.ax = ax # set genome tick formatter self.ax.xaxis.set_major_formatter(GenomeCoordFormatter(region)) self.ax.xaxis.set_major_locator(GenomeCoordLocator(nbins=5)) self.ax.xaxis.set_minor_locator(MinorGenomeCoordLocator(n=5)) self.ax.set_title(self.title) self._plot(region, **kwargs) self.ax.set_xlim(region.start, region.end) return self.fig, self.ax
def to_version(version): if isinstance(version, six.string_types): return Version(remove_blank(version)) else: return version
def __init__(self, op, version): self.version = to_version(version) if isinstance(op, six.string_types): op = COMPMAP[op] self.op = op
def match(self, version): if self.version.vstring == 'all': return True if not version or not isinstance(version, (six.string_types, Version)): return False version = to_version(version) return self.op(version, self.version)
def __init__(self, conds): if isinstance(conds, CondGroup): self.conds = conds.conds elif isinstance(conds, VersionCond): self.conds = [conds] elif isinstance(conds, six.string_types): self.conds = [VersionCond.from_str(x) for x in conds.split(',')] elif not conds: self.conds = [] else: self.conds = [VersionCond(op, version) for op, version in conds]
def __init__(self, ranges): if isinstance(ranges, six.string_types): self.ranges = [CondGroup(x) for x in ranges.split('|')] elif isinstance(ranges, (list, tuple)): self.ranges = [CondGroup(x) for x in ranges] elif not ranges: self.ranges = [] else: raise TypeError('unknown ranges type')
def should_skip(self, key=None, value=None): """ ?????????????? """ if isinstance(key, six.string_types): key_lower = key.lower() if any((exc in key_lower) for exc in self.excludes['partmatch']): return True if key in self.excludes['fullmatch']: return True return False
def __eq__(self, other): if isinstance(other, Payload): return other.content == self.content and other.pattern == self.pattern elif isinstance(other, six.string_types): return self.content == other else: return False
def build(cls, obj): """????????payload""" if isinstance(obj, Payload): return copy.deepcopy(obj) elif isinstance(obj, six.string_types): return cls(obj) elif isinstance(obj, (tuple, list)): return cls(*obj) elif isinstance(obj, dict): return cls(**obj)
def __init__(self, command, callback, filters=None, allow_edited=False, pass_args=False, pass_update_queue=False, pass_job_queue=False, pass_user_data=False, pass_chat_data=False): super(CommandHandler, self).__init__( callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue, pass_user_data=pass_user_data, pass_chat_data=pass_chat_data) if isinstance(command, string_types): self.command = [command.lower()] else: self.command = [x.lower() for x in command] self.filters = filters self.allow_edited = allow_edited self.pass_args = pass_args # We put this up here instead of with the rest of checking code # in check_update since we don't wanna spam a ton if isinstance(self.filters, list): warnings.warn('Using a list of filters in MessageHandler is getting ' 'deprecated, please use bitwise operators (& and |) ' 'instead. More info: https://git.io/vPTbc.')
def check_update(self, update): """Determines whether an update should be passed to this handlers :attr:`callback`. Args: update (:obj:`str`): An incomming command. Returns: :obj:`bool` """ return isinstance(update, string_types) and bool(re.match(self.pattern, update))
def __init__(self, pattern, callback, pass_groups=False, pass_groupdict=False, pass_update_queue=False, pass_job_queue=False, pass_user_data=False, pass_chat_data=False, allow_edited=False, message_updates=True, channel_post_updates=False, edited_updates=False ): if not message_updates and not channel_post_updates and not edited_updates: raise ValueError( 'message_updates, channel_post_updates and edited_updates are all False') if allow_edited: warnings.warn('allow_edited is getting deprecated, please use edited_updates instead') edited_updates = allow_edited super(RegexHandler, self).__init__( callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue, pass_user_data=pass_user_data, pass_chat_data=pass_chat_data) if isinstance(pattern, string_types): pattern = re.compile(pattern) self.pattern = pattern self.pass_groups = pass_groups self.pass_groupdict = pass_groupdict self.allow_edited = allow_edited self.message_updates = message_updates self.channel_post_updates = channel_post_updates self.edited_updates = edited_updates
def __init__(self, user_id=None, username=None): if not (bool(user_id) ^ bool(username)): raise ValueError('One and only one of user_id or username must be used') if user_id is not None and isinstance(user_id, int): self.user_ids = [user_id] else: self.user_ids = user_id if username is None: self.usernames = username elif isinstance(username, string_types): self.usernames = [username.replace('@', '')] else: self.usernames = [user.replace('@', '') for user in username]
def __init__(self, chat_id=None, username=None): if not (bool(chat_id) ^ bool(username)): raise ValueError('One and only one of chat_id or username must be used') if chat_id is not None and isinstance(chat_id, int): self.chat_ids = [chat_id] else: self.chat_ids = chat_id if username is None: self.usernames = username elif isinstance(username, string_types): self.usernames = [username.replace('@', '')] else: self.usernames = [chat.replace('@', '') for chat in username]
def __init__(self, lang): if isinstance(lang, string_types): self.lang = [lang] else: self.lang = lang self.name = 'Filters.language({})'.format(self.lang)
def asParser(fob, interpolation=None): """ConfigParser from a .ini filename or open file object. Idempotent.""" if isinstance(fob, ConfigParser): return fob if interpolation is True: parser = ConfigParser() else: parser = ConfigParser(interpolation=interpolation) if isinstance(fob, string_types): parser.read(fob) else: parser.readfp(fob) return parser
def get_database_id(cls, uri): """Parse a URI to extract the database ID""" if isinstance(uri, string_types): if not uri.startswith('local:') or '/' not in uri: return uriclsname, num = uri[6:].split('/', 1) uricls = get_named_class(uriclsname) if not uricls: return if uricls == cls or uricls in cls.mro() or cls in uricls.mro(): try: return int(num) except ValueError: pass
def _json_is_known_instance(json_record, object_importer): if isinstance(json_record, string_types): identifier = json_record json_record = None elif isinstance(json_record, dict): identifier = json_record.get('@id', None) if identifier: if object_importer is not None: instance = object_importer.get_existing(identifier) else: instance = get_named_object(identifier) return instance
def process_bind_param(self, value, dialect): if value is None: return None if isinstance(value, EnumSymbol): return value.value elif isinstance(value, string_types): # Should not happen, but mask the error for now. return value
def value_to_class(self, value, base_class): if isinstance(value, string_types): return BaseTableEnum.__members__.get(value, None) elif isinstance(value, type): return value else: raise RuntimeError("Wrong value")
def get_login_context(request, force_show_providers=False): slug = request.matchdict.get('discussion_slug', None) if slug: request.session['discussion'] = slug else: request.session.pop('discussion') discussion = discussion_from_request(request) get_routes = create_get_route(request, discussion) providers = get_provider_data(get_routes) hide_registration = (discussion and not public_roles.intersection(set(roles_with_permissions( discussion, P_READ))) and not roles_with_permissions( discussion, P_SELF_REGISTER_REQUEST, P_SELF_REGISTER)) if not force_show_providers: hide_providers = aslist(request.registry.settings.get( 'hide_login_providers', ())) if isinstance(hide_providers, string_types): hide_providers = (hide_providers, ) providers = [p for p in providers if p['type'] not in hide_providers] return dict(get_default_context(request), providers=providers, providers_json=json.dumps(providers), saml_providers=request.registry.settings.get( 'SOCIAL_AUTH_SAML_ENABLED_IDPS', {}), hide_registration=hide_registration, identifier = request.params.get('identifier', ''), google_consumer_key=request.registry.settings.get( 'google.consumer_key', ''), next=handle_next_view(request), get_route=get_routes)
def guess_range(versions, digits=2): """ ???????????????? ?? group_digits ????????? Examples? (digits=1) "1.1|1.2|1.3|1.4" --> ">=1.1,<=1.4" (digits=1) "1.1|1.2|1.3|1.4|2.1|2.2|2.3" --> ">=1.1,<=1.4|>=2.1,<=2.3" '1.1.1|1.1.2|1.1.3|1.2|1.2.4|2.0|2.0.2|3.0' --> '>=1.1.1,<=1.1.3|>=1.2,<=1.2.4|>=2.0,<=2.0.2|3.0' Args: versions (list[str]|str): ????????? digits (int): ????????? Returns: VersionRange """ if isinstance(versions, six.string_types): versions = [Version(x) for x in versions.split('|')] else: versions = [Version(x) for x in versions] versions.sort() if not versions: raise ValueError('must given at least one version') sections = [] group_buff = [versions[0]] for version in versions[1:]: if version.version[:digits] == group_buff[0].version[:digits]: group_buff.append(version) else: sections.append(_internal_guess_range(group_buff)) group_buff = [version] # ???? sections.append(_internal_guess_range(group_buff)) version_ranges = [] for low, high in sections: if low == high: cg = low.vstring else: cg = ">={},<={}".format(low, high) version_ranges.append(cg) vr = VersionRange(version_ranges) return vr # ----------------------------------------------------- # ------------------- BEGIN TESTS ------------------- # -----------------------------------------------------
def _do_create_from_json( cls, json, parse_def, context, duplicate_handling=None, object_importer=None): # Special case for JSON-LD added = False ls = cls() def guess_lang(value): from .discussion import Discussion discussion = context.get_instance_of_class(Discussion) if discussion: tr_service = discussion.translation_service() lang, _ = tr_service.identify(value) return LocaleLabel.UNDEFINED if isinstance(json, list): for entry_record in json: value = entry_record['@value'] if value: added = True lang = entry_record.get('@language', None) or guess_lang(value) ls.add_value(value, lang) elif isinstance(json, dict): if '@id' in json or '@type' in json: return super(LangString, cls)._do_create_from_json( json, parse_def, context, duplicate_handling, object_importer) elif '@value' in json: value = json['@value'] if value: added = True lang = json.get('@language', None) or guess_lang(value) ls.add_value(value, lang) else: for lang, value in json.items(): if value: added = True ls.add_value(value, lang) elif isinstance(json, string_types): if json: added = True lang = guess_lang(json) ls.add_value(json, lang) else: raise ValueError("Not a valid langstring: " + json) i_context = ls.get_instance_context(context) if added: cls.default_db.add(ls) else: i_context._instance = None return i_context
def _do_update_from_json( self, json, parse_def, context, duplicate_handling=None, object_importer=None): # Special case for JSON-LD if isinstance(json, list): for entry_record in json: lang = entry_record.get('@language', LocaleLabel.UNDEFINED) value = entry_record['@value'] entry = self.entries_as_dict.get(lang, None) if entry: entry.set_value(value) elif value: self.add_value(value, lang) elif isinstance(json, dict): if '@id' in json or '@type' in json: return super(LangString, self)._do_update_from_json( json, parse_def, context, duplicate_handling, object_importer) elif '@value' in json: value = json['@value'] if value: lang = json.get('@language', LocaleLabel.UNDEFINED) entry = self.entries_as_dict.get(lang, None) if entry: entry.set_value(value) elif value: self.add_value(value, lang) else: for lang, value in json.items(): entry = self.entries_as_dict.get(lang, None) if entry: entry.set_value(value) elif value: self.add_value(value, lang) elif isinstance(json, string_types): from .discussion import Discussion lang = LocaleLabel.UNDEFINED discussion = context.get_instance_of_class(Discussion) if discussion: tr_service = discussion.translation_service() lang, _ = tr_service.identify(json) entry = self.entries_as_dict.get(lang, None) if entry: entry.set_value(json) elif json: self.add_value(json, lang) else: raise ValueError("Not a valid langstring: " + json) return self # TODO: Reinstate when the javascript can handle empty body/subject. # def generic_json( # self, view_def_name='default', user_id=None, # permissions=(P_READ, ), base_uri='local:'): # if self.id == self.EMPTY_ID: # return None # return super(LangString, self).generic_json( # view_def_name=view_def_name, user_id=user_id, # permissions=permissions, base_uri=base_uri)
def validate_single_value(self, key, value, pref_data, data_type): # TODO: Validation for the datatypes. # base_type: (bool|json|int|string|text|scalar|url|email|domain|locale|langstr|permission|role) # type: base_type|list_of_(type)|dict_of_(base_type)_to_(type) if data_type.startswith("list_of_"): assert isinstance(value, (list, tuple)), "Not a list" return [ self.validate_single_value(key, val, pref_data, data_type[8:]) for val in value] elif data_type.startswith("dict_of_"): assert isinstance(value, (dict)), "Not a dict" key_type, value_type = data_type[8:].split("_to_", 1) assert "_" not in key_type return { self.validate_single_value(key, k, pref_data, key_type): self.validate_single_value(key, v, pref_data, value_type) for (k, v) in value.items()} elif data_type == "langstr": # Syntactic sugar for dict_of_locale_to_string assert isinstance(value, (dict)), "Not a dict" return { self.validate_single_value(key, k, pref_data, "locale"): self.validate_single_value(key, v, pref_data, "string") for (k, v) in value.items()} elif data_type == "bool": assert isinstance(value, bool), "Not a boolean" elif data_type == "int": assert isinstance(value, int), "Not an integer" elif data_type == "json": pass # no check else: assert isinstance(value, string_types), "Not a string" if data_type in ("string", "text"): pass elif data_type == "scalar": assert value in pref_data.get("scalar_values", ()), ( "value not allowed: " + value) elif data_type == "url": from urllib.parse import urlparse assert urlparse(value).scheme in ( 'http', 'https'), "Not a HTTP URL" elif data_type == "email": from pyisemail import is_email assert is_email(value), "Not an email" elif data_type == "locale": pass # TODO elif data_type == "permission": assert value in ASSEMBL_PERMISSIONS elif data_type == "role": if value not in SYSTEM_ROLES: from .auth import Role assert self.db.query(Role).filter_by( name=value).count() == 1, "Unknown role" elif data_type == "domain": from pyisemail.validators.dns_validator import DNSValidator v = DNSValidator() assert v.is_valid(value), "Not a valid domain" value = value.lower() else: raise RuntimeError("Invalid data_type: " + data_type) return value
def update_from_form(instance, form_data=None): mapper = inspect(instance.__class__) cols = {c.key: c for c in mapper.columns if not c.foreign_keys} setables = dict(pyinspect.getmembers( instance.__class__, lambda p: pyinspect.isdatadescriptor(p) and getattr(p, 'fset', None))) relns = {r.key: r for r in mapper.relationships if not r.uselist and len(r._calculated_foreign_keys) == 1 and iter( r._calculated_foreign_keys).next().table == mapper.local_table } unknown = set(form_data.keys()) - ( set(cols.keys()).union(set(setables.keys())).union(set(relns.keys()))) if unknown: raise HTTPBadRequest("Unknown keys: "+",".join(unknown)) params = dict(form_data) # type checking columns = {c.key: c for c in mapper.columns} for key, value in params.items(): if key in relns and isinstance(value, string_types): val_inst = relns[key].class_.get_instance(value) if not val_inst: raise HTTPBadRequest("Unknown instance: "+value) params[key] = val_inst elif key in columns and isinstance(columns[key].type, DeclEnumType) \ and isinstance(value, string_types): val_det = columns[key].type.enum.from_string(value) if not val_det: raise HTTPBadRequest("Cannot interpret " + value) params[key] = val_det elif key in columns and columns[key].type.python_type == datetime.datetime \ and isinstance(value, string_types): val_dt = datetime.datetime.strpstr(value) if not val_dt: raise HTTPBadRequest("Cannot interpret " + value) params[key] = val_dt elif key in columns and columns[key].type.python_type == int \ and isinstance(value, string_types): try: params[key] = int(value) except ValueError: raise HTTPBadRequest("Not a number: " + value) elif key in columns and not isinstance(value, columns[key].type.python_type): raise HTTPBadRequest("Value %s for key %s should be a %s" % ( value, key, columns[key].type.python_type)) try: for key, value in params.items(): setattr(instance, key, value) except: raise HTTPBadRequest()