id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
241,700 | tensorflow/mesh | mesh_tensorflow/ops.py | pnum_to_group | def pnum_to_group(mesh_shape, group_dims, pnum):
"""Group number for grouped allreduce.
Args:
mesh_shape: a Shape
group_dims: a list of integers (the dimensions reduced over)
pnum: an integer
Returns:
an integer
"""
coord = pnum_to_processor_coordinates(mesh_shape, pnum)
remaining_shape = ... | python | def pnum_to_group(mesh_shape, group_dims, pnum):
coord = pnum_to_processor_coordinates(mesh_shape, pnum)
remaining_shape = Shape(
[d for i, d in enumerate(mesh_shape) if i not in group_dims])
remaining_coord = [d for i, d in enumerate(coord) if i not in group_dims]
return processor_coordinates_to_pnum(rem... | [
"def",
"pnum_to_group",
"(",
"mesh_shape",
",",
"group_dims",
",",
"pnum",
")",
":",
"coord",
"=",
"pnum_to_processor_coordinates",
"(",
"mesh_shape",
",",
"pnum",
")",
"remaining_shape",
"=",
"Shape",
"(",
"[",
"d",
"for",
"i",
",",
"d",
"in",
"enumerate",
... | Group number for grouped allreduce.
Args:
mesh_shape: a Shape
group_dims: a list of integers (the dimensions reduced over)
pnum: an integer
Returns:
an integer | [
"Group",
"number",
"for",
"grouped",
"allreduce",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4312-L4327 |
241,701 | tensorflow/mesh | mesh_tensorflow/ops.py | processor_groups | def processor_groups(mesh_shape, group_dims):
"""Groups of processors which differ only in the given dimensions.
Args:
mesh_shape: a Shape
group_dims: a list of integers
Returns:
a list of lists of integers (processor numbers)
"""
group_numbers = [
pnum_to_group(mesh_shape, group_dims, pnu... | python | def processor_groups(mesh_shape, group_dims):
group_numbers = [
pnum_to_group(mesh_shape, group_dims, pnum)
for pnum in xrange(mesh_shape.size)]
ret = []
for pnum, g in enumerate(group_numbers):
while len(ret) <= g:
ret.append([])
ret[g].append(pnum)
return ret | [
"def",
"processor_groups",
"(",
"mesh_shape",
",",
"group_dims",
")",
":",
"group_numbers",
"=",
"[",
"pnum_to_group",
"(",
"mesh_shape",
",",
"group_dims",
",",
"pnum",
")",
"for",
"pnum",
"in",
"xrange",
"(",
"mesh_shape",
".",
"size",
")",
"]",
"ret",
"... | Groups of processors which differ only in the given dimensions.
Args:
mesh_shape: a Shape
group_dims: a list of integers
Returns:
a list of lists of integers (processor numbers) | [
"Groups",
"of",
"processors",
"which",
"differ",
"only",
"in",
"the",
"given",
"dimensions",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4330-L4348 |
241,702 | tensorflow/mesh | mesh_tensorflow/ops.py | mtf_range | def mtf_range(mesh, dim, dtype, name=None):
"""Create a 1d mesh tensor with a range from [0, dim.size).
Call externally as mtf.range()
Args:
mesh: a Mesh
dim: a Dimension
dtype: a tf.DType
name: an optional string
Returns:
a Tensor
"""
dim = convert_to_dimension(dim)
with tf.variabl... | python | def mtf_range(mesh, dim, dtype, name=None):
dim = convert_to_dimension(dim)
with tf.variable_scope(name, default_name="range"):
if dtype == tf.bfloat16:
# tf.range(dtype=bfloat16) gives the wrong shape.
# TODO(noam): report the bug.
tf_range = tf.cast(tf.range(dim.size), tf.bfloat16)
else:... | [
"def",
"mtf_range",
"(",
"mesh",
",",
"dim",
",",
"dtype",
",",
"name",
"=",
"None",
")",
":",
"dim",
"=",
"convert_to_dimension",
"(",
"dim",
")",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"range\"",
")",
":",
"if",... | Create a 1d mesh tensor with a range from [0, dim.size).
Call externally as mtf.range()
Args:
mesh: a Mesh
dim: a Dimension
dtype: a tf.DType
name: an optional string
Returns:
a Tensor | [
"Create",
"a",
"1d",
"mesh",
"tensor",
"with",
"a",
"range",
"from",
"[",
"0",
"dim",
".",
"size",
")",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4406-L4428 |
241,703 | tensorflow/mesh | mesh_tensorflow/ops.py | pretty_print_counters | def pretty_print_counters(counters):
"""print counters hierarchically.
Each counter is a pair of a string and a number.
The string can have slashes, meaning that the number also counts towards
each prefix. e.g. "parameters/trainable" counts towards both "parameters"
and "parameters/trainable".
Args:
... | python | def pretty_print_counters(counters):
totals = collections.defaultdict(int)
for (name, val) in counters:
prefixes = [name[:i] for i in xrange(len(name)) if name[i] == "/"] + [name]
for p in prefixes:
totals[p] += val
parts = []
for name, val in sorted(six.iteritems(totals)):
parts.append(" " * ... | [
"def",
"pretty_print_counters",
"(",
"counters",
")",
":",
"totals",
"=",
"collections",
".",
"defaultdict",
"(",
"int",
")",
"for",
"(",
"name",
",",
"val",
")",
"in",
"counters",
":",
"prefixes",
"=",
"[",
"name",
"[",
":",
"i",
"]",
"for",
"i",
"i... | print counters hierarchically.
Each counter is a pair of a string and a number.
The string can have slashes, meaning that the number also counts towards
each prefix. e.g. "parameters/trainable" counts towards both "parameters"
and "parameters/trainable".
Args:
counters: a list of (string, number) pair... | [
"print",
"counters",
"hierarchically",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4431-L4453 |
241,704 | tensorflow/mesh | mesh_tensorflow/ops.py | _parse_string_to_list_of_pairs | def _parse_string_to_list_of_pairs(s, seconds_to_int=False):
r"""Parses a string into a list of pairs.
In the input string, each pair is separated by a colon, and the delimiters
between pairs are any of " ,.;".
e.g. "rows:32,cols:32"
Args:
s: str to parse.
seconds_to_int: Boolean. If True, then the... | python | def _parse_string_to_list_of_pairs(s, seconds_to_int=False):
r"""Parses a string into a list of pairs.
In the input string, each pair is separated by a colon, and the delimiters
between pairs are any of " ,.;".
e.g. "rows:32,cols:32"
Args:
s: str to parse.
seconds_to_int: Boolean. If True, then the... | [
"def",
"_parse_string_to_list_of_pairs",
"(",
"s",
",",
"seconds_to_int",
"=",
"False",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"p",
"in",
"[",
"s",
".",
"split",
"(",
"\":\"",
")",
"for",
"s",
"in",
"re",
".",
"sub",
"(",
"\"[,.;]\"",
",",
"\" \"",
... | r"""Parses a string into a list of pairs.
In the input string, each pair is separated by a colon, and the delimiters
between pairs are any of " ,.;".
e.g. "rows:32,cols:32"
Args:
s: str to parse.
seconds_to_int: Boolean. If True, then the second elements are returned
as integers; otherwise the... | [
"r",
"Parses",
"a",
"string",
"into",
"a",
"list",
"of",
"pairs",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4456-L4483 |
241,705 | tensorflow/mesh | mesh_tensorflow/ops.py | parallel | def parallel(devices, fn, *args, **kwargs):
"""Call a function once on each device.
Args:
devices: a list of n devices
fn: a function
*args: arguments, each of which is a list of length n
**kwargs: keyword-args, each of which is a list of length n
Returns:
a list of length n
Raises:
Val... | python | def parallel(devices, fn, *args, **kwargs):
if not isinstance(devices, list):
raise ValueError("devices must be a list")
for x in list(args) + list(six.itervalues(kwargs)):
if not isinstance(x, list) or len(x) != len(devices):
raise ValueError(
"Argument not a list with same length as device... | [
"def",
"parallel",
"(",
"devices",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"devices",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"devices must be a list\"",
")",
"for",
"x",
"in",
"list"... | Call a function once on each device.
Args:
devices: a list of n devices
fn: a function
*args: arguments, each of which is a list of length n
**kwargs: keyword-args, each of which is a list of length n
Returns:
a list of length n
Raises:
ValueError: if the arguments are not all lists of le... | [
"Call",
"a",
"function",
"once",
"on",
"each",
"device",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4486-L4513 |
241,706 | tensorflow/mesh | mesh_tensorflow/ops.py | random_uniform | def random_uniform(mesh, shape, **kwargs):
"""Random uniform.
Args:
mesh: a Mesh
shape: a Shape
**kwargs: keyword args for tf.random.uniform, except seed
Returns:
a Tensor
"""
shape = convert_to_shape(shape)
return RandomOperation(mesh, shape, tf.random.uniform, **kwargs).outputs[0] | python | def random_uniform(mesh, shape, **kwargs):
shape = convert_to_shape(shape)
return RandomOperation(mesh, shape, tf.random.uniform, **kwargs).outputs[0] | [
"def",
"random_uniform",
"(",
"mesh",
",",
"shape",
",",
"*",
"*",
"kwargs",
")",
":",
"shape",
"=",
"convert_to_shape",
"(",
"shape",
")",
"return",
"RandomOperation",
"(",
"mesh",
",",
"shape",
",",
"tf",
".",
"random",
".",
"uniform",
",",
"*",
"*",... | Random uniform.
Args:
mesh: a Mesh
shape: a Shape
**kwargs: keyword args for tf.random.uniform, except seed
Returns:
a Tensor | [
"Random",
"uniform",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4611-L4623 |
241,707 | tensorflow/mesh | mesh_tensorflow/ops.py | dropout | def dropout(x, keep_prob, noise_shape=None, name=None):
"""Dropout layer.
Args:
x: a Tensor
keep_prob: a float between 0.0 and 1.0
noise_shape: an optional Shape (a subset of x.shape)
name: an optional string
Returns:
a Tensor
"""
noise_shape = convert_to_shape(noise_shape)
if noise_sh... | python | def dropout(x, keep_prob, noise_shape=None, name=None):
noise_shape = convert_to_shape(noise_shape)
if noise_shape is None:
noise_shape = x.shape
with tf.variable_scope(name, default_name="dropout"):
if keep_prob == 1.0:
return x
noise = cast(less(random_uniform(
x.mesh, noise_shape, dty... | [
"def",
"dropout",
"(",
"x",
",",
"keep_prob",
",",
"noise_shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"noise_shape",
"=",
"convert_to_shape",
"(",
"noise_shape",
")",
"if",
"noise_shape",
"is",
"None",
":",
"noise_shape",
"=",
"x",
".",
"sha... | Dropout layer.
Args:
x: a Tensor
keep_prob: a float between 0.0 and 1.0
noise_shape: an optional Shape (a subset of x.shape)
name: an optional string
Returns:
a Tensor | [
"Dropout",
"layer",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4626-L4647 |
241,708 | tensorflow/mesh | mesh_tensorflow/ops.py | _cumprod | def _cumprod(l):
"""Cumulative product of a list.
Args:
l: a list of integers
Returns:
a list with one more element (starting with 1)
"""
ret = [1]
for item in l:
ret.append(ret[-1] * item)
return ret | python | def _cumprod(l):
ret = [1]
for item in l:
ret.append(ret[-1] * item)
return ret | [
"def",
"_cumprod",
"(",
"l",
")",
":",
"ret",
"=",
"[",
"1",
"]",
"for",
"item",
"in",
"l",
":",
"ret",
".",
"append",
"(",
"ret",
"[",
"-",
"1",
"]",
"*",
"item",
")",
"return",
"ret"
] | Cumulative product of a list.
Args:
l: a list of integers
Returns:
a list with one more element (starting with 1) | [
"Cumulative",
"product",
"of",
"a",
"list",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4650-L4661 |
241,709 | tensorflow/mesh | mesh_tensorflow/ops.py | while_loop | def while_loop(cond_fn, body_fn, inputs, num_loop_vars=None,
has_accumulators=False, **kwargs):
"""While Loop.
See comments above for WhileLoopOperation
num_loop_vars is a hack for the multi-gpu setup. In this case, loops
are generally slow, as all loop variables are placed on device. By sett... | python | def while_loop(cond_fn, body_fn, inputs, num_loop_vars=None,
has_accumulators=False, **kwargs):
if num_loop_vars is None:
return WhileLoopOperation(cond_fn, body_fn, inputs, tf_kwargs=kwargs,
has_accumulators=has_accumulators).outputs
# Turn all loop vars except for ... | [
"def",
"while_loop",
"(",
"cond_fn",
",",
"body_fn",
",",
"inputs",
",",
"num_loop_vars",
"=",
"None",
",",
"has_accumulators",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"num_loop_vars",
"is",
"None",
":",
"return",
"WhileLoopOperation",
"(",
... | While Loop.
See comments above for WhileLoopOperation
num_loop_vars is a hack for the multi-gpu setup. In this case, loops
are generally slow, as all loop variables are placed on device. By setting
num_loop_vars=k, then all of the loop variables except for the first k
are handled as mtf Variables instead ... | [
"While",
"Loop",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4855-L4910 |
241,710 | tensorflow/mesh | mesh_tensorflow/ops.py | _shape_union | def _shape_union(shapes):
"""A shape containing the union of all dimensions in the input shapes.
Args:
shapes: a list of Shapes
Returns:
a Shape
"""
return Shape(sorted(list(set(sum([s.dims for s in shapes], []))))) | python | def _shape_union(shapes):
return Shape(sorted(list(set(sum([s.dims for s in shapes], []))))) | [
"def",
"_shape_union",
"(",
"shapes",
")",
":",
"return",
"Shape",
"(",
"sorted",
"(",
"list",
"(",
"set",
"(",
"sum",
"(",
"[",
"s",
".",
"dims",
"for",
"s",
"in",
"shapes",
"]",
",",
"[",
"]",
")",
")",
")",
")",
")"
] | A shape containing the union of all dimensions in the input shapes.
Args:
shapes: a list of Shapes
Returns:
a Shape | [
"A",
"shape",
"containing",
"the",
"union",
"of",
"all",
"dimensions",
"in",
"the",
"input",
"shapes",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4921-L4930 |
241,711 | tensorflow/mesh | mesh_tensorflow/ops.py | _tf_flatten_batch_dims | def _tf_flatten_batch_dims(x, num_nonbatch_dims):
"""Flatten all but last num_nonbatch_dims into one dimension.
Args:
x: a tf.Tensor:
num_nonbatch_dims: an integer
Returns:
a tf.Tensor with 1 + num_nonbatch_dims dimensions.
"""
shape = x.shape.as_list()
assert None not in shape
new_shape = (... | python | def _tf_flatten_batch_dims(x, num_nonbatch_dims):
shape = x.shape.as_list()
assert None not in shape
new_shape = ([list_product(shape[:-num_nonbatch_dims])]
+ shape[-num_nonbatch_dims:])
if new_shape != shape:
x = tf.reshape(x, new_shape)
return x | [
"def",
"_tf_flatten_batch_dims",
"(",
"x",
",",
"num_nonbatch_dims",
")",
":",
"shape",
"=",
"x",
".",
"shape",
".",
"as_list",
"(",
")",
"assert",
"None",
"not",
"in",
"shape",
"new_shape",
"=",
"(",
"[",
"list_product",
"(",
"shape",
"[",
":",
"-",
"... | Flatten all but last num_nonbatch_dims into one dimension.
Args:
x: a tf.Tensor:
num_nonbatch_dims: an integer
Returns:
a tf.Tensor with 1 + num_nonbatch_dims dimensions. | [
"Flatten",
"all",
"but",
"last",
"num_nonbatch_dims",
"into",
"one",
"dimension",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4933-L4949 |
241,712 | tensorflow/mesh | mesh_tensorflow/ops.py | _tf_restore_batch_dims | def _tf_restore_batch_dims(x, num_nonbatch_dims, prototype):
"""Reverse op of _tf_flatten_batch_dims.
Un-flatten the first dimension of x to match all but the last
num_nonbatch_dims dimensions of prototype.
Args:
x: a tf.Tensor with 1 + num_nonbatch_dims dimensions
num_nonbatch_dims: an integer
pr... | python | def _tf_restore_batch_dims(x, num_nonbatch_dims, prototype):
assert x.shape.ndims == 1 + num_nonbatch_dims
new_shape = (
prototype.shape.as_list()[:-num_nonbatch_dims] + x.shape.as_list()[1:])
assert None not in new_shape
if new_shape != x.shape.as_list():
x = tf.reshape(x, new_shape)
return x | [
"def",
"_tf_restore_batch_dims",
"(",
"x",
",",
"num_nonbatch_dims",
",",
"prototype",
")",
":",
"assert",
"x",
".",
"shape",
".",
"ndims",
"==",
"1",
"+",
"num_nonbatch_dims",
"new_shape",
"=",
"(",
"prototype",
".",
"shape",
".",
"as_list",
"(",
")",
"["... | Reverse op of _tf_flatten_batch_dims.
Un-flatten the first dimension of x to match all but the last
num_nonbatch_dims dimensions of prototype.
Args:
x: a tf.Tensor with 1 + num_nonbatch_dims dimensions
num_nonbatch_dims: an integer
prototype: a tf.Tensor
Returns:
a tf.Tensor | [
"Reverse",
"op",
"of",
"_tf_flatten_batch_dims",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4952-L4972 |
241,713 | tensorflow/mesh | mesh_tensorflow/ops.py | halo_exchange | def halo_exchange(x, blocks_dim, block_size_dim, halo_size, wrap=False):
"""Concat each block with the margins of adjacent blocks.
Get left and right blocks_dim and concatenate along block_size_dim.
Args:
x: a Tensor.
blocks_dim: a Dimension in x.shape
block_size_dim: a Dimension in x.shape
halo... | python | def halo_exchange(x, blocks_dim, block_size_dim, halo_size, wrap=False):
if halo_size == 0:
return x
block_size = block_size_dim.size
partial_size = halo_size % block_size
num_complete_blocks = halo_size // block_size
parts = [x]
for i in xrange(1, num_complete_blocks + 1):
parts = ([shift(x, i, b... | [
"def",
"halo_exchange",
"(",
"x",
",",
"blocks_dim",
",",
"block_size_dim",
",",
"halo_size",
",",
"wrap",
"=",
"False",
")",
":",
"if",
"halo_size",
"==",
"0",
":",
"return",
"x",
"block_size",
"=",
"block_size_dim",
".",
"size",
"partial_size",
"=",
"hal... | Concat each block with the margins of adjacent blocks.
Get left and right blocks_dim and concatenate along block_size_dim.
Args:
x: a Tensor.
blocks_dim: a Dimension in x.shape
block_size_dim: a Dimension in x.shape
halo_size: an integer
wrap: a boolean
Returns:
a Tensor with the same s... | [
"Concat",
"each",
"block",
"with",
"the",
"margins",
"of",
"adjacent",
"blocks",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L4975-L5011 |
241,714 | tensorflow/mesh | mesh_tensorflow/ops.py | conv2d_with_blocks | def conv2d_with_blocks(
conv_input,
conv_filter,
strides,
padding,
h_blocks_dim=None,
w_blocks_dim=None,
name=None):
"""conv2d operation with spatial partitioning.
Spatial partitioning is implemented by decomposing the image into blocks.
Block dimensions represented as h_blocks_dim an... | python | def conv2d_with_blocks(
conv_input,
conv_filter,
strides,
padding,
h_blocks_dim=None,
w_blocks_dim=None,
name=None):
filter_h_dim, filter_w_dim = conv_filter.shape.dims[:2]
assert filter_h_dim.size % 2 == 1
assert filter_w_dim.size % 2 == 1
h_dim, w_dim = conv_input.shape.dims[-3:-1]... | [
"def",
"conv2d_with_blocks",
"(",
"conv_input",
",",
"conv_filter",
",",
"strides",
",",
"padding",
",",
"h_blocks_dim",
"=",
"None",
",",
"w_blocks_dim",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"filter_h_dim",
",",
"filter_w_dim",
"=",
"conv_filter",... | conv2d operation with spatial partitioning.
Spatial partitioning is implemented by decomposing the image into blocks.
Block dimensions represented as h_blocks_dim and w_blocks_dim can be split
along the mesh axis. If split, then we do a halo exchange where each block
receives the part of the image from its lef... | [
"conv2d",
"operation",
"with",
"spatial",
"partitioning",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L5049-L5108 |
241,715 | tensorflow/mesh | mesh_tensorflow/ops.py | tensor_dim_to_mesh_dim_size | def tensor_dim_to_mesh_dim_size(layout, mesh_shape, tensor_dim):
"""How many ways does a tensor dimension get split.
This is used to "cheat" when building the mtf graph and peek at how a
tensor dimension will be split. Returns 1 if the tensor dimension is not
split.
Args:
layout: an input to convert_to... | python | def tensor_dim_to_mesh_dim_size(layout, mesh_shape, tensor_dim):
layout_rules = convert_to_layout_rules(layout)
mesh_shape = convert_to_shape(mesh_shape)
mesh_axis = layout_rules.tensor_dimension_to_mesh_axis(tensor_dim, mesh_shape)
if mesh_axis is None:
return 1
else:
return mesh_shape.dims[mesh_axis... | [
"def",
"tensor_dim_to_mesh_dim_size",
"(",
"layout",
",",
"mesh_shape",
",",
"tensor_dim",
")",
":",
"layout_rules",
"=",
"convert_to_layout_rules",
"(",
"layout",
")",
"mesh_shape",
"=",
"convert_to_shape",
"(",
"mesh_shape",
")",
"mesh_axis",
"=",
"layout_rules",
... | How many ways does a tensor dimension get split.
This is used to "cheat" when building the mtf graph and peek at how a
tensor dimension will be split. Returns 1 if the tensor dimension is not
split.
Args:
layout: an input to convert_to_layout_rules
mesh_shape: an input to convert_to_shape
tensor_... | [
"How",
"many",
"ways",
"does",
"a",
"tensor",
"dimension",
"get",
"split",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L5111-L5132 |
241,716 | tensorflow/mesh | mesh_tensorflow/ops.py | serialize_training_step | def serialize_training_step(features, model_fn, batch_dim, num_splits):
"""Break the training batch into multiple microbatches.
Returns two structures:
grads - a list of Tensors corresponding to the gradients on
graph.trainable_variables. These are summed across all microbatches
outputs - a dictionary ... | python | def serialize_training_step(features, model_fn, batch_dim, num_splits):
for v in features.values():
mesh = v.mesh
graph = v.graph
microbatch_dim = Dimension("microbatch", num_splits)
smaller_batch_dim = Dimension(batch_dim.name, batch_dim.size // num_splits)
cache = {}
def select(t, microbatch_num):
... | [
"def",
"serialize_training_step",
"(",
"features",
",",
"model_fn",
",",
"batch_dim",
",",
"num_splits",
")",
":",
"for",
"v",
"in",
"features",
".",
"values",
"(",
")",
":",
"mesh",
"=",
"v",
".",
"mesh",
"graph",
"=",
"v",
".",
"graph",
"microbatch_dim... | Break the training batch into multiple microbatches.
Returns two structures:
grads - a list of Tensors corresponding to the gradients on
graph.trainable_variables. These are summed across all microbatches
outputs - a dictionary of Tensors corresponding to the output dictionary of
model_fn. Each va... | [
"Break",
"the",
"training",
"batch",
"into",
"multiple",
"microbatches",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L5146-L5231 |
241,717 | tensorflow/mesh | mesh_tensorflow/ops.py | Shape.rename_dimension | def rename_dimension(self, old_name, new_name):
"""Returns a copy where one dimension is renamed."""
if old_name not in self.dimension_names:
raise ValueError("Shape %s does not have dimension named %s"
% (self, old_name))
return Shape(
[Dimension(new_name, d.size) if d.... | python | def rename_dimension(self, old_name, new_name):
if old_name not in self.dimension_names:
raise ValueError("Shape %s does not have dimension named %s"
% (self, old_name))
return Shape(
[Dimension(new_name, d.size) if d.name == old_name else d
for d in self.dims]) | [
"def",
"rename_dimension",
"(",
"self",
",",
"old_name",
",",
"new_name",
")",
":",
"if",
"old_name",
"not",
"in",
"self",
".",
"dimension_names",
":",
"raise",
"ValueError",
"(",
"\"Shape %s does not have dimension named %s\"",
"%",
"(",
"self",
",",
"old_name",
... | Returns a copy where one dimension is renamed. | [
"Returns",
"a",
"copy",
"where",
"one",
"dimension",
"is",
"renamed",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L163-L170 |
241,718 | tensorflow/mesh | mesh_tensorflow/ops.py | Shape.resize_dimension | def resize_dimension(self, name, new_size):
"""Returns a copy where one dimension has a different size."""
if name not in self.dimension_names:
raise ValueError("Shape %s does not have dimension named %s"
% (self, name))
return Shape(
[Dimension(name, new_size) if d.name... | python | def resize_dimension(self, name, new_size):
if name not in self.dimension_names:
raise ValueError("Shape %s does not have dimension named %s"
% (self, name))
return Shape(
[Dimension(name, new_size) if d.name == name else d
for d in self.dims]) | [
"def",
"resize_dimension",
"(",
"self",
",",
"name",
",",
"new_size",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"dimension_names",
":",
"raise",
"ValueError",
"(",
"\"Shape %s does not have dimension named %s\"",
"%",
"(",
"self",
",",
"name",
")",
")"... | Returns a copy where one dimension has a different size. | [
"Returns",
"a",
"copy",
"where",
"one",
"dimension",
"has",
"a",
"different",
"size",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L172-L179 |
241,719 | tensorflow/mesh | mesh_tensorflow/ops.py | LayoutRules.tensor_layout | def tensor_layout(self, tensor_shape, mesh_shape):
"""Computes TensorLayout given a Tensor Shape and a Mesh Shape.
Args:
tensor_shape: Shape.
mesh_shape: Shape.
Returns:
TensorLayout.
Raises:
ValueError: If two Tensor Dimensions map to the same Mesh Dimensions.
"""
ret... | python | def tensor_layout(self, tensor_shape, mesh_shape):
ret = [self.tensor_dimension_to_mesh_axis(d, mesh_shape)
for d in tensor_shape]
not_nones = [a for a in ret if a is not None]
if len(not_nones) != len(set(not_nones)):
raise ValueError(
"Two Tensor Dimensions may not map to the sa... | [
"def",
"tensor_layout",
"(",
"self",
",",
"tensor_shape",
",",
"mesh_shape",
")",
":",
"ret",
"=",
"[",
"self",
".",
"tensor_dimension_to_mesh_axis",
"(",
"d",
",",
"mesh_shape",
")",
"for",
"d",
"in",
"tensor_shape",
"]",
"not_nones",
"=",
"[",
"a",
"for"... | Computes TensorLayout given a Tensor Shape and a Mesh Shape.
Args:
tensor_shape: Shape.
mesh_shape: Shape.
Returns:
TensorLayout.
Raises:
ValueError: If two Tensor Dimensions map to the same Mesh Dimensions. | [
"Computes",
"TensorLayout",
"given",
"a",
"Tensor",
"Shape",
"and",
"a",
"Mesh",
"Shape",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L247-L268 |
241,720 | tensorflow/mesh | mesh_tensorflow/ops.py | TensorLayout.mesh_axis_to_tensor_axis | def mesh_axis_to_tensor_axis(self, mesh_ndims):
"""For each mesh axis, which Tensor axis maps to it.
Args:
mesh_ndims: int.
Returns:
Tuple of optional integers, with length mesh_ndims.
"""
ta2ma = self._tensor_axis_to_mesh_axis
return tuple(
[ta2ma.index(mesh_axis) if mesh_... | python | def mesh_axis_to_tensor_axis(self, mesh_ndims):
ta2ma = self._tensor_axis_to_mesh_axis
return tuple(
[ta2ma.index(mesh_axis) if mesh_axis in ta2ma else None
for mesh_axis in xrange(mesh_ndims)]) | [
"def",
"mesh_axis_to_tensor_axis",
"(",
"self",
",",
"mesh_ndims",
")",
":",
"ta2ma",
"=",
"self",
".",
"_tensor_axis_to_mesh_axis",
"return",
"tuple",
"(",
"[",
"ta2ma",
".",
"index",
"(",
"mesh_axis",
")",
"if",
"mesh_axis",
"in",
"ta2ma",
"else",
"None",
... | For each mesh axis, which Tensor axis maps to it.
Args:
mesh_ndims: int.
Returns:
Tuple of optional integers, with length mesh_ndims. | [
"For",
"each",
"mesh",
"axis",
"which",
"Tensor",
"axis",
"maps",
"to",
"it",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L339-L351 |
241,721 | tensorflow/mesh | mesh_tensorflow/ops.py | Graph.unique_name | def unique_name(self, name, mark_as_used=True):
"""Like tf.Graph.unique_name, returns a unique operation name for `name`.
Args:
name: The name for an operation.
mark_as_used: whether to mark this name as being used.
Returns:
A string to use as the name for the operation.
"""
scop... | python | def unique_name(self, name, mark_as_used=True):
scope_name = tf.get_variable_scope().name
if scope_name:
name = scope_name + "/" + name
# As in TensorFlow, treat names as case insensitive when deciding whether
# they are in use.
name_key = name.lower()
i = self._names_in_use.get(name_key,... | [
"def",
"unique_name",
"(",
"self",
",",
"name",
",",
"mark_as_used",
"=",
"True",
")",
":",
"scope_name",
"=",
"tf",
".",
"get_variable_scope",
"(",
")",
".",
"name",
"if",
"scope_name",
":",
"name",
"=",
"scope_name",
"+",
"\"/\"",
"+",
"name",
"# As in... | Like tf.Graph.unique_name, returns a unique operation name for `name`.
Args:
name: The name for an operation.
mark_as_used: whether to mark this name as being used.
Returns:
A string to use as the name for the operation. | [
"Like",
"tf",
".",
"Graph",
".",
"unique_name",
"returns",
"a",
"unique",
"operation",
"name",
"for",
"name",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L384-L413 |
241,722 | tensorflow/mesh | mesh_tensorflow/ops.py | Graph.combine_assignments | def combine_assignments(self, assignments):
"""Rewrite the current graph to combine "Assign" operations.
Combine similar Assign operations into grouped Assign operations.
This is useful when using the rewrite_stack_variables() optimization,
since variables can only be stacked if they are present in the... | python | def combine_assignments(self, assignments):
group_by_fn = collections.defaultdict(list)
for a in assignments:
if not isinstance(a, Assign):
raise ValueError("ops should be instances of mtf.Assign")
group_by_fn[a.assign_fn].append(a)
assignments_set = set(assignments)
self._operations... | [
"def",
"combine_assignments",
"(",
"self",
",",
"assignments",
")",
":",
"group_by_fn",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"a",
"in",
"assignments",
":",
"if",
"not",
"isinstance",
"(",
"a",
",",
"Assign",
")",
":",
"raise",
... | Rewrite the current graph to combine "Assign" operations.
Combine similar Assign operations into grouped Assign operations.
This is useful when using the rewrite_stack_variables() optimization,
since variables can only be stacked if they are present in the same set
of Assign operations.
This funct... | [
"Rewrite",
"the",
"current",
"graph",
"to",
"combine",
"Assign",
"operations",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L534-L567 |
241,723 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.tensor_layout | def tensor_layout(self, arg):
"""Compute TensorLayout for a Tensor or a Shape.
Args:
arg: Tensor or Shape.
Returns:
TensorLayout.
"""
if isinstance(arg, Tensor):
arg = arg.shape
return self.layout_rules.tensor_layout(arg, self.shape) | python | def tensor_layout(self, arg):
if isinstance(arg, Tensor):
arg = arg.shape
return self.layout_rules.tensor_layout(arg, self.shape) | [
"def",
"tensor_layout",
"(",
"self",
",",
"arg",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"Tensor",
")",
":",
"arg",
"=",
"arg",
".",
"shape",
"return",
"self",
".",
"layout_rules",
".",
"tensor_layout",
"(",
"arg",
",",
"self",
".",
"shape",
"... | Compute TensorLayout for a Tensor or a Shape.
Args:
arg: Tensor or Shape.
Returns:
TensorLayout. | [
"Compute",
"TensorLayout",
"for",
"a",
"Tensor",
"or",
"a",
"Shape",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L803-L814 |
241,724 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.mesh_axis_to_cumprod | def mesh_axis_to_cumprod(self, tensor_shape):
"""For each mesh axis, give the product of previous tensor axes.
Args:
tensor_shape: Shape.
Returns:
list with length self.ndims where each element is an integer or None.
"""
tensor_layout = self.tensor_layout(tensor_shape)
ma2ta = tens... | python | def mesh_axis_to_cumprod(self, tensor_shape):
tensor_layout = self.tensor_layout(tensor_shape)
ma2ta = tensor_layout.mesh_axis_to_tensor_axis(self.ndims)
ta2cumprod = tensor_shape.cumprod
return [None if ta is None else ta2cumprod[ta] for ta in ma2ta] | [
"def",
"mesh_axis_to_cumprod",
"(",
"self",
",",
"tensor_shape",
")",
":",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"ma2ta",
"=",
"tensor_layout",
".",
"mesh_axis_to_tensor_axis",
"(",
"self",
".",
"ndims",
")",
"ta2cumprod",
... | For each mesh axis, give the product of previous tensor axes.
Args:
tensor_shape: Shape.
Returns:
list with length self.ndims where each element is an integer or None. | [
"For",
"each",
"mesh",
"axis",
"give",
"the",
"product",
"of",
"previous",
"tensor",
"axes",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L816-L828 |
241,725 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.slice_shape | def slice_shape(self, tensor_shape):
"""Shape of each slice of the Tensor.
Args:
tensor_shape: Shape.
Returns:
list of integers with length tensor_shape.ndims.
Raises:
ValueError: If a Tensor dimension is not divisible by the corresponding
Mesh dimension.
"""
tensor_... | python | def slice_shape(self, tensor_shape):
tensor_layout = self.tensor_layout(tensor_shape)
ret = []
for tensor_dim, mesh_axis in zip(
tensor_shape, tensor_layout.tensor_axis_to_mesh_axis):
if mesh_axis is None:
ret.append(tensor_dim.size)
else:
mesh_dim = self.shape[mesh_axis]... | [
"def",
"slice_shape",
"(",
"self",
",",
"tensor_shape",
")",
":",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"ret",
"=",
"[",
"]",
"for",
"tensor_dim",
",",
"mesh_axis",
"in",
"zip",
"(",
"tensor_shape",
",",
"tensor_layout... | Shape of each slice of the Tensor.
Args:
tensor_shape: Shape.
Returns:
list of integers with length tensor_shape.ndims.
Raises:
ValueError: If a Tensor dimension is not divisible by the corresponding
Mesh dimension. | [
"Shape",
"of",
"each",
"slice",
"of",
"the",
"Tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L830-L857 |
241,726 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.slice_begin | def slice_begin(self, tensor_shape, pnum):
"""Begin position for the tensor slice for the given processor.
Args:
tensor_shape: Shape.
pnum: int <= self.size.
Returns:
list of integers with length tensor_shape.ndims.
"""
tensor_layout = self.tensor_layout(tensor_shape)
coordin... | python | def slice_begin(self, tensor_shape, pnum):
tensor_layout = self.tensor_layout(tensor_shape)
coordinates = pnum_to_processor_coordinates(self.shape, pnum)
ret = []
for dim_size, mesh_axis in zip(
tensor_shape.to_integer_list, tensor_layout.tensor_axis_to_mesh_axis):
if mesh_axis is None:
... | [
"def",
"slice_begin",
"(",
"self",
",",
"tensor_shape",
",",
"pnum",
")",
":",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"coordinates",
"=",
"pnum_to_processor_coordinates",
"(",
"self",
".",
"shape",
",",
"pnum",
")",
"ret"... | Begin position for the tensor slice for the given processor.
Args:
tensor_shape: Shape.
pnum: int <= self.size.
Returns:
list of integers with length tensor_shape.ndims. | [
"Begin",
"position",
"for",
"the",
"tensor",
"slice",
"for",
"the",
"given",
"processor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L859-L879 |
241,727 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.Print | def Print(self, x, data, message, **kwargs): # pylint: disable=invalid-name
"""Calls tf.Print.
Args:
x: LaidOutTensor.
data: list of LaidOutTensor.
message: str.
**kwargs: keyword arguments to tf.print.
Returns:
LaidOutTensor.
"""
del data, message, kwargs
tf.log... | python | def Print(self, x, data, message, **kwargs): # pylint: disable=invalid-name
del data, message, kwargs
tf.logging.warning("Warning - mtf.Print not implemented for this mesh type")
return x | [
"def",
"Print",
"(",
"self",
",",
"x",
",",
"data",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"del",
"data",
",",
"message",
",",
"kwargs",
"tf",
".",
"logging",
".",
"warning",
"(",
"\"Warning - mtf.Print not imple... | Calls tf.Print.
Args:
x: LaidOutTensor.
data: list of LaidOutTensor.
message: str.
**kwargs: keyword arguments to tf.print.
Returns:
LaidOutTensor. | [
"Calls",
"tf",
".",
"Print",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L908-L922 |
241,728 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.allsplit | def allsplit(self, x, mesh_axis, split_axis, which=None):
"""Inverse of allconcat - split each slice and keep only one piece of it.
The number of ways to split is the number of processors in the group.
The part that is kept corresponds to the processor's index in the group.
Args:
x: LaidOutTenso... | python | def allsplit(self, x, mesh_axis, split_axis, which=None):
if which is None:
which = self.laid_out_pcoord(mesh_axis)
num_splits = self.shape[mesh_axis].size
def my_fn(x, which):
slice_begin = [
dimsize // num_splits * which if i == split_axis else 0
for i, dimsize in enumerate... | [
"def",
"allsplit",
"(",
"self",
",",
"x",
",",
"mesh_axis",
",",
"split_axis",
",",
"which",
"=",
"None",
")",
":",
"if",
"which",
"is",
"None",
":",
"which",
"=",
"self",
".",
"laid_out_pcoord",
"(",
"mesh_axis",
")",
"num_splits",
"=",
"self",
".",
... | Inverse of allconcat - split each slice and keep only one piece of it.
The number of ways to split is the number of processors in the group.
The part that is kept corresponds to the processor's index in the group.
Args:
x: LaidOutTensor.
mesh_axis: int, the mesh axis along which to split.
... | [
"Inverse",
"of",
"allconcat",
"-",
"split",
"each",
"slice",
"and",
"keep",
"only",
"one",
"piece",
"of",
"it",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L937-L964 |
241,729 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.shift_by_n_processors | def shift_by_n_processors(self, x, mesh_axis, offset, wrap):
"""Receive the slice from processor pcoord - offset.
Args:
x: a LaidOutTensor
mesh_axis: an integer
offset: an integer
wrap: a boolean. If True, then wrap around. Otherwise, pad with zeros.
"""
n = self.shape[mesh_axis... | python | def shift_by_n_processors(self, x, mesh_axis, offset, wrap):
n = self.shape[mesh_axis].size
source_pcoord = []
for i in xrange(n):
c = i - offset
if c != c % n:
if wrap:
c = c % n
else:
c = None
source_pcoord.append(c)
return self.receive(x, mesh_axi... | [
"def",
"shift_by_n_processors",
"(",
"self",
",",
"x",
",",
"mesh_axis",
",",
"offset",
",",
"wrap",
")",
":",
"n",
"=",
"self",
".",
"shape",
"[",
"mesh_axis",
"]",
".",
"size",
"source_pcoord",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"n",
... | Receive the slice from processor pcoord - offset.
Args:
x: a LaidOutTensor
mesh_axis: an integer
offset: an integer
wrap: a boolean. If True, then wrap around. Otherwise, pad with zeros. | [
"Receive",
"the",
"slice",
"from",
"processor",
"pcoord",
"-",
"offset",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1017-L1036 |
241,730 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.laid_out_pcoord | def laid_out_pcoord(self, mesh_axis):
"""Returns a LaidOutTensor containing the processor coordinate.
Args:
mesh_axis: int.
Returns:
LaidOutTensor where each slice is an integer scalar.
"""
divisor = list_product(self.shape.to_integer_list[mesh_axis + 1:])
modulus = self.shape[mesh... | python | def laid_out_pcoord(self, mesh_axis):
divisor = list_product(self.shape.to_integer_list[mesh_axis + 1:])
modulus = self.shape[mesh_axis].size
def my_fn(pnum):
return (pnum // divisor) % modulus
return self.slicewise(my_fn, self.laid_out_pnum()) | [
"def",
"laid_out_pcoord",
"(",
"self",
",",
"mesh_axis",
")",
":",
"divisor",
"=",
"list_product",
"(",
"self",
".",
"shape",
".",
"to_integer_list",
"[",
"mesh_axis",
"+",
"1",
":",
"]",
")",
"modulus",
"=",
"self",
".",
"shape",
"[",
"mesh_axis",
"]",
... | Returns a LaidOutTensor containing the processor coordinate.
Args:
mesh_axis: int.
Returns:
LaidOutTensor where each slice is an integer scalar. | [
"Returns",
"a",
"LaidOutTensor",
"containing",
"the",
"processor",
"coordinate",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1046-L1059 |
241,731 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.laid_out_slice_num | def laid_out_slice_num(self, tensor_shape):
"""A LaidOutTensor with an int32 scalar, identical for identical slices.
This is useful for synchronizing random operations.
Args:
tensor_shape: a TensorShape
Returns:
a LaidOutTensor where each slice is an integer scalar.
"""
ret = self.... | python | def laid_out_slice_num(self, tensor_shape):
ret = self.slicewise(lambda: tf.to_int32(0))
tensor_layout = self.tensor_layout(tensor_shape)
for mesh_axis in tensor_layout.tensor_axis_to_mesh_axis:
if mesh_axis is not None:
def my_fn(x, pcoord, mesh_dim_size):
return x * mesh_dim_size +... | [
"def",
"laid_out_slice_num",
"(",
"self",
",",
"tensor_shape",
")",
":",
"ret",
"=",
"self",
".",
"slicewise",
"(",
"lambda",
":",
"tf",
".",
"to_int32",
"(",
"0",
")",
")",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"f... | A LaidOutTensor with an int32 scalar, identical for identical slices.
This is useful for synchronizing random operations.
Args:
tensor_shape: a TensorShape
Returns:
a LaidOutTensor where each slice is an integer scalar. | [
"A",
"LaidOutTensor",
"with",
"an",
"int32",
"scalar",
"identical",
"for",
"identical",
"slices",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1061-L1080 |
241,732 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.broadcast_impl | def broadcast_impl(self, old_slices, old_shape, new_shape):
"""Implementation of a broadcast operation.
Args:
old_slices: LaidOutTensor.
old_shape: Shape.
new_shape: Shape.
Returns:
LaidOutTensor.
"""
new_slice_shape = self.slice_shape(new_shape)
def tf_fn(x):
ret... | python | def broadcast_impl(self, old_slices, old_shape, new_shape):
new_slice_shape = self.slice_shape(new_shape)
def tf_fn(x):
return (tf.zeros(new_slice_shape, dtype=x.dtype) +
_expand_dims(x, old_shape, new_shape))
return self.slicewise(tf_fn, old_slices) | [
"def",
"broadcast_impl",
"(",
"self",
",",
"old_slices",
",",
"old_shape",
",",
"new_shape",
")",
":",
"new_slice_shape",
"=",
"self",
".",
"slice_shape",
"(",
"new_shape",
")",
"def",
"tf_fn",
"(",
"x",
")",
":",
"return",
"(",
"tf",
".",
"zeros",
"(",
... | Implementation of a broadcast operation.
Args:
old_slices: LaidOutTensor.
old_shape: Shape.
new_shape: Shape.
Returns:
LaidOutTensor. | [
"Implementation",
"of",
"a",
"broadcast",
"operation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1082-L1097 |
241,733 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.make_slices | def make_slices(self, tf_tensor, tensor_shape):
"""Turns a single tf.Tensor into a list of slices, one for each processor.
Args:
tf_tensor: tf.Tensor.
tensor_shape: Shape.
Returns:
list of tf.tensor with length self.size.
"""
tensor_layout = self.tensor_layout(tensor_shape)
s... | python | def make_slices(self, tf_tensor, tensor_shape):
tensor_layout = self.tensor_layout(tensor_shape)
slice_shape = self.slice_shape(tensor_shape)
def my_fn(pnum):
if tensor_layout.is_fully_replicated:
return tf_tensor
else:
slice_begin = self.slice_begin(tensor_shape, pnum)
r... | [
"def",
"make_slices",
"(",
"self",
",",
"tf_tensor",
",",
"tensor_shape",
")",
":",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"slice_shape",
"=",
"self",
".",
"slice_shape",
"(",
"tensor_shape",
")",
"def",
"my_fn",
"(",
"... | Turns a single tf.Tensor into a list of slices, one for each processor.
Args:
tf_tensor: tf.Tensor.
tensor_shape: Shape.
Returns:
list of tf.tensor with length self.size. | [
"Turns",
"a",
"single",
"tf",
".",
"Tensor",
"into",
"a",
"list",
"of",
"slices",
"one",
"for",
"each",
"processor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1099-L1119 |
241,734 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.combine_slices | def combine_slices(self, slices, tensor_shape, device=None):
"""Turns a set of slices into a single tensor.
Args:
slices: list of tf.Tensor with length self.size.
tensor_shape: Shape.
device: optional str. If absent, we use the devices of the slices.
Returns:
tf.Tensor.
"""
... | python | def combine_slices(self, slices, tensor_shape, device=None):
if tensor_shape.ndims == 0:
return slices[0]
ret = slices[:]
tensor_layout = self.tensor_layout(tensor_shape)
for mesh_dim, tensor_axis in zip(
self.shape, tensor_layout.mesh_axis_to_tensor_axis(self.ndims)):
slice_size = ... | [
"def",
"combine_slices",
"(",
"self",
",",
"slices",
",",
"tensor_shape",
",",
"device",
"=",
"None",
")",
":",
"if",
"tensor_shape",
".",
"ndims",
"==",
"0",
":",
"return",
"slices",
"[",
"0",
"]",
"ret",
"=",
"slices",
"[",
":",
"]",
"tensor_layout",... | Turns a set of slices into a single tensor.
Args:
slices: list of tf.Tensor with length self.size.
tensor_shape: Shape.
device: optional str. If absent, we use the devices of the slices.
Returns:
tf.Tensor. | [
"Turns",
"a",
"set",
"of",
"slices",
"into",
"a",
"single",
"tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1121-L1155 |
241,735 | tensorflow/mesh | mesh_tensorflow/ops.py | Operation._initialize_splittable_and_unsplittable_dims | def _initialize_splittable_and_unsplittable_dims(
self, default_splittability, exception_dims_iterable=None):
"""Initializer for splittable_dims and unsplittable_dims.
Helper method to categorize all dimensions in the input/output tensors as
either splittable or unsplittable.
Args:
default... | python | def _initialize_splittable_and_unsplittable_dims(
self, default_splittability, exception_dims_iterable=None):
default_dims = set()
exception_dims = set()
if exception_dims_iterable:
exception_dims.update(exception_dims_iterable)
for t in itertools.chain(self.inputs, self.outputs):
for... | [
"def",
"_initialize_splittable_and_unsplittable_dims",
"(",
"self",
",",
"default_splittability",
",",
"exception_dims_iterable",
"=",
"None",
")",
":",
"default_dims",
"=",
"set",
"(",
")",
"exception_dims",
"=",
"set",
"(",
")",
"if",
"exception_dims_iterable",
":",... | Initializer for splittable_dims and unsplittable_dims.
Helper method to categorize all dimensions in the input/output tensors as
either splittable or unsplittable.
Args:
default_splittability: a string which is either "splittable" or
"unsplittable".
exception_dims_iterable: an optional... | [
"Initializer",
"for",
"splittable_dims",
"and",
"unsplittable_dims",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1448-L1486 |
241,736 | tensorflow/mesh | mesh_tensorflow/ops.py | ReshapeOperation.lower | def lower(self, lowering):
"""Lower the ReshapeOperation.
Reshaping can require collective communication between processors.
We haven't yet implemented all possible reshapes. We try to handle the
common cases here - otherwise we raise a NotImplementedError.
Args:
lowering: a Lowering
Ra... | python | def lower(self, lowering):
old_shape = self.inputs[0].shape
new_shape = self.outputs[0].shape
mesh_impl = lowering.mesh_impl(self)
slices = lowering.tensors[self.inputs[0]]
mesh_axis_to_cumprod_old = mesh_impl.mesh_axis_to_cumprod(old_shape)
mesh_axis_to_cumprod_new = mesh_impl.mesh_axis_to_cump... | [
"def",
"lower",
"(",
"self",
",",
"lowering",
")",
":",
"old_shape",
"=",
"self",
".",
"inputs",
"[",
"0",
"]",
".",
"shape",
"new_shape",
"=",
"self",
".",
"outputs",
"[",
"0",
"]",
".",
"shape",
"mesh_impl",
"=",
"lowering",
".",
"mesh_impl",
"(",
... | Lower the ReshapeOperation.
Reshaping can require collective communication between processors.
We haven't yet implemented all possible reshapes. We try to handle the
common cases here - otherwise we raise a NotImplementedError.
Args:
lowering: a Lowering
Raises:
NotImplementedError: i... | [
"Lower",
"the",
"ReshapeOperation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3478-L3558 |
241,737 | tensorflow/mesh | mesh_tensorflow/transformer/utils.py | get_variable_dtype | def get_variable_dtype(
master_dtype=tf.bfloat16,
slice_dtype=tf.float32,
activation_dtype=tf.float32):
"""Datatypes to use for the run.
Args:
master_dtype: string, datatype for checkpoints
keep this the same between training and eval/inference
slice_dtype: string, datatype for variables ... | python | def get_variable_dtype(
master_dtype=tf.bfloat16,
slice_dtype=tf.float32,
activation_dtype=tf.float32):
return mtf.VariableDType(
master_dtype=tf.as_dtype(master_dtype),
slice_dtype=tf.as_dtype(slice_dtype),
activation_dtype=tf.as_dtype(activation_dtype)) | [
"def",
"get_variable_dtype",
"(",
"master_dtype",
"=",
"tf",
".",
"bfloat16",
",",
"slice_dtype",
"=",
"tf",
".",
"float32",
",",
"activation_dtype",
"=",
"tf",
".",
"float32",
")",
":",
"return",
"mtf",
".",
"VariableDType",
"(",
"master_dtype",
"=",
"tf",
... | Datatypes to use for the run.
Args:
master_dtype: string, datatype for checkpoints
keep this the same between training and eval/inference
slice_dtype: string, datatype for variables in memory
must be tf.float32 for training
activation_dtype: string, datatype for activations
less memory ... | [
"Datatypes",
"to",
"use",
"for",
"the",
"run",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L38-L57 |
241,738 | tensorflow/mesh | mesh_tensorflow/transformer/utils.py | build_model | def build_model(model_type="bitransformer",
input_vocab_size=gin.REQUIRED,
output_vocab_size=gin.REQUIRED,
layout_rules=None,
mesh_shape=None):
"""Build a transformer model.
Currently, three types of models are supported:
"bitransformer": The tradi... | python | def build_model(model_type="bitransformer",
input_vocab_size=gin.REQUIRED,
output_vocab_size=gin.REQUIRED,
layout_rules=None,
mesh_shape=None):
if model_type == "bitransformer":
return transformer.make_bitransformer(
input_vocab_size=input_vo... | [
"def",
"build_model",
"(",
"model_type",
"=",
"\"bitransformer\"",
",",
"input_vocab_size",
"=",
"gin",
".",
"REQUIRED",
",",
"output_vocab_size",
"=",
"gin",
".",
"REQUIRED",
",",
"layout_rules",
"=",
"None",
",",
"mesh_shape",
"=",
"None",
")",
":",
"if",
... | Build a transformer model.
Currently, three types of models are supported:
"bitransformer": The traditional encoder-decoder architecture from
"attention is all you need". Requires a non-text2self dataset.
"lm": an autoregressive language model (one layer stack). This is similar
to the decoder part ... | [
"Build",
"a",
"transformer",
"model",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L94-L139 |
241,739 | tensorflow/mesh | mesh_tensorflow/transformer/utils.py | decode_from_file | def decode_from_file(estimator,
vocabulary,
model_type,
batch_size,
sequence_length,
checkpoint_path="",
input_filename=gin.REQUIRED,
output_filename=gin.REQUIRED,
... | python | def decode_from_file(estimator,
vocabulary,
model_type,
batch_size,
sequence_length,
checkpoint_path="",
input_filename=gin.REQUIRED,
output_filename=gin.REQUIRED,
... | [
"def",
"decode_from_file",
"(",
"estimator",
",",
"vocabulary",
",",
"model_type",
",",
"batch_size",
",",
"sequence_length",
",",
"checkpoint_path",
"=",
"\"\"",
",",
"input_filename",
"=",
"gin",
".",
"REQUIRED",
",",
"output_filename",
"=",
"gin",
".",
"REQUI... | Decode from a text file.
Args:
estimator: a TPUEstimator
vocabulary: a mtf.transformer.vocabulary.Vocabulary
model_type: a string
batch_size: an integer
sequence_length: an integer (maximum decode length)
checkpoint_path: an optional string
input_filename: a string
output_filename: a ... | [
"Decode",
"from",
"a",
"text",
"file",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L385-L473 |
241,740 | tensorflow/mesh | mesh_tensorflow/transformer/utils.py | clean_decodes | def clean_decodes(ids, vocab_size, eos_id=1):
"""Stop at EOS or padding or OOV.
Args:
ids: a list of integers
vocab_size: an integer
eos_id: EOS id
Returns:
a list of integers
"""
ret = []
for i in ids:
if i == eos_id:
break
if i >= vocab_size:
break
ret.append(int(... | python | def clean_decodes(ids, vocab_size, eos_id=1):
ret = []
for i in ids:
if i == eos_id:
break
if i >= vocab_size:
break
ret.append(int(i))
return ret | [
"def",
"clean_decodes",
"(",
"ids",
",",
"vocab_size",
",",
"eos_id",
"=",
"1",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"i",
"in",
"ids",
":",
"if",
"i",
"==",
"eos_id",
":",
"break",
"if",
"i",
">=",
"vocab_size",
":",
"break",
"ret",
".",
"appen... | Stop at EOS or padding or OOV.
Args:
ids: a list of integers
vocab_size: an integer
eos_id: EOS id
Returns:
a list of integers | [
"Stop",
"at",
"EOS",
"or",
"padding",
"or",
"OOV",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L477-L495 |
241,741 | tensorflow/mesh | mesh_tensorflow/transformer/utils.py | auto_batch_size | def auto_batch_size(sequence_length,
mesh_shape,
layout_rules,
tokens_per_split=2048):
"""Automatically compute batch size.
Args:
sequence_length: an integer
mesh_shape: an input to mtf.convert_to_shape()
layout_rules: an input to mtf.convert_... | python | def auto_batch_size(sequence_length,
mesh_shape,
layout_rules,
tokens_per_split=2048):
num_splits = mtf.tensor_dim_to_mesh_dim_size(
layout_rules, mesh_shape, mtf.Dimension("batch", 0))
ret = max(1, tokens_per_split // sequence_length) * num_splits
... | [
"def",
"auto_batch_size",
"(",
"sequence_length",
",",
"mesh_shape",
",",
"layout_rules",
",",
"tokens_per_split",
"=",
"2048",
")",
":",
"num_splits",
"=",
"mtf",
".",
"tensor_dim_to_mesh_dim_size",
"(",
"layout_rules",
",",
"mesh_shape",
",",
"mtf",
".",
"Dimens... | Automatically compute batch size.
Args:
sequence_length: an integer
mesh_shape: an input to mtf.convert_to_shape()
layout_rules: an input to mtf.convert_to_layout_rules()
tokens_per_split: an integer
Returns:
an integer | [
"Automatically",
"compute",
"batch",
"size",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L499-L520 |
241,742 | tensorflow/mesh | mesh_tensorflow/transformer/utils.py | evaluate | def evaluate(estimator, eval_args):
"""Runs evaluation on the latest model checkpoint & logs to tensorboard.
Args:
estimator: A tf.Estimator object.
eval_args: Dictionary of {eval_name: (input_fn, eval_steps)} where eval_name
is the name of the evaluation set, e.g. "train" or "val", input_fn is an
... | python | def evaluate(estimator, eval_args):
values = {} # Default return value if evaluation fails.
checkpoint_path = estimator.latest_checkpoint()
if not checkpoint_path:
# This is expected if the training job has not yet saved a checkpoint.
return values
tf.logging.info("Starting evaluation on checkpoint %... | [
"def",
"evaluate",
"(",
"estimator",
",",
"eval_args",
")",
":",
"values",
"=",
"{",
"}",
"# Default return value if evaluation fails.",
"checkpoint_path",
"=",
"estimator",
".",
"latest_checkpoint",
"(",
")",
"if",
"not",
"checkpoint_path",
":",
"# This is expected i... | Runs evaluation on the latest model checkpoint & logs to tensorboard.
Args:
estimator: A tf.Estimator object.
eval_args: Dictionary of {eval_name: (input_fn, eval_steps)} where eval_name
is the name of the evaluation set, e.g. "train" or "val", input_fn is an
input function returning a tuple (fea... | [
"Runs",
"evaluation",
"on",
"the",
"latest",
"model",
"checkpoint",
"&",
"logs",
"to",
"tensorboard",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L715-L750 |
241,743 | tensorflow/mesh | mesh_tensorflow/simd_mesh_impl.py | _ring_2d | def _ring_2d(m, n):
"""Ring-order of a mxn mesh.
Args:
m: an integer
n: an integer
Returns:
a list of mxn pairs
"""
if m == 1:
return [(0, i) for i in range(n)]
if n == 1:
return [(i, 0) for i in range(m)]
if m % 2 != 0:
tf.logging.warning("Odd dimension")
return [(i % m, i //... | python | def _ring_2d(m, n):
if m == 1:
return [(0, i) for i in range(n)]
if n == 1:
return [(i, 0) for i in range(m)]
if m % 2 != 0:
tf.logging.warning("Odd dimension")
return [(i % m, i // m) for i in range(n * m)]
ret = [(0, 0)]
for i in range(m // 2):
for j in range(1, n):
ret.append((2 *... | [
"def",
"_ring_2d",
"(",
"m",
",",
"n",
")",
":",
"if",
"m",
"==",
"1",
":",
"return",
"[",
"(",
"0",
",",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"if",
"n",
"==",
"1",
":",
"return",
"[",
"(",
"i",
",",
"0",
")",
"for",... | Ring-order of a mxn mesh.
Args:
m: an integer
n: an integer
Returns:
a list of mxn pairs | [
"Ring",
"-",
"order",
"of",
"a",
"mxn",
"mesh",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/simd_mesh_impl.py#L568-L592 |
241,744 | tensorflow/mesh | mesh_tensorflow/simd_mesh_impl.py | tile_2d | def tile_2d(physical_shape, tile_shape,
outer_name="outer",
inner_name="inner",
cores_name=None):
"""2D tiling of a 3d physical mesh.
The "outer" mesh dimension corresponds to which tile.
The "inner" mesh dimension corresponds to the position within a tile
of processors.
... | python | def tile_2d(physical_shape, tile_shape,
outer_name="outer",
inner_name="inner",
cores_name=None):
logical_to_physical = []
p0, p1, p2 = physical_shape
t0, t1 = tile_shape
tile_ring = _ring_2d(t0, t1)
tiles_ring = _ring_2d(p0 // t0, p1 // t1)
for logical_pnum in range(p0 *... | [
"def",
"tile_2d",
"(",
"physical_shape",
",",
"tile_shape",
",",
"outer_name",
"=",
"\"outer\"",
",",
"inner_name",
"=",
"\"inner\"",
",",
"cores_name",
"=",
"None",
")",
":",
"logical_to_physical",
"=",
"[",
"]",
"p0",
",",
"p1",
",",
"p2",
"=",
"physical... | 2D tiling of a 3d physical mesh.
The "outer" mesh dimension corresponds to which tile.
The "inner" mesh dimension corresponds to the position within a tile
of processors.
Optionally, if cores_name is specified, then a 3 dimensional logical mesh
is returned, with the third dimension representing the two diff... | [
"2D",
"tiling",
"of",
"a",
"3d",
"physical",
"mesh",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/simd_mesh_impl.py#L595-L661 |
241,745 | tensorflow/mesh | mesh_tensorflow/simd_mesh_impl.py | SimdMeshImpl.slice | def slice(self, tf_tensor, tensor_shape):
""""Slice out the corresponding part of tensor given the pnum variable."""
tensor_layout = self.tensor_layout(tensor_shape)
if tensor_layout.is_fully_replicated:
return self.LaidOutTensor([tf_tensor])
else:
slice_shape = self.slice_shape(tensor_shap... | python | def slice(self, tf_tensor, tensor_shape):
"tensor_layout = self.tensor_layout(tensor_shape)
if tensor_layout.is_fully_replicated:
return self.LaidOutTensor([tf_tensor])
else:
slice_shape = self.slice_shape(tensor_shape)
slice_begins = [
self.slice_begin(tensor_shape, pnum) for p... | [
"def",
"slice",
"(",
"self",
",",
"tf_tensor",
",",
"tensor_shape",
")",
":",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"if",
"tensor_layout",
".",
"is_fully_replicated",
":",
"return",
"self",
".",
"LaidOutTensor",
"(",
"["... | Slice out the corresponding part of tensor given the pnum variable. | [
"Slice",
"out",
"the",
"corresponding",
"part",
"of",
"tensor",
"given",
"the",
"pnum",
"variable",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/simd_mesh_impl.py#L443-L458 |
241,746 | tensorflow/mesh | examples/mnist_dataset.py | read32 | def read32(bytestream):
"""Read 4 bytes from bytestream as an unsigned 32-bit integer."""
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(4), dtype=dt)[0] | python | def read32(bytestream):
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(4), dtype=dt)[0] | [
"def",
"read32",
"(",
"bytestream",
")",
":",
"dt",
"=",
"np",
".",
"dtype",
"(",
"np",
".",
"uint32",
")",
".",
"newbyteorder",
"(",
"'>'",
")",
"return",
"np",
".",
"frombuffer",
"(",
"bytestream",
".",
"read",
"(",
"4",
")",
",",
"dtype",
"=",
... | Read 4 bytes from bytestream as an unsigned 32-bit integer. | [
"Read",
"4",
"bytes",
"from",
"bytestream",
"as",
"an",
"unsigned",
"32",
"-",
"bit",
"integer",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist_dataset.py#L45-L48 |
241,747 | tensorflow/mesh | examples/mnist_dataset.py | check_image_file_header | def check_image_file_header(filename):
"""Validate that filename corresponds to images for the MNIST dataset."""
with tf.gfile.Open(filename, 'rb') as f:
magic = read32(f)
read32(f) # num_images, unused
rows = read32(f)
cols = read32(f)
if magic != 2051:
raise ValueError('Invalid magic nu... | python | def check_image_file_header(filename):
with tf.gfile.Open(filename, 'rb') as f:
magic = read32(f)
read32(f) # num_images, unused
rows = read32(f)
cols = read32(f)
if magic != 2051:
raise ValueError('Invalid magic number %d in MNIST file %s' % (magic,
... | [
"def",
"check_image_file_header",
"(",
"filename",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"magic",
"=",
"read32",
"(",
"f",
")",
"read32",
"(",
"f",
")",
"# num_images, unused",
"rows",
"="... | Validate that filename corresponds to images for the MNIST dataset. | [
"Validate",
"that",
"filename",
"corresponds",
"to",
"images",
"for",
"the",
"MNIST",
"dataset",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist_dataset.py#L51-L64 |
241,748 | tensorflow/mesh | examples/mnist_dataset.py | check_labels_file_header | def check_labels_file_header(filename):
"""Validate that filename corresponds to labels for the MNIST dataset."""
with tf.gfile.Open(filename, 'rb') as f:
magic = read32(f)
read32(f) # num_items, unused
if magic != 2049:
raise ValueError('Invalid magic number %d in MNIST file %s' % (magic,
... | python | def check_labels_file_header(filename):
with tf.gfile.Open(filename, 'rb') as f:
magic = read32(f)
read32(f) # num_items, unused
if magic != 2049:
raise ValueError('Invalid magic number %d in MNIST file %s' % (magic,
f.name)) | [
"def",
"check_labels_file_header",
"(",
"filename",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"magic",
"=",
"read32",
"(",
"f",
")",
"read32",
"(",
"f",
")",
"# num_items, unused",
"if",
"magi... | Validate that filename corresponds to labels for the MNIST dataset. | [
"Validate",
"that",
"filename",
"corresponds",
"to",
"labels",
"for",
"the",
"MNIST",
"dataset",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist_dataset.py#L67-L74 |
241,749 | tensorflow/mesh | examples/mnist_dataset.py | dataset | def dataset(directory, images_file, labels_file):
"""Download and parse MNIST dataset."""
images_file = download(directory, images_file)
labels_file = download(directory, labels_file)
check_image_file_header(images_file)
check_labels_file_header(labels_file)
def decode_image(image):
# Normalize from ... | python | def dataset(directory, images_file, labels_file):
images_file = download(directory, images_file)
labels_file = download(directory, labels_file)
check_image_file_header(images_file)
check_labels_file_header(labels_file)
def decode_image(image):
# Normalize from [0, 255] to [0.0, 1.0]
image = tf.decod... | [
"def",
"dataset",
"(",
"directory",
",",
"images_file",
",",
"labels_file",
")",
":",
"images_file",
"=",
"download",
"(",
"directory",
",",
"images_file",
")",
"labels_file",
"=",
"download",
"(",
"directory",
",",
"labels_file",
")",
"check_image_file_header",
... | Download and parse MNIST dataset. | [
"Download",
"and",
"parse",
"MNIST",
"dataset",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist_dataset.py#L95-L120 |
241,750 | mattjj/pyhsmm | pyhsmm/util/stats.py | sample_discrete | def sample_discrete(distn,size=[],dtype=np.int32):
'samples from a one-dimensional finite pmf'
distn = np.atleast_1d(distn)
assert (distn >=0).all() and distn.ndim == 1
if (0 == distn).all():
return np.random.randint(distn.shape[0],size=size)
cumvals = np.cumsum(distn)
return np.sum(np.a... | python | def sample_discrete(distn,size=[],dtype=np.int32):
'samples from a one-dimensional finite pmf'
distn = np.atleast_1d(distn)
assert (distn >=0).all() and distn.ndim == 1
if (0 == distn).all():
return np.random.randint(distn.shape[0],size=size)
cumvals = np.cumsum(distn)
return np.sum(np.a... | [
"def",
"sample_discrete",
"(",
"distn",
",",
"size",
"=",
"[",
"]",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
":",
"distn",
"=",
"np",
".",
"atleast_1d",
"(",
"distn",
")",
"assert",
"(",
"distn",
">=",
"0",
")",
".",
"all",
"(",
")",
"and",
... | samples from a one-dimensional finite pmf | [
"samples",
"from",
"a",
"one",
"-",
"dimensional",
"finite",
"pmf"
] | a9a39c2bfd539048e35877cb13283552eadc24e2 | https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/util/stats.py#L116-L123 |
241,751 | mattjj/pyhsmm | pyhsmm/models.py | _HMMBase.used_states | def used_states(self):
'a list of the used states in the order they appear'
c = itertools.count()
canonical_ids = collections.defaultdict(lambda: next(c))
for s in self.states_list:
for state in s.stateseq:
canonical_ids[state]
return list(map(operator... | python | def used_states(self):
'a list of the used states in the order they appear'
c = itertools.count()
canonical_ids = collections.defaultdict(lambda: next(c))
for s in self.states_list:
for state in s.stateseq:
canonical_ids[state]
return list(map(operator... | [
"def",
"used_states",
"(",
"self",
")",
":",
"c",
"=",
"itertools",
".",
"count",
"(",
")",
"canonical_ids",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"next",
"(",
"c",
")",
")",
"for",
"s",
"in",
"self",
".",
"states_list",
":",
"f... | a list of the used states in the order they appear | [
"a",
"list",
"of",
"the",
"used",
"states",
"in",
"the",
"order",
"they",
"appear"
] | a9a39c2bfd539048e35877cb13283552eadc24e2 | https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/models.py#L188-L196 |
241,752 | mattjj/pyhsmm | pyhsmm/util/plot.py | plot_gaussian_2D | def plot_gaussian_2D(mu, lmbda, color='b', centermarker=True,label='',alpha=1.,ax=None,artists=None):
'''
Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix.
'''
assert len(mu) == 2
ax = ax if ax else plt.gca()
# TODO use artists!
t = np.hstack([np.ara... | python | def plot_gaussian_2D(mu, lmbda, color='b', centermarker=True,label='',alpha=1.,ax=None,artists=None):
'''
Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix.
'''
assert len(mu) == 2
ax = ax if ax else plt.gca()
# TODO use artists!
t = np.hstack([np.ara... | [
"def",
"plot_gaussian_2D",
"(",
"mu",
",",
"lmbda",
",",
"color",
"=",
"'b'",
",",
"centermarker",
"=",
"True",
",",
"label",
"=",
"''",
",",
"alpha",
"=",
"1.",
",",
"ax",
"=",
"None",
",",
"artists",
"=",
"None",
")",
":",
"assert",
"len",
"(",
... | Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix. | [
"Plots",
"mean",
"and",
"cov",
"ellipsoid",
"into",
"current",
"axes",
".",
"Must",
"be",
"2D",
".",
"lmbda",
"is",
"a",
"covariance",
"matrix",
"."
] | a9a39c2bfd539048e35877cb13283552eadc24e2 | https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/util/plot.py#L7-L34 |
241,753 | mattjj/pyhsmm | pyhsmm/basic/abstractions.py | DurationDistribution.resample_with_censoring | def resample_with_censoring(self,data=[],censored_data=[]):
'''
censored_data is full of observations that were censored, meaning a
value of x really could have been anything >= x, so this method samples
them out to be at least that large
'''
filled_in = self._uncensor_da... | python | def resample_with_censoring(self,data=[],censored_data=[]):
'''
censored_data is full of observations that were censored, meaning a
value of x really could have been anything >= x, so this method samples
them out to be at least that large
'''
filled_in = self._uncensor_da... | [
"def",
"resample_with_censoring",
"(",
"self",
",",
"data",
"=",
"[",
"]",
",",
"censored_data",
"=",
"[",
"]",
")",
":",
"filled_in",
"=",
"self",
".",
"_uncensor_data",
"(",
"censored_data",
")",
"return",
"self",
".",
"resample",
"(",
"data",
"=",
"co... | censored_data is full of observations that were censored, meaning a
value of x really could have been anything >= x, so this method samples
them out to be at least that large | [
"censored_data",
"is",
"full",
"of",
"observations",
"that",
"were",
"censored",
"meaning",
"a",
"value",
"of",
"x",
"really",
"could",
"have",
"been",
"anything",
">",
"=",
"x",
"so",
"this",
"method",
"samples",
"them",
"out",
"to",
"be",
"at",
"least",
... | a9a39c2bfd539048e35877cb13283552eadc24e2 | https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/basic/abstractions.py#L70-L77 |
241,754 | mattjj/pyhsmm | pyhsmm/util/general.py | scoreatpercentile | def scoreatpercentile(data,per,axis=0):
'like the function in scipy.stats but with an axis argument and works on arrays'
a = np.sort(data,axis=axis)
idx = per/100. * (data.shape[axis]-1)
if (idx % 1 == 0):
return a[[slice(None) if ii != axis else idx for ii in range(a.ndim)]]
else:
... | python | def scoreatpercentile(data,per,axis=0):
'like the function in scipy.stats but with an axis argument and works on arrays'
a = np.sort(data,axis=axis)
idx = per/100. * (data.shape[axis]-1)
if (idx % 1 == 0):
return a[[slice(None) if ii != axis else idx for ii in range(a.ndim)]]
else:
... | [
"def",
"scoreatpercentile",
"(",
"data",
",",
"per",
",",
"axis",
"=",
"0",
")",
":",
"a",
"=",
"np",
".",
"sort",
"(",
"data",
",",
"axis",
"=",
"axis",
")",
"idx",
"=",
"per",
"/",
"100.",
"*",
"(",
"data",
".",
"shape",
"[",
"axis",
"]",
"... | like the function in scipy.stats but with an axis argument and works on arrays | [
"like",
"the",
"function",
"in",
"scipy",
".",
"stats",
"but",
"with",
"an",
"axis",
"argument",
"and",
"works",
"on",
"arrays"
] | a9a39c2bfd539048e35877cb13283552eadc24e2 | https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/util/general.py#L119-L131 |
241,755 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.content_type | def content_type(self, mime_type: Optional[MimeType] = None) -> str:
"""Get a random HTTP content type.
:return: Content type.
:Example:
Content-Type: application/json
"""
fmt = self.__file.mime_type(type_=mime_type)
return 'Content-Type: {}'.format(fmt) | python | def content_type(self, mime_type: Optional[MimeType] = None) -> str:
fmt = self.__file.mime_type(type_=mime_type)
return 'Content-Type: {}'.format(fmt) | [
"def",
"content_type",
"(",
"self",
",",
"mime_type",
":",
"Optional",
"[",
"MimeType",
"]",
"=",
"None",
")",
"->",
"str",
":",
"fmt",
"=",
"self",
".",
"__file",
".",
"mime_type",
"(",
"type_",
"=",
"mime_type",
")",
"return",
"'Content-Type: {}'",
"."... | Get a random HTTP content type.
:return: Content type.
:Example:
Content-Type: application/json | [
"Get",
"a",
"random",
"HTTP",
"content",
"type",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L46-L55 |
241,756 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.ip_v4 | def ip_v4(self, with_port: bool = False) -> str:
"""Generate a random IPv4 address.
:param with_port: Add port to IP.
:return: Random IPv4 address.
:Example:
19.121.223.58
"""
ip = '.'.join(str(self.random.randint(0, 255)) for _ in range(4))
if with... | python | def ip_v4(self, with_port: bool = False) -> str:
ip = '.'.join(str(self.random.randint(0, 255)) for _ in range(4))
if with_port:
ip += ':{}'.format(self.port())
return ip | [
"def",
"ip_v4",
"(",
"self",
",",
"with_port",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"ip",
"=",
"'.'",
".",
"join",
"(",
"str",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"255",
")",
")",
"for",
"_",
"in",
"range",
... | Generate a random IPv4 address.
:param with_port: Add port to IP.
:return: Random IPv4 address.
:Example:
19.121.223.58 | [
"Generate",
"a",
"random",
"IPv4",
"address",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L87-L101 |
241,757 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.ip_v6 | def ip_v6(self) -> str:
"""Generate a random IPv6 address.
:return: Random IPv6 address.
:Example:
2001:c244:cf9d:1fb1:c56d:f52c:8a04:94f3
"""
ipv6 = IPv6Address(
self.random.randint(
0, 2 ** 128 - 1,
),
)
retu... | python | def ip_v6(self) -> str:
ipv6 = IPv6Address(
self.random.randint(
0, 2 ** 128 - 1,
),
)
return str(ipv6) | [
"def",
"ip_v6",
"(",
"self",
")",
"->",
"str",
":",
"ipv6",
"=",
"IPv6Address",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"2",
"**",
"128",
"-",
"1",
",",
")",
",",
")",
"return",
"str",
"(",
"ipv6",
")"
] | Generate a random IPv6 address.
:return: Random IPv6 address.
:Example:
2001:c244:cf9d:1fb1:c56d:f52c:8a04:94f3 | [
"Generate",
"a",
"random",
"IPv6",
"address",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L103-L116 |
241,758 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.mac_address | def mac_address(self) -> str:
"""Generate a random MAC address.
:return: Random MAC address.
:Example:
00:16:3e:25:e7:b1
"""
mac_hex = [
0x00, 0x16, 0x3e,
self.random.randint(0x00, 0x7f),
self.random.randint(0x00, 0xff),
... | python | def mac_address(self) -> str:
mac_hex = [
0x00, 0x16, 0x3e,
self.random.randint(0x00, 0x7f),
self.random.randint(0x00, 0xff),
self.random.randint(0x00, 0xff),
]
mac = map(lambda x: '%02x' % x, mac_hex)
return ':'.join(mac) | [
"def",
"mac_address",
"(",
"self",
")",
"->",
"str",
":",
"mac_hex",
"=",
"[",
"0x00",
",",
"0x16",
",",
"0x3e",
",",
"self",
".",
"random",
".",
"randint",
"(",
"0x00",
",",
"0x7f",
")",
",",
"self",
".",
"random",
".",
"randint",
"(",
"0x00",
"... | Generate a random MAC address.
:return: Random MAC address.
:Example:
00:16:3e:25:e7:b1 | [
"Generate",
"a",
"random",
"MAC",
"address",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L118-L133 |
241,759 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.image_placeholder | def image_placeholder(width: Union[int, str] = 1920,
height: Union[int, str] = 1080) -> str:
"""Generate a link to the image placeholder.
:param width: Width of image.
:param height: Height of image.
:return: URL to image placeholder.
"""
url = ... | python | def image_placeholder(width: Union[int, str] = 1920,
height: Union[int, str] = 1080) -> str:
url = 'http://placehold.it/{width}x{height}'
return url.format(width=width, height=height) | [
"def",
"image_placeholder",
"(",
"width",
":",
"Union",
"[",
"int",
",",
"str",
"]",
"=",
"1920",
",",
"height",
":",
"Union",
"[",
"int",
",",
"str",
"]",
"=",
"1080",
")",
"->",
"str",
":",
"url",
"=",
"'http://placehold.it/{width}x{height}'",
"return"... | Generate a link to the image placeholder.
:param width: Width of image.
:param height: Height of image.
:return: URL to image placeholder. | [
"Generate",
"a",
"link",
"to",
"the",
"image",
"placeholder",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L146-L155 |
241,760 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.hashtags | def hashtags(self, quantity: int = 4) -> Union[str, list]:
"""Generate a list of hashtags.
:param quantity: The quantity of hashtags.
:return: The list of hashtags.
:raises NonEnumerableError: if category is not in Hashtag.
:Example:
['#love', '#sky', '#nice']
... | python | def hashtags(self, quantity: int = 4) -> Union[str, list]:
tags = ['#' + self.random.choice(HASHTAGS)
for _ in range(quantity)]
if int(quantity) == 1:
return tags[0]
return tags | [
"def",
"hashtags",
"(",
"self",
",",
"quantity",
":",
"int",
"=",
"4",
")",
"->",
"Union",
"[",
"str",
",",
"list",
"]",
":",
"tags",
"=",
"[",
"'#'",
"+",
"self",
".",
"random",
".",
"choice",
"(",
"HASHTAGS",
")",
"for",
"_",
"in",
"range",
"... | Generate a list of hashtags.
:param quantity: The quantity of hashtags.
:return: The list of hashtags.
:raises NonEnumerableError: if category is not in Hashtag.
:Example:
['#love', '#sky', '#nice'] | [
"Generate",
"a",
"list",
"of",
"hashtags",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L191-L207 |
241,761 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.home_page | def home_page(self, tld_type: Optional[TLDType] = None) -> str:
"""Generate a random home page.
:param tld_type: TLD type.
:return: Random home page.
:Example:
http://www.fontir.info
"""
resource = self.random.choice(USERNAMES)
domain = self.top_leve... | python | def home_page(self, tld_type: Optional[TLDType] = None) -> str:
resource = self.random.choice(USERNAMES)
domain = self.top_level_domain(
tld_type=tld_type,
)
return 'http://www.{}{}'.format(
resource, domain) | [
"def",
"home_page",
"(",
"self",
",",
"tld_type",
":",
"Optional",
"[",
"TLDType",
"]",
"=",
"None",
")",
"->",
"str",
":",
"resource",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"USERNAMES",
")",
"domain",
"=",
"self",
".",
"top_level_domain",
"(... | Generate a random home page.
:param tld_type: TLD type.
:return: Random home page.
:Example:
http://www.fontir.info | [
"Generate",
"a",
"random",
"home",
"page",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L209-L224 |
241,762 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.top_level_domain | def top_level_domain(self, tld_type: Optional[TLDType] = None) -> str:
"""Return random top level domain.
:param tld_type: Enum object DomainType
:return: Top level domain.
:raises NonEnumerableError: if tld_type not in DomainType.
"""
key = self._validate_enum(item=tld_... | python | def top_level_domain(self, tld_type: Optional[TLDType] = None) -> str:
key = self._validate_enum(item=tld_type, enum=TLDType)
return self.random.choice(TLD[key]) | [
"def",
"top_level_domain",
"(",
"self",
",",
"tld_type",
":",
"Optional",
"[",
"TLDType",
"]",
"=",
"None",
")",
"->",
"str",
":",
"key",
"=",
"self",
".",
"_validate_enum",
"(",
"item",
"=",
"tld_type",
",",
"enum",
"=",
"TLDType",
")",
"return",
"sel... | Return random top level domain.
:param tld_type: Enum object DomainType
:return: Top level domain.
:raises NonEnumerableError: if tld_type not in DomainType. | [
"Return",
"random",
"top",
"level",
"domain",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L226-L234 |
241,763 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.network_protocol | def network_protocol(self, layer: Optional[Layer] = None) -> str:
"""Get a random network protocol form OSI model.
:param layer: Enum object Layer.
:return: Protocol name.
:Example:
AMQP
"""
key = self._validate_enum(item=layer, enum=Layer)
protocols... | python | def network_protocol(self, layer: Optional[Layer] = None) -> str:
key = self._validate_enum(item=layer, enum=Layer)
protocols = NETWORK_PROTOCOLS[key]
return self.random.choice(protocols) | [
"def",
"network_protocol",
"(",
"self",
",",
"layer",
":",
"Optional",
"[",
"Layer",
"]",
"=",
"None",
")",
"->",
"str",
":",
"key",
"=",
"self",
".",
"_validate_enum",
"(",
"item",
"=",
"layer",
",",
"enum",
"=",
"Layer",
")",
"protocols",
"=",
"NET... | Get a random network protocol form OSI model.
:param layer: Enum object Layer.
:return: Protocol name.
:Example:
AMQP | [
"Get",
"a",
"random",
"network",
"protocol",
"form",
"OSI",
"model",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L247-L258 |
241,764 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.port | def port(self, port_range: PortRange = PortRange.ALL) -> int:
"""Generate random port.
:param port_range: Range enum object.
:return: Port number.
:raises NonEnumerableError: if port_range is not in PortRange.
:Example:
8080
"""
if port_range and por... | python | def port(self, port_range: PortRange = PortRange.ALL) -> int:
if port_range and port_range in PortRange:
return self.random.randint(*port_range.value)
else:
raise NonEnumerableError(PortRange) | [
"def",
"port",
"(",
"self",
",",
"port_range",
":",
"PortRange",
"=",
"PortRange",
".",
"ALL",
")",
"->",
"int",
":",
"if",
"port_range",
"and",
"port_range",
"in",
"PortRange",
":",
"return",
"self",
".",
"random",
".",
"randint",
"(",
"*",
"port_range"... | Generate random port.
:param port_range: Range enum object.
:return: Port number.
:raises NonEnumerableError: if port_range is not in PortRange.
:Example:
8080 | [
"Generate",
"random",
"port",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L260-L273 |
241,765 | lk-geimfari/mimesis | mimesis/providers/transport.py | Transport.truck | def truck(self, model_mask: str = '#### @@') -> str:
"""Generate a truck model.
:param model_mask: Mask of truck model. Here '@' is a
placeholder of characters and '#' is a placeholder of digits.
:return: Dummy truck model.
:Example:
Caledon-966O.
"""
... | python | def truck(self, model_mask: str = '#### @@') -> str:
return '{}-{}'.format(
self.random.choice(TRUCKS),
self.random.custom_code(model_mask),
) | [
"def",
"truck",
"(",
"self",
",",
"model_mask",
":",
"str",
"=",
"'#### @@'",
")",
"->",
"str",
":",
"return",
"'{}-{}'",
".",
"format",
"(",
"self",
".",
"random",
".",
"choice",
"(",
"TRUCKS",
")",
",",
"self",
".",
"random",
".",
"custom_code",
"(... | Generate a truck model.
:param model_mask: Mask of truck model. Here '@' is a
placeholder of characters and '#' is a placeholder of digits.
:return: Dummy truck model.
:Example:
Caledon-966O. | [
"Generate",
"a",
"truck",
"model",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/transport.py#L29-L42 |
241,766 | lk-geimfari/mimesis | mimesis/providers/transport.py | Transport.airplane | def airplane(self, model_mask: str = '###') -> str:
"""Generate a dummy airplane model.
:param model_mask: Mask of truck model. Here '@' is a
placeholder of characters and '#' is a placeholder of digits.
:return: Airplane model.
:Example:
Boeing 727.
"""... | python | def airplane(self, model_mask: str = '###') -> str:
model = self.random.custom_code(mask=model_mask)
plane = self.random.choice(AIRPLANES)
return '{} {}'.format(plane, model) | [
"def",
"airplane",
"(",
"self",
",",
"model_mask",
":",
"str",
"=",
"'###'",
")",
"->",
"str",
":",
"model",
"=",
"self",
".",
"random",
".",
"custom_code",
"(",
"mask",
"=",
"model_mask",
")",
"plane",
"=",
"self",
".",
"random",
".",
"choice",
"(",... | Generate a dummy airplane model.
:param model_mask: Mask of truck model. Here '@' is a
placeholder of characters and '#' is a placeholder of digits.
:return: Airplane model.
:Example:
Boeing 727. | [
"Generate",
"a",
"dummy",
"airplane",
"model",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/transport.py#L54-L66 |
241,767 | lk-geimfari/mimesis | mimesis/providers/transport.py | Transport.vehicle_registration_code | def vehicle_registration_code(self, locale: Optional[str] = None) -> str:
"""Get vehicle registration code of country.
:param locale: Registration code for locale (country).
:return: Vehicle registration code.
"""
if locale:
return VRC_BY_LOCALES[locale]
ret... | python | def vehicle_registration_code(self, locale: Optional[str] = None) -> str:
if locale:
return VRC_BY_LOCALES[locale]
return self.random.choice(VR_CODES) | [
"def",
"vehicle_registration_code",
"(",
"self",
",",
"locale",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"str",
":",
"if",
"locale",
":",
"return",
"VRC_BY_LOCALES",
"[",
"locale",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"("... | Get vehicle registration code of country.
:param locale: Registration code for locale (country).
:return: Vehicle registration code. | [
"Get",
"vehicle",
"registration",
"code",
"of",
"country",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/transport.py#L68-L77 |
241,768 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.bulk_create_datetimes | def bulk_create_datetimes(date_start: DateTime,
date_end: DateTime, **kwargs) -> List[DateTime]:
"""Bulk create datetime objects.
This method creates list of datetime objects from
``date_start`` to ``date_end``.
You can use the following keyword arguments:... | python | def bulk_create_datetimes(date_start: DateTime,
date_end: DateTime, **kwargs) -> List[DateTime]:
dt_objects = []
if not date_start and not date_end:
raise ValueError('You must pass date_start and date_end')
if date_end < date_start:
raise V... | [
"def",
"bulk_create_datetimes",
"(",
"date_start",
":",
"DateTime",
",",
"date_end",
":",
"DateTime",
",",
"*",
"*",
"kwargs",
")",
"->",
"List",
"[",
"DateTime",
"]",
":",
"dt_objects",
"=",
"[",
"]",
"if",
"not",
"date_start",
"and",
"not",
"date_end",
... | Bulk create datetime objects.
This method creates list of datetime objects from
``date_start`` to ``date_end``.
You can use the following keyword arguments:
* ``days``
* ``hours``
* ``minutes``
* ``seconds``
* ``microseconds``
See datetime modu... | [
"Bulk",
"create",
"datetime",
"objects",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L35-L73 |
241,769 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.week_date | def week_date(self, start: int = 2017, end: int = 2018) -> str:
"""Get week number with year.
:param start: From start.
:param end: To end.
:return: Week number.
"""
year = self.year(start, end)
week = self.random.randint(1, 52)
return '{year}-W{week}'.fo... | python | def week_date(self, start: int = 2017, end: int = 2018) -> str:
year = self.year(start, end)
week = self.random.randint(1, 52)
return '{year}-W{week}'.format(
year=year,
week=week,
) | [
"def",
"week_date",
"(",
"self",
",",
"start",
":",
"int",
"=",
"2017",
",",
"end",
":",
"int",
"=",
"2018",
")",
"->",
"str",
":",
"year",
"=",
"self",
".",
"year",
"(",
"start",
",",
"end",
")",
"week",
"=",
"self",
".",
"random",
".",
"randi... | Get week number with year.
:param start: From start.
:param end: To end.
:return: Week number. | [
"Get",
"week",
"number",
"with",
"year",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L75-L87 |
241,770 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.day_of_week | def day_of_week(self, abbr: bool = False) -> str:
"""Get a random day of week.
:param abbr: Abbreviated day name.
:return: Day of the week.
"""
key = 'abbr' if abbr else 'name'
days = self._data['day'].get(key)
return self.random.choice(days) | python | def day_of_week(self, abbr: bool = False) -> str:
key = 'abbr' if abbr else 'name'
days = self._data['day'].get(key)
return self.random.choice(days) | [
"def",
"day_of_week",
"(",
"self",
",",
"abbr",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"key",
"=",
"'abbr'",
"if",
"abbr",
"else",
"'name'",
"days",
"=",
"self",
".",
"_data",
"[",
"'day'",
"]",
".",
"get",
"(",
"key",
")",
"return",
"... | Get a random day of week.
:param abbr: Abbreviated day name.
:return: Day of the week. | [
"Get",
"a",
"random",
"day",
"of",
"week",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L89-L97 |
241,771 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.month | def month(self, abbr: bool = False) -> str:
"""Get a random month.
:param abbr: Abbreviated month name.
:return: Month name.
"""
key = 'abbr' if abbr else 'name'
months = self._data['month'].get(key)
return self.random.choice(months) | python | def month(self, abbr: bool = False) -> str:
key = 'abbr' if abbr else 'name'
months = self._data['month'].get(key)
return self.random.choice(months) | [
"def",
"month",
"(",
"self",
",",
"abbr",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"key",
"=",
"'abbr'",
"if",
"abbr",
"else",
"'name'",
"months",
"=",
"self",
".",
"_data",
"[",
"'month'",
"]",
".",
"get",
"(",
"key",
")",
"return",
"se... | Get a random month.
:param abbr: Abbreviated month name.
:return: Month name. | [
"Get",
"a",
"random",
"month",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L99-L107 |
241,772 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.year | def year(self, minimum: int = 1990, maximum: int = 2050) -> int:
"""Generate a random year.
:param minimum: Minimum value.
:param maximum: Maximum value.
:return: Year.
"""
return self.random.randint(minimum, maximum) | python | def year(self, minimum: int = 1990, maximum: int = 2050) -> int:
return self.random.randint(minimum, maximum) | [
"def",
"year",
"(",
"self",
",",
"minimum",
":",
"int",
"=",
"1990",
",",
"maximum",
":",
"int",
"=",
"2050",
")",
"->",
"int",
":",
"return",
"self",
".",
"random",
".",
"randint",
"(",
"minimum",
",",
"maximum",
")"
] | Generate a random year.
:param minimum: Minimum value.
:param maximum: Maximum value.
:return: Year. | [
"Generate",
"a",
"random",
"year",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L109-L116 |
241,773 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.periodicity | def periodicity(self) -> str:
"""Get a random periodicity string.
:return: Periodicity.
"""
periodicity = self._data['periodicity']
return self.random.choice(periodicity) | python | def periodicity(self) -> str:
periodicity = self._data['periodicity']
return self.random.choice(periodicity) | [
"def",
"periodicity",
"(",
"self",
")",
"->",
"str",
":",
"periodicity",
"=",
"self",
".",
"_data",
"[",
"'periodicity'",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"periodicity",
")"
] | Get a random periodicity string.
:return: Periodicity. | [
"Get",
"a",
"random",
"periodicity",
"string",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L125-L131 |
241,774 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.date | def date(self, start: int = 2000, end: int = 2019) -> Date:
"""Generate random date object.
:param start: Minimum value of year.
:param end: Maximum value of year.
:return: Formatted date.
"""
year = self.random.randint(start, end)
month = self.random.randint(1, ... | python | def date(self, start: int = 2000, end: int = 2019) -> Date:
year = self.random.randint(start, end)
month = self.random.randint(1, 12)
day = self.random.randint(1, monthrange(year, month)[1])
date_object = date(year, month, day)
return date_object | [
"def",
"date",
"(",
"self",
",",
"start",
":",
"int",
"=",
"2000",
",",
"end",
":",
"int",
"=",
"2019",
")",
"->",
"Date",
":",
"year",
"=",
"self",
".",
"random",
".",
"randint",
"(",
"start",
",",
"end",
")",
"month",
"=",
"self",
".",
"rando... | Generate random date object.
:param start: Minimum value of year.
:param end: Maximum value of year.
:return: Formatted date. | [
"Generate",
"random",
"date",
"object",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L133-L144 |
241,775 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.formatted_date | def formatted_date(self, fmt: str = '', **kwargs) -> str:
"""Generate random date as string.
:param fmt: The format of date, if None then use standard
accepted in the current locale.
:param kwargs: Keyword arguments for :meth:`~Datetime.date()`
:return: Formatted date.
... | python | def formatted_date(self, fmt: str = '', **kwargs) -> str:
date_obj = self.date(**kwargs)
if not fmt:
fmt = self._data['formats'].get('date')
return date_obj.strftime(fmt) | [
"def",
"formatted_date",
"(",
"self",
",",
"fmt",
":",
"str",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"date_obj",
"=",
"self",
".",
"date",
"(",
"*",
"*",
"kwargs",
")",
"if",
"not",
"fmt",
":",
"fmt",
"=",
"self",
".",
"_dat... | Generate random date as string.
:param fmt: The format of date, if None then use standard
accepted in the current locale.
:param kwargs: Keyword arguments for :meth:`~Datetime.date()`
:return: Formatted date. | [
"Generate",
"random",
"date",
"as",
"string",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L146-L159 |
241,776 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.time | def time(self) -> Time:
"""Generate a random time object.
:return: ``datetime.time`` object.
"""
random_time = time(
self.random.randint(0, 23),
self.random.randint(0, 59),
self.random.randint(0, 59),
self.random.randint(0, 999999),
... | python | def time(self) -> Time:
random_time = time(
self.random.randint(0, 23),
self.random.randint(0, 59),
self.random.randint(0, 59),
self.random.randint(0, 999999),
)
return random_time | [
"def",
"time",
"(",
"self",
")",
"->",
"Time",
":",
"random_time",
"=",
"time",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"23",
")",
",",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"59",
")",
",",
"self",
".",
"rando... | Generate a random time object.
:return: ``datetime.time`` object. | [
"Generate",
"a",
"random",
"time",
"object",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L161-L172 |
241,777 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.formatted_time | def formatted_time(self, fmt: str = '') -> str:
"""Generate string formatted time.
:param fmt: The format of time, if None then use standard
accepted in the current locale.
:return: String formatted time.
"""
time_obj = self.time()
if not fmt:
fm... | python | def formatted_time(self, fmt: str = '') -> str:
time_obj = self.time()
if not fmt:
fmt = self._data['formats'].get('time')
return time_obj.strftime(fmt) | [
"def",
"formatted_time",
"(",
"self",
",",
"fmt",
":",
"str",
"=",
"''",
")",
"->",
"str",
":",
"time_obj",
"=",
"self",
".",
"time",
"(",
")",
"if",
"not",
"fmt",
":",
"fmt",
"=",
"self",
".",
"_data",
"[",
"'formats'",
"]",
".",
"get",
"(",
"... | Generate string formatted time.
:param fmt: The format of time, if None then use standard
accepted in the current locale.
:return: String formatted time. | [
"Generate",
"string",
"formatted",
"time",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L174-L185 |
241,778 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.datetime | def datetime(self, start: int = 2000, end: int = 2035,
timezone: Optional[str] = None) -> DateTime:
"""Generate random datetime.
:param start: Minimum value of year.
:param end: Maximum value of year.
:param timezone: Set custom timezone (pytz required).
:return... | python | def datetime(self, start: int = 2000, end: int = 2035,
timezone: Optional[str] = None) -> DateTime:
datetime_obj = datetime.combine(
date=self.date(start, end),
time=self.time(),
)
if timezone:
if not pytz:
raise ImportError('T... | [
"def",
"datetime",
"(",
"self",
",",
"start",
":",
"int",
"=",
"2000",
",",
"end",
":",
"int",
"=",
"2035",
",",
"timezone",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"DateTime",
":",
"datetime_obj",
"=",
"datetime",
".",
"combine",
... | Generate random datetime.
:param start: Minimum value of year.
:param end: Maximum value of year.
:param timezone: Set custom timezone (pytz required).
:return: Datetime | [
"Generate",
"random",
"datetime",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L208-L227 |
241,779 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.formatted_datetime | def formatted_datetime(self, fmt: str = '', **kwargs) -> str:
"""Generate datetime string in human readable format.
:param fmt: Custom format (default is format for current locale)
:param kwargs: Keyword arguments for :meth:`~Datetime.datetime()`
:return: Formatted datetime string.
... | python | def formatted_datetime(self, fmt: str = '', **kwargs) -> str:
dt_obj = self.datetime(**kwargs)
if not fmt:
date_fmt = self._data['formats'].get('date')
time_fmt = self._data['formats'].get('time')
fmt = '{} {}'.format(date_fmt, time_fmt)
return dt_obj.strfti... | [
"def",
"formatted_datetime",
"(",
"self",
",",
"fmt",
":",
"str",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"dt_obj",
"=",
"self",
".",
"datetime",
"(",
"*",
"*",
"kwargs",
")",
"if",
"not",
"fmt",
":",
"date_fmt",
"=",
"self",
"... | Generate datetime string in human readable format.
:param fmt: Custom format (default is format for current locale)
:param kwargs: Keyword arguments for :meth:`~Datetime.datetime()`
:return: Formatted datetime string. | [
"Generate",
"datetime",
"string",
"in",
"human",
"readable",
"format",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L229-L243 |
241,780 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.timestamp | def timestamp(self, posix: bool = True, **kwargs) -> Union[str, int]:
"""Generate random timestamp.
:param posix: POSIX time.
:param kwargs: Kwargs for :meth:`~Datetime.datetime()`.
:return: Timestamp.
"""
stamp = self.datetime(**kwargs)
if posix:
re... | python | def timestamp(self, posix: bool = True, **kwargs) -> Union[str, int]:
stamp = self.datetime(**kwargs)
if posix:
return timegm(stamp.utctimetuple())
return stamp.strftime('%Y-%m-%dT%H:%M:%SZ') | [
"def",
"timestamp",
"(",
"self",
",",
"posix",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"->",
"Union",
"[",
"str",
",",
"int",
"]",
":",
"stamp",
"=",
"self",
".",
"datetime",
"(",
"*",
"*",
"kwargs",
")",
"if",
"posix",
":",
"re... | Generate random timestamp.
:param posix: POSIX time.
:param kwargs: Kwargs for :meth:`~Datetime.datetime()`.
:return: Timestamp. | [
"Generate",
"random",
"timestamp",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L245-L257 |
241,781 | lk-geimfari/mimesis | mimesis/providers/cryptographic.py | Cryptographic.uuid | def uuid(self, version: int = None) -> str:
"""Generate random UUID.
:param version: UUID version.
:return: UUID
"""
bits = self.random.getrandbits(128)
return str(uuid.UUID(int=bits, version=version)) | python | def uuid(self, version: int = None) -> str:
bits = self.random.getrandbits(128)
return str(uuid.UUID(int=bits, version=version)) | [
"def",
"uuid",
"(",
"self",
",",
"version",
":",
"int",
"=",
"None",
")",
"->",
"str",
":",
"bits",
"=",
"self",
".",
"random",
".",
"getrandbits",
"(",
"128",
")",
"return",
"str",
"(",
"uuid",
".",
"UUID",
"(",
"int",
"=",
"bits",
",",
"version... | Generate random UUID.
:param version: UUID version.
:return: UUID | [
"Generate",
"random",
"UUID",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/cryptographic.py#L32-L39 |
241,782 | lk-geimfari/mimesis | mimesis/providers/cryptographic.py | Cryptographic.hash | def hash(self, algorithm: Algorithm = None) -> str: # noqa: A003
"""Generate random hash.
To change hashing algorithm, pass parameter ``algorithm``
with needed value of the enum object :class:`~mimesis.enums.Algorithm`
:param algorithm: Enum object :class:`~mimesis.enums.Algorithm`.
... | python | def hash(self, algorithm: Algorithm = None) -> str: # noqa: A003
key = self._validate_enum(algorithm, Algorithm)
if hasattr(hashlib, key):
fn = getattr(hashlib, key)
return fn(self.uuid().encode()).hexdigest() | [
"def",
"hash",
"(",
"self",
",",
"algorithm",
":",
"Algorithm",
"=",
"None",
")",
"->",
"str",
":",
"# noqa: A003",
"key",
"=",
"self",
".",
"_validate_enum",
"(",
"algorithm",
",",
"Algorithm",
")",
"if",
"hasattr",
"(",
"hashlib",
",",
"key",
")",
":... | Generate random hash.
To change hashing algorithm, pass parameter ``algorithm``
with needed value of the enum object :class:`~mimesis.enums.Algorithm`
:param algorithm: Enum object :class:`~mimesis.enums.Algorithm`.
:return: Hash.
:raises NonEnumerableError: if algorithm is not... | [
"Generate",
"random",
"hash",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/cryptographic.py#L41-L55 |
241,783 | lk-geimfari/mimesis | mimesis/providers/cryptographic.py | Cryptographic.mnemonic_phrase | def mnemonic_phrase(self, length: int = 12) -> str:
"""Generate pseudo mnemonic phrase.
:param length: Number of words.
:return: Mnemonic code.
"""
words = self.__words['normal']
return ' '.join(self.random.choice(words) for _ in range(length)) | python | def mnemonic_phrase(self, length: int = 12) -> str:
words = self.__words['normal']
return ' '.join(self.random.choice(words) for _ in range(length)) | [
"def",
"mnemonic_phrase",
"(",
"self",
",",
"length",
":",
"int",
"=",
"12",
")",
"->",
"str",
":",
"words",
"=",
"self",
".",
"__words",
"[",
"'normal'",
"]",
"return",
"' '",
".",
"join",
"(",
"self",
".",
"random",
".",
"choice",
"(",
"words",
"... | Generate pseudo mnemonic phrase.
:param length: Number of words.
:return: Mnemonic code. | [
"Generate",
"pseudo",
"mnemonic",
"phrase",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/cryptographic.py#L104-L111 |
241,784 | lk-geimfari/mimesis | setup.py | Minimizer.initialize_options | def initialize_options(self):
"""Find all files of all locales."""
self.paths = []
self.separators = (',', ':')
self.data_dir = join(here, 'mimesis', 'data')
self.before_total = 0
self.after_total = 0
for root, _, files in os.walk(self.data_dir):
for ... | python | def initialize_options(self):
self.paths = []
self.separators = (',', ':')
self.data_dir = join(here, 'mimesis', 'data')
self.before_total = 0
self.after_total = 0
for root, _, files in os.walk(self.data_dir):
for file in sorted(files):
if spl... | [
"def",
"initialize_options",
"(",
"self",
")",
":",
"self",
".",
"paths",
"=",
"[",
"]",
"self",
".",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
"self",
".",
"data_dir",
"=",
"join",
"(",
"here",
",",
"'mimesis'",
",",
"'data'",
")",
"self",
"... | Find all files of all locales. | [
"Find",
"all",
"files",
"of",
"all",
"locales",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/setup.py#L34-L46 |
241,785 | lk-geimfari/mimesis | setup.py | Minimizer.run | def run(self):
"""Start json minimizer and exit when all json files were minimized."""
for rel_path in sorted(self.paths):
file_path = join(self.data_dir, rel_path)
self.minify(file_path)
after = self.size_of(self.after_total)
before = self.size_of(self.before_to... | python | def run(self):
for rel_path in sorted(self.paths):
file_path = join(self.data_dir, rel_path)
self.minify(file_path)
after = self.size_of(self.after_total)
before = self.size_of(self.before_total)
saved = self.size_of(self.before_total - self.after_total)
... | [
"def",
"run",
"(",
"self",
")",
":",
"for",
"rel_path",
"in",
"sorted",
"(",
"self",
".",
"paths",
")",
":",
"file_path",
"=",
"join",
"(",
"self",
".",
"data_dir",
",",
"rel_path",
")",
"self",
".",
"minify",
"(",
"file_path",
")",
"after",
"=",
"... | Start json minimizer and exit when all json files were minimized. | [
"Start",
"json",
"minimizer",
"and",
"exit",
"when",
"all",
"json",
"files",
"were",
"minimized",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/setup.py#L92-L106 |
241,786 | lk-geimfari/mimesis | mimesis/providers/structure.py | Structure.css | def css(self) -> str:
"""Generate a random snippet of CSS.
:return: CSS.
"""
selector = self.random.choice(CSS_SELECTORS)
css_sel = '{}{}'.format(selector, self.__text.word())
cont_tag = self.random.choice(list(HTML_CONTAINER_TAGS.keys()))
mrk_tag = self.random.... | python | def css(self) -> str:
selector = self.random.choice(CSS_SELECTORS)
css_sel = '{}{}'.format(selector, self.__text.word())
cont_tag = self.random.choice(list(HTML_CONTAINER_TAGS.keys()))
mrk_tag = self.random.choice(HTML_MARKUP_TAGS)
base = '{}'.format(self.random.choice([cont_ta... | [
"def",
"css",
"(",
"self",
")",
"->",
"str",
":",
"selector",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"CSS_SELECTORS",
")",
"css_sel",
"=",
"'{}{}'",
".",
"format",
"(",
"selector",
",",
"self",
".",
"__text",
".",
"word",
"(",
")",
")",
"c... | Generate a random snippet of CSS.
:return: CSS. | [
"Generate",
"a",
"random",
"snippet",
"of",
"CSS",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/structure.py#L37-L51 |
241,787 | lk-geimfari/mimesis | mimesis/providers/structure.py | Structure.css_property | def css_property(self) -> str:
"""Generate a random snippet of CSS that assigns value to a property.
:return: CSS property.
:Examples:
'background-color: #f4d3a1'
"""
prop = self.random.choice(list(CSS_PROPERTIES.keys()))
val = CSS_PROPERTIES[prop]
... | python | def css_property(self) -> str:
prop = self.random.choice(list(CSS_PROPERTIES.keys()))
val = CSS_PROPERTIES[prop]
if isinstance(val, list):
val = self.random.choice(val)
elif val == 'color':
val = self.__text.hex_color()
elif val == 'size':
val... | [
"def",
"css_property",
"(",
"self",
")",
"->",
"str",
":",
"prop",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"list",
"(",
"CSS_PROPERTIES",
".",
"keys",
"(",
")",
")",
")",
"val",
"=",
"CSS_PROPERTIES",
"[",
"prop",
"]",
"if",
"isinstance",
"("... | Generate a random snippet of CSS that assigns value to a property.
:return: CSS property.
:Examples:
'background-color: #f4d3a1' | [
"Generate",
"a",
"random",
"snippet",
"of",
"CSS",
"that",
"assigns",
"value",
"to",
"a",
"property",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/structure.py#L53-L72 |
241,788 | lk-geimfari/mimesis | mimesis/providers/structure.py | Structure.html | def html(self) -> str:
"""Generate a random HTML tag with text inside and some attrs set.
:return: HTML.
:Examples:
'<span class="select" id="careers">
Ports are created with the built-in function open_port.
</span>'
"""
tag_name = self.rando... | python | def html(self) -> str:
tag_name = self.random.choice(list(HTML_CONTAINER_TAGS))
tag_attributes = list(HTML_CONTAINER_TAGS[tag_name]) # type: ignore
k = self.random.randint(1, len(tag_attributes))
selected_attrs = self.random.sample(tag_attributes, k=k)
attrs = []
for a... | [
"def",
"html",
"(",
"self",
")",
"->",
"str",
":",
"tag_name",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"list",
"(",
"HTML_CONTAINER_TAGS",
")",
")",
"tag_attributes",
"=",
"list",
"(",
"HTML_CONTAINER_TAGS",
"[",
"tag_name",
"]",
")",
"# type: igno... | Generate a random HTML tag with text inside and some attrs set.
:return: HTML.
:Examples:
'<span class="select" id="careers">
Ports are created with the built-in function open_port.
</span>' | [
"Generate",
"a",
"random",
"HTML",
"tag",
"with",
"text",
"inside",
"and",
"some",
"attrs",
"set",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/structure.py#L74-L100 |
241,789 | lk-geimfari/mimesis | mimesis/providers/structure.py | Structure.html_attribute_value | def html_attribute_value(self, tag: str = None,
attribute: str = None) -> str:
"""Generate random value for specified HTML tag attribute.
:param tag: An HTML tag.
:param attribute: An attribute of the specified tag.
:return: An attribute.
:raises Not... | python | def html_attribute_value(self, tag: str = None,
attribute: str = None) -> str:
if not tag:
tag = self.random.choice(
list(HTML_CONTAINER_TAGS.keys()),
)
if not attribute:
attribute = self.random.choice(
list... | [
"def",
"html_attribute_value",
"(",
"self",
",",
"tag",
":",
"str",
"=",
"None",
",",
"attribute",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"if",
"not",
"tag",
":",
"tag",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"list",
"(",
"HTML_CO... | Generate random value for specified HTML tag attribute.
:param tag: An HTML tag.
:param attribute: An attribute of the specified tag.
:return: An attribute.
:raises NotImplementedError: if tag is unsupported. | [
"Generate",
"random",
"value",
"for",
"specified",
"HTML",
"tag",
"attribute",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/structure.py#L102-L138 |
241,790 | lk-geimfari/mimesis | mimesis/providers/development.py | Development.version | def version(self, calver: bool = False, pre_release: bool = False) -> str:
"""Generate version number.
:param calver: Calendar versioning.
:param pre_release: Pre-release.
:return: Version.
:Example:
0.2.1
"""
# TODO: Optimize
version = '{}.{... | python | def version(self, calver: bool = False, pre_release: bool = False) -> str:
# TODO: Optimize
version = '{}.{}.{}'
major, minor, patch = self.random.randints(3, 0, 10)
if calver:
if minor == 0:
minor += 1
if patch == 0:
patch += 1
... | [
"def",
"version",
"(",
"self",
",",
"calver",
":",
"bool",
"=",
"False",
",",
"pre_release",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"# TODO: Optimize",
"version",
"=",
"'{}.{}.{}'",
"major",
",",
"minor",
",",
"patch",
"=",
"self",
".",
"ran... | Generate version number.
:param calver: Calendar versioning.
:param pre_release: Pre-release.
:return: Version.
:Example:
0.2.1 | [
"Generate",
"version",
"number",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/development.py#L29-L60 |
241,791 | lk-geimfari/mimesis | mimesis/providers/science.py | Science.chemical_element | def chemical_element(self, name_only: bool = True) -> Union[dict, str]:
"""Generate a random chemical element.
:param name_only: If False then will be returned dict.
:return: Name of chemical element or dict.
:rtype: dict or str
:Example:
{'Symbol': 'S', 'Name': 'Su... | python | def chemical_element(self, name_only: bool = True) -> Union[dict, str]:
elements = self._data['chemical_element']
nm, sm, an = self.random.choice(elements).split('|')
if not name_only:
return {
'name': nm.strip(),
'symbol': sm.strip(),
... | [
"def",
"chemical_element",
"(",
"self",
",",
"name_only",
":",
"bool",
"=",
"True",
")",
"->",
"Union",
"[",
"dict",
",",
"str",
"]",
":",
"elements",
"=",
"self",
".",
"_data",
"[",
"'chemical_element'",
"]",
"nm",
",",
"sm",
",",
"an",
"=",
"self",... | Generate a random chemical element.
:param name_only: If False then will be returned dict.
:return: Name of chemical element or dict.
:rtype: dict or str
:Example:
{'Symbol': 'S', 'Name': 'Sulfur', 'Atomic number': '16'} | [
"Generate",
"a",
"random",
"chemical",
"element",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/science.py#L42-L62 |
241,792 | lk-geimfari/mimesis | mimesis/builtins/pt_br.py | BrazilSpecProvider.cpf | def cpf(self, with_mask: bool = True) -> str:
"""Get a random CPF.
:param with_mask: Use CPF mask (###.###.###-##).
:returns: Random CPF.
:Example:
001.137.297-40
"""
def get_verifying_digit_cpf(cpf, peso):
"""Calculate the verifying digit for th... | python | def cpf(self, with_mask: bool = True) -> str:
def get_verifying_digit_cpf(cpf, peso):
"""Calculate the verifying digit for the CPF.
:param cpf: List of integers with the CPF.
:param peso: Integer with the weight for the modulo 11 calculate.
:returns: The verifyin... | [
"def",
"cpf",
"(",
"self",
",",
"with_mask",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"def",
"get_verifying_digit_cpf",
"(",
"cpf",
",",
"peso",
")",
":",
"\"\"\"Calculate the verifying digit for the CPF.\n\n :param cpf: List of integers with the CPF.\n... | Get a random CPF.
:param with_mask: Use CPF mask (###.###.###-##).
:returns: Random CPF.
:Example:
001.137.297-40 | [
"Get",
"a",
"random",
"CPF",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/pt_br.py#L23-L58 |
241,793 | lk-geimfari/mimesis | mimesis/builtins/pt_br.py | BrazilSpecProvider.cnpj | def cnpj(self, with_mask: bool = True) -> str:
"""Get a random CNPJ.
:param with_mask: Use cnpj mask (###.###.###-##)
:returns: Random cnpj.
:Example:
77.732.230/0001-70
"""
def get_verifying_digit_cnpj(cnpj, peso):
"""Calculate the verifying dig... | python | def cnpj(self, with_mask: bool = True) -> str:
def get_verifying_digit_cnpj(cnpj, peso):
"""Calculate the verifying digit for the CNPJ.
:param cnpj: List of integers with the CNPJ.
:param peso: Integer with the weight for the modulo 11 calculate.
:returns: The ve... | [
"def",
"cnpj",
"(",
"self",
",",
"with_mask",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"def",
"get_verifying_digit_cnpj",
"(",
"cnpj",
",",
"peso",
")",
":",
"\"\"\"Calculate the verifying digit for the CNPJ.\n\n :param cnpj: List of integers with the C... | Get a random CNPJ.
:param with_mask: Use cnpj mask (###.###.###-##)
:returns: Random cnpj.
:Example:
77.732.230/0001-70 | [
"Get",
"a",
"random",
"CNPJ",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/pt_br.py#L60-L101 |
241,794 | lk-geimfari/mimesis | mimesis/decorators.py | romanized | def romanized(locale: str = '') -> Callable:
"""Romanize the Cyrillic text.
Transliterate the Cyrillic language from the Cyrillic
script into the Latin alphabet.
.. note:: At this moment it works only for `ru`, `uk`, `kk`.
:param locale: Locale code.
:return: Latinized text.
"""
def r... | python | def romanized(locale: str = '') -> Callable:
def romanized_deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
# String can contain ascii symbols, digits and
# punctuation symbols.
alphabet = {s: s for s in
... | [
"def",
"romanized",
"(",
"locale",
":",
"str",
"=",
"''",
")",
"->",
"Callable",
":",
"def",
"romanized_deco",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"... | Romanize the Cyrillic text.
Transliterate the Cyrillic language from the Cyrillic
script into the Latin alphabet.
.. note:: At this moment it works only for `ru`, `uk`, `kk`.
:param locale: Locale code.
:return: Latinized text. | [
"Romanize",
"the",
"Cyrillic",
"text",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/decorators.py#L14-L44 |
241,795 | lk-geimfari/mimesis | mimesis/providers/food.py | Food._choice_from | def _choice_from(self, key: str) -> str:
"""Choice random element."""
data = self._data[key]
return self.random.choice(data) | python | def _choice_from(self, key: str) -> str:
data = self._data[key]
return self.random.choice(data) | [
"def",
"_choice_from",
"(",
"self",
",",
"key",
":",
"str",
")",
"->",
"str",
":",
"data",
"=",
"self",
".",
"_data",
"[",
"key",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"data",
")"
] | Choice random element. | [
"Choice",
"random",
"element",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/food.py#L27-L30 |
241,796 | lk-geimfari/mimesis | mimesis/builtins/ru.py | RussiaSpecProvider.generate_sentence | def generate_sentence(self) -> str:
"""Generate sentence from the parts.
:return: Sentence.
"""
sentences = self._data['sentence']
sentence = [
self.random.choice(sentences[k]) for k
in ('head', 'p1', 'p2', 'tail')
]
return '{0} {1} {2} {3... | python | def generate_sentence(self) -> str:
sentences = self._data['sentence']
sentence = [
self.random.choice(sentences[k]) for k
in ('head', 'p1', 'p2', 'tail')
]
return '{0} {1} {2} {3}'.format(*sentence) | [
"def",
"generate_sentence",
"(",
"self",
")",
"->",
"str",
":",
"sentences",
"=",
"self",
".",
"_data",
"[",
"'sentence'",
"]",
"sentence",
"=",
"[",
"self",
".",
"random",
".",
"choice",
"(",
"sentences",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"(",
... | Generate sentence from the parts.
:return: Sentence. | [
"Generate",
"sentence",
"from",
"the",
"parts",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/ru.py#L25-L35 |
241,797 | lk-geimfari/mimesis | mimesis/builtins/ru.py | RussiaSpecProvider.patronymic | def patronymic(self, gender: Gender = None) -> str:
"""Generate random patronymic name.
:param gender: Gender of person.
:return: Patronymic name.
:Example:
Алексеевна.
"""
gender = self._validate_enum(gender, Gender)
patronymics = self._data['patron... | python | def patronymic(self, gender: Gender = None) -> str:
gender = self._validate_enum(gender, Gender)
patronymics = self._data['patronymic'][gender]
return self.random.choice(patronymics) | [
"def",
"patronymic",
"(",
"self",
",",
"gender",
":",
"Gender",
"=",
"None",
")",
"->",
"str",
":",
"gender",
"=",
"self",
".",
"_validate_enum",
"(",
"gender",
",",
"Gender",
")",
"patronymics",
"=",
"self",
".",
"_data",
"[",
"'patronymic'",
"]",
"["... | Generate random patronymic name.
:param gender: Gender of person.
:return: Patronymic name.
:Example:
Алексеевна. | [
"Generate",
"random",
"patronymic",
"name",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/ru.py#L37-L48 |
241,798 | lk-geimfari/mimesis | mimesis/builtins/ru.py | RussiaSpecProvider.passport_series | def passport_series(self, year: int = None) -> str:
"""Generate random series of passport.
:param year: Year of manufacture.
:type year: int or None
:return: Series.
:Example:
02 15.
"""
if not year:
year = self.random.randint(10, 18)
... | python | def passport_series(self, year: int = None) -> str:
if not year:
year = self.random.randint(10, 18)
region = self.random.randint(1, 99)
return '{:02d} {}'.format(region, year) | [
"def",
"passport_series",
"(",
"self",
",",
"year",
":",
"int",
"=",
"None",
")",
"->",
"str",
":",
"if",
"not",
"year",
":",
"year",
"=",
"self",
".",
"random",
".",
"randint",
"(",
"10",
",",
"18",
")",
"region",
"=",
"self",
".",
"random",
"."... | Generate random series of passport.
:param year: Year of manufacture.
:type year: int or None
:return: Series.
:Example:
02 15. | [
"Generate",
"random",
"series",
"of",
"passport",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/ru.py#L50-L64 |
241,799 | lk-geimfari/mimesis | mimesis/builtins/ru.py | RussiaSpecProvider.snils | def snils(self) -> str:
"""Generate snils with special algorithm.
:return: SNILS.
:Example:
41917492600.
"""
numbers = []
control_codes = []
for i in range(0, 9):
numbers.append(self.random.randint(0, 9))
for i in range(9, 0, -1... | python | def snils(self) -> str:
numbers = []
control_codes = []
for i in range(0, 9):
numbers.append(self.random.randint(0, 9))
for i in range(9, 0, -1):
control_codes.append(numbers[9 - i] * i)
control_code = sum(control_codes)
code = ''.join(str(numbe... | [
"def",
"snils",
"(",
"self",
")",
"->",
"str",
":",
"numbers",
"=",
"[",
"]",
"control_codes",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"9",
")",
":",
"numbers",
".",
"append",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"0... | Generate snils with special algorithm.
:return: SNILS.
:Example:
41917492600. | [
"Generate",
"snils",
"with",
"special",
"algorithm",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/ru.py#L90-L123 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.