Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
take_along_axis | (arr, indices, axis) |
Take values from the input array by matching 1d index and data slices.
This iterates over matching 1d slices oriented along the specified axis in
the index and data arrays, and uses the former to look up values in the
latter. These slices can be different lengths.
Functions returning an index alo... |
Take values from the input array by matching 1d index and data slices. | def take_along_axis(arr, indices, axis):
"""
Take values from the input array by matching 1d index and data slices.
This iterates over matching 1d slices oriented along the specified axis in
the index and data arrays, and uses the former to look up values in the
latter. These slices can be differen... | [
"def",
"take_along_axis",
"(",
"arr",
",",
"indices",
",",
"axis",
")",
":",
"# normalize inputs",
"if",
"axis",
"is",
"None",
":",
"arr",
"=",
"arr",
".",
"flat",
"arr_shape",
"=",
"(",
"len",
"(",
"arr",
")",
",",
")",
"# flatiter has no .shape",
"axis... | [
58,
0
] | [
171,
62
] | python | en | ['en', 'error', 'th'] | False |
put_along_axis | (arr, indices, values, axis) |
Put values into the destination array by matching 1d index and data slices.
This iterates over matching 1d slices oriented along the specified axis in
the index and data arrays, and uses the former to place values into the
latter. These slices can be different lengths.
Functions returning an inde... |
Put values into the destination array by matching 1d index and data slices. | def put_along_axis(arr, indices, values, axis):
"""
Put values into the destination array by matching 1d index and data slices.
This iterates over matching 1d slices oriented along the specified axis in
the index and data arrays, and uses the former to place values into the
latter. These slices can... | [
"def",
"put_along_axis",
"(",
"arr",
",",
"indices",
",",
"values",
",",
"axis",
")",
":",
"# normalize inputs",
"if",
"axis",
"is",
"None",
":",
"arr",
"=",
"arr",
".",
"flat",
"axis",
"=",
"0",
"arr_shape",
"=",
"(",
"len",
"(",
"arr",
")",
",",
... | [
179,
0
] | [
261,
64
] | python | en | ['en', 'error', 'th'] | False |
apply_along_axis | (func1d, axis, arr, *args, **kwargs) |
Apply a function to 1-D slices along the given axis.
Execute `func1d(a, *args)` where `func1d` operates on 1-D arrays and `a`
is a 1-D slice of `arr` along `axis`.
This is equivalent to (but faster than) the following use of `ndindex` and
`s_`, which sets each of ``ii``, ``jj``, and ``kk`` to a t... |
Apply a function to 1-D slices along the given axis. | def apply_along_axis(func1d, axis, arr, *args, **kwargs):
"""
Apply a function to 1-D slices along the given axis.
Execute `func1d(a, *args)` where `func1d` operates on 1-D arrays and `a`
is a 1-D slice of `arr` along `axis`.
This is equivalent to (but faster than) the following use of `ndindex` a... | [
"def",
"apply_along_axis",
"(",
"func1d",
",",
"axis",
",",
"arr",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# handle negative axes",
"arr",
"=",
"asanyarray",
"(",
"arr",
")",
"nd",
"=",
"arr",
".",
"ndim",
"axis",
"=",
"normalize_axis_index... | [
269,
0
] | [
413,
42
] | python | en | ['en', 'error', 'th'] | False |
apply_over_axes | (func, a, axes) |
Apply a function repeatedly over multiple axes.
`func` is called as `res = func(a, axis)`, where `axis` is the first
element of `axes`. The result `res` of the function call must have
either the same dimensions as `a` or one less dimension. If `res`
has one less dimension than `a`, a dimension i... |
Apply a function repeatedly over multiple axes. | def apply_over_axes(func, a, axes):
"""
Apply a function repeatedly over multiple axes.
`func` is called as `res = func(a, axis)`, where `axis` is the first
element of `axes`. The result `res` of the function call must have
either the same dimensions as `a` or one less dimension. If `res`
has... | [
"def",
"apply_over_axes",
"(",
"func",
",",
"a",
",",
"axes",
")",
":",
"val",
"=",
"asarray",
"(",
"a",
")",
"N",
"=",
"a",
".",
"ndim",
"if",
"array",
"(",
"axes",
")",
".",
"ndim",
"==",
"0",
":",
"axes",
"=",
"(",
"axes",
",",
")",
"for",... | [
421,
0
] | [
504,
14
] | python | en | ['en', 'error', 'th'] | False |
expand_dims | (a, axis) |
Expand the shape of an array.
Insert a new axis that will appear at the `axis` position in the expanded
array shape.
.. note:: Previous to NumPy 1.13.0, neither ``axis < -a.ndim - 1`` nor
``axis > a.ndim`` raised errors or put the new axis where documented.
Those axis values are now dep... |
Expand the shape of an array. | def expand_dims(a, axis):
"""
Expand the shape of an array.
Insert a new axis that will appear at the `axis` position in the expanded
array shape.
.. note:: Previous to NumPy 1.13.0, neither ``axis < -a.ndim - 1`` nor
``axis > a.ndim`` raised errors or put the new axis where documented.
... | [
"def",
"expand_dims",
"(",
"a",
",",
"axis",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"matrix",
")",
":",
"a",
"=",
"asarray",
"(",
"a",
")",
"else",
":",
"a",
"=",
"asanyarray",
"(",
"a",
")",
"shape",
"=",
"a",
".",
"shape",
"if",
"axis",... | [
512,
0
] | [
586,
56
] | python | en | ['en', 'error', 'th'] | False |
column_stack | (tup) |
Stack 1-D arrays as columns into a 2-D array.
Take a sequence of 1-D arrays and stack them as columns
to make a single 2-D array. 2-D arrays are stacked as-is,
just like with `hstack`. 1-D arrays are turned into 2-D columns
first.
Parameters
----------
tup : sequence of 1-D or 2-D ar... |
Stack 1-D arrays as columns into a 2-D array. | def column_stack(tup):
"""
Stack 1-D arrays as columns into a 2-D array.
Take a sequence of 1-D arrays and stack them as columns
to make a single 2-D array. 2-D arrays are stacked as-is,
just like with `hstack`. 1-D arrays are turned into 2-D columns
first.
Parameters
----------
t... | [
"def",
"column_stack",
"(",
"tup",
")",
":",
"if",
"not",
"overrides",
".",
"ARRAY_FUNCTION_ENABLED",
":",
"# raise warning if necessary",
"_arrays_for_stack_dispatcher",
"(",
"tup",
",",
"stacklevel",
"=",
"2",
")",
"arrays",
"=",
"[",
"]",
"for",
"v",
"in",
... | [
597,
0
] | [
640,
37
] | python | en | ['en', 'error', 'th'] | False |
dstack | (tup) |
Stack arrays in sequence depth wise (along third axis).
This is equivalent to concatenation along the third axis after 2-D arrays
of shape `(M,N)` have been reshaped to `(M,N,1)` and 1-D arrays of shape
`(N,)` have been reshaped to `(1,N,1)`. Rebuilds arrays divided by
`dsplit`.
This function... |
Stack arrays in sequence depth wise (along third axis). | def dstack(tup):
"""
Stack arrays in sequence depth wise (along third axis).
This is equivalent to concatenation along the third axis after 2-D arrays
of shape `(M,N)` have been reshaped to `(M,N,1)` and 1-D arrays of shape
`(N,)` have been reshaped to `(1,N,1)`. Rebuilds arrays divided by
`dsp... | [
"def",
"dstack",
"(",
"tup",
")",
":",
"if",
"not",
"overrides",
".",
"ARRAY_FUNCTION_ENABLED",
":",
"# raise warning if necessary",
"_arrays_for_stack_dispatcher",
"(",
"tup",
",",
"stacklevel",
"=",
"2",
")",
"arrs",
"=",
"atleast_3d",
"(",
"*",
"tup",
")",
... | [
648,
0
] | [
705,
35
] | python | en | ['en', 'error', 'th'] | False |
array_split | (ary, indices_or_sections, axis=0) |
Split an array into multiple sub-arrays.
Please refer to the ``split`` documentation. The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis. For an array of length l that should be split
into n... |
Split an array into multiple sub-arrays. | def array_split(ary, indices_or_sections, axis=0):
"""
Split an array into multiple sub-arrays.
Please refer to the ``split`` documentation. The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis... | [
"def",
"array_split",
"(",
"ary",
",",
"indices_or_sections",
",",
"axis",
"=",
"0",
")",
":",
"try",
":",
"Ntotal",
"=",
"ary",
".",
"shape",
"[",
"axis",
"]",
"except",
"AttributeError",
":",
"Ntotal",
"=",
"len",
"(",
"ary",
")",
"try",
":",
"# ha... | [
722,
0
] | [
774,
19
] | python | en | ['en', 'error', 'th'] | False |
split | (ary, indices_or_sections, axis=0) |
Split an array into multiple sub-arrays.
Parameters
----------
ary : ndarray
Array to be divided into sub-arrays.
indices_or_sections : int or 1-D array
If `indices_or_sections` is an integer, N, the array will be divided
into N equal arrays along `axis`. If such a split i... |
Split an array into multiple sub-arrays. | def split(ary, indices_or_sections, axis=0):
"""
Split an array into multiple sub-arrays.
Parameters
----------
ary : ndarray
Array to be divided into sub-arrays.
indices_or_sections : int or 1-D array
If `indices_or_sections` is an integer, N, the array will be divided
... | [
"def",
"split",
"(",
"ary",
",",
"indices_or_sections",
",",
"axis",
"=",
"0",
")",
":",
"try",
":",
"len",
"(",
"indices_or_sections",
")",
"except",
"TypeError",
":",
"sections",
"=",
"indices_or_sections",
"N",
"=",
"ary",
".",
"shape",
"[",
"axis",
"... | [
782,
0
] | [
857,
14
] | python | en | ['en', 'error', 'th'] | False |
hsplit | (ary, indices_or_sections) |
Split an array into multiple sub-arrays horizontally (column-wise).
Please refer to the `split` documentation. `hsplit` is equivalent
to `split` with ``axis=1``, the array is always split along the second
axis regardless of the array dimension.
See Also
--------
split : Split an array in... |
Split an array into multiple sub-arrays horizontally (column-wise). | def hsplit(ary, indices_or_sections):
"""
Split an array into multiple sub-arrays horizontally (column-wise).
Please refer to the `split` documentation. `hsplit` is equivalent
to `split` with ``axis=1``, the array is always split along the second
axis regardless of the array dimension.
See Al... | [
"def",
"hsplit",
"(",
"ary",
",",
"indices_or_sections",
")",
":",
"if",
"_nx",
".",
"ndim",
"(",
"ary",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'hsplit only works on arrays of 1 or more dimensions'",
")",
"if",
"ary",
".",
"ndim",
">",
"1",
":",
... | [
865,
0
] | [
925,
49
] | python | en | ['en', 'error', 'th'] | False |
vsplit | (ary, indices_or_sections) |
Split an array into multiple sub-arrays vertically (row-wise).
Please refer to the ``split`` documentation. ``vsplit`` is equivalent
to ``split`` with `axis=0` (default), the array is always split along the
first axis regardless of the array dimension.
See Also
--------
split : Split an ... |
Split an array into multiple sub-arrays vertically (row-wise). | def vsplit(ary, indices_or_sections):
"""
Split an array into multiple sub-arrays vertically (row-wise).
Please refer to the ``split`` documentation. ``vsplit`` is equivalent
to ``split`` with `axis=0` (default), the array is always split along the
first axis regardless of the array dimension.
... | [
"def",
"vsplit",
"(",
"ary",
",",
"indices_or_sections",
")",
":",
"if",
"_nx",
".",
"ndim",
"(",
"ary",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"'vsplit only works on arrays of 2 or more dimensions'",
")",
"return",
"split",
"(",
"ary",
",",
"indices_... | [
929,
0
] | [
974,
45
] | python | en | ['en', 'error', 'th'] | False |
dsplit | (ary, indices_or_sections) |
Split array into multiple sub-arrays along the 3rd axis (depth).
Please refer to the `split` documentation. `dsplit` is equivalent
to `split` with ``axis=2``, the array is always split along the third
axis provided the array dimension is greater than or equal to 3.
See Also
--------
spli... |
Split array into multiple sub-arrays along the 3rd axis (depth). | def dsplit(ary, indices_or_sections):
"""
Split array into multiple sub-arrays along the 3rd axis (depth).
Please refer to the `split` documentation. `dsplit` is equivalent
to `split` with ``axis=2``, the array is always split along the third
axis provided the array dimension is greater than or eq... | [
"def",
"dsplit",
"(",
"ary",
",",
"indices_or_sections",
")",
":",
"if",
"_nx",
".",
"ndim",
"(",
"ary",
")",
"<",
"3",
":",
"raise",
"ValueError",
"(",
"'dsplit only works on arrays of 3 or more dimensions'",
")",
"return",
"split",
"(",
"ary",
",",
"indices_... | [
978,
0
] | [
1019,
45
] | python | en | ['en', 'error', 'th'] | False |
get_array_prepare | (*args) | Find the wrapper for the array with the highest priority.
In case of ties, leftmost wins. If no wrapper is found, return None
| Find the wrapper for the array with the highest priority. | def get_array_prepare(*args):
"""Find the wrapper for the array with the highest priority.
In case of ties, leftmost wins. If no wrapper is found, return None
"""
wrappers = sorted((getattr(x, '__array_priority__', 0), -i,
x.__array_prepare__) for i, x in enumerate(args)
... | [
"def",
"get_array_prepare",
"(",
"*",
"args",
")",
":",
"wrappers",
"=",
"sorted",
"(",
"(",
"getattr",
"(",
"x",
",",
"'__array_priority__'",
",",
"0",
")",
",",
"-",
"i",
",",
"x",
".",
"__array_prepare__",
")",
"for",
"i",
",",
"x",
"in",
"enumera... | [
1021,
0
] | [
1031,
15
] | python | en | ['en', 'en', 'en'] | True |
get_array_wrap | (*args) | Find the wrapper for the array with the highest priority.
In case of ties, leftmost wins. If no wrapper is found, return None
| Find the wrapper for the array with the highest priority. | def get_array_wrap(*args):
"""Find the wrapper for the array with the highest priority.
In case of ties, leftmost wins. If no wrapper is found, return None
"""
wrappers = sorted((getattr(x, '__array_priority__', 0), -i,
x.__array_wrap__) for i, x in enumerate(args)
... | [
"def",
"get_array_wrap",
"(",
"*",
"args",
")",
":",
"wrappers",
"=",
"sorted",
"(",
"(",
"getattr",
"(",
"x",
",",
"'__array_priority__'",
",",
"0",
")",
",",
"-",
"i",
",",
"x",
".",
"__array_wrap__",
")",
"for",
"i",
",",
"x",
"in",
"enumerate",
... | [
1033,
0
] | [
1043,
15
] | python | en | ['en', 'en', 'en'] | True |
kron | (a, b) |
Kronecker product of two arrays.
Computes the Kronecker product, a composite array made of blocks of the
second array scaled by the first.
Parameters
----------
a, b : array_like
Returns
-------
out : ndarray
See Also
--------
outer : The outer product
Notes
... |
Kronecker product of two arrays. | def kron(a, b):
"""
Kronecker product of two arrays.
Computes the Kronecker product, a composite array made of blocks of the
second array scaled by the first.
Parameters
----------
a, b : array_like
Returns
-------
out : ndarray
See Also
--------
outer : The outer... | [
"def",
"kron",
"(",
"a",
",",
"b",
")",
":",
"b",
"=",
"asanyarray",
"(",
"b",
")",
"a",
"=",
"array",
"(",
"a",
",",
"copy",
"=",
"False",
",",
"subok",
"=",
"True",
",",
"ndmin",
"=",
"b",
".",
"ndim",
")",
"ndb",
",",
"nda",
"=",
"b",
... | [
1051,
0
] | [
1147,
17
] | python | en | ['en', 'error', 'th'] | False |
tile | (A, reps) |
Construct an array by repeating A the number of times given by reps.
If `reps` has length ``d``, the result will have dimension of
``max(d, A.ndim)``.
If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new
axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication,
... |
Construct an array by repeating A the number of times given by reps. | def tile(A, reps):
"""
Construct an array by repeating A the number of times given by reps.
If `reps` has length ``d``, the result will have dimension of
``max(d, A.ndim)``.
If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new
axes. So a shape (3,) array is promoted to (1, ... | [
"def",
"tile",
"(",
"A",
",",
"reps",
")",
":",
"try",
":",
"tup",
"=",
"tuple",
"(",
"reps",
")",
"except",
"TypeError",
":",
"tup",
"=",
"(",
"reps",
",",
")",
"d",
"=",
"len",
"(",
"tup",
")",
"if",
"all",
"(",
"x",
"==",
"1",
"for",
"x"... | [
1155,
0
] | [
1243,
31
] | python | en | ['en', 'error', 'th'] | False |
is_norm | (modules) | Check if is one of the norms. | Check if is one of the norms. | def is_norm(modules):
"""Check if is one of the norms."""
if isinstance(modules, (GroupNorm, _BatchNorm)):
return True
return False | [
"def",
"is_norm",
"(",
"modules",
")",
":",
"if",
"isinstance",
"(",
"modules",
",",
"(",
"GroupNorm",
",",
"_BatchNorm",
")",
")",
":",
"return",
"True",
"return",
"False"
] | [
9,
0
] | [
13,
16
] | python | en | ['en', 'en', 'en'] | True |
parameterized_argument_value_pairs | (func, p) | Return tuples of parameterized arguments and their values.
This is useful if you are writing your own doc_func
function and need to know the values for each parameter name::
>>> def func(a, foo=None, bar=42, **kwargs): pass
>>> p = param(1, foo=7, extra=99)
>>> para... | Return tuples of parameterized arguments and their values. | def parameterized_argument_value_pairs(func, p):
"""Return tuples of parameterized arguments and their values.
This is useful if you are writing your own doc_func
function and need to know the values for each parameter name::
>>> def func(a, foo=None, bar=42, **kwargs): pass
... | [
"def",
"parameterized_argument_value_pairs",
"(",
"func",
",",
"p",
")",
":",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"arg_offset",
"=",
"1",
"if",
"argspec",
".",
"args",
"[",
":",
"1",
"]",
"==",
"[",
"\"self\"",
"]",
"else",
... | [
148,
0
] | [
205,
17
] | python | en | ['en', 'en', 'en'] | True |
short_repr | (x, n=64) | A shortened repr of ``x`` which is guaranteed to be ``unicode``::
>>> short_repr("foo")
u"foo"
>>> short_repr("123456789", n=4)
u"12...89"
| A shortened repr of ``x`` which is guaranteed to be ``unicode``:: | def short_repr(x, n=64):
""" A shortened repr of ``x`` which is guaranteed to be ``unicode``::
>>> short_repr("foo")
u"foo"
>>> short_repr("123456789", n=4)
u"12...89"
"""
x_repr = repr(x)
if isinstance(x_repr, bytes_type):
try:
x_rep... | [
"def",
"short_repr",
"(",
"x",
",",
"n",
"=",
"64",
")",
":",
"x_repr",
"=",
"repr",
"(",
"x",
")",
"if",
"isinstance",
"(",
"x_repr",
",",
"bytes_type",
")",
":",
"try",
":",
"x_repr",
"=",
"text_type",
"(",
"x_repr",
",",
"\"utf-8\"",
")",
"excep... | [
207,
0
] | [
224,
17
] | python | en | ['en', 'en', 'en'] | True |
detect_runner | () | Guess which test runner we're using by traversing the stack and looking
for the first matching module. This *should* be reasonably safe, as
it's done during test disocvery where the test runner should be the
stack frame immediately outside. | Guess which test runner we're using by traversing the stack and looking
for the first matching module. This *should* be reasonably safe, as
it's done during test disocvery where the test runner should be the
stack frame immediately outside. | def detect_runner():
""" Guess which test runner we're using by traversing the stack and looking
for the first matching module. This *should* be reasonably safe, as
it's done during test disocvery where the test runner should be the
stack frame immediately outside. """
if _test_runner_ov... | [
"def",
"detect_runner",
"(",
")",
":",
"if",
"_test_runner_override",
"is",
"not",
"None",
":",
"return",
"_test_runner_override",
"global",
"_test_runner_guess",
"if",
"_test_runner_guess",
"is",
"False",
":",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"f... | [
271,
0
] | [
294,
29
] | python | en | ['en', 'en', 'en'] | True |
param.explicit | (cls, args=None, kwargs=None) | Creates a ``param`` by explicitly specifying ``args`` and
``kwargs``::
>>> param.explicit([1,2,3])
param(*(1, 2, 3))
>>> param.explicit(kwargs={"foo": 42})
param(*(), **{"foo": "42"})
| Creates a ``param`` by explicitly specifying ``args`` and
``kwargs``:: | def explicit(cls, args=None, kwargs=None):
""" Creates a ``param`` by explicitly specifying ``args`` and
``kwargs``::
>>> param.explicit([1,2,3])
param(*(1, 2, 3))
>>> param.explicit(kwargs={"foo": 42})
param(*(), **{"foo": "42"})
... | [
"def",
"explicit",
"(",
"cls",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"args",
"=",
"args",
"or",
"(",
")",
"kwargs",
"=",
"kwargs",
"or",
"{",
"}",
"return",
"cls",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
100,
4
] | [
111,
35
] | python | en | ['en', 'en', 'en'] | True |
param.from_decorator | (cls, args) | Returns an instance of ``param()`` for ``@parameterized`` argument
``args``::
>>> param.from_decorator((42, ))
param(args=(42, ), kwargs={})
>>> param.from_decorator("foo")
param(args=("foo", ), kwargs={})
| Returns an instance of ``param()`` for ``@parameterized`` argument
``args``:: | def from_decorator(cls, args):
""" Returns an instance of ``param()`` for ``@parameterized`` argument
``args``::
>>> param.from_decorator((42, ))
param(args=(42, ), kwargs={})
>>> param.from_decorator("foo")
param(args=("foo", ), kwarg... | [
"def",
"from_decorator",
"(",
"cls",
",",
"args",
")",
":",
"if",
"isinstance",
"(",
"args",
",",
"param",
")",
":",
"return",
"args",
"elif",
"isinstance",
"(",
"args",
",",
"string_types",
")",
":",
"args",
"=",
"(",
"args",
",",
")",
"try",
":",
... | [
114,
4
] | [
135,
13
] | python | en | ['en', 'en', 'en'] | True |
parameterized._terrible_magic_get_defining_classes | (self) | Returns the set of parent classes of the class currently being defined.
Will likely only work if called from the ``parameterized`` decorator.
This function is entirely @brandon_rhodes's fault, as he suggested
the implementation: http://stackoverflow.com/a/8793684/71522
| Returns the set of parent classes of the class currently being defined.
Will likely only work if called from the ``parameterized`` decorator.
This function is entirely | def _terrible_magic_get_defining_classes(self):
""" Returns the set of parent classes of the class currently being defined.
Will likely only work if called from the ``parameterized`` decorator.
This function is entirely @brandon_rhodes's fault, as he suggested
the implementat... | [
"def",
"_terrible_magic_get_defining_classes",
"(",
"self",
")",
":",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"if",
"len",
"(",
"stack",
")",
"<=",
"4",
":",
"return",
"[",
"]",
"frame",
"=",
"stack",
"[",
"4",
"]",
"code_context",
"=",
"frame... | [
386,
4
] | [
401,
79
] | python | en | ['en', 'en', 'en'] | True |
parameterized.expand | (cls, input, name_func=None, doc_func=None, **legacy) | A "brute force" method of parameterizing test cases. Creates new
test cases and injects them into the namespace that the wrapped
function is being defined in. Useful for parameterizing tests in
subclasses of 'UnitTest', where Nose test generators don't work.
>>> @parame... | A "brute force" method of parameterizing test cases. Creates new
test cases and injects them into the namespace that the wrapped
function is being defined in. Useful for parameterizing tests in
subclasses of 'UnitTest', where Nose test generators don't work. | def expand(cls, input, name_func=None, doc_func=None, **legacy):
""" A "brute force" method of parameterizing test cases. Creates new
test cases and injects them into the namespace that the wrapped
function is being defined in. Useful for parameterizing tests in
subclasses of... | [
"def",
"expand",
"(",
"cls",
",",
"input",
",",
"name_func",
"=",
"None",
",",
"doc_func",
"=",
"None",
",",
"*",
"*",
"legacy",
")",
":",
"if",
"\"testcase_func_name\"",
"in",
"legacy",
":",
"warnings",
".",
"warn",
"(",
"\"testcase_func_name= is deprecated... | [
422,
4
] | [
465,
43
] | python | en | ['en', 'en', 'en'] | True |
test_ddp_sharded_plugin_correctness_multi_gpu_multi_optim | () |
Ensures same results using multiple optimizers across multiple GPUs
|
Ensures same results using multiple optimizers across multiple GPUs
| def test_ddp_sharded_plugin_correctness_multi_gpu_multi_optim():
"""
Ensures same results using multiple optimizers across multiple GPUs
"""
plugin_parity_test(
gpus=2,
model_cls=SeedTrainLoaderMultipleOptimizersModel,
max_percent_speed_diff=0.25, # todo: Increase speed diff... | [
"def",
"test_ddp_sharded_plugin_correctness_multi_gpu_multi_optim",
"(",
")",
":",
"plugin_parity_test",
"(",
"gpus",
"=",
"2",
",",
"model_cls",
"=",
"SeedTrainLoaderMultipleOptimizersModel",
",",
"max_percent_speed_diff",
"=",
"0.25",
",",
"# todo: Increase speed diff since o... | [
121,
0
] | [
129,
5
] | python | en | ['en', 'error', 'th'] | False |
test_ddp_sharded_plugin_correctness_multi_gpu_multi_optim_manual | (tmpdir) |
Ensures using multiple optimizers across multiple GPUs with manual optimization
|
Ensures using multiple optimizers across multiple GPUs with manual optimization
| def test_ddp_sharded_plugin_correctness_multi_gpu_multi_optim_manual(tmpdir):
"""
Ensures using multiple optimizers across multiple GPUs with manual optimization
"""
plugin_parity_test(
gpus=2,
model_cls=SeedTrainLoaderManualModel,
max_percent_speed_diff=0.25, # todo: Increa... | [
"def",
"test_ddp_sharded_plugin_correctness_multi_gpu_multi_optim_manual",
"(",
"tmpdir",
")",
":",
"plugin_parity_test",
"(",
"gpus",
"=",
"2",
",",
"model_cls",
"=",
"SeedTrainLoaderManualModel",
",",
"max_percent_speed_diff",
"=",
"0.25",
",",
"# todo: Increase speed diff ... | [
136,
0
] | [
144,
5
] | python | en | ['en', 'error', 'th'] | False |
record_ddp_fit_model_stats | (trainer, model, use_cuda) |
Helper to calculate wall clock time for fit + max allocated memory.
Args:
trainer: The trainer object.
model: The model to fit.
use_cuda: Whether to sync CUDA kernels.
Returns:
Max Memory if using GPUs, and total wall clock time.
|
Helper to calculate wall clock time for fit + max allocated memory. | def record_ddp_fit_model_stats(trainer, model, use_cuda):
"""
Helper to calculate wall clock time for fit + max allocated memory.
Args:
trainer: The trainer object.
model: The model to fit.
use_cuda: Whether to sync CUDA kernels.
Returns:
Max Memory if using GPUs, and t... | [
"def",
"record_ddp_fit_model_stats",
"(",
"trainer",
",",
"model",
",",
"use_cuda",
")",
":",
"max_memory",
"=",
"None",
"time_start",
"=",
"time",
".",
"perf_counter",
"(",
")",
"if",
"use_cuda",
":",
"torch",
".",
"cuda",
".",
"reset_peak_memory_stats",
"(",... | [
211,
0
] | [
238,
33
] | python | en | ['en', 'error', 'th'] | False |
plugin_parity_test | (
model_cls: Type[SeedTrainLoaderModel],
seed: int = 42,
gpus: int = 0,
precision: int = 32,
max_percent_speed_diff: float = 0.1,
) |
Ensures that the trained model is identical to the standard DDP implementation.
Also checks for speed/memory regressions, we should expect always less memory but performance to fluctuate.
Args:
model_cls: Model class to use for test.
seed: Seed for generators. Note that this does not handl... |
Ensures that the trained model is identical to the standard DDP implementation.
Also checks for speed/memory regressions, we should expect always less memory but performance to fluctuate. | def plugin_parity_test(
model_cls: Type[SeedTrainLoaderModel],
seed: int = 42,
gpus: int = 0,
precision: int = 32,
max_percent_speed_diff: float = 0.1,
):
"""
Ensures that the trained model is identical to the standard DDP implementation.
Also checks for speed/memory regressions, we shou... | [
"def",
"plugin_parity_test",
"(",
"model_cls",
":",
"Type",
"[",
"SeedTrainLoaderModel",
"]",
",",
"seed",
":",
"int",
"=",
"42",
",",
"gpus",
":",
"int",
"=",
"0",
",",
"precision",
":",
"int",
"=",
"32",
",",
"max_percent_speed_diff",
":",
"float",
"="... | [
241,
0
] | [
308,
73
] | python | en | ['en', 'error', 'th'] | False |
test__eval_step__flow | (tmpdir) |
Tests that only training_step can be used
|
Tests that only training_step can be used
| def test__eval_step__flow(tmpdir):
"""
Tests that only training_step can be used
"""
class TestModel(DeterministicModel):
def training_step(self, batch, batch_idx):
acc = self.step(batch, batch_idx)
acc = acc + batch_idx
self.training_step_called = True
... | [
"def",
"test__eval_step__flow",
"(",
"tmpdir",
")",
":",
"class",
"TestModel",
"(",
"DeterministicModel",
")",
":",
"def",
"training_step",
"(",
"self",
",",
"batch",
",",
"batch_idx",
")",
":",
"acc",
"=",
"self",
".",
"step",
"(",
"batch",
",",
"batch_id... | [
28,
0
] | [
69,
48
] | python | en | ['en', 'error', 'th'] | False |
test__eval_step__eval_step_end__flow | (tmpdir) |
Tests that only training_step can be used
|
Tests that only training_step can be used
| def test__eval_step__eval_step_end__flow(tmpdir):
"""
Tests that only training_step can be used
"""
class TestModel(DeterministicModel):
def training_step(self, batch, batch_idx):
acc = self.step(batch, batch_idx)
acc = acc + batch_idx
self.training_step_cal... | [
"def",
"test__eval_step__eval_step_end__flow",
"(",
"tmpdir",
")",
":",
"class",
"TestModel",
"(",
"DeterministicModel",
")",
":",
"def",
"training_step",
"(",
"self",
",",
"batch",
",",
"batch_idx",
")",
":",
"acc",
"=",
"self",
".",
"step",
"(",
"batch",
"... | [
73,
0
] | [
119,
48
] | python | en | ['en', 'error', 'th'] | False |
test__eval_step__epoch_end__flow | (tmpdir) |
Tests that only training_step can be used
|
Tests that only training_step can be used
| def test__eval_step__epoch_end__flow(tmpdir):
"""
Tests that only training_step can be used
"""
class TestModel(DeterministicModel):
def training_step(self, batch, batch_idx):
acc = self.step(batch, batch_idx)
acc = acc + batch_idx
self.training_step_called ... | [
"def",
"test__eval_step__epoch_end__flow",
"(",
"tmpdir",
")",
":",
"class",
"TestModel",
"(",
"DeterministicModel",
")",
":",
"def",
"training_step",
"(",
"self",
",",
"batch",
",",
"batch_idx",
")",
":",
"acc",
"=",
"self",
".",
"step",
"(",
"batch",
",",
... | [
123,
0
] | [
179,
44
] | python | en | ['en', 'error', 'th'] | False |
test__validation_step__step_end__epoch_end__flow | (tmpdir) |
Tests that only training_step can be used
|
Tests that only training_step can be used
| def test__validation_step__step_end__epoch_end__flow(tmpdir):
"""
Tests that only training_step can be used
"""
class TestModel(DeterministicModel):
def training_step(self, batch, batch_idx):
acc = self.step(batch, batch_idx)
acc = acc + batch_idx
self.train... | [
"def",
"test__validation_step__step_end__epoch_end__flow",
"(",
"tmpdir",
")",
":",
"class",
"TestModel",
"(",
"DeterministicModel",
")",
":",
"def",
"training_step",
"(",
"self",
",",
"batch",
",",
"batch_idx",
")",
":",
"acc",
"=",
"self",
".",
"step",
"(",
... | [
183,
0
] | [
244,
44
] | python | en | ['en', 'error', 'th'] | False |
generate_main_code | (serialization_composite_h_file) |
Main code generator.
Renders the header file for serialization composites.
The location of output file is provided as argument.
|
Main code generator.
Renders the header file for serialization composites.
The location of output file is provided as argument.
| def generate_main_code(serialization_composite_h_file):
"""
Main code generator.
Renders the header file for serialization composites.
The location of output file is provided as argument.
"""
generate_code('serialization_composite_h.j2', serialization_composite_h_file) | [
"def",
"generate_main_code",
"(",
"serialization_composite_h_file",
")",
":",
"generate_code",
"(",
"'serialization_composite_h.j2'",
",",
"serialization_composite_h_file",
")"
] | [
5,
0
] | [
11,
81
] | python | en | ['en', 'error', 'th'] | False |
generate_test_code | (serialization_composite_test_cc_file) |
Test code generator.
Renders the test file for serialization composites.
The location of output file is provided as argument.
|
Test code generator.
Renders the test file for serialization composites.
The location of output file is provided as argument.
| def generate_test_code(serialization_composite_test_cc_file):
"""
Test code generator.
Renders the test file for serialization composites.
The location of output file is provided as argument.
"""
generate_code('serialization_composite_test_cc.j2', serialization_composite_test_cc_file) | [
"def",
"generate_test_code",
"(",
"serialization_composite_test_cc_file",
")",
":",
"generate_code",
"(",
"'serialization_composite_test_cc.j2'",
",",
"serialization_composite_test_cc_file",
")"
] | [
14,
0
] | [
20,
93
] | python | en | ['en', 'error', 'th'] | False |
generate_code | (template_name, output_file) |
Gets definition of structures to render.
Then renders these structures using template provided into provided output file.
|
Gets definition of structures to render.
Then renders these structures using template provided into provided output file.
| def generate_code(template_name, output_file):
"""
Gets definition of structures to render.
Then renders these structures using template provided into provided output file.
"""
field_counts = get_field_counts()
template = RenderingHelper.get_template(template_name)
contents = template.render(count... | [
"def",
"generate_code",
"(",
"template_name",
",",
"output_file",
")",
":",
"field_counts",
"=",
"get_field_counts",
"(",
")",
"template",
"=",
"RenderingHelper",
".",
"get_template",
"(",
"template_name",
")",
"contents",
"=",
"template",
".",
"render",
"(",
"c... | [
23,
0
] | [
32,
26
] | python | en | ['en', 'error', 'th'] | False |
get_field_counts | () |
Generate argument counts that should be processed by composite deserializers.
|
Generate argument counts that should be processed by composite deserializers.
| def get_field_counts():
"""
Generate argument counts that should be processed by composite deserializers.
"""
return range(1, 12) | [
"def",
"get_field_counts",
"(",
")",
":",
"return",
"range",
"(",
"1",
",",
"12",
")"
] | [
35,
0
] | [
39,
23
] | python | en | ['en', 'error', 'th'] | False |
has_len | (dataloader: DataLoader) | Checks if a given Dataloader has __len__ method implemented i.e. if
it is a finite dataloader or infinite dataloader. | Checks if a given Dataloader has __len__ method implemented i.e. if
it is a finite dataloader or infinite dataloader. | def has_len(dataloader: DataLoader) -> bool:
""" Checks if a given Dataloader has __len__ method implemented i.e. if
it is a finite dataloader or infinite dataloader. """
try:
# try getting the length
if len(dataloader) == 0:
raise ValueError('`Dataloader` returned 0 length. Ple... | [
"def",
"has_len",
"(",
"dataloader",
":",
"DataLoader",
")",
"->",
"bool",
":",
"try",
":",
"# try getting the length",
"if",
"len",
"(",
"dataloader",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'`Dataloader` returned 0 length. Please make sure that it returns ... | [
25,
0
] | [
45,
18
] | python | en | ['en', 'en', 'en'] | True |
get_len | (dataloader: DataLoader) | Return the length of the given DataLoader. If ``__len__`` method is not implemented, return float('inf'). | Return the length of the given DataLoader. If ``__len__`` method is not implemented, return float('inf'). | def get_len(dataloader: DataLoader) -> Union[int, float]:
""" Return the length of the given DataLoader. If ``__len__`` method is not implemented, return float('inf'). """
if has_len(dataloader):
return len(dataloader)
return float('inf') | [
"def",
"get_len",
"(",
"dataloader",
":",
"DataLoader",
")",
"->",
"Union",
"[",
"int",
",",
"float",
"]",
":",
"if",
"has_len",
"(",
"dataloader",
")",
":",
"return",
"len",
"(",
"dataloader",
")",
"return",
"float",
"(",
"'inf'",
")"
] | [
48,
0
] | [
54,
23
] | python | en | ['en', 'en', 'en'] | True |
do_search | () | Extract the posted data; perform the search; return results. | Extract the posted data; perform the search; return results. | def do_search() -> 'html':
"""Extract the posted data; perform the search; return results."""
@copy_current_request_context
def log_request(req: 'flask_request', res: str) -> None:
"""Log details of the web request and the results."""
sleep(15) # This makes log_request really slow...
... | [
"def",
"do_search",
"(",
")",
"->",
"'html'",
":",
"@",
"copy_current_request_context",
"def",
"log_request",
"(",
"req",
":",
"'flask_request'",
",",
"res",
":",
"str",
")",
"->",
"None",
":",
"\"\"\"Log details of the web request and the results.\"\"\"",
"sleep",
... | [
31,
0
] | [
62,
48
] | python | en | ['en', 'en', 'en'] | True |
entry_page | () | Display this webapp's HTML form. | Display this webapp's HTML form. | def entry_page() -> 'html':
"""Display this webapp's HTML form."""
return render_template('entry.html',
the_title='Welcome to search4letters on the web!') | [
"def",
"entry_page",
"(",
")",
"->",
"'html'",
":",
"return",
"render_template",
"(",
"'entry.html'",
",",
"the_title",
"=",
"'Welcome to search4letters on the web!'",
")"
] | [
67,
0
] | [
70,
77
] | python | en | ['en', 'en', 'en'] | True |
view_the_log | () | Display the contents of the log file as a HTML table. | Display the contents of the log file as a HTML table. | def view_the_log() -> 'html':
"""Display the contents of the log file as a HTML table."""
try:
with UseDatabase(app.config['dbconfig']) as cursor:
_SQL = """select phrase, letters, ip, browser_string, results
from log"""
cursor.execute(_SQL)
conten... | [
"def",
"view_the_log",
"(",
")",
"->",
"'html'",
":",
"try",
":",
"with",
"UseDatabase",
"(",
"app",
".",
"config",
"[",
"'dbconfig'",
"]",
")",
"as",
"cursor",
":",
"_SQL",
"=",
"\"\"\"select phrase, letters, ip, browser_string, results\n from log\... | [
75,
0
] | [
97,
18
] | python | en | ['en', 'en', 'en'] | True |
ExperimentWriter.log_hparams | (self, params: Dict[str, Any]) | Record hparams | Record hparams | def log_hparams(self, params: Dict[str, Any]) -> None:
"""Record hparams"""
self.hparams.update(params) | [
"def",
"log_hparams",
"(",
"self",
",",
"params",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"self",
".",
"hparams",
".",
"update",
"(",
"params",
")"
] | [
62,
4
] | [
64,
35
] | python | en | ['en', 'fil', 'en'] | False |
ExperimentWriter.log_metrics | (self, metrics_dict: Dict[str, float], step: Optional[int] = None) | Record metrics | Record metrics | def log_metrics(self, metrics_dict: Dict[str, float], step: Optional[int] = None) -> None:
"""Record metrics"""
def _handle_value(value):
if isinstance(value, torch.Tensor):
return value.item()
return value
if step is None:
step = len(self.me... | [
"def",
"log_metrics",
"(",
"self",
",",
"metrics_dict",
":",
"Dict",
"[",
"str",
",",
"float",
"]",
",",
"step",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"None",
":",
"def",
"_handle_value",
"(",
"value",
")",
":",
"if",
"isinstance"... | [
66,
4
] | [
79,
36
] | python | en | ['en', 'sr', 'en'] | False |
ExperimentWriter.save | (self) | Save recorded hparams and metrics into files | Save recorded hparams and metrics into files | def save(self) -> None:
"""Save recorded hparams and metrics into files"""
hparams_file = os.path.join(self.log_dir, self.NAME_HPARAMS_FILE)
save_hparams_to_yaml(hparams_file, self.hparams)
if not self.metrics:
return
last_m = {}
for m in self.metrics:
... | [
"def",
"save",
"(",
"self",
")",
"->",
"None",
":",
"hparams_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"log_dir",
",",
"self",
".",
"NAME_HPARAMS_FILE",
")",
"save_hparams_to_yaml",
"(",
"hparams_file",
",",
"self",
".",
"hparams",
")... | [
81,
4
] | [
97,
47
] | python | en | ['en', 'en', 'en'] | True |
CSVLogger.root_dir | (self) |
Parent directory for all checkpoint subdirectories.
If the experiment name parameter is ``None`` or the empty string, no experiment subdirectory is used
and the checkpoint will be saved in "save_dir/version_dir"
|
Parent directory for all checkpoint subdirectories.
If the experiment name parameter is ``None`` or the empty string, no experiment subdirectory is used
and the checkpoint will be saved in "save_dir/version_dir"
| def root_dir(self) -> str:
"""
Parent directory for all checkpoint subdirectories.
If the experiment name parameter is ``None`` or the empty string, no experiment subdirectory is used
and the checkpoint will be saved in "save_dir/version_dir"
"""
if not self.name:
... | [
"def",
"root_dir",
"(",
"self",
")",
"->",
"str",
":",
"if",
"not",
"self",
".",
"name",
":",
"return",
"self",
".",
"save_dir",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"save_dir",
",",
"self",
".",
"name",
")"
] | [
137,
4
] | [
145,
53
] | python | en | ['en', 'error', 'th'] | False |
CSVLogger.log_dir | (self) |
The log directory for this run. By default, it is named
``'version_${self.version}'`` but it can be overridden by passing a string value
for the constructor's version parameter instead of ``None`` or an int.
|
The log directory for this run. By default, it is named
``'version_${self.version}'`` but it can be overridden by passing a string value
for the constructor's version parameter instead of ``None`` or an int.
| def log_dir(self) -> str:
"""
The log directory for this run. By default, it is named
``'version_${self.version}'`` but it can be overridden by passing a string value
for the constructor's version parameter instead of ``None`` or an int.
"""
# create a pseudo standard pat... | [
"def",
"log_dir",
"(",
"self",
")",
"->",
"str",
":",
"# create a pseudo standard path ala test-tube",
"version",
"=",
"self",
".",
"version",
"if",
"isinstance",
"(",
"self",
".",
"version",
",",
"str",
")",
"else",
"f\"version_{self.version}\"",
"log_dir",
"=",
... | [
148,
4
] | [
157,
22
] | python | en | ['en', 'error', 'th'] | False |
CSVLogger.experiment | (self) | r"""
Actual ExperimentWriter object. To use ExperimentWriter features in your
:class:`~pytorch_lightning.core.lightning.LightningModule` do the following.
Example::
self.logger.experiment.some_experiment_writer_function()
| r""" | def experiment(self) -> ExperimentWriter:
r"""
Actual ExperimentWriter object. To use ExperimentWriter features in your
:class:`~pytorch_lightning.core.lightning.LightningModule` do the following.
Example::
self.logger.experiment.some_experiment_writer_function()
... | [
"def",
"experiment",
"(",
"self",
")",
"->",
"ExperimentWriter",
":",
"if",
"self",
".",
"_experiment",
":",
"return",
"self",
".",
"_experiment",
"os",
".",
"makedirs",
"(",
"self",
".",
"root_dir",
",",
"exist_ok",
"=",
"True",
")",
"self",
".",
"_expe... | [
165,
4
] | [
181,
31
] | python | cy | ['en', 'cy', 'hi'] | False |
vp_start_gui | () | Starting point when module is the main routine. | Starting point when module is the main routine. | def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = Tk()
root.resizable(False, False)
top = Notepads_managment(root)
notepad_support.init(root, top)
root.mainloop() | [
"def",
"vp_start_gui",
"(",
")",
":",
"global",
"val",
",",
"w",
",",
"root",
"root",
"=",
"Tk",
"(",
")",
"root",
".",
"resizable",
"(",
"False",
",",
"False",
")",
"top",
"=",
"Notepads_managment",
"(",
"root",
")",
"notepad_support",
".",
"init",
... | [
23,
0
] | [
30,
19
] | python | en | ['en', 'en', 'en'] | True |
create_Notepads_managment | (root, *args, **kwargs) | Starting point when module is imported by another program. | Starting point when module is imported by another program. | def create_Notepads_managment(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = Toplevel(root)
top = Notepads_managment(w)
notepad_support.init(w, top, *args, **kwargs)
return (w, top) | [
"def",
"create_Notepads_managment",
"(",
"root",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"w",
",",
"w_win",
",",
"rt",
"rt",
"=",
"root",
"w",
"=",
"Toplevel",
"(",
"root",
")",
"top",
"=",
"Notepads_managment",
"(",
"w",
")",
... | [
36,
0
] | [
43,
19
] | python | en | ['en', 'en', 'en'] | True |
Notepads_managment.__init__ | (self, top=None) | This class configures and populates the toplevel window.
top is the toplevel containing window. | This class configures and populates the toplevel window.
top is the toplevel containing window. | def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana... | [
"def",
"__init__",
"(",
"self",
",",
"top",
"=",
"None",
")",
":",
"_bgcolor",
"=",
"'#d9d9d9'",
"# X11 color: 'gray85'",
"_fgcolor",
"=",
"'#000000'",
"# X11 color: 'black'",
"_compcolor",
"=",
"'#d9d9d9'",
"# X11 color: 'gray85'",
"_ana1color",
"=",
"'#d9d9d9'",
"... | [
53,
4
] | [
194,
62
] | python | en | ['en', 'en', 'en'] | True |
setup_module | () |
Build the required testing extension module
|
Build the required testing extension module | def setup_module():
"""
Build the required testing extension module
"""
global wrap
# Check compiler availability first
if not util.has_c_compiler():
pytest.skip("No C compiler available")
if wrap is None:
config_code = """
config.add_extension('test_array_from_pyo... | [
"def",
"setup_module",
"(",
")",
":",
"global",
"wrap",
"# Check compiler availability first",
"if",
"not",
"util",
".",
"has_c_compiler",
"(",
")",
":",
"pytest",
".",
"skip",
"(",
"\"No C compiler available\"",
")",
"if",
"wrap",
"is",
"None",
":",
"config_cod... | [
17,
0
] | [
39,
71
] | python | en | ['en', 'error', 'th'] | False |
Array.has_shared_memory | (self) | Check that created array shares data with input array.
| Check that created array shares data with input array.
| def has_shared_memory(self):
"""Check that created array shares data with input array.
"""
if self.obj is self.arr:
return True
if not isinstance(self.obj, ndarray):
return False
obj_attr = wrap.array_attrs(self.obj)
return obj_attr[0] == self.arr_... | [
"def",
"has_shared_memory",
"(",
"self",
")",
":",
"if",
"self",
".",
"obj",
"is",
"self",
".",
"arr",
":",
"return",
"True",
"if",
"not",
"isinstance",
"(",
"self",
".",
"obj",
",",
"ndarray",
")",
":",
"return",
"False",
"obj_attr",
"=",
"wrap",
".... | [
284,
4
] | [
292,
46
] | python | en | ['en', 'en', 'en'] | True |
toWord | (action) |
Parameters: List of moves
Returns: Returns List of moves in Word
|
Parameters: List of moves
Returns: Returns List of moves in Word
| def toWord(action):
'''
Parameters: List of moves
Returns: Returns List of moves in Word
'''
if(action==0):
return "Left"
if(action==1):
return "Right"
if(action==2):
return "Top"
if(action==3):
return "Bottom" | [
"def",
"toWord",
"(",
"action",
")",
":",
"if",
"(",
"action",
"==",
"0",
")",
":",
"return",
"\"Left\"",
"if",
"(",
"action",
"==",
"1",
")",
":",
"return",
"\"Right\"",
"if",
"(",
"action",
"==",
"2",
")",
":",
"return",
"\"Top\"",
"if",
"(",
"... | [
319,
0
] | [
331,
23
] | python | en | ['en', 'error', 'th'] | False |
Node.__init__ | (self,state,depth = 0,moves = None,optimizer=0) |
Parameters:
state: State of Puzzle
depth: Depth of State in Space Search Tree
moves: Moves List to reach this state from initial state
optimizer: Used for UCS Only
0 - Manhattan Distance
1 - Hamming Dist... |
Parameters:
state: State of Puzzle
depth: Depth of State in Space Search Tree
moves: Moves List to reach this state from initial state
optimizer: Used for UCS Only
0 - Manhattan Distance
1 - Hamming Dist... | def __init__(self,state,depth = 0,moves = None,optimizer=0):
'''
Parameters:
state: State of Puzzle
depth: Depth of State in Space Search Tree
moves: Moves List to reach this state from initial state
optimizer: Used for UCS Only
... | [
"def",
"__init__",
"(",
"self",
",",
"state",
",",
"depth",
"=",
"0",
",",
"moves",
"=",
"None",
",",
"optimizer",
"=",
"0",
")",
":",
"self",
".",
"state",
"=",
"state",
"self",
".",
"size",
"=",
"len",
"(",
"state",
")",
"self",
".",
"depth",
... | [
8,
4
] | [
28,
30
] | python | en | ['en', 'error', 'th'] | False |
Node.getAvailableActions | (self) |
Parameters: Current State
Returns: Available Actions for Current State
0 - Left 1 - Right 2 - Top 3 - Bottom
Restrictions: state is self.size x self.size Array
|
Parameters: Current State
Returns: Available Actions for Current State
0 - Left 1 - Right 2 - Top 3 - Bottom
Restrictions: state is self.size x self.size Array
| def getAvailableActions(self):
'''
Parameters: Current State
Returns: Available Actions for Current State
0 - Left 1 - Right 2 - Top 3 - Bottom
Restrictions: state is self.size x self.size Array
'''
action = list()
for i in range(s... | [
"def",
"getAvailableActions",
"(",
"self",
")",
":",
"action",
"=",
"list",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"size",
")",
":",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"size",
")",
":",
"if",
"self",
".",
"state",
"[",
... | [
31,
4
] | [
51,
21
] | python | en | ['en', 'error', 'th'] | False |
Node.getResultFromAction | (self,action) |
Parameters: Current State , Action
Returns: Node with New State
Restrictions: Action will always be valid and state is self.size x self.size Array
|
Parameters: Current State , Action
Returns: Node with New State
Restrictions: Action will always be valid and state is self.size x self.size Array
| def getResultFromAction(self,action):
'''
Parameters: Current State , Action
Returns: Node with New State
Restrictions: Action will always be valid and state is self.size x self.size Array
'''
newstate = deepcopy(self.state)
newMoves = deepcopy(self.mo... | [
"def",
"getResultFromAction",
"(",
"self",
",",
"action",
")",
":",
"newstate",
"=",
"deepcopy",
"(",
"self",
".",
"state",
")",
"newMoves",
"=",
"deepcopy",
"(",
"self",
".",
"moves",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"size",
")",
":... | [
53,
4
] | [
80,
19
] | python | en | ['en', 'error', 'th'] | False |
Node.isGoalState | (self) |
Parameters: State
Returns: True if Goal State, otherwise False
Restrictions: State is self.size x self.size Array
|
Parameters: State
Returns: True if Goal State, otherwise False
Restrictions: State is self.size x self.size Array
| def isGoalState(self):
'''
Parameters: State
Returns: True if Goal State, otherwise False
Restrictions: State is self.size x self.size Array
'''
for i in range(self.size):
for j in range(self.size):
if(i==j and j==self.size-1):
... | [
"def",
"isGoalState",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"size",
")",
":",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"size",
")",
":",
"if",
"(",
"i",
"==",
"j",
"and",
"j",
"==",
"self",
".",
"size",
"-",
... | [
82,
4
] | [
94,
19
] | python | en | ['en', 'error', 'th'] | False |
Node.getManhattanDistance | (self) |
Parameters: State
Returns: Manhattan Distance between Current State and Goal State
Restrictions: State must be a self.size x self.size Array
|
Parameters: State
Returns: Manhattan Distance between Current State and Goal State
Restrictions: State must be a self.size x self.size Array
| def getManhattanDistance(self):
'''
Parameters: State
Returns: Manhattan Distance between Current State and Goal State
Restrictions: State must be a self.size x self.size Array
'''
ans = 0
for i in range(self.size):
for j in range(self.size... | [
"def",
"getManhattanDistance",
"(",
"self",
")",
":",
"ans",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"size",
")",
":",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"size",
")",
":",
"if",
"(",
"self",
".",
"state",
"[",
"i",
"]",... | [
96,
4
] | [
108,
18
] | python | en | ['en', 'error', 'th'] | False |
Solver.isSolvable | (self) |
Parameters: State
Returns: True if state is solvable, otherwise False
|
Parameters: State
Returns: True if state is solvable, otherwise False
| def isSolvable(self):
'''
Parameters: State
Returns: True if state is solvable, otherwise False
'''
flatState = [j for sub in self.state for j in sub]
inversions = 0
for i in range(len(flatState)-1):
for j in range(i+1,len(flatState)):
... | [
"def",
"isSolvable",
"(",
"self",
")",
":",
"flatState",
"=",
"[",
"j",
"for",
"sub",
"in",
"self",
".",
"state",
"for",
"j",
"in",
"sub",
"]",
"inversions",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"flatState",
")",
"-",
"1",
")",
... | [
218,
4
] | [
229,
30
] | python | en | ['en', 'error', 'th'] | False |
Solver.breadth_first_search | (self) |
Parameters: State
Returns: List of Moves to solve the state, otherwise None if unsolvable
|
Parameters: State
Returns: List of Moves to solve the state, otherwise None if unsolvable
| def breadth_first_search(self):
'''
Parameters: State
Returns: List of Moves to solve the state, otherwise None if unsolvable
'''
if(self.isSolvable()==False):
return (None,None)
closed = list()
q = deque()
q.append(Node(state = self.s... | [
"def",
"breadth_first_search",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"isSolvable",
"(",
")",
"==",
"False",
")",
":",
"return",
"(",
"None",
",",
"None",
")",
"closed",
"=",
"list",
"(",
")",
"q",
"=",
"deque",
"(",
")",
"q",
".",
"appen... | [
231,
4
] | [
252,
26
] | python | en | ['en', 'error', 'th'] | False |
Solver.depth_first_search | (self) |
Parameters: State
Returns: List of Moves to solve the state, otherwise None if unsolvable
|
Parameters: State
Returns: List of Moves to solve the state, otherwise None if unsolvable
| def depth_first_search(self):
'''
Parameters: State
Returns: List of Moves to solve the state, otherwise None if unsolvable
'''
if(self.isSolvable()==False):
return (None,None)
closed = list()
q = list()
q.append(Node(state = self.state... | [
"def",
"depth_first_search",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"isSolvable",
"(",
")",
"==",
"False",
")",
":",
"return",
"(",
"None",
",",
"None",
")",
"closed",
"=",
"list",
"(",
")",
"q",
"=",
"list",
"(",
")",
"q",
".",
"append",... | [
254,
4
] | [
273,
26
] | python | en | ['en', 'error', 'th'] | False |
Solver.uniform_cost_search | (self,optimizer=0) |
Parameters: State, Optimizer
Returns: List of Moves to solve the state, otherwise None if unsolvable
|
Parameters: State, Optimizer
Returns: List of Moves to solve the state, otherwise None if unsolvable
| def uniform_cost_search(self,optimizer=0):
'''
Parameters: State, Optimizer
Returns: List of Moves to solve the state, otherwise None if unsolvable
'''
if(self.isSolvable()==False):
return (None,None)
closed = list()
q = PriorityQueue()
... | [
"def",
"uniform_cost_search",
"(",
"self",
",",
"optimizer",
"=",
"0",
")",
":",
"if",
"(",
"self",
".",
"isSolvable",
"(",
")",
"==",
"False",
")",
":",
"return",
"(",
"None",
",",
"None",
")",
"closed",
"=",
"list",
"(",
")",
"q",
"=",
"PriorityQ... | [
275,
4
] | [
294,
26
] | python | en | ['en', 'error', 'th'] | False |
Solver.a_star | (self) |
Parameters: State, Optimizer
Returns: List of Moves to solve the state, otherwise None if unsolvable
|
Parameters: State, Optimizer
Returns: List of Moves to solve the state, otherwise None if unsolvable
| def a_star(self):
'''
Parameters: State, Optimizer
Returns: List of Moves to solve the state, otherwise None if unsolvable
'''
if(self.isSolvable()==False):
return (None,None)
closed = dict()
q = PriorityQueue()
node = Node(state = self... | [
"def",
"a_star",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"isSolvable",
"(",
")",
"==",
"False",
")",
":",
"return",
"(",
"None",
",",
"None",
")",
"closed",
"=",
"dict",
"(",
")",
"q",
"=",
"PriorityQueue",
"(",
")",
"node",
"=",
"Node",
... | [
296,
4
] | [
317,
26
] | python | en | ['en', 'error', 'th'] | False |
DDPSpawnShardedPlugin._optim_state_dict | (self, optimizer) |
Retrieves state dict only on rank 0, which contains the entire optimizer state after calling
:meth:`consolidate_state_dict`.
|
Retrieves state dict only on rank 0, which contains the entire optimizer state after calling
:meth:`consolidate_state_dict`.
| def _optim_state_dict(self, optimizer):
"""
Retrieves state dict only on rank 0, which contains the entire optimizer state after calling
:meth:`consolidate_state_dict`.
"""
return optimizer.state_dict() | [
"def",
"_optim_state_dict",
"(",
"self",
",",
"optimizer",
")",
":",
"return",
"optimizer",
".",
"state_dict",
"(",
")"
] | [
44,
4
] | [
49,
37
] | python | en | ['en', 'error', 'th'] | False |
fftshift | (x, axes=None) |
Shift the zero-frequency component to the center of the spectrum.
This function swaps half-spaces for all axes listed (defaults to all).
Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.
Parameters
----------
x : array_like
Input array.
axes : int or shape tu... |
Shift the zero-frequency component to the center of the spectrum. | def fftshift(x, axes=None):
"""
Shift the zero-frequency component to the center of the spectrum.
This function swaps half-spaces for all axes listed (defaults to all).
Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.
Parameters
----------
x : array_like
Inpu... | [
"def",
"fftshift",
"(",
"x",
",",
"axes",
"=",
"None",
")",
":",
"x",
"=",
"asarray",
"(",
"x",
")",
"if",
"axes",
"is",
"None",
":",
"axes",
"=",
"tuple",
"(",
"range",
"(",
"x",
".",
"ndim",
")",
")",
"shift",
"=",
"[",
"dim",
"//",
"2",
... | [
22,
0
] | [
75,
31
] | python | en | ['en', 'error', 'th'] | False |
ifftshift | (x, axes=None) |
The inverse of `fftshift`. Although identical for even-length `x`, the
functions differ by one sample for odd-length `x`.
Parameters
----------
x : array_like
Input array.
axes : int or shape tuple, optional
Axes over which to calculate. Defaults to None, which shifts all axes... |
The inverse of `fftshift`. Although identical for even-length `x`, the
functions differ by one sample for odd-length `x`. | def ifftshift(x, axes=None):
"""
The inverse of `fftshift`. Although identical for even-length `x`, the
functions differ by one sample for odd-length `x`.
Parameters
----------
x : array_like
Input array.
axes : int or shape tuple, optional
Axes over which to calculate. Def... | [
"def",
"ifftshift",
"(",
"x",
",",
"axes",
"=",
"None",
")",
":",
"x",
"=",
"asarray",
"(",
"x",
")",
"if",
"axes",
"is",
"None",
":",
"axes",
"=",
"tuple",
"(",
"range",
"(",
"x",
".",
"ndim",
")",
")",
"shift",
"=",
"[",
"-",
"(",
"dim",
... | [
79,
0
] | [
122,
31
] | python | en | ['en', 'error', 'th'] | False |
fftfreq | (n, d=1.0) |
Return the Discrete Fourier Transform sample frequencies.
The returned float array `f` contains the frequency bin centers in cycles
per unit of the sample spacing (with zero at the start). For instance, if
the sample spacing is in seconds, then the frequency unit is cycles/second.
Given a window... |
Return the Discrete Fourier Transform sample frequencies. | def fftfreq(n, d=1.0):
"""
Return the Discrete Fourier Transform sample frequencies.
The returned float array `f` contains the frequency bin centers in cycles
per unit of the sample spacing (with zero at the start). For instance, if
the sample spacing is in seconds, then the frequency unit is cycl... | [
"def",
"fftfreq",
"(",
"n",
",",
"d",
"=",
"1.0",
")",
":",
"if",
"not",
"isinstance",
"(",
"n",
",",
"integer_types",
")",
":",
"raise",
"ValueError",
"(",
"\"n should be an integer\"",
")",
"val",
"=",
"1.0",
"/",
"(",
"n",
"*",
"d",
")",
"results"... | [
126,
0
] | [
171,
24
] | python | en | ['en', 'error', 'th'] | False |
rfftfreq | (n, d=1.0) |
Return the Discrete Fourier Transform sample frequencies
(for usage with rfft, irfft).
The returned float array `f` contains the frequency bin centers in cycles
per unit of the sample spacing (with zero at the start). For instance, if
the sample spacing is in seconds, then the frequency unit is c... |
Return the Discrete Fourier Transform sample frequencies
(for usage with rfft, irfft). | def rfftfreq(n, d=1.0):
"""
Return the Discrete Fourier Transform sample frequencies
(for usage with rfft, irfft).
The returned float array `f` contains the frequency bin centers in cycles
per unit of the sample spacing (with zero at the start). For instance, if
the sample spacing is in second... | [
"def",
"rfftfreq",
"(",
"n",
",",
"d",
"=",
"1.0",
")",
":",
"if",
"not",
"isinstance",
"(",
"n",
",",
"integer_types",
")",
":",
"raise",
"ValueError",
"(",
"\"n should be an integer\"",
")",
"val",
"=",
"1.0",
"/",
"(",
"n",
"*",
"d",
")",
"N",
"... | [
175,
0
] | [
223,
24
] | python | en | ['en', 'error', 'th'] | False |
DDP2Plugin.reduce | (self, tensor, *args, **kwargs) |
Reduces a tensor from all processes to one aggregated tensor.
In DDP2, the reduction here is only across local devices within the node.
Args:
tensor: the tensor to sync and reduce
*args: ignored for DDP2
**kwargs: ignored for DDP2
Return:
... |
Reduces a tensor from all processes to one aggregated tensor.
In DDP2, the reduction here is only across local devices within the node. | def reduce(self, tensor, *args, **kwargs):
"""
Reduces a tensor from all processes to one aggregated tensor.
In DDP2, the reduction here is only across local devices within the node.
Args:
tensor: the tensor to sync and reduce
*args: ignored for DDP2
... | [
"def",
"reduce",
"(",
"self",
",",
"tensor",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"tensor",
",",
"Result",
")",
":",
"tensor",
".",
"dp_reduce",
"(",
")",
"elif",
"isinstance",
"(",
"tensor",
",",
"torch",
"... | [
27,
4
] | [
46,
21
] | python | en | ['en', 'error', 'th'] | False |
test_zero_division | (metric_class, metric_fn) | Test that zero_division works correctly (currently should just set to 0). | Test that zero_division works correctly (currently should just set to 0). | def test_zero_division(metric_class, metric_fn):
""" Test that zero_division works correctly (currently should just set to 0). """
preds = torch.tensor([1, 2, 1, 1])
target = torch.tensor([2, 1, 2, 1])
cl_metric = metric_class(average="none", num_classes=3)
cl_metric(preds, target)
result_cl ... | [
"def",
"test_zero_division",
"(",
"metric_class",
",",
"metric_fn",
")",
":",
"preds",
"=",
"torch",
".",
"tensor",
"(",
"[",
"1",
",",
"2",
",",
"1",
",",
"1",
"]",
")",
"target",
"=",
"torch",
".",
"tensor",
"(",
"[",
"2",
",",
"1",
",",
"2",
... | [
114,
0
] | [
126,
44
] | python | en | ['en', 'en', 'en'] | True |
test_no_support | (metric_class, metric_fn) | This tests a rare edge case, where there is only one class present
in target, and ignore_index is set to exactly that class - and the
average method is equal to 'weighted'.
This would mean that the sum of weights equals zero, and would, without
taking care of this case, return NaN. However, the reducti... | This tests a rare edge case, where there is only one class present
in target, and ignore_index is set to exactly that class - and the
average method is equal to 'weighted'. | def test_no_support(metric_class, metric_fn):
"""This tests a rare edge case, where there is only one class present
in target, and ignore_index is set to exactly that class - and the
average method is equal to 'weighted'.
This would mean that the sum of weights equals zero, and would, without
takin... | [
"def",
"test_no_support",
"(",
"metric_class",
",",
"metric_fn",
")",
":",
"preds",
"=",
"torch",
".",
"tensor",
"(",
"[",
"1",
",",
"1",
",",
"0",
",",
"0",
"]",
")",
"target",
"=",
"torch",
".",
"tensor",
"(",
"[",
"0",
",",
"0",
",",
"0",
",... | [
130,
0
] | [
150,
38
] | python | en | ['en', 'en', 'en'] | True |
test_precision_recall_joint | (average) | A simple test of the joint precision_recall metric.
No need to test this thorougly, as it is just a combination of precision and recall,
which are already tested thoroughly.
| A simple test of the joint precision_recall metric. | def test_precision_recall_joint(average):
"""A simple test of the joint precision_recall metric.
No need to test this thorougly, as it is just a combination of precision and recall,
which are already tested thoroughly.
"""
precision_result = precision(
_input_mcls_prob.preds[0], _input_mcl... | [
"def",
"test_precision_recall_joint",
"(",
"average",
")",
":",
"precision_result",
"=",
"precision",
"(",
"_input_mcls_prob",
".",
"preds",
"[",
"0",
"]",
",",
"_input_mcls_prob",
".",
"target",
"[",
"0",
"]",
",",
"average",
"=",
"average",
",",
"num_classes... | [
283,
0
] | [
302,
60
] | python | en | ['en', 'en', 'en'] | True |
test_top_k | (
metric_class,
metric_fn,
k: int,
preds: torch.Tensor,
target: torch.Tensor,
average: str,
expected_prec: torch.Tensor,
expected_recall: torch.Tensor,
) | A simple test to check that top_k works as expected.
Just a sanity check, the tests in StatScores should already guarantee
the corectness of results.
| A simple test to check that top_k works as expected. | def test_top_k(
metric_class,
metric_fn,
k: int,
preds: torch.Tensor,
target: torch.Tensor,
average: str,
expected_prec: torch.Tensor,
expected_recall: torch.Tensor,
):
"""A simple test to check that top_k works as expected.
Just a sanity check, the tests in StatScores should al... | [
"def",
"test_top_k",
"(",
"metric_class",
",",
"metric_fn",
",",
"k",
":",
"int",
",",
"preds",
":",
"torch",
".",
"Tensor",
",",
"target",
":",
"torch",
".",
"Tensor",
",",
"average",
":",
"str",
",",
"expected_prec",
":",
"torch",
".",
"Tensor",
",",... | [
321,
0
] | [
346,
97
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.__init__ | (self, reg_config, logger=None, filter_internal=True) | Constructor
| Constructor
| def __init__(self, reg_config, logger=None, filter_internal=True):
"""Constructor
"""
self._logger = logger or logging.getLogger(__name__)
self._logger.debug('Creating register model with "{}"'.format(
reg_config))
self._reg_config_name = reg_config
self._... | [
"def",
"__init__",
"(",
"self",
",",
"reg_config",
",",
"logger",
"=",
"None",
",",
"filter_internal",
"=",
"True",
")",
":",
"self",
".",
"_logger",
"=",
"logger",
"or",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"self",
".",
"_logger",
".",
"... | [
51,
4
] | [
113,
51
] | python | en | ['en', 'en', 'pt'] | False |
Registers_Model._filter_internal | (self) | Omits all registers and/or bit groups marked as internal in the register definition from the model
| Omits all registers and/or bit groups marked as internal in the register definition from the model
| def _filter_internal(self):
"""Omits all registers and/or bit groups marked as internal in the register definition from the model
"""
temp_regs = {}
for r in self._regs:
if 'internal' in self._regs[r]:
if self._regs[r]['internal']:
# if the... | [
"def",
"_filter_internal",
"(",
"self",
")",
":",
"temp_regs",
"=",
"{",
"}",
"for",
"r",
"in",
"self",
".",
"_regs",
":",
"if",
"'internal'",
"in",
"self",
".",
"_regs",
"[",
"r",
"]",
":",
"if",
"self",
".",
"_regs",
"[",
"r",
"]",
"[",
"'inter... | [
115,
4
] | [
138,
30
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.set_read_driver | (self, driver_func, name=None) | Sets a read driver to the model. Typically used to make reads from the model read from a device over an interface.
:param driver_func: The driver function (callback) used to read from the interface
:type driver_func: function
:param name: Name of the driver. If not specified then it sets the de... | Sets a read driver to the model. Typically used to make reads from the model read from a device over an interface. | def set_read_driver(self, driver_func, name=None):
"""Sets a read driver to the model. Typically used to make reads from the model read from a device over an interface.
:param driver_func: The driver function (callback) used to read from the interface
:type driver_func: function
:param ... | [
"def",
"set_read_driver",
"(",
"self",
",",
"driver_func",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"or",
"'default'",
"self",
".",
"_read_driver",
"[",
"name",
"]",
"=",
"driver_func"
] | [
140,
4
] | [
149,
45
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.set_write_driver | (self, driver_func, name=None) | Sets a write driver to the model. Typically used to make writes to the model write to a device over an interface.
:param driver_func: The driver function (callback) used to write to the interface
:type driver_func: function
:param name: Name of the driver. If not specified then it sets the defa... | Sets a write driver to the model. Typically used to make writes to the model write to a device over an interface. | def set_write_driver(self, driver_func, name=None):
"""Sets a write driver to the model. Typically used to make writes to the model write to a device over an interface.
:param driver_func: The driver function (callback) used to write to the interface
:type driver_func: function
:param n... | [
"def",
"set_write_driver",
"(",
"self",
",",
"driver_func",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"or",
"'default'",
"self",
".",
"_write_driver",
"[",
"name",
"]",
"=",
"driver_func"
] | [
151,
4
] | [
160,
46
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.add_unused_bits_and_order | (self) | Adds 'unused' to any non-specified bit groups (only if there is already a bit group defined for that register)
| Adds 'unused' to any non-specified bit groups (only if there is already a bit group defined for that register)
| def add_unused_bits_and_order(self):
"""Adds 'unused' to any non-specified bit groups (only if there is already a bit group defined for that register)
"""
for r in self._regs:
if 'bit_groups' in self._regs[r]:
self.check_bitgroup(self._regs[r]['bit_groups'])
... | [
"def",
"add_unused_bits_and_order",
"(",
"self",
")",
":",
"for",
"r",
"in",
"self",
".",
"_regs",
":",
"if",
"'bit_groups'",
"in",
"self",
".",
"_regs",
"[",
"r",
"]",
":",
"self",
".",
"check_bitgroup",
"(",
"self",
".",
"_regs",
"[",
"r",
"]",
"["... | [
162,
4
] | [
218,
59
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.check_bitgroup | (self, bitgroup) | Checks correctness of bit groups specified in definition file
:param bitgroup: The single bit groups dict of a register
(containing the individual bit groups)
:type bitgroup: dict
| Checks correctness of bit groups specified in definition file | def check_bitgroup(self, bitgroup):
"""Checks correctness of bit groups specified in definition file
:param bitgroup: The single bit groups dict of a register
(containing the individual bit groups)
:type bitgroup: dict
"""
for bg in bitgroup:
... | [
"def",
"check_bitgroup",
"(",
"self",
",",
"bitgroup",
")",
":",
"for",
"bg",
"in",
"bitgroup",
":",
"if",
"'bit'",
"in",
"bg",
":",
"if",
"bg",
"[",
"'bit'",
"]",
">=",
"0",
"and",
"bg",
"[",
"'bit'",
"]",
"<",
"self",
".",
"_data_bits",
":",
"r... | [
220,
4
] | [
237,
74
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.__str__ | (self) | Returns string representation of a register model
| Returns string representation of a register model
| def __str__(self):
"""Returns string representation of a register model
"""
return self.get_reg_string() | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"self",
".",
"get_reg_string",
"(",
")"
] | [
239,
4
] | [
242,
36
] | python | en | ['en', 'da', 'en'] | True |
Registers_Model.as_markdown | (self, expand_bitgroups=False) | Exports the register model as a markdown table
:param expand_bitgroups: Whether to have a row for each individual
bitgroup or not
:type expand_bitgroups: bool, optional
| Exports the register model as a markdown table | def as_markdown(self, expand_bitgroups=False):
"""Exports the register model as a markdown table
:param expand_bitgroups: Whether to have a row for each individual
bitgroup or not
:type expand_bitgroups: bool, optional
"""
output_text = '| Addres... | [
"def",
"as_markdown",
"(",
"self",
",",
"expand_bitgroups",
"=",
"False",
")",
":",
"output_text",
"=",
"'| Address | Name | Description | POR |'",
"output_text",
"+=",
"'\\n| ------- | --------------- | ------------------------ | --- |'",
"hex_digits",
"=",... | [
244,
4
] | [
266,
26
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.reg_bits | (self, val, msb, lsb) | Returns a string representation of a bitgroup in a binary string form (i.e. a register). E.g. used for bit group PoR binary values in latex and html documentation tables.
:param val: the full register value (typically the PoR value)
:type val: int
:param msb: The MSB index of the bit group with... | Returns a string representation of a bitgroup in a binary string form (i.e. a register). E.g. used for bit group PoR binary values in latex and html documentation tables. | def reg_bits(self, val, msb, lsb):
"""Returns a string representation of a bitgroup in a binary string form (i.e. a register). E.g. used for bit group PoR binary values in latex and html documentation tables.
:param val: the full register value (typically the PoR value)
:type val: int
:... | [
"def",
"reg_bits",
"(",
"self",
",",
"val",
",",
"msb",
",",
"lsb",
")",
":",
"new_val",
"=",
"\"{0:0100b}\"",
".",
"format",
"(",
"val",
")",
"new_val",
"=",
"new_val",
"[",
":",
":",
"-",
"1",
"]",
"new_val",
"=",
"new_val",
"[",
"lsb",
":",
"m... | [
268,
4
] | [
288,
68
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model._get_highest_address | (self) | Returns the highest address specified in the register (note that the returned value does not have the base address included).
:return: The highest register address
:rtype: int
| Returns the highest address specified in the register (note that the returned value does not have the base address included).
:return: The highest register address
:rtype: int
| def _get_highest_address(self):
"""Returns the highest address specified in the register (note that the returned value does not have the base address included).
:return: The highest register address
:rtype: int
"""
highest = 0
for k in self._regs:
if... | [
"def",
"_get_highest_address",
"(",
"self",
")",
":",
"highest",
"=",
"0",
"for",
"k",
"in",
"self",
".",
"_regs",
":",
"if",
"k",
">",
"highest",
":",
"highest",
"=",
"k",
"return",
"(",
"k",
"*",
"self",
".",
"_reg_offset",
")"
] | [
290,
4
] | [
300,
35
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.as_code_constants | (self, reg_name) | Exports the register model information as code constants (defines) for generating the embedded code constants (register addresses and bit group masks
:param reg_name: The name of the overall register file in the software
defines
:type reg_name: str
:return: The text of ... | Exports the register model information as code constants (defines) for generating the embedded code constants (register addresses and bit group masks | def as_code_constants(self, reg_name):
"""Exports the register model information as code constants (defines) for generating the embedded code constants (register addresses and bit group masks
:param reg_name: The name of the overall register file in the software
defines
... | [
"def",
"as_code_constants",
"(",
"self",
",",
"reg_name",
")",
":",
"hex_digits",
"=",
"int",
"(",
"(",
"self",
".",
"_data_bits",
"/",
"4",
")",
"+",
"0.5",
")",
"lf",
"=",
"line_format",
".",
"Line_Format",
"(",
"reg_name",
",",
"60",
",",
"hex_digit... | [
302,
4
] | [
348,
26
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.as_latex | (
self,
detail_level=0,
reg_address=None,
show_offset_only=True) | Exports the register file to a latex table
:param detail_level: 0: registers only, 1: also show any bit groups
2: also show any value tables for individual bit
groups
:type detail_level: int
:param reg_address: If specified, the returned... | Exports the register file to a latex table | def as_latex(
self,
detail_level=0,
reg_address=None,
show_offset_only=True):
"""Exports the register file to a latex table
:param detail_level: 0: registers only, 1: also show any bit groups
2: also show a... | [
"def",
"as_latex",
"(",
"self",
",",
"detail_level",
"=",
"0",
",",
"reg_address",
"=",
"None",
",",
"show_offset_only",
"=",
"True",
")",
":",
"output_text",
"=",
"''",
"temp_base_addr",
"=",
"self",
".",
"_base_address",
"temp_base_addr",
"=",
"0",
"hex_di... | [
350,
4
] | [
423,
26
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.as_html | (self,
detail_level=0,
show_offset_only=True,
show_notes=False) | Exports the register file to a html table. If internal registers have not already been filtered, then these are styled differently to distinguish them
:param detail_level: 0: registers only, 1: also show any bit groups
2: also show any value tables for individual bit
... | Exports the register file to a html table. If internal registers have not already been filtered, then these are styled differently to distinguish them | def as_html(self,
detail_level=0,
show_offset_only=True,
show_notes=False):
"""Exports the register file to a html table. If internal registers have not already been filtered, then these are styled differently to distinguish them
:param detail_level: 0... | [
"def",
"as_html",
"(",
"self",
",",
"detail_level",
"=",
"0",
",",
"show_offset_only",
"=",
"True",
",",
"show_notes",
"=",
"False",
")",
":",
"output_text",
"=",
"''",
"temp_base_addr",
"=",
"self",
".",
"_base_address",
"if",
"show_offset_only",
":",
"temp... | [
425,
4
] | [
524,
26
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.get_value_table | (self, addr, bit_group) | Returns value table from a specific bit group of a specific register. E.g. used to get perf values for M0N0S2 chip
:param addr: The address of the register containing the relevant bit group (can be the name of the register or address [excluding offset]).
:type addr: str, int
:return: the value... | Returns value table from a specific bit group of a specific register. E.g. used to get perf values for M0N0S2 chip | def get_value_table(self, addr, bit_group):
"""Returns value table from a specific bit group of a specific register. E.g. used to get perf values for M0N0S2 chip
:param addr: The address of the register containing the relevant bit group (can be the name of the register or address [excluding offset]).
... | [
"def",
"get_value_table",
"(",
"self",
",",
"addr",
",",
"bit_group",
")",
":",
"return",
"self",
".",
"read_model",
"(",
"addr",
",",
"bit_group",
"=",
"bit_group",
")",
"[",
"'value_table'",
"]"
] | [
526,
4
] | [
534,
71
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.get_base_address | (self) | Returns the base address of the register file
:return: the base address
:rtype: int
| Returns the base address of the register file | def get_base_address(self):
"""Returns the base address of the register file
:return: the base address
:rtype: int
"""
return self._base_address | [
"def",
"get_base_address",
"(",
"self",
")",
":",
"return",
"self",
".",
"_base_address"
] | [
536,
4
] | [
542,
33
] | python | en | ['en', 'no', 'en'] | True |
Registers_Model.get_reg_string | (self, data_base='hex') | Returns a string representation of the register file
:param data_base: The number system to use to represent the values
(allowed values: "bin", "hex", "dec")
:type data_base: str, optional
| Returns a string representation of the register file | def get_reg_string(self, data_base='hex'):
"""Returns a string representation of the register file
:param data_base: The number system to use to represent the values
(allowed values: "bin", "hex", "dec")
:type data_base: str, optional
"""
result_str = "... | [
"def",
"get_reg_string",
"(",
"self",
",",
"data_base",
"=",
"'hex'",
")",
":",
"result_str",
"=",
"\"\"",
"if",
"(",
"self",
".",
"_base_address",
")",
":",
"result_str",
"+=",
"\"base address: 0x{:X}\\n\"",
".",
"format",
"(",
"self",
".",
"_base_address",
... | [
544,
4
] | [
562,
54
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.read_model | (self, addr, bit_group=None) | Reads a register or bit group value from the model (i.e. not using the read driver)
:param addr: The register address. Either the name of the register or
the numerical address (without base address added).
:type addr: int, str
:param bit_group: Name of the bit group to rea... | Reads a register or bit group value from the model (i.e. not using the read driver) | def read_model(self, addr, bit_group=None):
"""Reads a register or bit group value from the model (i.e. not using the read driver)
:param addr: The register address. Either the name of the register or
the numerical address (without base address added).
:type addr: int, str... | [
"def",
"read_model",
"(",
"self",
",",
"addr",
",",
"bit_group",
"=",
"None",
")",
":",
"num_addr",
"=",
"None",
"if",
"isinstance",
"(",
"addr",
",",
"(",
"int",
")",
")",
":",
"if",
"not",
"addr",
"in",
"self",
".",
"_regs",
":",
"raise",
"ValueE... | [
564,
4
] | [
627,
148
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.read_device | (self, address, driver_name='default') | Reads a device register directly via a read driver
:param address: The register absolute address (including the base address)
:type address: int
:param driver_name: The name of the read driver to use. If not
specified, uses the default read driver
:type drive... | Reads a device register directly via a read driver | def read_device(self, address, driver_name='default'):
"""Reads a device register directly via a read driver
:param address: The register absolute address (including the base address)
:type address: int
:param driver_name: The name of the read driver to use. If not
... | [
"def",
"read_device",
"(",
"self",
",",
"address",
",",
"driver_name",
"=",
"'default'",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Read device address: {:0X} using driver: {}\"",
".",
"format",
"(",
"address",
",",
"driver_name",
")",
")",
"return"... | [
629,
4
] | [
641,
54
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.write_device | (self, address, data, driver_name='default') | Writes a device register directly via a write driver
:param address: The register absolute address (including the base address)
:type address: int
:param data: Data to write
:type data: int
:param driver_name: The name of the write driver to use. If not
... | Writes a device register directly via a write driver | def write_device(self, address, data, driver_name='default'):
"""Writes a device register directly via a write driver
:param address: The register absolute address (including the base address)
:type address: int
:param data: Data to write
:type data: int
:param driver_na... | [
"def",
"write_device",
"(",
"self",
",",
"address",
",",
"data",
",",
"driver_name",
"=",
"'default'",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Write device address: {:0X}, data: {:0X}, using driver: {}\"",
".",
"format",
"(",
"address",
",",
"data"... | [
643,
4
] | [
658,
61
] | python | en | ['en', 'pt', 'en'] | True |
Registers_Model.select_bit_range | (self, val, msb, lsb) | Extracts bit group value from the full register value
:param val: The register value
:type val: int
:param msb: The bit group MSB index
:type msb: int
:param lsb: The bit group LSB index
:type lsb: int
:return: The value of the bit group
:rtype: int
... | Extracts bit group value from the full register value | def select_bit_range(self, val, msb, lsb):
"""Extracts bit group value from the full register value
:param val: The register value
:type val: int
:param msb: The bit group MSB index
:type msb: int
:param lsb: The bit group LSB index
:type lsb: int
:return... | [
"def",
"select_bit_range",
"(",
"self",
",",
"val",
",",
"msb",
",",
"lsb",
")",
":",
"if",
"val",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Value must be positive\"",
")",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Select bit range in: {0:b}'",
".",
... | [
660,
4
] | [
681,
22
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.write_set | (self,
addr,
data,
write_driver_name='default') | Writes to a register using the dedicated hardware "set" function (if available, some registers have a hardware-supported SET command if a specific offset is applied to the address). Updates the model.
:param addr: The name of the register to set or the numerical
relative address (excludi... | Writes to a register using the dedicated hardware "set" function (if available, some registers have a hardware-supported SET command if a specific offset is applied to the address). Updates the model. | def write_set(self,
addr,
data,
write_driver_name='default'):
""" Writes to a register using the dedicated hardware "set" function (if available, some registers have a hardware-supported SET command if a specific offset is applied to the address). Updates the model.
... | [
"def",
"write_set",
"(",
"self",
",",
"addr",
",",
"data",
",",
"write_driver_name",
"=",
"'default'",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Write set: A: {}, Data {:X}\"",
".",
"format",
"(",
"addr",
",",
"data",
")",
")",
"if",
"not",
... | [
683,
4
] | [
714,
46
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.write_clear | (self,
addr,
data,
write_driver_name='default') | Writes to a register using the dedicated hardware "clear" function (if available, some registers have a hardware-supported CLEAR command if a specific offset is applied to the address). Updates the model.
:param addr: The name of the register to clear or the numerical
relative address (e... | Writes to a register using the dedicated hardware "clear" function (if available, some registers have a hardware-supported CLEAR command if a specific offset is applied to the address). Updates the model. | def write_clear(self,
addr,
data,
write_driver_name='default'):
""" Writes to a register using the dedicated hardware "clear" function (if available, some registers have a hardware-supported CLEAR command if a specific offset is applied to the address). Updates the mode... | [
"def",
"write_clear",
"(",
"self",
",",
"addr",
",",
"data",
",",
"write_driver_name",
"=",
"'default'",
")",
":",
"if",
"not",
"self",
".",
"_clr_addr_offset",
":",
"raise",
"NotImplementedError",
"(",
"\"This register does not have clear function\"",
")",
"new_val... | [
716,
4
] | [
746,
46
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.write | (self,
addr,
data,
bit_group=None,
write_driver_name='default',
read_device=False,
read_driver_name='default') | Write to a register or bit group via a write driver and update the model. The typical way to write a value to a register.
:param addr: The name of the register or numerical relative address
(excluding offset) of the register to write to.
:type addr: str, int
:param data: ... | Write to a register or bit group via a write driver and update the model. The typical way to write a value to a register. | def write(self,
addr,
data,
bit_group=None,
write_driver_name='default',
read_device=False,
read_driver_name='default'):
"""Write to a register or bit group via a write driver and update the model. The typical way to write a val... | [
"def",
"write",
"(",
"self",
",",
"addr",
",",
"data",
",",
"bit_group",
"=",
"None",
",",
"write_driver_name",
"=",
"'default'",
",",
"read_device",
"=",
"False",
",",
"read_driver_name",
"=",
"'default'",
")",
":",
"model_rd_data",
"=",
"self",
".",
"rea... | [
748,
4
] | [
836,
19
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.read | (self,
addr,
bit_group=None,
driver_name='default') | Read from a register or bit group via a read driver. The typical way to read a value from a register.
:param addr: The name of the register or numerical relative address
(excluding offset) of the register to read from.
:type addr: str, int
:param bit_group: The name of th... | Read from a register or bit group via a read driver. The typical way to read a value from a register. | def read(self,
addr,
bit_group=None,
driver_name='default'):
"""Read from a register or bit group via a read driver. The typical way to read a value from a register.
:param addr: The name of the register or numerical relative address
(excludi... | [
"def",
"read",
"(",
"self",
",",
"addr",
",",
"bit_group",
"=",
"None",
",",
"driver_name",
"=",
"'default'",
")",
":",
"model_data",
"=",
"self",
".",
"read_model",
"(",
"addr",
",",
"bit_group",
")",
"if",
"not",
"self",
".",
"_read_driver",
"[",
"dr... | [
838,
4
] | [
877,
86
] | python | en | ['en', 'en', 'en'] | True |
Registers_Model.get_valid_addresses | (self) | Gets all defined addresses in the register file
:return: The defined (valid) integer relative addresses
:rtype: list
| Gets all defined addresses in the register file | def get_valid_addresses(self):
"""Gets all defined addresses in the register file
:return: The defined (valid) integer relative addresses
:rtype: list
"""
return list(self._regs.keys()) | [
"def",
"get_valid_addresses",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"_regs",
".",
"keys",
"(",
")",
")"
] | [
879,
4
] | [
885,
38
] | python | en | ['en', 'en', 'en'] | True |
DummyDrivers.__init__ | (self, logger=None) | Constructor method
| Constructor method
| def __init__(self, logger=None):
"""Constructor method
"""
self._logger = logger or logging.getLogger(__name__) | [
"def",
"__init__",
"(",
"self",
",",
"logger",
"=",
"None",
")",
":",
"self",
".",
"_logger",
"=",
"logger",
"or",
"logging",
".",
"getLogger",
"(",
"__name__",
")"
] | [
54,
4
] | [
57,
60
] | python | en | ['en', 'nl', 'en'] | False |
DummyDrivers.dummy_read | (self, address) | The "dummy" read function which does not read and just logs a warning.
:param address: The address to do a dummy read from
:type address: int
:return: Always returns 0
:rtype: int
| The "dummy" read function which does not read and just logs a warning. | def dummy_read(self, address):
"""The "dummy" read function which does not read and just logs a warning.
:param address: The address to do a dummy read from
:type address: int
:return: Always returns 0
:rtype: int
"""
self._logger.warn("DUMMY DEVICE READ: A: 0x{:... | [
"def",
"dummy_read",
"(",
"self",
",",
"address",
")",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"\"DUMMY DEVICE READ: A: 0x{:08X}\"",
".",
"format",
"(",
"address",
")",
")",
"return",
"0"
] | [
59,
4
] | [
68,
16
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.