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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
prod | (a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
initial=np._NoValue, where=np._NoValue) |
Return the product of array elements over a given axis.
Parameters
----------
a : array_like
Input data.
axis : None or int or tuple of ints, optional
Axis or axes along which a product is performed. The default,
axis=None, will calculate the product of all the elements in... |
Return the product of array elements over a given axis. | def prod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
initial=np._NoValue, where=np._NoValue):
"""
Return the product of array elements over a given axis.
Parameters
----------
a : array_like
Input data.
axis : None or int or tuple of ints, optional
Axis or... | [
"def",
"prod",
"(",
"a",
",",
"axis",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"out",
"=",
"None",
",",
"keepdims",
"=",
"np",
".",
"_NoValue",
",",
"initial",
"=",
"np",
".",
"_NoValue",
",",
"where",
"=",
"np",
".",
"_NoValue",
")",
":",
... | [
2792,
0
] | [
2910,
74
] | python | en | ['en', 'error', 'th'] | False |
cumprod | (a, axis=None, dtype=None, out=None) |
Return the cumulative product of elements along a given axis.
Parameters
----------
a : array_like
Input array.
axis : int, optional
Axis along which the cumulative product is computed. By default
the input is flattened.
dtype : dtype, optional
Type of the retu... |
Return the cumulative product of elements along a given axis. | def cumprod(a, axis=None, dtype=None, out=None):
"""
Return the cumulative product of elements along a given axis.
Parameters
----------
a : array_like
Input array.
axis : int, optional
Axis along which the cumulative product is computed. By default
the input is flatten... | [
"def",
"cumprod",
"(",
"a",
",",
"axis",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"return",
"_wrapfunc",
"(",
"a",
",",
"'cumprod'",
",",
"axis",
"=",
"axis",
",",
"dtype",
"=",
"dtype",
",",
"out",
"=",
"out",
... | [
2918,
0
] | [
2978,
67
] | python | en | ['en', 'error', 'th'] | False |
ndim | (a) |
Return the number of dimensions of an array.
Parameters
----------
a : array_like
Input array. If it is not already an ndarray, a conversion is
attempted.
Returns
-------
number_of_dimensions : int
The number of dimensions in `a`. Scalars are zero-dimensional.
... |
Return the number of dimensions of an array. | def ndim(a):
"""
Return the number of dimensions of an array.
Parameters
----------
a : array_like
Input array. If it is not already an ndarray, a conversion is
attempted.
Returns
-------
number_of_dimensions : int
The number of dimensions in `a`. Scalars are ... | [
"def",
"ndim",
"(",
"a",
")",
":",
"try",
":",
"return",
"a",
".",
"ndim",
"except",
"AttributeError",
":",
"return",
"asarray",
"(",
"a",
")",
".",
"ndim"
] | [
2986,
0
] | [
3020,
30
] | python | en | ['en', 'error', 'th'] | False |
size | (a, axis=None) |
Return the number of elements along a given axis.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which the elements are counted. By default, give
the total number of elements.
Returns
-------
element_count : int
Number... |
Return the number of elements along a given axis. | def size(a, axis=None):
"""
Return the number of elements along a given axis.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which the elements are counted. By default, give
the total number of elements.
Returns
-------
ele... | [
"def",
"size",
"(",
"a",
",",
"axis",
"=",
"None",
")",
":",
"if",
"axis",
"is",
"None",
":",
"try",
":",
"return",
"a",
".",
"size",
"except",
"AttributeError",
":",
"return",
"asarray",
"(",
"a",
")",
".",
"size",
"else",
":",
"try",
":",
"retu... | [
3028,
0
] | [
3071,
41
] | python | en | ['en', 'error', 'th'] | False |
GPIOInterrupt.close | (self) | This method must be called to release the pin for use by other processes | This method must be called to release the pin for use by other processes | def close(self):
"""This method must be called to release the pin for use by other processes"""
GPIO.cleanup(self.gpio_pin) | [
"def",
"close",
"(",
"self",
")",
":",
"GPIO",
".",
"cleanup",
"(",
"self",
".",
"gpio_pin",
")"
] | [
13,
4
] | [
15,
35
] | python | en | ['en', 'en', 'en'] | True |
GPIOInterrupt.wait_for | (self, timeout: int) |
Returns true if when the pin transitions from low to high.
Assumes some other process will reset the pin to low.
:param timeout: time to wait for the interrupt in milliseconds
:return: True if the interrupt happened. False if it timed out.
|
Returns true if when the pin transitions from low to high.
Assumes some other process will reset the pin to low.
:param timeout: time to wait for the interrupt in milliseconds
:return: True if the interrupt happened. False if it timed out.
| def wait_for(self, timeout: int) -> bool:
"""
Returns true if when the pin transitions from low to high.
Assumes some other process will reset the pin to low.
:param timeout: time to wait for the interrupt in milliseconds
:return: True if the interrupt happened. False if it ... | [
"def",
"wait_for",
"(",
"self",
",",
"timeout",
":",
"int",
")",
"->",
"bool",
":",
"ready",
"=",
"False",
"# Dividing sleep time by 300 instead of 30 double CPU load but cuts\r",
"# IMU timestamp variation from about 20% to less than 1%\r",
"sleep_time",
"=",
"(",
"timeout",... | [
17,
4
] | [
32,
20
] | python | en | ['en', 'ja', 'th'] | False |
SSIM.update | (self, preds: torch.Tensor, target: torch.Tensor) |
Update state with predictions and targets.
Args:
preds: Predictions from model
target: Ground truth values
|
Update state with predictions and targets. | def update(self, preds: torch.Tensor, target: torch.Tensor):
"""
Update state with predictions and targets.
Args:
preds: Predictions from model
target: Ground truth values
"""
preds, target = _ssim_update(preds, target)
self.y_pred.append(preds)
... | [
"def",
"update",
"(",
"self",
",",
"preds",
":",
"torch",
".",
"Tensor",
",",
"target",
":",
"torch",
".",
"Tensor",
")",
":",
"preds",
",",
"target",
"=",
"_ssim_update",
"(",
"preds",
",",
"target",
")",
"self",
".",
"y_pred",
".",
"append",
"(",
... | [
84,
4
] | [
94,
29
] | python | en | ['en', 'error', 'th'] | False |
SSIM.compute | (self) |
Computes explained variance over state.
|
Computes explained variance over state.
| def compute(self):
"""
Computes explained variance over state.
"""
preds = torch.cat(self.y_pred, dim=0)
target = torch.cat(self.y, dim=0)
return _ssim_compute(
preds, target, self.kernel_size, self.sigma, self.reduction, self.data_range, self.k1, self.k2
... | [
"def",
"compute",
"(",
"self",
")",
":",
"preds",
"=",
"torch",
".",
"cat",
"(",
"self",
".",
"y_pred",
",",
"dim",
"=",
"0",
")",
"target",
"=",
"torch",
".",
"cat",
"(",
"self",
".",
"y",
",",
"dim",
"=",
"0",
")",
"return",
"_ssim_compute",
... | [
96,
4
] | [
104,
9
] | python | en | ['en', 'error', 'th'] | False |
MeanSquaredError.update | (self, preds: torch.Tensor, target: torch.Tensor) |
Update state with predictions and targets.
Args:
preds: Predictions from model
target: Ground truth values
|
Update state with predictions and targets. | def update(self, preds: torch.Tensor, target: torch.Tensor):
"""
Update state with predictions and targets.
Args:
preds: Predictions from model
target: Ground truth values
"""
sum_squared_error, n_obs = _mean_squared_error_update(preds, target)
s... | [
"def",
"update",
"(",
"self",
",",
"preds",
":",
"torch",
".",
"Tensor",
",",
"target",
":",
"torch",
".",
"Tensor",
")",
":",
"sum_squared_error",
",",
"n_obs",
"=",
"_mean_squared_error_update",
"(",
"preds",
",",
"target",
")",
"self",
".",
"sum_squared... | [
69,
4
] | [
80,
27
] | python | en | ['en', 'error', 'th'] | False |
MeanSquaredError.compute | (self) |
Computes mean squared error over state.
|
Computes mean squared error over state.
| def compute(self):
"""
Computes mean squared error over state.
"""
return _mean_squared_error_compute(self.sum_squared_error, self.total) | [
"def",
"compute",
"(",
"self",
")",
":",
"return",
"_mean_squared_error_compute",
"(",
"self",
".",
"sum_squared_error",
",",
"self",
".",
"total",
")"
] | [
82,
4
] | [
86,
78
] | python | en | ['en', 'error', 'th'] | False |
import_nose | () | Import nose only when needed.
| Import nose only when needed.
| def import_nose():
""" Import nose only when needed.
"""
nose_is_good = True
minimum_nose_version = (1, 0, 0)
try:
import nose
except ImportError:
nose_is_good = False
else:
if nose.__versioninfo__ < minimum_nose_version:
nose_is_good = False
if not n... | [
"def",
"import_nose",
"(",
")",
":",
"nose_is_good",
"=",
"True",
"minimum_nose_version",
"=",
"(",
"1",
",",
"0",
",",
"0",
")",
"try",
":",
"import",
"nose",
"except",
"ImportError",
":",
"nose_is_good",
"=",
"False",
"else",
":",
"if",
"nose",
".",
... | [
58,
0
] | [
77,
15
] | python | en | ['en', 'en', 'en'] | True |
assert_ | (val, msg='') |
Assert that works in release mode.
Accepts callable msg to allow deferring evaluation until failure.
The Python built-in ``assert`` does not work when executing code in
optimized mode (the ``-O`` flag) - no byte-code is generated for it.
For documentation on usage, refer to the Python documentati... |
Assert that works in release mode.
Accepts callable msg to allow deferring evaluation until failure. | def assert_(val, msg=''):
"""
Assert that works in release mode.
Accepts callable msg to allow deferring evaluation until failure.
The Python built-in ``assert`` does not work when executing code in
optimized mode (the ``-O`` flag) - no byte-code is generated for it.
For documentation on usage... | [
"def",
"assert_",
"(",
"val",
",",
"msg",
"=",
"''",
")",
":",
"__tracebackhide__",
"=",
"True",
"# Hide traceback for py.test",
"if",
"not",
"val",
":",
"try",
":",
"smsg",
"=",
"msg",
"(",
")",
"except",
"TypeError",
":",
"smsg",
"=",
"msg",
"raise",
... | [
80,
0
] | [
97,
34
] | python | en | ['en', 'error', 'th'] | False |
gisnan | (x) | like isnan, but always raise an error if type not supported instead of
returning a TypeError object.
Notes
-----
isnan and other ufunc sometimes return a NotImplementedType object instead
of raising any exception. This function is a wrapper to make sure an
exception is always raised.
This ... | like isnan, but always raise an error if type not supported instead of
returning a TypeError object. | def gisnan(x):
"""like isnan, but always raise an error if type not supported instead of
returning a TypeError object.
Notes
-----
isnan and other ufunc sometimes return a NotImplementedType object instead
of raising any exception. This function is a wrapper to make sure an
exception is alw... | [
"def",
"gisnan",
"(",
"x",
")",
":",
"from",
"numpy",
".",
"core",
"import",
"isnan",
"st",
"=",
"isnan",
"(",
"x",
")",
"if",
"isinstance",
"(",
"st",
",",
"type",
"(",
"NotImplemented",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"isnan not supported... | [
100,
0
] | [
115,
13
] | python | en | ['en', 'en', 'en'] | True |
gisfinite | (x) | like isfinite, but always raise an error if type not supported instead of
returning a TypeError object.
Notes
-----
isfinite and other ufunc sometimes return a NotImplementedType object instead
of raising any exception. This function is a wrapper to make sure an
exception is always raised.
... | like isfinite, but always raise an error if type not supported instead of
returning a TypeError object. | def gisfinite(x):
"""like isfinite, but always raise an error if type not supported instead of
returning a TypeError object.
Notes
-----
isfinite and other ufunc sometimes return a NotImplementedType object instead
of raising any exception. This function is a wrapper to make sure an
excepti... | [
"def",
"gisfinite",
"(",
"x",
")",
":",
"from",
"numpy",
".",
"core",
"import",
"isfinite",
",",
"errstate",
"with",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
")",
":",
"st",
"=",
"isfinite",
"(",
"x",
")",
"if",
"isinstance",
"(",
"st",
",",
"typ... | [
118,
0
] | [
134,
13
] | python | en | ['en', 'en', 'en'] | True |
gisinf | (x) | like isinf, but always raise an error if type not supported instead of
returning a TypeError object.
Notes
-----
isinf and other ufunc sometimes return a NotImplementedType object instead
of raising any exception. This function is a wrapper to make sure an
exception is always raised.
This ... | like isinf, but always raise an error if type not supported instead of
returning a TypeError object. | def gisinf(x):
"""like isinf, but always raise an error if type not supported instead of
returning a TypeError object.
Notes
-----
isinf and other ufunc sometimes return a NotImplementedType object instead
of raising any exception. This function is a wrapper to make sure an
exception is alw... | [
"def",
"gisinf",
"(",
"x",
")",
":",
"from",
"numpy",
".",
"core",
"import",
"isinf",
",",
"errstate",
"with",
"errstate",
"(",
"invalid",
"=",
"'ignore'",
")",
":",
"st",
"=",
"isinf",
"(",
"x",
")",
"if",
"isinstance",
"(",
"st",
",",
"type",
"("... | [
137,
0
] | [
153,
13
] | python | en | ['en', 'en', 'en'] | True |
rand | (*args) | Returns an array of random numbers with the given shape.
This only uses the standard library, so it is useful for testing purposes.
| Returns an array of random numbers with the given shape. | def rand(*args):
"""Returns an array of random numbers with the given shape.
This only uses the standard library, so it is useful for testing purposes.
"""
import random
from numpy.core import zeros, float64
results = zeros(args, float64)
f = results.flat
for i in range(len(f)):
... | [
"def",
"rand",
"(",
"*",
"args",
")",
":",
"import",
"random",
"from",
"numpy",
".",
"core",
"import",
"zeros",
",",
"float64",
"results",
"=",
"zeros",
"(",
"args",
",",
"float64",
")",
"f",
"=",
"results",
".",
"flat",
"for",
"i",
"in",
"range",
... | [
158,
0
] | [
169,
18
] | python | en | ['en', 'en', 'en'] | True |
assert_equal | (actual, desired, err_msg='', verbose=True) |
Raises an AssertionError if two objects are not equal.
Given two objects (scalars, lists, tuples, dictionaries or numpy arrays),
check that all elements of these objects are equal. An exception is raised
at the first conflicting values.
This function handles NaN comparisons as if NaN was a "norma... |
Raises an AssertionError if two objects are not equal. | def assert_equal(actual, desired, err_msg='', verbose=True):
"""
Raises an AssertionError if two objects are not equal.
Given two objects (scalars, lists, tuples, dictionaries or numpy arrays),
check that all elements of these objects are equal. An exception is raised
at the first conflicting value... | [
"def",
"assert_equal",
"(",
"actual",
",",
"desired",
",",
"err_msg",
"=",
"''",
",",
"verbose",
"=",
"True",
")",
":",
"__tracebackhide__",
"=",
"True",
"# Hide traceback for py.test",
"if",
"isinstance",
"(",
"desired",
",",
"dict",
")",
":",
"if",
"not",
... | [
295,
0
] | [
433,
17
] | python | en | ['en', 'error', 'th'] | False |
print_assert_equal | (test_string, actual, desired) |
Test if two objects are equal, and print an error message if test fails.
The test is performed with ``actual == desired``.
Parameters
----------
test_string : str
The message supplied to AssertionError.
actual : object
The object to test for equality against `desired`.
des... |
Test if two objects are equal, and print an error message if test fails. | def print_assert_equal(test_string, actual, desired):
"""
Test if two objects are equal, and print an error message if test fails.
The test is performed with ``actual == desired``.
Parameters
----------
test_string : str
The message supplied to AssertionError.
actual : object
... | [
"def",
"print_assert_equal",
"(",
"test_string",
",",
"actual",
",",
"desired",
")",
":",
"__tracebackhide__",
"=",
"True",
"# Hide traceback for py.test",
"import",
"pprint",
"if",
"not",
"(",
"actual",
"==",
"desired",
")",
":",
"msg",
"=",
"StringIO",
"(",
... | [
436,
0
] | [
474,
44
] | python | en | ['en', 'error', 'th'] | False |
assert_almost_equal | (actual,desired,decimal=7,err_msg='',verbose=True) |
Raises an AssertionError if two items are not equal up to desired
precision.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
compari... |
Raises an AssertionError if two items are not equal up to desired
precision. | def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=True):
"""
Raises an AssertionError if two items are not equal up to desired
precision.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
... | [
"def",
"assert_almost_equal",
"(",
"actual",
",",
"desired",
",",
"decimal",
"=",
"7",
",",
"err_msg",
"=",
"''",
",",
"verbose",
"=",
"True",
")",
":",
"__tracebackhide__",
"=",
"True",
"# Hide traceback for py.test",
"from",
"numpy",
".",
"core",
"import",
... | [
477,
0
] | [
599,
46
] | python | en | ['en', 'error', 'th'] | False |
assert_approx_equal | (actual,desired,significant=7,err_msg='',verbose=True) |
Raises an AssertionError if two items are not equal up to significant
digits.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
compar... |
Raises an AssertionError if two items are not equal up to significant
digits. | def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True):
"""
Raises an AssertionError if two items are not equal up to significant
digits.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
... | [
"def",
"assert_approx_equal",
"(",
"actual",
",",
"desired",
",",
"significant",
"=",
"7",
",",
"err_msg",
"=",
"''",
",",
"verbose",
"=",
"True",
")",
":",
"__tracebackhide__",
"=",
"True",
"# Hide traceback for py.test",
"import",
"numpy",
"as",
"np",
"(",
... | [
602,
0
] | [
698,
33
] | python | en | ['en', 'error', 'th'] | False |
assert_array_equal | (x, y, err_msg='', verbose=True) |
Raises an AssertionError if two array_like objects are not equal.
Given two array_like objects, check that the shape is equal and all
elements of these objects are equal. An exception is raised at
shape mismatch or conflicting values. In contrast to the standard usage
in numpy, NaNs are compared l... |
Raises an AssertionError if two array_like objects are not equal. | def assert_array_equal(x, y, err_msg='', verbose=True):
"""
Raises an AssertionError if two array_like objects are not equal.
Given two array_like objects, check that the shape is equal and all
elements of these objects are equal. An exception is raised at
shape mismatch or conflicting values. In c... | [
"def",
"assert_array_equal",
"(",
"x",
",",
"y",
",",
"err_msg",
"=",
"''",
",",
"verbose",
"=",
"True",
")",
":",
"__tracebackhide__",
"=",
"True",
"# Hide traceback for py.test",
"assert_array_compare",
"(",
"operator",
".",
"__eq__",
",",
"x",
",",
"y",
"... | [
851,
0
] | [
917,
72
] | python | en | ['en', 'error', 'th'] | False |
assert_array_almost_equal | (x, y, decimal=6, err_msg='', verbose=True) |
Raises an AssertionError if two objects are not equal up to desired
precision.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
compa... |
Raises an AssertionError if two objects are not equal up to desired
precision. | def assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True):
"""
Raises an AssertionError if two objects are not equal up to desired
precision.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
... | [
"def",
"assert_array_almost_equal",
"(",
"x",
",",
"y",
",",
"decimal",
"=",
"6",
",",
"err_msg",
"=",
"''",
",",
"verbose",
"=",
"True",
")",
":",
"__tracebackhide__",
"=",
"True",
"# Hide traceback for py.test",
"from",
"numpy",
".",
"core",
"import",
"num... | [
920,
0
] | [
1028,
31
] | python | en | ['en', 'error', 'th'] | False |
assert_array_less | (x, y, err_msg='', verbose=True) |
Raises an AssertionError if two array_like objects are not ordered by less
than.
Given two array_like objects, check that the shape is equal and all
elements of the first object are strictly smaller than those of the
second object. An exception is raised at shape mismatch or incorrectly
ordere... |
Raises an AssertionError if two array_like objects are not ordered by less
than. | def assert_array_less(x, y, err_msg='', verbose=True):
"""
Raises an AssertionError if two array_like objects are not ordered by less
than.
Given two array_like objects, check that the shape is equal and all
elements of the first object are strictly smaller than those of the
second object. An e... | [
"def",
"assert_array_less",
"(",
"x",
",",
"y",
",",
"err_msg",
"=",
"''",
",",
"verbose",
"=",
"True",
")",
":",
"__tracebackhide__",
"=",
"True",
"# Hide traceback for py.test",
"assert_array_compare",
"(",
"operator",
".",
"__lt__",
",",
"x",
",",
"y",
",... | [
1031,
0
] | [
1108,
41
] | python | en | ['en', 'error', 'th'] | False |
assert_string_equal | (actual, desired) |
Test if two strings are equal.
If the given strings are equal, `assert_string_equal` does nothing.
If they are not equal, an AssertionError is raised, and the diff
between the strings is shown.
Parameters
----------
actual : str
The string to test for equality against the expected... |
Test if two strings are equal. | def assert_string_equal(actual, desired):
"""
Test if two strings are equal.
If the given strings are equal, `assert_string_equal` does nothing.
If they are not equal, an AssertionError is raised, and the diff
between the strings is shown.
Parameters
----------
actual : str
The... | [
"def",
"assert_string_equal",
"(",
"actual",
",",
"desired",
")",
":",
"# delay import of difflib to reduce startup time",
"__tracebackhide__",
"=",
"True",
"# Hide traceback for py.test",
"import",
"difflib",
"if",
"not",
"isinstance",
"(",
"actual",
",",
"str",
")",
"... | [
1115,
0
] | [
1182,
33
] | python | en | ['en', 'error', 'th'] | False |
rundocs | (filename=None, raise_on_error=True) |
Run doctests found in the given file.
By default `rundocs` raises an AssertionError on failure.
Parameters
----------
filename : str
The path to the file for which the doctests are run.
raise_on_error : bool
Whether to raise an AssertionError when a doctest fails. Default is
... |
Run doctests found in the given file. | def rundocs(filename=None, raise_on_error=True):
"""
Run doctests found in the given file.
By default `rundocs` raises an AssertionError on failure.
Parameters
----------
filename : str
The path to the file for which the doctests are run.
raise_on_error : bool
Whether to ra... | [
"def",
"rundocs",
"(",
"filename",
"=",
"None",
",",
"raise_on_error",
"=",
"True",
")",
":",
"from",
"numpy",
".",
"compat",
"import",
"npy_load_module",
"import",
"doctest",
"if",
"filename",
"is",
"None",
":",
"f",
"=",
"sys",
".",
"_getframe",
"(",
"... | [
1185,
0
] | [
1228,
74
] | python | en | ['en', 'error', 'th'] | False |
raises | (*args) | Decorator to check for raised exceptions.
The decorated test function must raise one of the passed exceptions to
pass. If you want to test many assertions about exceptions in a single
test, you may want to use `assert_raises` instead.
.. warning::
This decorator is nose specific, do not use it... | Decorator to check for raised exceptions. | def raises(*args):
"""Decorator to check for raised exceptions.
The decorated test function must raise one of the passed exceptions to
pass. If you want to test many assertions about exceptions in a single
test, you may want to use `assert_raises` instead.
.. warning::
This decorator is no... | [
"def",
"raises",
"(",
"*",
"args",
")",
":",
"nose",
"=",
"import_nose",
"(",
")",
"return",
"nose",
".",
"tools",
".",
"raises",
"(",
"*",
"args",
")"
] | [
1231,
0
] | [
1266,
35
] | python | en | ['en', 'en', 'en'] | True |
assert_raises | (*args, **kwargs) |
assert_raises(exception_class, callable, *args, **kwargs)
assert_raises(exception_class)
Fail unless an exception of class exception_class is thrown
by callable when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
thrown, it will not be caught, and... |
assert_raises(exception_class, callable, *args, **kwargs)
assert_raises(exception_class) | def assert_raises(*args, **kwargs):
"""
assert_raises(exception_class, callable, *args, **kwargs)
assert_raises(exception_class)
Fail unless an exception of class exception_class is thrown
by callable when invoked with arguments args and keyword
arguments kwargs. If a different type of exceptio... | [
"def",
"assert_raises",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"__tracebackhide__",
"=",
"True",
"# Hide traceback for py.test",
"return",
"_d",
".",
"assertRaises",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
1280,
0
] | [
1306,
42
] | python | en | ['en', 'error', 'th'] | False |
assert_raises_regex | (exception_class, expected_regexp, *args, **kwargs) |
assert_raises_regex(exception_class, expected_regexp, callable, *args,
**kwargs)
assert_raises_regex(exception_class, expected_regexp)
Fail unless an exception of class exception_class and with message that
matches expected_regexp is thrown by callable when invoked with argumen... |
assert_raises_regex(exception_class, expected_regexp, callable, *args,
**kwargs)
assert_raises_regex(exception_class, expected_regexp) | def assert_raises_regex(exception_class, expected_regexp, *args, **kwargs):
"""
assert_raises_regex(exception_class, expected_regexp, callable, *args,
**kwargs)
assert_raises_regex(exception_class, expected_regexp)
Fail unless an exception of class exception_class and with messa... | [
"def",
"assert_raises_regex",
"(",
"exception_class",
",",
"expected_regexp",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"__tracebackhide__",
"=",
"True",
"# Hide traceback for py.test",
"if",
"sys",
".",
"version_info",
".",
"major",
">=",
"3",
":",
... | [
1309,
0
] | [
1337,
70
] | python | en | ['en', 'error', 'th'] | False |
decorate_methods | (cls, decorator, testmatch=None) |
Apply a decorator to all methods in a class matching a regular expression.
The given decorator is applied to all public methods of `cls` that are
matched by the regular expression `testmatch`
(``testmatch.search(methodname)``). Methods that are private, i.e. start
with an underscore, are ignored.
... |
Apply a decorator to all methods in a class matching a regular expression. | def decorate_methods(cls, decorator, testmatch=None):
"""
Apply a decorator to all methods in a class matching a regular expression.
The given decorator is applied to all public methods of `cls` that are
matched by the regular expression `testmatch`
(``testmatch.search(methodname)``). Methods that ... | [
"def",
"decorate_methods",
"(",
"cls",
",",
"decorator",
",",
"testmatch",
"=",
"None",
")",
":",
"if",
"testmatch",
"is",
"None",
":",
"testmatch",
"=",
"re",
".",
"compile",
"(",
"r'(?:^|[\\\\b_\\\\.%s-])[Tt]est'",
"%",
"os",
".",
"sep",
")",
"else",
":"... | [
1340,
0
] | [
1384,
10
] | python | en | ['en', 'error', 'th'] | False |
measure | (code_str, times=1, label=None) |
Return elapsed time for executing code in the namespace of the caller.
The supplied code string is compiled with the Python builtin ``compile``.
The precision of the timing is 10 milli-seconds. If the code will execute
fast on this timescale, it can be executed many times to get reasonable
timing ... |
Return elapsed time for executing code in the namespace of the caller. | def measure(code_str, times=1, label=None):
"""
Return elapsed time for executing code in the namespace of the caller.
The supplied code string is compiled with the Python builtin ``compile``.
The precision of the timing is 10 milli-seconds. If the code will execute
fast on this timescale, it can b... | [
"def",
"measure",
"(",
"code_str",
",",
"times",
"=",
"1",
",",
"label",
"=",
"None",
")",
":",
"frame",
"=",
"sys",
".",
"_getframe",
"(",
"1",
")",
"locs",
",",
"globs",
"=",
"frame",
".",
"f_locals",
",",
"frame",
".",
"f_globals",
"code",
"=",
... | [
1387,
0
] | [
1432,
23
] | python | en | ['en', 'error', 'th'] | False |
_assert_valid_refcount | (op) |
Check that ufuncs don't mishandle refcount of object `1`.
Used in a few regression tests.
|
Check that ufuncs don't mishandle refcount of object `1`.
Used in a few regression tests.
| def _assert_valid_refcount(op):
"""
Check that ufuncs don't mishandle refcount of object `1`.
Used in a few regression tests.
"""
if not HAS_REFCOUNT:
return True
import numpy as np, gc
b = np.arange(100*100).reshape(100, 100)
c = b
i = 1
gc.disable()
try:
r... | [
"def",
"_assert_valid_refcount",
"(",
"op",
")",
":",
"if",
"not",
"HAS_REFCOUNT",
":",
"return",
"True",
"import",
"numpy",
"as",
"np",
",",
"gc",
"b",
"=",
"np",
".",
"arange",
"(",
"100",
"*",
"100",
")",
".",
"reshape",
"(",
"100",
",",
"100",
... | [
1435,
0
] | [
1456,
9
] | python | en | ['en', 'error', 'th'] | False |
assert_allclose | (actual, desired, rtol=1e-7, atol=0, equal_nan=True,
err_msg='', verbose=True) |
Raises an AssertionError if two objects are not equal up to desired
tolerance.
The test is equivalent to ``allclose(actual, desired, rtol, atol)`` (note
that ``allclose`` has different default values). It compares the difference
between `actual` and `desired` to ``atol + rtol * abs(desired)``.
... |
Raises an AssertionError if two objects are not equal up to desired
tolerance. | def assert_allclose(actual, desired, rtol=1e-7, atol=0, equal_nan=True,
err_msg='', verbose=True):
"""
Raises an AssertionError if two objects are not equal up to desired
tolerance.
The test is equivalent to ``allclose(actual, desired, rtol, atol)`` (note
that ``allclose`` has d... | [
"def",
"assert_allclose",
"(",
"actual",
",",
"desired",
",",
"rtol",
"=",
"1e-7",
",",
"atol",
"=",
"0",
",",
"equal_nan",
"=",
"True",
",",
"err_msg",
"=",
"''",
",",
"verbose",
"=",
"True",
")",
":",
"__tracebackhide__",
"=",
"True",
"# Hide traceback... | [
1459,
0
] | [
1514,
77
] | python | en | ['en', 'error', 'th'] | False |
assert_array_almost_equal_nulp | (x, y, nulp=1) |
Compare two arrays relatively to their spacing.
This is a relatively robust method to compare two arrays whose amplitude
is variable.
Parameters
----------
x, y : array_like
Input arrays.
nulp : int, optional
The maximum number of unit in the last place for tolerance (see ... |
Compare two arrays relatively to their spacing. | def assert_array_almost_equal_nulp(x, y, nulp=1):
"""
Compare two arrays relatively to their spacing.
This is a relatively robust method to compare two arrays whose amplitude
is variable.
Parameters
----------
x, y : array_like
Input arrays.
nulp : int, optional
The max... | [
"def",
"assert_array_almost_equal_nulp",
"(",
"x",
",",
"y",
",",
"nulp",
"=",
"1",
")",
":",
"__tracebackhide__",
"=",
"True",
"# Hide traceback for py.test",
"import",
"numpy",
"as",
"np",
"ax",
"=",
"np",
".",
"abs",
"(",
"x",
")",
"ay",
"=",
"np",
".... | [
1517,
0
] | [
1577,
33
] | python | en | ['en', 'error', 'th'] | False |
assert_array_max_ulp | (a, b, maxulp=1, dtype=None) |
Check that all items of arrays differ in at most N Units in the Last Place.
Parameters
----------
a, b : array_like
Input arrays to be compared.
maxulp : int, optional
The maximum number of units in the last place that elements of `a` and
`b` can differ. Default is 1.
d... |
Check that all items of arrays differ in at most N Units in the Last Place. | def assert_array_max_ulp(a, b, maxulp=1, dtype=None):
"""
Check that all items of arrays differ in at most N Units in the Last Place.
Parameters
----------
a, b : array_like
Input arrays to be compared.
maxulp : int, optional
The maximum number of units in the last place that el... | [
"def",
"assert_array_max_ulp",
"(",
"a",
",",
"b",
",",
"maxulp",
"=",
"1",
",",
"dtype",
"=",
"None",
")",
":",
"__tracebackhide__",
"=",
"True",
"# Hide traceback for py.test",
"import",
"numpy",
"as",
"np",
"ret",
"=",
"nulp_diff",
"(",
"a",
",",
"b",
... | [
1580,
0
] | [
1622,
14
] | python | en | ['en', 'error', 'th'] | False |
nulp_diff | (x, y, dtype=None) | For each item in x and y, return the number of representable floating
points between them.
Parameters
----------
x : array_like
first input array
y : array_like
second input array
dtype : dtype, optional
Data-type to convert `x` and `y` to if given. Default is None.
... | For each item in x and y, return the number of representable floating
points between them. | def nulp_diff(x, y, dtype=None):
"""For each item in x and y, return the number of representable floating
points between them.
Parameters
----------
x : array_like
first input array
y : array_like
second input array
dtype : dtype, optional
Data-type to convert `x` an... | [
"def",
"nulp_diff",
"(",
"x",
",",
"y",
",",
"dtype",
"=",
"None",
")",
":",
"import",
"numpy",
"as",
"np",
"if",
"dtype",
":",
"x",
"=",
"np",
".",
"array",
"(",
"x",
",",
"dtype",
"=",
"dtype",
")",
"y",
"=",
"np",
".",
"array",
"(",
"y",
... | [
1625,
0
] | [
1676,
27
] | python | en | ['en', 'en', 'en'] | True |
integer_repr | (x) | Return the signed-magnitude interpretation of the binary representation of
x. | Return the signed-magnitude interpretation of the binary representation of
x. | def integer_repr(x):
"""Return the signed-magnitude interpretation of the binary representation of
x."""
import numpy as np
if x.dtype == np.float16:
return _integer_repr(x, np.int16, np.int16(-2**15))
elif x.dtype == np.float32:
return _integer_repr(x, np.int32, np.int32(-2**31))
... | [
"def",
"integer_repr",
"(",
"x",
")",
":",
"import",
"numpy",
"as",
"np",
"if",
"x",
".",
"dtype",
"==",
"np",
".",
"float16",
":",
"return",
"_integer_repr",
"(",
"x",
",",
"np",
".",
"int16",
",",
"np",
".",
"int16",
"(",
"-",
"2",
"**",
"15",
... | [
1694,
0
] | [
1705,
58
] | python | en | ['en', 'it', 'en'] | True |
assert_warns | (warning_class, *args, **kwargs) |
Fail unless the given callable throws the specified warning.
A warning of class warning_class should be thrown by the callable when
invoked with arguments args and keyword arguments kwargs.
If a different type of warning is thrown, it will not be caught.
If called with all arguments other than th... |
Fail unless the given callable throws the specified warning. | def assert_warns(warning_class, *args, **kwargs):
"""
Fail unless the given callable throws the specified warning.
A warning of class warning_class should be thrown by the callable when
invoked with arguments args and keyword arguments kwargs.
If a different type of warning is thrown, it will not b... | [
"def",
"assert_warns",
"(",
"warning_class",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
":",
"return",
"_assert_warns_context",
"(",
"warning_class",
")",
"func",
"=",
"args",
"[",
"0",
"]",
"args",
"=",
"args",
"[",
"1",... | [
1719,
0
] | [
1759,
36
] | python | en | ['en', 'error', 'th'] | False |
assert_no_warnings | (*args, **kwargs) |
Fail if the given callable produces any warnings.
If called with all arguments omitted, may be used as a context manager:
with assert_no_warnings():
do_something()
The ability to be used as a context manager is new in NumPy v1.11.0.
.. versionadded:: 1.7.0
Parameters
--... |
Fail if the given callable produces any warnings. | def assert_no_warnings(*args, **kwargs):
"""
Fail if the given callable produces any warnings.
If called with all arguments omitted, may be used as a context manager:
with assert_no_warnings():
do_something()
The ability to be used as a context manager is new in NumPy v1.11.0.
... | [
"def",
"assert_no_warnings",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
":",
"return",
"_assert_no_warnings_context",
"(",
")",
"func",
"=",
"args",
"[",
"0",
"]",
"args",
"=",
"args",
"[",
"1",
":",
"]",
"with",
"_asse... | [
1773,
0
] | [
1806,
36
] | python | en | ['en', 'error', 'th'] | False |
_gen_alignment_data | (dtype=float32, type='binary', max_size=24) |
generator producing data with different alignment and offsets
to test simd vectorization
Parameters
----------
dtype : dtype
data type to produce
type : string
'unary': create data for unary operations, creates one input
and output array
'binary': creat... |
generator producing data with different alignment and offsets
to test simd vectorization | def _gen_alignment_data(dtype=float32, type='binary', max_size=24):
"""
generator producing data with different alignment and offsets
to test simd vectorization
Parameters
----------
dtype : dtype
data type to produce
type : string
'unary': create data for unary operations, ... | [
"def",
"_gen_alignment_data",
"(",
"dtype",
"=",
"float32",
",",
"type",
"=",
"'binary'",
",",
"max_size",
"=",
"24",
")",
":",
"ufmt",
"=",
"'unary offset=(%d, %d), size=%d, dtype=%r, %s'",
"bfmt",
"=",
"'binary offset=(%d, %d, %d), size=%d, dtype=%r, %s'",
"for",
"o",... | [
1809,
0
] | [
1875,
58
] | python | en | ['en', 'error', 'th'] | False |
tempdir | (*args, **kwargs) | Context manager to provide a temporary test folder.
All arguments are passed as this to the underlying tempfile.mkdtemp
function.
| Context manager to provide a temporary test folder. | def tempdir(*args, **kwargs):
"""Context manager to provide a temporary test folder.
All arguments are passed as this to the underlying tempfile.mkdtemp
function.
"""
tmpdir = mkdtemp(*args, **kwargs)
try:
yield tmpdir
finally:
shutil.rmtree(tmpdir) | [
"def",
"tempdir",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tmpdir",
"=",
"mkdtemp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"yield",
"tmpdir",
"finally",
":",
"shutil",
".",
"rmtree",
"(",
"tmpdir",
")"
] | [
1884,
0
] | [
1895,
29
] | python | en | ['en', 'en', 'en'] | True |
temppath | (*args, **kwargs) | Context manager for temporary files.
Context manager that returns the path to a closed temporary file. Its
parameters are the same as for tempfile.mkstemp and are passed directly
to that function. The underlying file is removed when the context is
exited, so it should be closed at that time.
Windo... | Context manager for temporary files. | def temppath(*args, **kwargs):
"""Context manager for temporary files.
Context manager that returns the path to a closed temporary file. Its
parameters are the same as for tempfile.mkstemp and are passed directly
to that function. The underlying file is removed when the context is
exited, so it sho... | [
"def",
"temppath",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"fd",
",",
"path",
"=",
"mkstemp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"os",
".",
"close",
"(",
"fd",
")",
"try",
":",
"yield",
"path",
"finally",
":",
"os",
... | [
1899,
0
] | [
1917,
23
] | python | en | ['en', 'en', 'en'] | True |
assert_no_gc_cycles | (*args, **kwargs) |
Fail if the given callable produces any reference cycles.
If called with all arguments omitted, may be used as a context manager:
with assert_no_gc_cycles():
do_something()
.. versionadded:: 1.15.0
Parameters
----------
func : callable
The callable to test.
\... |
Fail if the given callable produces any reference cycles. | def assert_no_gc_cycles(*args, **kwargs):
"""
Fail if the given callable produces any reference cycles.
If called with all arguments omitted, may be used as a context manager:
with assert_no_gc_cycles():
do_something()
.. versionadded:: 1.15.0
Parameters
----------
fu... | [
"def",
"assert_no_gc_cycles",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
":",
"return",
"_assert_no_gc_cycles_context",
"(",
")",
"func",
"=",
"args",
"[",
"0",
"]",
"args",
"=",
"args",
"[",
"1",
":",
"]",
"with",
"_as... | [
2317,
0
] | [
2349,
29
] | python | en | ['en', 'error', 'th'] | False |
break_cycles | () |
Break reference cycles by calling gc.collect
Objects can call other objects' methods (for instance, another object's
__del__) inside their own __del__. On PyPy, the interpreter only runs
between calls to gc.collect, so multiple calls are needed to completely
release all cycles.
|
Break reference cycles by calling gc.collect
Objects can call other objects' methods (for instance, another object's
__del__) inside their own __del__. On PyPy, the interpreter only runs
between calls to gc.collect, so multiple calls are needed to completely
release all cycles.
| def break_cycles():
"""
Break reference cycles by calling gc.collect
Objects can call other objects' methods (for instance, another object's
__del__) inside their own __del__. On PyPy, the interpreter only runs
between calls to gc.collect, so multiple calls are needed to completely
release all ... | [
"def",
"break_cycles",
"(",
")",
":",
"gc",
".",
"collect",
"(",
")",
"if",
"IS_PYPY",
":",
"# interpreter runs now, to call deleted objects' __del__ methods",
"gc",
".",
"collect",
"(",
")",
"# one more, just to make sure",
"gc",
".",
"collect",
"(",
")"
] | [
2351,
0
] | [
2365,
20
] | python | en | ['en', 'error', 'th'] | False |
suppress_warnings.filter | (self, category=Warning, message="", module=None) |
Add a new suppressing filter or apply it if the state is entered.
Parameters
----------
category : class, optional
Warning class to filter
message : string, optional
Regular expression matching the warning message.
module : module, optional
... |
Add a new suppressing filter or apply it if the state is entered. | def filter(self, category=Warning, message="", module=None):
"""
Add a new suppressing filter or apply it if the state is entered.
Parameters
----------
category : class, optional
Warning class to filter
message : string, optional
Regular expressi... | [
"def",
"filter",
"(",
"self",
",",
"category",
"=",
"Warning",
",",
"message",
"=",
"\"\"",
",",
"module",
"=",
"None",
")",
":",
"self",
".",
"_filter",
"(",
"category",
"=",
"category",
",",
"message",
"=",
"message",
",",
"module",
"=",
"module",
... | [
2107,
4
] | [
2128,
34
] | python | en | ['en', 'error', 'th'] | False |
suppress_warnings.record | (self, category=Warning, message="", module=None) |
Append a new recording filter or apply it if the state is entered.
All warnings matching will be appended to the ``log`` attribute.
Parameters
----------
category : class, optional
Warning class to filter
message : string, optional
Regular expre... |
Append a new recording filter or apply it if the state is entered. | def record(self, category=Warning, message="", module=None):
"""
Append a new recording filter or apply it if the state is entered.
All warnings matching will be appended to the ``log`` attribute.
Parameters
----------
category : class, optional
Warning clas... | [
"def",
"record",
"(",
"self",
",",
"category",
"=",
"Warning",
",",
"message",
"=",
"\"\"",
",",
"module",
"=",
"None",
")",
":",
"return",
"self",
".",
"_filter",
"(",
"category",
"=",
"category",
",",
"message",
"=",
"message",
",",
"module",
"=",
... | [
2130,
4
] | [
2158,
40
] | python | en | ['en', 'error', 'th'] | False |
suppress_warnings.__call__ | (self, func) |
Function decorator to apply certain suppressions to a whole
function.
|
Function decorator to apply certain suppressions to a whole
function.
| def __call__(self, func):
"""
Function decorator to apply certain suppressions to a whole
function.
"""
@wraps(func)
def new_func(*args, **kwargs):
with self:
return func(*args, **kwargs)
return new_func | [
"def",
"__call__",
"(",
"self",
",",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"... | [
2252,
4
] | [
2262,
23
] | python | en | ['en', 'error', 'th'] | False |
version_upgrade_xform | (n, envoy_internal_shadow, file_proto, params) | Transform a FileDescriptorProto from vN[alpha\d] to v(N+1).
Args:
n: version N to upgrade from.
envoy_internal_shadow: generate a shadow for Envoy internal use containing deprecated fields.
file_proto: vN[alpha\d] FileDescriptorProto message.
params: plugin parameters.
Returns:... | Transform a FileDescriptorProto from vN[alpha\d] to v(N+1). | def version_upgrade_xform(n, envoy_internal_shadow, file_proto, params):
"""Transform a FileDescriptorProto from vN[alpha\d] to v(N+1).
Args:
n: version N to upgrade from.
envoy_internal_shadow: generate a shadow for Envoy internal use containing deprecated fields.
file_proto: vN[alpha\... | [
"def",
"version_upgrade_xform",
"(",
"n",
",",
"envoy_internal_shadow",
",",
"file_proto",
",",
"params",
")",
":",
"# Load type database.",
"if",
"params",
"[",
"'type_db_path'",
"]",
":",
"utils",
".",
"load_type_db",
"(",
"params",
"[",
"'type_db_path'",
"]",
... | [
243,
0
] | [
275,
93
] | python | en | ['en', 'sv', 'en'] | True |
UpgradeVisitor._deprecate | (self, proto, field_or_value) | Deprecate a field or value in a message/enum proto.
Args:
proto: DescriptorProto or EnumDescriptorProto message.
field_or_value: field or value inside proto.
| Deprecate a field or value in a message/enum proto. | def _deprecate(self, proto, field_or_value):
"""Deprecate a field or value in a message/enum proto.
Args:
proto: DescriptorProto or EnumDescriptorProto message.
field_or_value: field or value inside proto.
"""
if self._envoy_internal_shadow:
field_or_... | [
"def",
"_deprecate",
"(",
"self",
",",
"proto",
",",
"field_or_value",
")",
":",
"if",
"self",
".",
"_envoy_internal_shadow",
":",
"field_or_value",
".",
"name",
"=",
"'hidden_envoy_deprecated_'",
"+",
"field_or_value",
".",
"name",
"else",
":",
"reserved",
"=",... | [
97,
4
] | [
111,
59
] | python | en | ['en', 'en', 'en'] | True |
UpgradeVisitor._rename | (self, proto, migrate_annotation) | Rename a field/enum/service/message
Args:
proto: DescriptorProto or corresponding proto message
migrate_annotation: udpa.annotations.MigrateAnnotation message
| Rename a field/enum/service/message | def _rename(self, proto, migrate_annotation):
"""Rename a field/enum/service/message
Args:
proto: DescriptorProto or corresponding proto message
migrate_annotation: udpa.annotations.MigrateAnnotation message
"""
if migrate_annotation.rename:
proto.nam... | [
"def",
"_rename",
"(",
"self",
",",
"proto",
",",
"migrate_annotation",
")",
":",
"if",
"migrate_annotation",
".",
"rename",
":",
"proto",
".",
"name",
"=",
"migrate_annotation",
".",
"rename",
"migrate_annotation",
".",
"rename",
"=",
"\"\""
] | [
113,
4
] | [
122,
42
] | python | en | ['ro', 'fr', 'en'] | False |
UpgradeVisitor._oneof_promotion | (self, msg_proto, field_proto, migrate_annotation) | Promote a field to a oneof.
Args:
msg_proto: DescriptorProto for message containing field.
field_proto: FieldDescriptorProto for field.
migrate_annotation: udpa.annotations.FieldMigrateAnnotation message
| Promote a field to a oneof. | def _oneof_promotion(self, msg_proto, field_proto, migrate_annotation):
"""Promote a field to a oneof.
Args:
msg_proto: DescriptorProto for message containing field.
field_proto: FieldDescriptorProto for field.
migrate_annotation: udpa.annotations.FieldMigrateAnnotat... | [
"def",
"_oneof_promotion",
"(",
"self",
",",
"msg_proto",
",",
"field_proto",
",",
"migrate_annotation",
")",
":",
"if",
"migrate_annotation",
".",
"oneof_promotion",
":",
"oneof_index",
"=",
"-",
"1",
"for",
"n",
",",
"oneof_decl",
"in",
"enumerate",
"(",
"ms... | [
124,
4
] | [
142,
51
] | python | en | ['en', 'en', 'en'] | True |
asarray | (a, dtype=None, order=None) | Convert the input to an array.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples
of lists and ndarrays.
dtype : data-type, optional
By default, the data-... | Convert the input to an array. | def asarray(a, dtype=None, order=None):
"""Convert the input to an array.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples
of lists and ndarrays.
dtype : da... | [
"def",
"asarray",
"(",
"a",
",",
"dtype",
"=",
"None",
",",
"order",
"=",
"None",
")",
":",
"return",
"array",
"(",
"a",
",",
"dtype",
",",
"copy",
"=",
"False",
",",
"order",
"=",
"order",
")"
] | [
16,
0
] | [
84,
51
] | python | en | ['en', 'lb', 'en'] | True |
asanyarray | (a, dtype=None, order=None) | Convert the input to an ndarray, but pass ndarray subclasses through.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes scalars, lists, lists of tuples, tuples, tuples of tuples,
tuples of lists, and ndarrays.
dtype : ... | Convert the input to an ndarray, but pass ndarray subclasses through. | def asanyarray(a, dtype=None, order=None):
"""Convert the input to an ndarray, but pass ndarray subclasses through.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes scalars, lists, lists of tuples, tuples, tuples of tuples,
... | [
"def",
"asanyarray",
"(",
"a",
",",
"dtype",
"=",
"None",
",",
"order",
"=",
"None",
")",
":",
"return",
"array",
"(",
"a",
",",
"dtype",
",",
"copy",
"=",
"False",
",",
"order",
"=",
"order",
",",
"subok",
"=",
"True",
")"
] | [
88,
0
] | [
137,
63
] | python | en | ['en', 'lb', 'en'] | True |
ascontiguousarray | (a, dtype=None) |
Return a contiguous array (ndim >= 1) in memory (C order).
Parameters
----------
a : array_like
Input array.
dtype : str or dtype object, optional
Data-type of returned array.
Returns
-------
out : ndarray
Contiguous array of same shape and content as `a`, with... |
Return a contiguous array (ndim >= 1) in memory (C order). | def ascontiguousarray(a, dtype=None):
"""
Return a contiguous array (ndim >= 1) in memory (C order).
Parameters
----------
a : array_like
Input array.
dtype : str or dtype object, optional
Data-type of returned array.
Returns
-------
out : ndarray
Contiguous... | [
"def",
"ascontiguousarray",
"(",
"a",
",",
"dtype",
"=",
"None",
")",
":",
"return",
"array",
"(",
"a",
",",
"dtype",
",",
"copy",
"=",
"False",
",",
"order",
"=",
"'C'",
",",
"ndmin",
"=",
"1",
")"
] | [
141,
0
] | [
178,
58
] | python | en | ['en', 'error', 'th'] | False |
asfortranarray | (a, dtype=None) |
Return an array (ndim >= 1) laid out in Fortran order in memory.
Parameters
----------
a : array_like
Input array.
dtype : str or dtype object, optional
By default, the data-type is inferred from the input data.
Returns
-------
out : ndarray
The input `a` in Fo... |
Return an array (ndim >= 1) laid out in Fortran order in memory. | def asfortranarray(a, dtype=None):
"""
Return an array (ndim >= 1) laid out in Fortran order in memory.
Parameters
----------
a : array_like
Input array.
dtype : str or dtype object, optional
By default, the data-type is inferred from the input data.
Returns
-------
... | [
"def",
"asfortranarray",
"(",
"a",
",",
"dtype",
"=",
"None",
")",
":",
"return",
"array",
"(",
"a",
",",
"dtype",
",",
"copy",
"=",
"False",
",",
"order",
"=",
"'F'",
",",
"ndmin",
"=",
"1",
")"
] | [
182,
0
] | [
219,
58
] | python | en | ['en', 'error', 'th'] | False |
require | (a, dtype=None, requirements=None) |
Return an ndarray of the provided type that satisfies requirements.
This function is useful to be sure that an array with the correct flags
is returned for passing to compiled code (perhaps through ctypes).
Parameters
----------
a : array_like
The object to be converted to a type-and-r... |
Return an ndarray of the provided type that satisfies requirements. | def require(a, dtype=None, requirements=None):
"""
Return an ndarray of the provided type that satisfies requirements.
This function is useful to be sure that an array with the correct flags
is returned for passing to compiled code (perhaps through ctypes).
Parameters
----------
a : array_... | [
"def",
"require",
"(",
"a",
",",
"dtype",
"=",
"None",
",",
"requirements",
"=",
"None",
")",
":",
"possible_flags",
"=",
"{",
"'C'",
":",
"'C'",
",",
"'C_CONTIGUOUS'",
":",
"'C'",
",",
"'CONTIGUOUS'",
":",
"'C'",
",",
"'F'",
":",
"'F'",
",",
"'F_CON... | [
223,
0
] | [
323,
14
] | python | en | ['en', 'error', 'th'] | False |
test_error_on_different_mode | () | test that an error is raised if the user pass in data of
different modes (binary, multi-label, multi-class)
| test that an error is raised if the user pass in data of
different modes (binary, multi-label, multi-class)
| def test_error_on_different_mode():
""" test that an error is raised if the user pass in data of
different modes (binary, multi-label, multi-class)
"""
metric = AUROC()
# pass in multi-class data
metric.update(torch.randn(10, 5).softmax(dim=-1), torch.randint(0, 5, (10, )))
with pytest.r... | [
"def",
"test_error_on_different_mode",
"(",
")",
":",
"metric",
"=",
"AUROC",
"(",
")",
"# pass in multi-class data",
"metric",
".",
"update",
"(",
"torch",
".",
"randn",
"(",
"10",
",",
"5",
")",
".",
"softmax",
"(",
"dim",
"=",
"-",
"1",
")",
",",
"t... | [
132,
0
] | [
141,
70
] | python | en | ['en', 'en', 'en'] | True |
_special_sparse_dot | (W, H, X) | Computes np.dot(W, H), only where X is non zero. | Computes np.dot(W, H), only where X is non zero. | def _special_sparse_dot(W, H, X):
"""Computes np.dot(W, H), only where X is non zero."""
if sp.issparse(X):
ii, jj = X.nonzero()
n_vals = ii.shape[0]
dot_vals = np.empty(n_vals)
n_components = W.shape[1]
batch_size = max(n_components, n_vals // n_components)
for ... | [
"def",
"_special_sparse_dot",
"(",
"W",
",",
"H",
",",
"X",
")",
":",
"if",
"sp",
".",
"issparse",
"(",
"X",
")",
":",
"ii",
",",
"jj",
"=",
"X",
".",
"nonzero",
"(",
")",
"n_vals",
"=",
"ii",
".",
"shape",
"[",
"0",
"]",
"dot_vals",
"=",
"np... | [
32,
0
] | [
50,
27
] | python | en | ['en', 'el-Latn', 'en'] | True |
trace_dot | (X, Y) | Trace of np.dot(X, Y.T) | Trace of np.dot(X, Y.T) | def trace_dot(X, Y):
"""Trace of np.dot(X, Y.T)"""
return np.dot(X.ravel(), Y.ravel()) | [
"def",
"trace_dot",
"(",
"X",
",",
"Y",
")",
":",
"return",
"np",
".",
"dot",
"(",
"X",
".",
"ravel",
"(",
")",
",",
"Y",
".",
"ravel",
"(",
")",
")"
] | [
53,
0
] | [
55,
39
] | python | en | ['en', 'en', 'en'] | True |
beta_divergence_ppc | (X, X_rep, beta, square_root=False) | Compute the beta-divergence of X and dot(W, H).
Parameters
----------
X : float or array-like, shape (n_samples, n_features)
X_rep: float or array-like, shape (n_samples, n_features)
beta : float,
Parameter of the beta-divergence.
If beta == 2, this is half the Frobenius *squared* no... | Compute the beta-divergence of X and dot(W, H).
Parameters
----------
X : float or array-like, shape (n_samples, n_features)
X_rep: float or array-like, shape (n_samples, n_features)
beta : float,
Parameter of the beta-divergence.
If beta == 2, this is half the Frobenius *squared* no... | def beta_divergence_ppc(X, X_rep, beta, square_root=False):
"""Compute the beta-divergence of X and dot(W, H).
Parameters
----------
X : float or array-like, shape (n_samples, n_features)
X_rep: float or array-like, shape (n_samples, n_features)
beta : float,
Parameter of the beta-diverg... | [
"def",
"beta_divergence_ppc",
"(",
"X",
",",
"X_rep",
",",
"beta",
",",
"square_root",
"=",
"False",
")",
":",
"EPSILON",
"=",
"np",
".",
"finfo",
"(",
"np",
".",
"float32",
")",
".",
"eps",
"# The method can be called with scalars",
"if",
"not",
"sp",
"."... | [
58,
0
] | [
129,
18
] | python | en | ['en', 'en', 'en'] | True |
TestStepVariations.test_step | (self, batch, batch_idx, *args, **kwargs) |
Default, baseline test_step
:param batch:
:return:
|
Default, baseline test_step
:param batch:
:return:
| def test_step(self, batch, batch_idx, *args, **kwargs):
"""
Default, baseline test_step
:param batch:
:return:
"""
self.test_step_called = True
x, y = batch
x = x.view(x.size(0), -1)
y_hat = self(x)
loss_test = self.loss(y, y_hat)
... | [
"def",
"test_step",
"(",
"self",
",",
"batch",
",",
"batch_idx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"test_step_called",
"=",
"True",
"x",
",",
"y",
"=",
"batch",
"x",
"=",
"x",
".",
"view",
"(",
"x",
".",
"size",
... | [
24,
4
] | [
58,
25
] | python | en | ['en', 'error', 'th'] | False |
TestStepVariations.test_step__multiple_dataloaders | (self, batch, batch_idx, dataloader_idx, **kwargs) |
Default, baseline test_step
:param batch:
:return:
|
Default, baseline test_step
:param batch:
:return:
| def test_step__multiple_dataloaders(self, batch, batch_idx, dataloader_idx, **kwargs):
"""
Default, baseline test_step
:param batch:
:return:
"""
x, y = batch
x = x.view(x.size(0), -1)
y_hat = self(x)
loss_test = self.loss(y, y_hat)
# acc... | [
"def",
"test_step__multiple_dataloaders",
"(",
"self",
",",
"batch",
",",
"batch_idx",
",",
"dataloader_idx",
",",
"*",
"*",
"kwargs",
")",
":",
"x",
",",
"y",
"=",
"batch",
"x",
"=",
"x",
".",
"view",
"(",
"x",
".",
"size",
"(",
"0",
")",
",",
"-"... | [
60,
4
] | [
95,
25
] | python | en | ['en', 'error', 'th'] | False |
_run_horovod | (trainer_options, on_gpu=False) | Execute the training script across multiple workers in parallel. | Execute the training script across multiple workers in parallel. | def _run_horovod(trainer_options, on_gpu=False):
"""Execute the training script across multiple workers in parallel."""
num_processes = trainer_options.get('gpus', 2)
# for Horovod, we interpret `gpus` to be set per worker
trainer_options.update(gpus=1 if on_gpu else None)
tutils.reset_seed()
cm... | [
"def",
"_run_horovod",
"(",
"trainer_options",
",",
"on_gpu",
"=",
"False",
")",
":",
"num_processes",
"=",
"trainer_options",
".",
"get",
"(",
"'gpus'",
",",
"2",
")",
"# for Horovod, we interpret `gpus` to be set per worker",
"trainer_options",
".",
"update",
"(",
... | [
51,
0
] | [
65,
25
] | python | en | ['en', 'en', 'en'] | True |
test_horovod_cpu | (tmpdir) | Test Horovod running multi-process on CPU. | Test Horovod running multi-process on CPU. | def test_horovod_cpu(tmpdir):
"""Test Horovod running multi-process on CPU."""
trainer_options = dict(
default_root_dir=str(tmpdir),
weights_save_path=str(tmpdir),
gradient_clip_val=1.0,
progress_bar_refresh_rate=0,
max_epochs=1,
limit_train_batches=0.4,
l... | [
"def",
"test_horovod_cpu",
"(",
"tmpdir",
")",
":",
"trainer_options",
"=",
"dict",
"(",
"default_root_dir",
"=",
"str",
"(",
"tmpdir",
")",
",",
"weights_save_path",
"=",
"str",
"(",
"tmpdir",
")",
",",
"gradient_clip_val",
"=",
"1.0",
",",
"progress_bar_refr... | [
69,
0
] | [
82,
33
] | python | en | ['en', 'en', 'en'] | True |
test_horovod_cpu_implicit | (tmpdir) | Test Horovod without specifying a backend, inferring from env set by `horovodrun`. | Test Horovod without specifying a backend, inferring from env set by `horovodrun`. | def test_horovod_cpu_implicit(tmpdir):
"""Test Horovod without specifying a backend, inferring from env set by `horovodrun`."""
trainer_options = dict(
default_root_dir=str(tmpdir),
weights_save_path=str(tmpdir),
gradient_clip_val=1.0,
progress_bar_refresh_rate=0,
max_epo... | [
"def",
"test_horovod_cpu_implicit",
"(",
"tmpdir",
")",
":",
"trainer_options",
"=",
"dict",
"(",
"default_root_dir",
"=",
"str",
"(",
"tmpdir",
")",
",",
"weights_save_path",
"=",
"str",
"(",
"tmpdir",
")",
",",
"gradient_clip_val",
"=",
"1.0",
",",
"progress... | [
86,
0
] | [
98,
33
] | python | en | ['en', 'en', 'en'] | True |
test_horovod_multi_gpu | (tmpdir) | Test Horovod with multi-GPU support. | Test Horovod with multi-GPU support. | def test_horovod_multi_gpu(tmpdir):
"""Test Horovod with multi-GPU support."""
trainer_options = dict(
default_root_dir=str(tmpdir),
weights_save_path=str(tmpdir),
gradient_clip_val=1.0,
progress_bar_refresh_rate=0,
max_epochs=1,
limit_train_batches=0.4,
l... | [
"def",
"test_horovod_multi_gpu",
"(",
"tmpdir",
")",
":",
"trainer_options",
"=",
"dict",
"(",
"default_root_dir",
"=",
"str",
"(",
"tmpdir",
")",
",",
"weights_save_path",
"=",
"str",
"(",
"tmpdir",
")",
",",
"gradient_clip_val",
"=",
"1.0",
",",
"progress_ba... | [
104,
0
] | [
118,
46
] | python | en | ['en', 'en', 'en'] | True |
test_horovod_apex | (tmpdir) | Test Horovod with multi-GPU support using apex amp. | Test Horovod with multi-GPU support using apex amp. | def test_horovod_apex(tmpdir):
"""Test Horovod with multi-GPU support using apex amp."""
trainer_options = dict(
default_root_dir=str(tmpdir),
weights_save_path=str(tmpdir),
gradient_clip_val=1.0,
progress_bar_refresh_rate=0,
max_epochs=1,
limit_train_batches=0.4,... | [
"def",
"test_horovod_apex",
"(",
"tmpdir",
")",
":",
"trainer_options",
"=",
"dict",
"(",
"default_root_dir",
"=",
"str",
"(",
"tmpdir",
")",
",",
"weights_save_path",
"=",
"str",
"(",
"tmpdir",
")",
",",
"gradient_clip_val",
"=",
"1.0",
",",
"progress_bar_ref... | [
126,
0
] | [
142,
46
] | python | en | ['en', 'en', 'en'] | True |
test_horovod_amp | (tmpdir) | Test Horovod with multi-GPU support using native amp. | Test Horovod with multi-GPU support using native amp. | def test_horovod_amp(tmpdir):
"""Test Horovod with multi-GPU support using native amp."""
trainer_options = dict(
default_root_dir=str(tmpdir),
weights_save_path=str(tmpdir),
gradient_clip_val=1.0,
progress_bar_refresh_rate=0,
max_epochs=1,
limit_train_batches=0.4... | [
"def",
"test_horovod_amp",
"(",
"tmpdir",
")",
":",
"trainer_options",
"=",
"dict",
"(",
"default_root_dir",
"=",
"str",
"(",
"tmpdir",
")",
",",
"weights_save_path",
"=",
"str",
"(",
"tmpdir",
")",
",",
"gradient_clip_val",
"=",
"1.0",
",",
"progress_bar_refr... | [
150,
0
] | [
166,
46
] | python | en | ['en', 'en', 'en'] | True |
test_result_reduce_horovod | (tmpdir) | Make sure result logging works with Horovod.
This test mirrors tests/core/test_results.py::_ddp_test_fn
| Make sure result logging works with Horovod. | def test_result_reduce_horovod(tmpdir):
"""Make sure result logging works with Horovod.
This test mirrors tests/core/test_results.py::_ddp_test_fn
"""
tutils.reset_seed()
tutils.set_random_master_port()
def hvd_test_fn():
path_here = os.path.abspath(os.path.dirname(__file__))
p... | [
"def",
"test_result_reduce_horovod",
"(",
"tmpdir",
")",
":",
"tutils",
".",
"reset_seed",
"(",
")",
"tutils",
".",
"set_random_master_port",
"(",
")",
"def",
"hvd_test_fn",
"(",
")",
":",
"path_here",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
"."... | [
235,
0
] | [
279,
34
] | python | en | ['en', 'en', 'en'] | True |
get_api_version | (input_path) | Returns the API version from a given API version input file.
Args:
input_path: the file containing the API version (API_VERSION).
Returns:
a namedtuple containing the major, minor, patch versions.
Raises:
ApiVersionParsingError: If the given file has no lines or more than one line, or i... | Returns the API version from a given API version input file. | def get_api_version(input_path):
"""Returns the API version from a given API version input file.
Args:
input_path: the file containing the API version (API_VERSION).
Returns:
a namedtuple containing the major, minor, patch versions.
Raises:
ApiVersionParsingError: If the given file ... | [
"def",
"get_api_version",
"(",
"input_path",
")",
":",
"lines",
"=",
"pathlib",
".",
"Path",
"(",
"input_path",
")",
".",
"read_text",
"(",
")",
".",
"splitlines",
"(",
")",
"if",
"len",
"(",
"lines",
")",
"!=",
"1",
"or",
"lines",
"[",
"0",
"]",
"... | [
14,
0
] | [
34,
53
] | python | en | ['en', 'en', 'en'] | True |
compute_oldest_api_version | (current_version: ApiVersion) | Computest the oldest API version the client supports. According to the
specification (see: api/API_VERSIONING.md), Envoy supports up to 2 most
recent minor versions. Therefore if the latest API version "X.Y.Z", Envoy's
oldest API version is "X.Y-1.0". Note that the major number is always the
same as the... | Computest the oldest API version the client supports. According to the
specification (see: api/API_VERSIONING.md), Envoy supports up to 2 most
recent minor versions. Therefore if the latest API version "X.Y.Z", Envoy's
oldest API version is "X.Y-1.0". Note that the major number is always the
same as the... | def compute_oldest_api_version(current_version: ApiVersion):
"""Computest the oldest API version the client supports. According to the
specification (see: api/API_VERSIONING.md), Envoy supports up to 2 most
recent minor versions. Therefore if the latest API version "X.Y.Z", Envoy's
oldest API version is... | [
"def",
"compute_oldest_api_version",
"(",
"current_version",
":",
"ApiVersion",
")",
":",
"return",
"ApiVersion",
"(",
"current_version",
".",
"major",
",",
"max",
"(",
"current_version",
".",
"minor",
"-",
"1",
",",
"0",
")",
",",
"0",
")"
] | [
37,
0
] | [
52,
82
] | python | en | ['en', 'en', 'en'] | True |
is_deprecated_annotation_version | (version: str) | Validates that a given version string is of format X.Y, where X and Y are
integers, X>0, and Y>=0.
Args:
version: a minor version deprecation annotation value (see api/envoy/annotations/deprecation.proto)
Returns:
True iff the given string represents a valid X.Y version.
| Validates that a given version string is of format X.Y, where X and Y are
integers, X>0, and Y>=0. | def is_deprecated_annotation_version(version: str):
"""Validates that a given version string is of format X.Y, where X and Y are
integers, X>0, and Y>=0.
Args:
version: a minor version deprecation annotation value (see api/envoy/annotations/deprecation.proto)
Returns:
True iff the given st... | [
"def",
"is_deprecated_annotation_version",
"(",
"version",
":",
"str",
")",
":",
"if",
"version",
".",
"count",
"(",
"'.'",
")",
"!=",
"1",
":",
"return",
"False",
"# Validate major and minor parts.",
"try",
":",
"major",
",",
"minor",
"=",
"[",
"int",
"(",
... | [
55,
0
] | [
76,
15
] | python | en | ['en', 'en', 'en'] | True |
TestAppendFieldsObj.test_append_to_objects | (self) | Test append_fields when the base array contains objects | Test append_fields when the base array contains objects | def test_append_to_objects(self):
"Test append_fields when the base array contains objects"
obj = self.data['obj']
x = np.array([(obj, 1.), (obj, 2.)],
dtype=[('A', object), ('B', float)])
y = np.array([10, 20], dtype=int)
test = append_fields(x, 'C', data=y... | [
"def",
"test_append_to_objects",
"(",
"self",
")",
":",
"obj",
"=",
"self",
".",
"data",
"[",
"'obj'",
"]",
"x",
"=",
"np",
".",
"array",
"(",
"[",
"(",
"obj",
",",
"1.",
")",
",",
"(",
"obj",
",",
"2.",
")",
"]",
",",
"dtype",
"=",
"[",
"(",... | [
970,
4
] | [
979,
35
] | python | en | ['en', 'en', 'en'] | True |
normalize_keyword | (keyword) | Normalize keyword for became id
- Replace white space with '-'
- Convert to lowercase | Normalize keyword for became id | def normalize_keyword(keyword):
"""Normalize keyword for became id
- Replace white space with '-'
- Convert to lowercase"""
return keyword.lower().replace(' ', '-') | [
"def",
"normalize_keyword",
"(",
"keyword",
")",
":",
"return",
"keyword",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"'-'",
")"
] | [
9,
0
] | [
14,
44
] | python | en | ['en', 'en', 'en'] | True |
keyword2html | (keyword_node) | Return HTML version of keyword with id. | Return HTML version of keyword with id. | def keyword2html(keyword_node):
"""Return HTML version of keyword with id."""
keyword = pf.stringify(keyword_node)
id = normalize_keyword(keyword)
return [{"t": "Span",
"c": [[id, [],[]],
keyword_node]}] | [
"def",
"keyword2html",
"(",
"keyword_node",
")",
":",
"keyword",
"=",
"pf",
".",
"stringify",
"(",
"keyword_node",
")",
"id",
"=",
"normalize_keyword",
"(",
"keyword",
")",
"return",
"[",
"{",
"\"t\"",
":",
"\"Span\"",
",",
"\"c\"",
":",
"[",
"[",
"id",
... | [
16,
0
] | [
22,
32
] | python | en | ['en', 'en', 'en'] | True |
id4glossary | (key, value, format, meta) | Add id to keywords at glossary. | Add id to keywords at glossary. | def id4glossary(key, value, format, meta):
"""Add id to keywords at glossary."""
if key == "DefinitionList":
for definition in value:
definition[0] = keyword2html(definition[0])
return {"t": key,
"c": value} | [
"def",
"id4glossary",
"(",
"key",
",",
"value",
",",
"format",
",",
"meta",
")",
":",
"if",
"key",
"==",
"\"DefinitionList\"",
":",
"for",
"definition",
"in",
"value",
":",
"definition",
"[",
"0",
"]",
"=",
"keyword2html",
"(",
"definition",
"[",
"0",
... | [
24,
0
] | [
30,
27
] | python | en | ['en', 'en', 'en'] | True |
_check_mode | (mode, encoding, newline) | Check mode and that encoding and newline are compatible.
Parameters
----------
mode : str
File open mode.
encoding : str
File encoding.
newline : str
Newline for text files.
| Check mode and that encoding and newline are compatible. | def _check_mode(mode, encoding, newline):
"""Check mode and that encoding and newline are compatible.
Parameters
----------
mode : str
File open mode.
encoding : str
File encoding.
newline : str
Newline for text files.
"""
if "t" in mode:
if "b" in mode:... | [
"def",
"_check_mode",
"(",
"mode",
",",
"encoding",
",",
"newline",
")",
":",
"if",
"\"t\"",
"in",
"mode",
":",
"if",
"\"b\"",
"in",
"mode",
":",
"raise",
"ValueError",
"(",
"\"Invalid mode: %r\"",
"%",
"(",
"mode",
",",
")",
")",
"else",
":",
"if",
... | [
51,
0
] | [
71,
79
] | python | en | ['en', 'en', 'en'] | True |
_python2_bz2open | (fn, mode, encoding, newline) | Wrapper to open bz2 in text mode.
Parameters
----------
fn : str
File name
mode : {'r', 'w'}
File mode. Note that bz2 Text files are not supported.
encoding : str
Ignored, text bz2 files not supported in Python2.
newline : str
Ignored, text bz2 files not supporte... | Wrapper to open bz2 in text mode. | def _python2_bz2open(fn, mode, encoding, newline):
"""Wrapper to open bz2 in text mode.
Parameters
----------
fn : str
File name
mode : {'r', 'w'}
File mode. Note that bz2 Text files are not supported.
encoding : str
Ignored, text bz2 files not supported in Python2.
... | [
"def",
"_python2_bz2open",
"(",
"fn",
",",
"mode",
",",
"encoding",
",",
"newline",
")",
":",
"import",
"bz2",
"_check_mode",
"(",
"mode",
",",
"encoding",
",",
"newline",
")",
"if",
"\"t\"",
"in",
"mode",
":",
"# BZ2File is missing necessary functions for TextI... | [
74,
0
] | [
97,
32
] | python | en | ['en', 'en', 'en'] | True |
_python2_gzipopen | (fn, mode, encoding, newline) | Wrapper to open gzip in text mode.
Parameters
----------
fn : str, bytes, file
File path or opened file.
mode : str
File mode. The actual files are opened as binary, but will decoded
using the specified `encoding` and `newline`.
encoding : str
Encoding to be used wh... | Wrapper to open gzip in text mode. | def _python2_gzipopen(fn, mode, encoding, newline):
""" Wrapper to open gzip in text mode.
Parameters
----------
fn : str, bytes, file
File path or opened file.
mode : str
File mode. The actual files are opened as binary, but will decoded
using the specified `encoding` and `... | [
"def",
"_python2_gzipopen",
"(",
"fn",
",",
"mode",
",",
"encoding",
",",
"newline",
")",
":",
"import",
"gzip",
"# gzip is lacking read1 needed for TextIOWrapper",
"class",
"GzipWrap",
"(",
"gzip",
".",
"GzipFile",
")",
":",
"def",
"read1",
"(",
"self",
",",
... | [
99,
0
] | [
135,
26
] | python | en | ['en', 'en', 'en'] | True |
open | (path, mode='r', destpath=os.curdir, encoding=None, newline=None) |
Open `path` with `mode` and return the file object.
If ``path`` is an URL, it will be downloaded, stored in the
`DataSource` `destpath` directory and opened from there.
Parameters
----------
path : str
Local file path or URL to open.
mode : str, optional
Mode to open `path... |
Open `path` with `mode` and return the file object. | def open(path, mode='r', destpath=os.curdir, encoding=None, newline=None):
"""
Open `path` with `mode` and return the file object.
If ``path`` is an URL, it will be downloaded, stored in the
`DataSource` `destpath` directory and opened from there.
Parameters
----------
path : str
L... | [
"def",
"open",
"(",
"path",
",",
"mode",
"=",
"'r'",
",",
"destpath",
"=",
"os",
".",
"curdir",
",",
"encoding",
"=",
"None",
",",
"newline",
"=",
"None",
")",
":",
"ds",
"=",
"DataSource",
"(",
"destpath",
")",
"return",
"ds",
".",
"open",
"(",
... | [
230,
0
] | [
268,
66
] | python | en | ['en', 'error', 'th'] | False |
_FileOpeners.keys | (self) |
Return the keys of currently supported file openers.
Parameters
----------
None
Returns
-------
keys : list
The keys are None for uncompressed files and the file extension
strings (i.e. ``'.gz'``, ``'.xz'``) for supported compression
... |
Return the keys of currently supported file openers. | def keys(self):
"""
Return the keys of currently supported file openers.
Parameters
----------
None
Returns
-------
keys : list
The keys are None for uncompressed files and the file extension
strings (i.e. ``'.gz'``, ``'.xz'``) fo... | [
"def",
"keys",
"(",
"self",
")",
":",
"self",
".",
"_load",
"(",
")",
"return",
"list",
"(",
"self",
".",
"_file_openers",
".",
"keys",
"(",
")",
")"
] | [
205,
4
] | [
222,
46
] | python | en | ['en', 'error', 'th'] | False |
Repository.__init__ | (self, baseurl, destpath=os.curdir) | Create a Repository with a shared url or directory of baseurl. | Create a Repository with a shared url or directory of baseurl. | def __init__(self, baseurl, destpath=os.curdir):
"""Create a Repository with a shared url or directory of baseurl."""
DataSource.__init__(self, destpath=destpath)
self._baseurl = baseurl | [
"def",
"__init__",
"(",
"self",
",",
"baseurl",
",",
"destpath",
"=",
"os",
".",
"curdir",
")",
":",
"DataSource",
".",
"__init__",
"(",
"self",
",",
"destpath",
"=",
"destpath",
")",
"self",
".",
"_baseurl",
"=",
"baseurl"
] | [
665,
4
] | [
668,
31
] | python | en | ['en', 'en', 'en'] | True |
Repository._fullpath | (self, path) | Return complete path for path. Prepends baseurl if necessary. | Return complete path for path. Prepends baseurl if necessary. | def _fullpath(self, path):
"""Return complete path for path. Prepends baseurl if necessary."""
splitpath = path.split(self._baseurl, 2)
if len(splitpath) == 1:
result = os.path.join(self._baseurl, path)
else:
result = path # path contains baseurl already
... | [
"def",
"_fullpath",
"(",
"self",
",",
"path",
")",
":",
"splitpath",
"=",
"path",
".",
"split",
"(",
"self",
".",
"_baseurl",
",",
"2",
")",
"if",
"len",
"(",
"splitpath",
")",
"==",
"1",
":",
"result",
"=",
"os",
".",
"path",
".",
"join",
"(",
... | [
673,
4
] | [
680,
21
] | python | en | ['en', 'en', 'en'] | True |
Repository._findfile | (self, path) | Extend DataSource method to prepend baseurl to ``path``. | Extend DataSource method to prepend baseurl to ``path``. | def _findfile(self, path):
"""Extend DataSource method to prepend baseurl to ``path``."""
return DataSource._findfile(self, self._fullpath(path)) | [
"def",
"_findfile",
"(",
"self",
",",
"path",
")",
":",
"return",
"DataSource",
".",
"_findfile",
"(",
"self",
",",
"self",
".",
"_fullpath",
"(",
"path",
")",
")"
] | [
682,
4
] | [
684,
63
] | python | en | ['en', 'en', 'en'] | True |
Repository.abspath | (self, path) |
Return absolute path of file in the Repository directory.
If `path` is an URL, then `abspath` will return either the location
the file exists locally or the location it would exist when opened
using the `open` method.
Parameters
----------
path : str
... |
Return absolute path of file in the Repository directory. | def abspath(self, path):
"""
Return absolute path of file in the Repository directory.
If `path` is an URL, then `abspath` will return either the location
the file exists locally or the location it would exist when opened
using the `open` method.
Parameters
----... | [
"def",
"abspath",
"(",
"self",
",",
"path",
")",
":",
"return",
"DataSource",
".",
"abspath",
"(",
"self",
",",
"self",
".",
"_fullpath",
"(",
"path",
")",
")"
] | [
686,
4
] | [
707,
61
] | python | en | ['en', 'error', 'th'] | False |
Repository.exists | (self, path) |
Test if path exists prepending Repository base URL to path.
Test if `path` exists as (and in this order):
- a local file.
- a remote URL that has been downloaded and stored locally in the
`DataSource` directory.
- a remote URL that has not been downloaded, but is val... |
Test if path exists prepending Repository base URL to path. | def exists(self, path):
"""
Test if path exists prepending Repository base URL to path.
Test if `path` exists as (and in this order):
- a local file.
- a remote URL that has been downloaded and stored locally in the
`DataSource` directory.
- a remote URL that ... | [
"def",
"exists",
"(",
"self",
",",
"path",
")",
":",
"return",
"DataSource",
".",
"exists",
"(",
"self",
",",
"self",
".",
"_fullpath",
"(",
"path",
")",
")"
] | [
709,
4
] | [
741,
60
] | python | en | ['en', 'error', 'th'] | False |
Repository.open | (self, path, mode='r', encoding=None, newline=None) |
Open and return file-like object prepending Repository base URL.
If `path` is an URL, it will be downloaded, stored in the
DataSource directory and opened from there.
Parameters
----------
path : str
Local file path or URL to open. This may, but does not ha... |
Open and return file-like object prepending Repository base URL. | def open(self, path, mode='r', encoding=None, newline=None):
"""
Open and return file-like object prepending Repository base URL.
If `path` is an URL, it will be downloaded, stored in the
DataSource directory and opened from there.
Parameters
----------
path : s... | [
"def",
"open",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"'r'",
",",
"encoding",
"=",
"None",
",",
"newline",
"=",
"None",
")",
":",
"return",
"DataSource",
".",
"open",
"(",
"self",
",",
"self",
".",
"_fullpath",
"(",
"path",
")",
",",
"mode",
... | [
743,
4
] | [
773,
66
] | python | en | ['en', 'error', 'th'] | False |
Repository.listdir | (self) |
List files in the source Repository.
Returns
-------
files : list of str
List of file names (not containing a directory part).
Notes
-----
Does not currently work for remote repositories.
|
List files in the source Repository. | def listdir(self):
"""
List files in the source Repository.
Returns
-------
files : list of str
List of file names (not containing a directory part).
Notes
-----
Does not currently work for remote repositories.
"""
if self._i... | [
"def",
"listdir",
"(",
"self",
")",
":",
"if",
"self",
".",
"_isurl",
"(",
"self",
".",
"_baseurl",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Directory listing of URLs, not supported yet.\"",
")",
"else",
":",
"return",
"os",
".",
"listdir",
"(",
"self... | [
775,
4
] | [
793,
44
] | python | en | ['en', 'error', 'th'] | False |
is_block | (modules) | Check if is ResNet building block. | Check if is ResNet building block. | def is_block(modules):
"""Check if is ResNet building block."""
if isinstance(modules, (BasicBlock, Bottleneck)):
return True
return False | [
"def",
"is_block",
"(",
"modules",
")",
":",
"if",
"isinstance",
"(",
"modules",
",",
"(",
"BasicBlock",
",",
"Bottleneck",
")",
")",
":",
"return",
"True",
"return",
"False"
] | [
11,
0
] | [
15,
16
] | python | en | ['en', 'en', 'en'] | True |
all_zeros | (modules) | Check if the weight(and bias) is all zero. | Check if the weight(and bias) is all zero. | def all_zeros(modules):
"""Check if the weight(and bias) is all zero."""
weight_zero = torch.equal(modules.weight.data,
torch.zeros_like(modules.weight.data))
if hasattr(modules, 'bias'):
bias_zero = torch.equal(modules.bias.data,
torch.z... | [
"def",
"all_zeros",
"(",
"modules",
")",
":",
"weight_zero",
"=",
"torch",
".",
"equal",
"(",
"modules",
".",
"weight",
".",
"data",
",",
"torch",
".",
"zeros_like",
"(",
"modules",
".",
"weight",
".",
"data",
")",
")",
"if",
"hasattr",
"(",
"modules",... | [
18,
0
] | [
28,
36
] | python | en | ['en', 'en', 'en'] | True |
check_norm_state | (modules, train_state) | Check if norm layer is in correct train state. | Check if norm layer is in correct train state. | def check_norm_state(modules, train_state):
"""Check if norm layer is in correct train state."""
for mod in modules:
if isinstance(mod, _BatchNorm):
if mod.training != train_state:
return False
return True | [
"def",
"check_norm_state",
"(",
"modules",
",",
"train_state",
")",
":",
"for",
"mod",
"in",
"modules",
":",
"if",
"isinstance",
"(",
"mod",
",",
"_BatchNorm",
")",
":",
"if",
"mod",
".",
"training",
"!=",
"train_state",
":",
"return",
"False",
"return",
... | [
31,
0
] | [
37,
15
] | python | en | ['en', 'en', 'en'] | True |
test_resnet | () | Test resnet backbone. | Test resnet backbone. | def test_resnet():
"""Test resnet backbone."""
with pytest.raises(KeyError):
# ResNet depth should be in [18, 34, 50, 101, 152]
ResNet(20)
with pytest.raises(AssertionError):
# In ResNet: 1 <= num_stages <= 4
ResNet(50, num_stages=0)
with pytest.raises(AssertionError):
... | [
"def",
"test_resnet",
"(",
")",
":",
"with",
"pytest",
".",
"raises",
"(",
"KeyError",
")",
":",
"# ResNet depth should be in [18, 34, 50, 101, 152]",
"ResNet",
"(",
"20",
")",
"with",
"pytest",
".",
"raises",
"(",
"AssertionError",
")",
":",
"# In ResNet: 1 <= nu... | [
372,
0
] | [
507,
41
] | python | en | ['nl', 'no', 'en'] | False |
_run_standard_hparams_test | (tmpdir, model, cls, try_overwrite=False) |
Tests for the existence of an arg 'test_arg=14'
|
Tests for the existence of an arg 'test_arg=14'
| def _run_standard_hparams_test(tmpdir, model, cls, try_overwrite=False):
"""
Tests for the existence of an arg 'test_arg=14'
"""
hparam_type = type(model.hparams)
# test proper property assignments
assert model.hparams.test_arg == 14
# verify we can train
trainer = Trainer(default_root_... | [
"def",
"_run_standard_hparams_test",
"(",
"tmpdir",
",",
"model",
",",
"cls",
",",
"try_overwrite",
"=",
"False",
")",
":",
"hparam_type",
"=",
"type",
"(",
"model",
".",
"hparams",
")",
"# test proper property assignments",
"assert",
"model",
".",
"hparams",
".... | [
83,
0
] | [
112,
30
] | python | en | ['en', 'error', 'th'] | False |
test_explicit_args_hparams | (tmpdir) |
Tests that a model can take implicit args and assign
|
Tests that a model can take implicit args and assign
| def test_explicit_args_hparams(tmpdir):
"""
Tests that a model can take implicit args and assign
"""
# define model
class LocalModel(BoringModel):
def __init__(self, test_arg, test_arg2):
super().__init__()
self.save_hyperparameters('test_arg', 'test_arg2')
mod... | [
"def",
"test_explicit_args_hparams",
"(",
"tmpdir",
")",
":",
"# define model",
"class",
"LocalModel",
"(",
"BoringModel",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"test_arg",
",",
"test_arg2",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
... | [
156,
0
] | [
175,
41
] | python | en | ['en', 'error', 'th'] | False |
test_implicit_args_hparams | (tmpdir) |
Tests that a model can take regular args and assign
|
Tests that a model can take regular args and assign
| def test_implicit_args_hparams(tmpdir):
"""
Tests that a model can take regular args and assign
"""
# define model
class LocalModel(BoringModel):
def __init__(self, test_arg, test_arg2):
super().__init__()
self.save_hyperparameters()
model = LocalModel(test_arg... | [
"def",
"test_implicit_args_hparams",
"(",
"tmpdir",
")",
":",
"# define model",
"class",
"LocalModel",
"(",
"BoringModel",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"test_arg",
",",
"test_arg2",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
... | [
178,
0
] | [
197,
41
] | python | en | ['en', 'error', 'th'] | False |
test_explicit_missing_args_hparams | (tmpdir) |
Tests that a model can take regular args and assign
|
Tests that a model can take regular args and assign
| def test_explicit_missing_args_hparams(tmpdir):
"""
Tests that a model can take regular args and assign
"""
# define model
class LocalModel(BoringModel):
def __init__(self, test_arg, test_arg2):
super().__init__()
self.save_hyperparameters('test_arg')
model = L... | [
"def",
"test_explicit_missing_args_hparams",
"(",
"tmpdir",
")",
":",
"# define model",
"class",
"LocalModel",
"(",
"BoringModel",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"test_arg",
",",
"test_arg2",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
... | [
200,
0
] | [
232,
30
] | python | en | ['en', 'error', 'th'] | False |
test_collect_init_arguments | (tmpdir, cls) | Test that the model automatically saves the arguments passed into the constructor | Test that the model automatically saves the arguments passed into the constructor | def test_collect_init_arguments(tmpdir, cls):
""" Test that the model automatically saves the arguments passed into the constructor """
extra_args = {}
if cls is AggSubClassBoringModel:
extra_args.update(my_loss=torch.nn.CosineEmbeddingLoss())
elif cls is DictConfSubClassBoringModel:
ext... | [
"def",
"test_collect_init_arguments",
"(",
"tmpdir",
",",
"cls",
")",
":",
"extra_args",
"=",
"{",
"}",
"if",
"cls",
"is",
"AggSubClassBoringModel",
":",
"extra_args",
".",
"update",
"(",
"my_loss",
"=",
"torch",
".",
"nn",
".",
"CosineEmbeddingLoss",
"(",
"... | [
321,
0
] | [
363,
41
] | python | en | ['en', 'en', 'en'] | True |
test_collect_init_arguments_with_local_vars | (cls) | Tests that only the arguments are collected and not local variables. | Tests that only the arguments are collected and not local variables. | def test_collect_init_arguments_with_local_vars(cls):
""" Tests that only the arguments are collected and not local variables. """
model = cls(arg1=1, arg2=2)
assert 'local_var' not in model.hparams
assert model.hparams['arg1'] == 'overwritten'
assert model.hparams['arg2'] == 2 | [
"def",
"test_collect_init_arguments_with_local_vars",
"(",
"cls",
")",
":",
"model",
"=",
"cls",
"(",
"arg1",
"=",
"1",
",",
"arg2",
"=",
"2",
")",
"assert",
"'local_var'",
"not",
"in",
"model",
".",
"hparams",
"assert",
"model",
".",
"hparams",
"[",
"'arg... | [
403,
0
] | [
408,
37
] | python | en | ['en', 'en', 'en'] | True |
test_single_config_models_fail | (tmpdir, cls, config) | Test fail on passing unsupported config type. | Test fail on passing unsupported config type. | def test_single_config_models_fail(tmpdir, cls, config):
""" Test fail on passing unsupported config type. """
with pytest.raises(ValueError):
_ = cls(**config) | [
"def",
"test_single_config_models_fail",
"(",
"tmpdir",
",",
"cls",
",",
"config",
")",
":",
"with",
"pytest",
".",
"raises",
"(",
"ValueError",
")",
":",
"_",
"=",
"cls",
"(",
"*",
"*",
"config",
")"
] | [
457,
0
] | [
460,
25
] | python | en | ['en', 'en', 'en'] | True |
test_model_nohparams_train_test | (tmpdir, cls) | Test models that do not tae any argument in init. | Test models that do not tae any argument in init. | def test_model_nohparams_train_test(tmpdir, cls):
"""Test models that do not tae any argument in init."""
model = cls()
trainer = Trainer(
max_epochs=1,
default_root_dir=tmpdir,
)
train_loader = DataLoader(RandomDataset(32, 64), batch_size=32)
trainer.fit(model, train_loader)
... | [
"def",
"test_model_nohparams_train_test",
"(",
"tmpdir",
",",
"cls",
")",
":",
"model",
"=",
"cls",
"(",
")",
"trainer",
"=",
"Trainer",
"(",
"max_epochs",
"=",
"1",
",",
"default_root_dir",
"=",
"tmpdir",
",",
")",
"train_loader",
"=",
"DataLoader",
"(",
... | [
540,
0
] | [
553,
46
] | python | en | ['en', 'en', 'en'] | True |
test_model_ignores_non_exist_kwargument | (tmpdir) | Test that the model takes only valid class arguments. | Test that the model takes only valid class arguments. | def test_model_ignores_non_exist_kwargument(tmpdir):
"""Test that the model takes only valid class arguments."""
class LocalModel(BoringModel):
def __init__(self, batch_size=15):
super().__init__()
self.save_hyperparameters()
model = LocalModel()
assert model.hparams.b... | [
"def",
"test_model_ignores_non_exist_kwargument",
"(",
"tmpdir",
")",
":",
"class",
"LocalModel",
"(",
"BoringModel",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"batch_size",
"=",
"15",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".... | [
556,
0
] | [
575,
49
] | 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.