我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用collections.Sequence()。
def _fields_list_to_dict(fields, option_name): """Takes a sequence of field names and returns a matching dictionary. ["a", "b"] becomes {"a": 1, "b": 1} and ["a.b.c", "d", "a.c"] becomes {"a.b.c": 1, "d": 1, "a.c": 1} """ if isinstance(fields, collections.Mapping): return fields if isinstance(fields, collections.Sequence): if not all(isinstance(field, string_type) for field in fields): raise TypeError("%s must be a list of key names, each an " "instance of %s" % (option_name, string_type.__name__)) return dict.fromkeys(fields, 1) raise TypeError("%s must be a mapping or " "list of key names" % (option_name,))
def write(self, bl, **kargs): if Block in self.writeable_objects: if isinstance(bl, collections.Sequence): assert hasattr(self, 'write_all_blocks'), \ '%s does not offer to store a sequence of blocks' % \ self.__class__.__name__ self.write_all_blocks(bl, **kargs) else: self.write_block(bl, **kargs) elif Segment in self.writeable_objects: assert len(bl.segments) == 1, \ '%s is based on segment so if you try to write a block it ' + \ 'must contain only one Segment' % self.__class__.__name__ self.write_segment(bl.segments[0], **kargs) else: raise NotImplementedError ######## All individual read methods #######################
def objwalk(obj, path=(), memo=None): if memo is None: memo = set() iterator = None if isinstance(obj, Mapping): iterator = iteritems elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, string_types): iterator = enumerate if iterator: if id(obj) not in memo: memo.add(id(obj)) for path_component, value in iterator(obj): for result in objwalk(value, path + (path_component,), memo): yield result memo.remove(id(obj)) else: yield path, obj # optional test code from here on
def __init__( self, exprs, savelist = False ): super(ParseExpression,self).__init__(savelist) if isinstance( exprs, _generatorType ): exprs = list(exprs) if isinstance( exprs, basestring ): self.exprs = [ Literal( exprs ) ] elif isinstance( exprs, collections.Sequence ): # if sequence of strings provided, wrap with Literal if all(isinstance(expr, basestring) for expr in exprs): exprs = map(Literal, exprs) self.exprs = list(exprs) else: try: self.exprs = list( exprs ) except TypeError: self.exprs = [ exprs ] self.callPreparse = False
def publish(self, titles): """ Publish a set of episodes to the Podcast's RSS feed. :param titles: Either a single episode title or a sequence of episode titles to publish. """ if isinstance(titles, Sequence) and not isinstance(titles, six.string_types): for title in titles: self.episodes[title].publish() elif isinstance(titles, six.string_types): self.episodes[titles].publish() else: raise TypeError('titles must be a string or a sequence of strings.') self.update_rss_feed()
def unpublish(self, titles): """ Unpublish a set of episodes to the Podcast's RSS feed. :param titles: Either a single episode title or a sequence of episode titles to publish. """ if isinstance(titles, Sequence) and not isinstance(titles, six.string_types): for title in titles: self.episodes[title].unpublish() elif isinstance(titles, six.string_types): self.episodes[titles].unpublish() else: raise TypeError('titles must be a string or a sequence of strings.') self.update_rss_feed()
def setUpClass(cls): template_path = [] template_uniq = set() for member in cls.__mro__: try: path = member._rft_template_path except AttributeError: continue if isinstance(path, basestring): path = [path] elif isinstance(path, collections.Sequence): pass else: path = [path] uniq_path = set(path) - template_uniq template_uniq.update(uniq_path) template_path.extend(x for x in path if x in uniq_path) cls.env = environment.Environment(template_path, cls._rft_config_path) cls.env.setupclass() super(TestCaseMixin, cls).setUpClass()
def Slice(*args, **kwargs): # pylint: disable=invalid-name """A block which applies Python slicing to a PyObject, Tuple, or Sequence. For example, to reverse a sequence: ```python (Map(Scalar()) >> Slice(step=-1)).eval(range(5)) => [4, 3, 2, 1, 0]
Positional arguments are not accepted in order to avoid the ambiguity of slice(start=N) vs. slice(stop=N).
Args: *args: Positional arguments; must be empty (see above). **kwargs: Keyword arguments; start=None, stop=None, step=None, name=None.
start=None, stop=None, step=None, name=None
Returns: The block. """ if args: raise TypeError('Slice does not accept positional arguments; allowed ' 'keyword arguments are start, stop, and step') name = kwargs.pop('name', None) return GetItem(_get_slice(**kwargs), name=name).set_constructor_name( 'td.Slice') ```
def replace_vars(data, repl_vars): """Return the given data structure with appropriate variables replaced. Args: data (Any): Data of an arbitrary type. Returns: Any: Data of the same time, possibly with replaced values. """ if isinstance(data, (six.text_type, six.binary_type)): for k, v in repl_vars.items(): data = data.replace('${' + k + '}', v) return data if isinstance(data, collections.Sequence): return type(data)([replace_vars(d, repl_vars) for d in data]) if isinstance(data, collections.Mapping): return type(data)([(k, replace_vars(v, repl_vars)) for k, v in data.items()]) return data
def __init__(self, emmodel, rtsolver, emmodel_kwargs=None, rtsolver_kwargs=None): """create a new model. It is not recommanded to instantiate Model class directly. Instead use the :py:meth:`make_model` function. """ # emmodel can be a single value (class or string) or an array with the same size as snowpack layers array if isinstance(emmodel, collections.Sequence) and not isinstance(emmodel, six.string_types): self.emmodel = [get_emmodel(em) for em in emmodel] else: self.emmodel = get_emmodel(emmodel) if isinstance(rtsolver, six.string_types): self.rtsolver = import_class(rtsolver, root='smrt.rtsolver') else: self.rtsolver = rtsolver # The implementation avoid metaclass by supplying an optional list of arguments to the emmodel and rtsolver # to alter the behavior the emmodel (or rtsolver) # this is not the most general case, but metaclass can still be used for advanced user self.emmodel_kwargs = emmodel_kwargs if emmodel_kwargs is not None else dict() self.rtsolver_kwargs = rtsolver_kwargs if rtsolver_kwargs is not None else dict()
def tau_range(self, trange): """Return a scaled tau range. Tau scaling factor is the maximum tau value to avoid and empty solution (where all variables are discarded). The value is estimated on the maximum correlation between data and labels. Parameters ---------- trange : :class:`numpy.ndarray` Tau range containing relative values (expected maximum is lesser than 1.0 and minimum greater than 0.0). Returns ------- tau_range : :class:`numpy.ndarray` Scaled tau range. """ if np.max(trange) >= 1.0 or np.min(trange) < 0.0: raise ValueError('Relative tau should be in [0,1)') if isinstance(trange, Sequence): trange = np.sort(trange) return trange * self.tau_scaling_factor
def mu_range(self, mrange): """Return a scaled mu range. Mu scaling factor is estimated on the maximum eigenvalue of the correlation matrix and is used to simplify the parameters choice. Parameters ---------- mrange : :class:`numpy.ndarray` Mu range containing relative values (expected maximum is lesser than 1.0 and minimum greater than 0.0). Returns ------- mu_range : :class:`numpy.ndarray` Scaled mu range. """ if np.min(mrange) < 0.0: raise ValueError('Relative mu should be greater than / equal to 0') if isinstance(mrange, Sequence): mrange = np.sort(mrange) return mrange * self.mu_scaling_factor
def __format_value(cls, value, context, start_key): if value is NotImplemented: raise NotImplementedError if isinstance(value, six.string_types): for key in cls._string_format_regex.findall(value): if key == start_key: raise errors.ValueSubstitutionInfiniteLoopError context[key] = cls.__format_value( context[key], context, start_key) return value.format(**context) if isinstance(value, Mapping): return OrderedDict( (k, cls.__format_value(v, context, start_key)) for k, v in value.items()) if isinstance(value, Sequence): return [cls.__format_value(v, context, start_key) for v in value] return value
def allocate_remotes(remotes): """ Utility method for building a Malmo ClientPool. Using this method allows sharing the same ClientPool across mutiple experiment :param remotes: tuple or array of tuples. Each tuple can be (), (ip,), (ip, port) :return: Malmo ClientPool with all registered clients """ if not isinstance(remotes, list): remotes = [remotes] pool = ClientPool() for remote in remotes: if isinstance(remote, ClientInfo): pool.add(remote) elif isinstance(remote, Sequence): if len(remote) == 0: pool.add(ClientInfo('localhost', 10000)) elif len(remote) == 1: pool.add(ClientInfo(remote[0], 10000)) else: pool.add(ClientInfo(remote[0], int(remote[1]))) return pool
def _resolve_coerce(self, schema): """add coerce rules to convert datatypes of int and float, recusively using the rules combinations of cerberus: {TERM : {RULE: --> str (STOP) --> list/Sequence --> str (STOP) --> dict => (if type: ADD) + RECALL --> dict/Mapping => (if type: ADD) + RECALL }} """ for term, rules in schema.items(): if isinstance(rules, _str_type): continue elif isinstance(rules, Sequence): for subschema in rules: if isinstance(subschema, Mapping): if 'type' in subschema.keys(): self._add_coerce(subschema) self._resolve_coerce(subschema) elif isinstance(rules, Mapping): if 'type' in rules.keys(): self._add_coerce(rules) self._resolve_coerce(rules) else: NotImplemented
def check_edge_range(edge_range_spec): "Validates the edge rage specified" if edge_range_spec is None: edge_range = edge_range_spec elif isinstance(edge_range_spec, (collections.Sequence, np.ndarray)): if len(edge_range_spec) != 2: raise ValueError('edge_range must be a tuple of two values: (min, max)') if edge_range_spec[0] >= edge_range_spec[1]: raise ValueError('edge_range : min {} is not less than max {} !'.format(edge_range_spec[0], edge_range_spec[1])) # CLI args are strings unless converted to numeric edge_range = np.float64(edge_range_spec) if not np.all(np.isfinite(edge_range)): raise ValueError('Infinite or NaN values in edge range : {}'.format(edge_range_spec)) # converting it to tuple to make it immutable edge_range = tuple(edge_range) else: raise ValueError('Invalid edge range! Must be a tuple of two values (min, max)') return edge_range
def _setup_getitem(self, default_comparator, index): if not isinstance(index, util.string_types) and \ isinstance(index, collections.Sequence): index = default_comparator._check_literal( self.expr, operators.json_path_getitem_op, index, bindparam_type=JSON.JSONPathType ) operator = operators.json_path_getitem_op else: index = default_comparator._check_literal( self.expr, operators.json_getitem_op, index, bindparam_type=JSON.JSONIndexType ) operator = operators.json_getitem_op return operator, index, self.type
def output(channel, outmode): # type: (int or Sequence[int], int or bool or Sequence[int] or Sequence[bool]) -> None __check_mode() if isinstance(channel, Sequence): def zip_outmode(): # type: () -> Sequence[tuple] if isinstance(outmode, Sequence): assert len(channel) == len(outmode) return zip(channel, outmode) else: return zip(channel, [outmode] * len(channel)) for (c, m) in zip_outmode(): __output(__to_channel(c), m) else: __output(__to_channel(channel), outmode)
def make_command(self, value): cmd = self.config.get('cmd') if value is None: return cmd, elif not cmd and isinstance(value, Sequence): return value elif not cmd and isinstance(value, str): return value, elif isinstance(cmd, list) and isinstance(value, str): return cmd + [value] elif isinstance(cmd, list) and isinstance(value, Sequence): result = list(cmd) result.extend(value) return result elif isinstance(cmd, list) and isinstance(value, Mapping): return [i.format_map(value) for i in cmd] elif isinstance(cmd, str) and isinstance(value, str): return self.config.cmd + ' ' + value, elif isinstance(cmd, str) and isinstance(value, Mapping): return self.config.cmd.format_map(value), elif isinstance(cmd, str) and isinstance(value, Sequence): return self.config.cmd.format(*value), else: raise ValueError(value)
def raw_key(self, key): if self._prefix: url = self._prefix / key elif self._template and isinstance(key, Mapping): url = URL(self._template.format_map(key)) elif self._template and isinstance(key, Sequence): url = URL(self._template.format(*key)) elif self._template: url = URL(self._template.format(key)) elif isinstance(key, str): url = URL(key) else: url = key if self._allow_hosts and url.host not in self._allow_hosts: raise KeyError(key) return url
def test_sort_school(self): students = [ (3, ("Kyle",)), (4, ("Christopher", "Jennifer",)), (6, ("Kareem",)) ] for grade, students_in_grade in students: for student in students_in_grade: self.school.add(student, grade) result = self.school.sort() # Attempts to catch false positives self.assertTrue(isinstance(result, Sequence) or isinstance(result, GeneratorType) or callable(getattr(result, '__reversed__', False))) result_list = list(result.items() if hasattr(result, "items") else result) self.assertEqual(result_list, students)
def _sorted_roles(self) -> 'List[dt_role.Role]': if not self._member.guild: return [] roles = [] for id in self._member.role_ids: try: roles.append(self._member.guild.roles[id]) except (KeyError, AttributeError): pass return sorted(roles) # opt: the default Sequence makes us re-create the sorted role list constantly # we don't wanna cache it, without introducing invalidation hell # so we just put `__iter__` on `_sorted_roles`
def gram_ctc(xs, label_unigram, label_bigram, blank_symbol, input_length=None, length_unigram=None, reduce='mean'): if not isinstance(xs, collections.Sequence): raise TypeError('xs must be a list of Variables') if not isinstance(blank_symbol, int): raise TypeError('blank_symbol must be non-negative integer.') assert blank_symbol >= 0 assert blank_symbol < xs[0].shape[1] assert len(xs[0].shape) == 2 assert label_unigram.shape[1] == label_bigram.shape[1] if input_length is None: xp = cuda.get_array_module(xs[0].data) input_length = variable.Variable(xp.full((len(xs[0].data),), len(xs), dtype=np.int32)) length_unigram = variable.Variable(xp.full((len(label_unigram.data),), len(label_unigram.data[0]), dtype=np.int32)) return GramCTC(blank_symbol, reduce)(input_length, length_unigram, label_unigram, label_bigram, *xs)
def _post_process_dict(self, dict_val): if dict_val is None: return for key, value in tuple(dict_val.items()): if value is None: continue if isinstance(value, Summarizable): dict_val[key] = value = value.summarize() if isinstance(value, dict): self._post_process_dict(value) elif ( isinstance(value, Sequence) and len(value) > 0 and all( val is None or isinstance(val, dict) for val in value)): for val in value: self._post_process_dict(val) else: if isinstance(value, Const): dict_val[key] = value = value.value self._post_process_other(dict_val, key, value)