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
python类Sequence()的实例源码
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 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 __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 __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 __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 __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 __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 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 _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 __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 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 __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 _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 _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)