nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
chanyn/3Dpose_ssl | 585696676279683a279b1ecca136c0e0d02aef2a | caffe-3dssl/python/caffe/coord_map.py | python | crop_params | (fn) | return (axis, offset) | Extract the crop layer parameters with defaults. | Extract the crop layer parameters with defaults. | [
"Extract",
"the",
"crop",
"layer",
"parameters",
"with",
"defaults",
"."
] | def crop_params(fn):
"""
Extract the crop layer parameters with defaults.
"""
params = fn.params.get('crop_param', fn.params)
axis = params.get('axis', 2) # default to spatial crop for N, C, H, W
offset = np.array(params.get('offset', 0), ndmin=1)
return (axis, offset) | [
"def",
"crop_params",
"(",
"fn",
")",
":",
"params",
"=",
"fn",
".",
"params",
".",
"get",
"(",
"'crop_param'",
",",
"fn",
".",
"params",
")",
"axis",
"=",
"params",
".",
"get",
"(",
"'axis'",
",",
"2",
")",
"# default to spatial crop for N, C, H, W",
"offset",
"=",
"np",
".",
"array",
"(",
"params",
".",
"get",
"(",
"'offset'",
",",
"0",
")",
",",
"ndmin",
"=",
"1",
")",
"return",
"(",
"axis",
",",
"offset",
")"
] | https://github.com/chanyn/3Dpose_ssl/blob/585696676279683a279b1ecca136c0e0d02aef2a/caffe-3dssl/python/caffe/coord_map.py#L40-L47 | |
gromacs/gromacs | 7dec3a3f99993cf5687a122de3e12de31c21c399 | python_packaging/src/gmxapi/operation.py | python | InputCollectionDescription.from_function | (function) | return InputCollectionDescription(description.items()) | Inspect a function to be wrapped.
Used internally by gmxapi.operation.function_wrapper()
Raises:
exceptions.ProtocolError if function signature cannot be determined to be valid.
Returns:
InputCollectionDescription for the function input signature. | Inspect a function to be wrapped. | [
"Inspect",
"a",
"function",
"to",
"be",
"wrapped",
"."
] | def from_function(function):
"""Inspect a function to be wrapped.
Used internally by gmxapi.operation.function_wrapper()
Raises:
exceptions.ProtocolError if function signature cannot be determined to be valid.
Returns:
InputCollectionDescription for the function input signature.
"""
# First, inspect the function.
assert callable(function)
signature = inspect.signature(function)
# The function must have clear and static input schema
# Make sure that all parameters have clear names, whether or not they are used in a call.
for name, param in signature.parameters.items():
disallowed = any([param.kind == param.POSITIONAL_ONLY,
param.kind == param.VAR_POSITIONAL,
param.kind == param.VAR_KEYWORD])
if disallowed:
raise exceptions.ProtocolError(
'Cannot wrap function. Operations must have well-defined parameter names.')
if param.name == 'input':
raise exceptions.ProtocolError(
'Function signature includes the (reserved) "input" keyword argument.')
description = collections.OrderedDict()
for param in signature.parameters.values():
if param.name == 'output':
# Wrapped functions may accept the output parameter to publish results, but
# that is not part of the Operation input signature.
continue
if param.annotation == param.empty:
if param.default == param.empty or param.default is None:
raise exceptions.ProtocolError(
f'Could not infer parameter type for {param.name}')
dtype = type(param.default)
if isinstance(dtype, collections.abc.Iterable) \
and not isinstance(dtype, (str, bytes, collections.abc.Mapping)):
dtype = datamodel.NDArray
else:
dtype = param.annotation
description[param.name] = param.replace(annotation=dtype)
return InputCollectionDescription(description.items()) | [
"def",
"from_function",
"(",
"function",
")",
":",
"# First, inspect the function.",
"assert",
"callable",
"(",
"function",
")",
"signature",
"=",
"inspect",
".",
"signature",
"(",
"function",
")",
"# The function must have clear and static input schema",
"# Make sure that all parameters have clear names, whether or not they are used in a call.",
"for",
"name",
",",
"param",
"in",
"signature",
".",
"parameters",
".",
"items",
"(",
")",
":",
"disallowed",
"=",
"any",
"(",
"[",
"param",
".",
"kind",
"==",
"param",
".",
"POSITIONAL_ONLY",
",",
"param",
".",
"kind",
"==",
"param",
".",
"VAR_POSITIONAL",
",",
"param",
".",
"kind",
"==",
"param",
".",
"VAR_KEYWORD",
"]",
")",
"if",
"disallowed",
":",
"raise",
"exceptions",
".",
"ProtocolError",
"(",
"'Cannot wrap function. Operations must have well-defined parameter names.'",
")",
"if",
"param",
".",
"name",
"==",
"'input'",
":",
"raise",
"exceptions",
".",
"ProtocolError",
"(",
"'Function signature includes the (reserved) \"input\" keyword argument.'",
")",
"description",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"param",
"in",
"signature",
".",
"parameters",
".",
"values",
"(",
")",
":",
"if",
"param",
".",
"name",
"==",
"'output'",
":",
"# Wrapped functions may accept the output parameter to publish results, but",
"# that is not part of the Operation input signature.",
"continue",
"if",
"param",
".",
"annotation",
"==",
"param",
".",
"empty",
":",
"if",
"param",
".",
"default",
"==",
"param",
".",
"empty",
"or",
"param",
".",
"default",
"is",
"None",
":",
"raise",
"exceptions",
".",
"ProtocolError",
"(",
"f'Could not infer parameter type for {param.name}'",
")",
"dtype",
"=",
"type",
"(",
"param",
".",
"default",
")",
"if",
"isinstance",
"(",
"dtype",
",",
"collections",
".",
"abc",
".",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"dtype",
",",
"(",
"str",
",",
"bytes",
",",
"collections",
".",
"abc",
".",
"Mapping",
")",
")",
":",
"dtype",
"=",
"datamodel",
".",
"NDArray",
"else",
":",
"dtype",
"=",
"param",
".",
"annotation",
"description",
"[",
"param",
".",
"name",
"]",
"=",
"param",
".",
"replace",
"(",
"annotation",
"=",
"dtype",
")",
"return",
"InputCollectionDescription",
"(",
"description",
".",
"items",
"(",
")",
")"
] | https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/python_packaging/src/gmxapi/operation.py#L391-L434 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/decomposition/_dict_learning.py | python | dict_learning | (X, n_components, alpha, max_iter=100, tol=1e-8,
method='lars', n_jobs=None, dict_init=None, code_init=None,
callback=None, verbose=False, random_state=None,
return_n_iter=False, positive_dict=False,
positive_code=False, method_max_iter=1000) | Solves a dictionary learning matrix factorization problem.
Finds the best dictionary and the corresponding sparse code for
approximating the data matrix X by solving::
(U^*, V^*) = argmin 0.5 || X - U V ||_2^2 + alpha * || U ||_1
(U,V)
with || V_k ||_2 = 1 for all 0 <= k < n_components
where V is the dictionary and U is the sparse code.
Read more in the :ref:`User Guide <DictionaryLearning>`.
Parameters
----------
X : array of shape (n_samples, n_features)
Data matrix.
n_components : int,
Number of dictionary atoms to extract.
alpha : int,
Sparsity controlling parameter.
max_iter : int,
Maximum number of iterations to perform.
tol : float,
Tolerance for the stopping condition.
method : {'lars', 'cd'}
lars: uses the least angle regression method to solve the lasso problem
(linear_model.lars_path)
cd: uses the coordinate descent method to compute the
Lasso solution (linear_model.Lasso). Lars will be faster if
the estimated components are sparse.
n_jobs : int or None, optional (default=None)
Number of parallel jobs to run.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
dict_init : array of shape (n_components, n_features),
Initial value for the dictionary for warm restart scenarios.
code_init : array of shape (n_samples, n_components),
Initial value for the sparse code for warm restart scenarios.
callback : callable or None, optional (default: None)
Callable that gets invoked every five iterations
verbose : bool, optional (default: False)
To control the verbosity of the procedure.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
return_n_iter : bool
Whether or not to return the number of iterations.
positive_dict : bool
Whether to enforce positivity when finding the dictionary.
.. versionadded:: 0.20
positive_code : bool
Whether to enforce positivity when finding the code.
.. versionadded:: 0.20
method_max_iter : int, optional (default=1000)
Maximum number of iterations to perform.
.. versionadded:: 0.22
Returns
-------
code : array of shape (n_samples, n_components)
The sparse code factor in the matrix factorization.
dictionary : array of shape (n_components, n_features),
The dictionary factor in the matrix factorization.
errors : array
Vector of errors at each iteration.
n_iter : int
Number of iterations run. Returned only if `return_n_iter` is
set to True.
See also
--------
dict_learning_online
DictionaryLearning
MiniBatchDictionaryLearning
SparsePCA
MiniBatchSparsePCA | Solves a dictionary learning matrix factorization problem. | [
"Solves",
"a",
"dictionary",
"learning",
"matrix",
"factorization",
"problem",
"."
] | def dict_learning(X, n_components, alpha, max_iter=100, tol=1e-8,
method='lars', n_jobs=None, dict_init=None, code_init=None,
callback=None, verbose=False, random_state=None,
return_n_iter=False, positive_dict=False,
positive_code=False, method_max_iter=1000):
"""Solves a dictionary learning matrix factorization problem.
Finds the best dictionary and the corresponding sparse code for
approximating the data matrix X by solving::
(U^*, V^*) = argmin 0.5 || X - U V ||_2^2 + alpha * || U ||_1
(U,V)
with || V_k ||_2 = 1 for all 0 <= k < n_components
where V is the dictionary and U is the sparse code.
Read more in the :ref:`User Guide <DictionaryLearning>`.
Parameters
----------
X : array of shape (n_samples, n_features)
Data matrix.
n_components : int,
Number of dictionary atoms to extract.
alpha : int,
Sparsity controlling parameter.
max_iter : int,
Maximum number of iterations to perform.
tol : float,
Tolerance for the stopping condition.
method : {'lars', 'cd'}
lars: uses the least angle regression method to solve the lasso problem
(linear_model.lars_path)
cd: uses the coordinate descent method to compute the
Lasso solution (linear_model.Lasso). Lars will be faster if
the estimated components are sparse.
n_jobs : int or None, optional (default=None)
Number of parallel jobs to run.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
dict_init : array of shape (n_components, n_features),
Initial value for the dictionary for warm restart scenarios.
code_init : array of shape (n_samples, n_components),
Initial value for the sparse code for warm restart scenarios.
callback : callable or None, optional (default: None)
Callable that gets invoked every five iterations
verbose : bool, optional (default: False)
To control the verbosity of the procedure.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
return_n_iter : bool
Whether or not to return the number of iterations.
positive_dict : bool
Whether to enforce positivity when finding the dictionary.
.. versionadded:: 0.20
positive_code : bool
Whether to enforce positivity when finding the code.
.. versionadded:: 0.20
method_max_iter : int, optional (default=1000)
Maximum number of iterations to perform.
.. versionadded:: 0.22
Returns
-------
code : array of shape (n_samples, n_components)
The sparse code factor in the matrix factorization.
dictionary : array of shape (n_components, n_features),
The dictionary factor in the matrix factorization.
errors : array
Vector of errors at each iteration.
n_iter : int
Number of iterations run. Returned only if `return_n_iter` is
set to True.
See also
--------
dict_learning_online
DictionaryLearning
MiniBatchDictionaryLearning
SparsePCA
MiniBatchSparsePCA
"""
if method not in ('lars', 'cd'):
raise ValueError('Coding method %r not supported as a fit algorithm.'
% method)
_check_positive_coding(method, positive_code)
method = 'lasso_' + method
t0 = time.time()
# Avoid integer division problems
alpha = float(alpha)
random_state = check_random_state(random_state)
# Init the code and the dictionary with SVD of Y
if code_init is not None and dict_init is not None:
code = np.array(code_init, order='F')
# Don't copy V, it will happen below
dictionary = dict_init
else:
code, S, dictionary = linalg.svd(X, full_matrices=False)
dictionary = S[:, np.newaxis] * dictionary
r = len(dictionary)
if n_components <= r: # True even if n_components=None
code = code[:, :n_components]
dictionary = dictionary[:n_components, :]
else:
code = np.c_[code, np.zeros((len(code), n_components - r))]
dictionary = np.r_[dictionary,
np.zeros((n_components - r, dictionary.shape[1]))]
# Fortran-order dict, as we are going to access its row vectors
dictionary = np.array(dictionary, order='F')
residuals = 0
errors = []
current_cost = np.nan
if verbose == 1:
print('[dict_learning]', end=' ')
# If max_iter is 0, number of iterations returned should be zero
ii = -1
for ii in range(max_iter):
dt = (time.time() - t0)
if verbose == 1:
sys.stdout.write(".")
sys.stdout.flush()
elif verbose:
print("Iteration % 3i "
"(elapsed time: % 3is, % 4.1fmn, current cost % 7.3f)"
% (ii, dt, dt / 60, current_cost))
# Update code
code = sparse_encode(X, dictionary, algorithm=method, alpha=alpha,
init=code, n_jobs=n_jobs, positive=positive_code,
max_iter=method_max_iter, verbose=verbose)
# Update dictionary
dictionary, residuals = _update_dict(dictionary.T, X.T, code.T,
verbose=verbose, return_r2=True,
random_state=random_state,
positive=positive_dict)
dictionary = dictionary.T
# Cost function
current_cost = 0.5 * residuals + alpha * np.sum(np.abs(code))
errors.append(current_cost)
if ii > 0:
dE = errors[-2] - errors[-1]
# assert(dE >= -tol * errors[-1])
if dE < tol * errors[-1]:
if verbose == 1:
# A line return
print("")
elif verbose:
print("--- Convergence reached after %d iterations" % ii)
break
if ii % 5 == 0 and callback is not None:
callback(locals())
if return_n_iter:
return code, dictionary, errors, ii + 1
else:
return code, dictionary, errors | [
"def",
"dict_learning",
"(",
"X",
",",
"n_components",
",",
"alpha",
",",
"max_iter",
"=",
"100",
",",
"tol",
"=",
"1e-8",
",",
"method",
"=",
"'lars'",
",",
"n_jobs",
"=",
"None",
",",
"dict_init",
"=",
"None",
",",
"code_init",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"random_state",
"=",
"None",
",",
"return_n_iter",
"=",
"False",
",",
"positive_dict",
"=",
"False",
",",
"positive_code",
"=",
"False",
",",
"method_max_iter",
"=",
"1000",
")",
":",
"if",
"method",
"not",
"in",
"(",
"'lars'",
",",
"'cd'",
")",
":",
"raise",
"ValueError",
"(",
"'Coding method %r not supported as a fit algorithm.'",
"%",
"method",
")",
"_check_positive_coding",
"(",
"method",
",",
"positive_code",
")",
"method",
"=",
"'lasso_'",
"+",
"method",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"# Avoid integer division problems",
"alpha",
"=",
"float",
"(",
"alpha",
")",
"random_state",
"=",
"check_random_state",
"(",
"random_state",
")",
"# Init the code and the dictionary with SVD of Y",
"if",
"code_init",
"is",
"not",
"None",
"and",
"dict_init",
"is",
"not",
"None",
":",
"code",
"=",
"np",
".",
"array",
"(",
"code_init",
",",
"order",
"=",
"'F'",
")",
"# Don't copy V, it will happen below",
"dictionary",
"=",
"dict_init",
"else",
":",
"code",
",",
"S",
",",
"dictionary",
"=",
"linalg",
".",
"svd",
"(",
"X",
",",
"full_matrices",
"=",
"False",
")",
"dictionary",
"=",
"S",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"*",
"dictionary",
"r",
"=",
"len",
"(",
"dictionary",
")",
"if",
"n_components",
"<=",
"r",
":",
"# True even if n_components=None",
"code",
"=",
"code",
"[",
":",
",",
":",
"n_components",
"]",
"dictionary",
"=",
"dictionary",
"[",
":",
"n_components",
",",
":",
"]",
"else",
":",
"code",
"=",
"np",
".",
"c_",
"[",
"code",
",",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"code",
")",
",",
"n_components",
"-",
"r",
")",
")",
"]",
"dictionary",
"=",
"np",
".",
"r_",
"[",
"dictionary",
",",
"np",
".",
"zeros",
"(",
"(",
"n_components",
"-",
"r",
",",
"dictionary",
".",
"shape",
"[",
"1",
"]",
")",
")",
"]",
"# Fortran-order dict, as we are going to access its row vectors",
"dictionary",
"=",
"np",
".",
"array",
"(",
"dictionary",
",",
"order",
"=",
"'F'",
")",
"residuals",
"=",
"0",
"errors",
"=",
"[",
"]",
"current_cost",
"=",
"np",
".",
"nan",
"if",
"verbose",
"==",
"1",
":",
"print",
"(",
"'[dict_learning]'",
",",
"end",
"=",
"' '",
")",
"# If max_iter is 0, number of iterations returned should be zero",
"ii",
"=",
"-",
"1",
"for",
"ii",
"in",
"range",
"(",
"max_iter",
")",
":",
"dt",
"=",
"(",
"time",
".",
"time",
"(",
")",
"-",
"t0",
")",
"if",
"verbose",
"==",
"1",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\".\"",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"elif",
"verbose",
":",
"print",
"(",
"\"Iteration % 3i \"",
"\"(elapsed time: % 3is, % 4.1fmn, current cost % 7.3f)\"",
"%",
"(",
"ii",
",",
"dt",
",",
"dt",
"/",
"60",
",",
"current_cost",
")",
")",
"# Update code",
"code",
"=",
"sparse_encode",
"(",
"X",
",",
"dictionary",
",",
"algorithm",
"=",
"method",
",",
"alpha",
"=",
"alpha",
",",
"init",
"=",
"code",
",",
"n_jobs",
"=",
"n_jobs",
",",
"positive",
"=",
"positive_code",
",",
"max_iter",
"=",
"method_max_iter",
",",
"verbose",
"=",
"verbose",
")",
"# Update dictionary",
"dictionary",
",",
"residuals",
"=",
"_update_dict",
"(",
"dictionary",
".",
"T",
",",
"X",
".",
"T",
",",
"code",
".",
"T",
",",
"verbose",
"=",
"verbose",
",",
"return_r2",
"=",
"True",
",",
"random_state",
"=",
"random_state",
",",
"positive",
"=",
"positive_dict",
")",
"dictionary",
"=",
"dictionary",
".",
"T",
"# Cost function",
"current_cost",
"=",
"0.5",
"*",
"residuals",
"+",
"alpha",
"*",
"np",
".",
"sum",
"(",
"np",
".",
"abs",
"(",
"code",
")",
")",
"errors",
".",
"append",
"(",
"current_cost",
")",
"if",
"ii",
">",
"0",
":",
"dE",
"=",
"errors",
"[",
"-",
"2",
"]",
"-",
"errors",
"[",
"-",
"1",
"]",
"# assert(dE >= -tol * errors[-1])",
"if",
"dE",
"<",
"tol",
"*",
"errors",
"[",
"-",
"1",
"]",
":",
"if",
"verbose",
"==",
"1",
":",
"# A line return",
"print",
"(",
"\"\"",
")",
"elif",
"verbose",
":",
"print",
"(",
"\"--- Convergence reached after %d iterations\"",
"%",
"ii",
")",
"break",
"if",
"ii",
"%",
"5",
"==",
"0",
"and",
"callback",
"is",
"not",
"None",
":",
"callback",
"(",
"locals",
"(",
")",
")",
"if",
"return_n_iter",
":",
"return",
"code",
",",
"dictionary",
",",
"errors",
",",
"ii",
"+",
"1",
"else",
":",
"return",
"code",
",",
"dictionary",
",",
"errors"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/decomposition/_dict_learning.py#L425-L617 | ||
google/swiftshader | 8ccc63f045d5975fb67f9dfd3d2b8235b0526990 | third_party/SPIRV-Tools/utils/check_copyright.py | python | find | (top, filename_glob, skip_glob_dir_list, skip_glob_files_list) | return file_list | Returns files in the tree rooted at top matching filename_glob but not
in directories matching skip_glob_dir_list nor files matching
skip_glob_dir_list. | Returns files in the tree rooted at top matching filename_glob but not
in directories matching skip_glob_dir_list nor files matching
skip_glob_dir_list. | [
"Returns",
"files",
"in",
"the",
"tree",
"rooted",
"at",
"top",
"matching",
"filename_glob",
"but",
"not",
"in",
"directories",
"matching",
"skip_glob_dir_list",
"nor",
"files",
"matching",
"skip_glob_dir_list",
"."
] | def find(top, filename_glob, skip_glob_dir_list, skip_glob_files_list):
"""Returns files in the tree rooted at top matching filename_glob but not
in directories matching skip_glob_dir_list nor files matching
skip_glob_dir_list."""
file_list = []
for path, dirs, files in os.walk(top):
for glob in skip_glob_dir_list:
for match in fnmatch.filter(dirs, glob):
dirs.remove(match)
for filename in fnmatch.filter(files, filename_glob):
full_file = os.path.join(path, filename)
if full_file not in skip_glob_files_list:
file_list.append(full_file)
return file_list | [
"def",
"find",
"(",
"top",
",",
"filename_glob",
",",
"skip_glob_dir_list",
",",
"skip_glob_files_list",
")",
":",
"file_list",
"=",
"[",
"]",
"for",
"path",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"top",
")",
":",
"for",
"glob",
"in",
"skip_glob_dir_list",
":",
"for",
"match",
"in",
"fnmatch",
".",
"filter",
"(",
"dirs",
",",
"glob",
")",
":",
"dirs",
".",
"remove",
"(",
"match",
")",
"for",
"filename",
"in",
"fnmatch",
".",
"filter",
"(",
"files",
",",
"filename_glob",
")",
":",
"full_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"if",
"full_file",
"not",
"in",
"skip_glob_files_list",
":",
"file_list",
".",
"append",
"(",
"full_file",
")",
"return",
"file_list"
] | https://github.com/google/swiftshader/blob/8ccc63f045d5975fb67f9dfd3d2b8235b0526990/third_party/SPIRV-Tools/utils/check_copyright.py#L72-L86 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/debug/cli/analyzer_cli.py | python | DebugAnalyzer.list_outputs | (self, args, screen_info=None) | return self._list_inputs_or_outputs(
parsed.recursive,
parsed.node_name,
parsed.depth,
parsed.control,
parsed.op_type,
do_outputs=True) | Command handler for inputs.
Show inputs to a given node.
Args:
args: Command-line arguments, excluding the command prefix, as a list of
str.
screen_info: Optional dict input containing screen information such as
cols.
Returns:
Output text lines as a RichTextLines object. | Command handler for inputs. | [
"Command",
"handler",
"for",
"inputs",
"."
] | def list_outputs(self, args, screen_info=None):
"""Command handler for inputs.
Show inputs to a given node.
Args:
args: Command-line arguments, excluding the command prefix, as a list of
str.
screen_info: Optional dict input containing screen information such as
cols.
Returns:
Output text lines as a RichTextLines object.
"""
# Screen info not currently used by this handler. Include this line to
# mute pylint.
_ = screen_info
# TODO(cais): Use screen info to format the output lines more prettily,
# e.g., hanging indent of long node names.
parsed = self._arg_parsers["list_outputs"].parse_args(args)
return self._list_inputs_or_outputs(
parsed.recursive,
parsed.node_name,
parsed.depth,
parsed.control,
parsed.op_type,
do_outputs=True) | [
"def",
"list_outputs",
"(",
"self",
",",
"args",
",",
"screen_info",
"=",
"None",
")",
":",
"# Screen info not currently used by this handler. Include this line to",
"# mute pylint.",
"_",
"=",
"screen_info",
"# TODO(cais): Use screen info to format the output lines more prettily,",
"# e.g., hanging indent of long node names.",
"parsed",
"=",
"self",
".",
"_arg_parsers",
"[",
"\"list_outputs\"",
"]",
".",
"parse_args",
"(",
"args",
")",
"return",
"self",
".",
"_list_inputs_or_outputs",
"(",
"parsed",
".",
"recursive",
",",
"parsed",
".",
"node_name",
",",
"parsed",
".",
"depth",
",",
"parsed",
".",
"control",
",",
"parsed",
".",
"op_type",
",",
"do_outputs",
"=",
"True",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/debug/cli/analyzer_cli.py#L495-L524 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/grid.py | python | GridTableBase.SetAttr | (*args, **kwargs) | return _grid.GridTableBase_SetAttr(*args, **kwargs) | SetAttr(self, GridCellAttr attr, int row, int col) | SetAttr(self, GridCellAttr attr, int row, int col) | [
"SetAttr",
"(",
"self",
"GridCellAttr",
"attr",
"int",
"row",
"int",
"col",
")"
] | def SetAttr(*args, **kwargs):
"""SetAttr(self, GridCellAttr attr, int row, int col)"""
return _grid.GridTableBase_SetAttr(*args, **kwargs) | [
"def",
"SetAttr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridTableBase_SetAttr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L910-L912 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/python/debug/cli/command_parser.py | python | extract_output_file_path | (args) | return args, output_file_path | Extract output file path from command arguments.
Args:
args: (list of str) command arguments.
Returns:
(list of str) Command arguments with the output file path part stripped.
(str or None) Output file path (if any).
Raises:
SyntaxError: If there is no file path after the last ">" character. | Extract output file path from command arguments. | [
"Extract",
"output",
"file",
"path",
"from",
"command",
"arguments",
"."
] | def extract_output_file_path(args):
"""Extract output file path from command arguments.
Args:
args: (list of str) command arguments.
Returns:
(list of str) Command arguments with the output file path part stripped.
(str or None) Output file path (if any).
Raises:
SyntaxError: If there is no file path after the last ">" character.
"""
if args and args[-1].endswith(">"):
raise SyntaxError("Redirect file path is empty")
elif args and args[-1].startswith(">"):
try:
_parse_interval(args[-1])
if len(args) > 1 and args[-2].startswith("-"):
output_file_path = None
else:
output_file_path = args[-1][1:]
args = args[:-1]
except ValueError:
output_file_path = args[-1][1:]
args = args[:-1]
elif len(args) > 1 and args[-2] == ">":
output_file_path = args[-1]
args = args[:-2]
elif args and args[-1].count(">") == 1:
gt_index = args[-1].index(">")
if gt_index > 0 and args[-1][gt_index - 1] == "=":
output_file_path = None
else:
output_file_path = args[-1][gt_index + 1:]
args[-1] = args[-1][:gt_index]
elif len(args) > 1 and args[-2].endswith(">"):
output_file_path = args[-1]
args = args[:-1]
args[-1] = args[-1][:-1]
else:
output_file_path = None
return args, output_file_path | [
"def",
"extract_output_file_path",
"(",
"args",
")",
":",
"if",
"args",
"and",
"args",
"[",
"-",
"1",
"]",
".",
"endswith",
"(",
"\">\"",
")",
":",
"raise",
"SyntaxError",
"(",
"\"Redirect file path is empty\"",
")",
"elif",
"args",
"and",
"args",
"[",
"-",
"1",
"]",
".",
"startswith",
"(",
"\">\"",
")",
":",
"try",
":",
"_parse_interval",
"(",
"args",
"[",
"-",
"1",
"]",
")",
"if",
"len",
"(",
"args",
")",
">",
"1",
"and",
"args",
"[",
"-",
"2",
"]",
".",
"startswith",
"(",
"\"-\"",
")",
":",
"output_file_path",
"=",
"None",
"else",
":",
"output_file_path",
"=",
"args",
"[",
"-",
"1",
"]",
"[",
"1",
":",
"]",
"args",
"=",
"args",
"[",
":",
"-",
"1",
"]",
"except",
"ValueError",
":",
"output_file_path",
"=",
"args",
"[",
"-",
"1",
"]",
"[",
"1",
":",
"]",
"args",
"=",
"args",
"[",
":",
"-",
"1",
"]",
"elif",
"len",
"(",
"args",
")",
">",
"1",
"and",
"args",
"[",
"-",
"2",
"]",
"==",
"\">\"",
":",
"output_file_path",
"=",
"args",
"[",
"-",
"1",
"]",
"args",
"=",
"args",
"[",
":",
"-",
"2",
"]",
"elif",
"args",
"and",
"args",
"[",
"-",
"1",
"]",
".",
"count",
"(",
"\">\"",
")",
"==",
"1",
":",
"gt_index",
"=",
"args",
"[",
"-",
"1",
"]",
".",
"index",
"(",
"\">\"",
")",
"if",
"gt_index",
">",
"0",
"and",
"args",
"[",
"-",
"1",
"]",
"[",
"gt_index",
"-",
"1",
"]",
"==",
"\"=\"",
":",
"output_file_path",
"=",
"None",
"else",
":",
"output_file_path",
"=",
"args",
"[",
"-",
"1",
"]",
"[",
"gt_index",
"+",
"1",
":",
"]",
"args",
"[",
"-",
"1",
"]",
"=",
"args",
"[",
"-",
"1",
"]",
"[",
":",
"gt_index",
"]",
"elif",
"len",
"(",
"args",
")",
">",
"1",
"and",
"args",
"[",
"-",
"2",
"]",
".",
"endswith",
"(",
"\">\"",
")",
":",
"output_file_path",
"=",
"args",
"[",
"-",
"1",
"]",
"args",
"=",
"args",
"[",
":",
"-",
"1",
"]",
"args",
"[",
"-",
"1",
"]",
"=",
"args",
"[",
"-",
"1",
"]",
"[",
":",
"-",
"1",
"]",
"else",
":",
"output_file_path",
"=",
"None",
"return",
"args",
",",
"output_file_path"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/cli/command_parser.py#L103-L147 | |
JoseExposito/touchegg | 1f3fda214358d071c05da4bf17c070c33d67b5eb | cmake/cpplint.py | python | _CppLintState.IncrementErrorCount | (self, category) | Bumps the module's error statistic. | Bumps the module's error statistic. | [
"Bumps",
"the",
"module",
"s",
"error",
"statistic",
"."
] | def IncrementErrorCount(self, category):
"""Bumps the module's error statistic."""
self.error_count += 1
if self.counting in ('toplevel', 'detailed'):
if self.counting != 'detailed':
category = category.split('/')[0]
if category not in self.errors_by_category:
self.errors_by_category[category] = 0
self.errors_by_category[category] += 1 | [
"def",
"IncrementErrorCount",
"(",
"self",
",",
"category",
")",
":",
"self",
".",
"error_count",
"+=",
"1",
"if",
"self",
".",
"counting",
"in",
"(",
"'toplevel'",
",",
"'detailed'",
")",
":",
"if",
"self",
".",
"counting",
"!=",
"'detailed'",
":",
"category",
"=",
"category",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
"if",
"category",
"not",
"in",
"self",
".",
"errors_by_category",
":",
"self",
".",
"errors_by_category",
"[",
"category",
"]",
"=",
"0",
"self",
".",
"errors_by_category",
"[",
"category",
"]",
"+=",
"1"
] | https://github.com/JoseExposito/touchegg/blob/1f3fda214358d071c05da4bf17c070c33d67b5eb/cmake/cpplint.py#L943-L951 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/Paste/paste/util/multidict.py | python | UnicodeMultiDict.dict_of_lists | (self) | return unicode_dict | Returns a dictionary where each key is associated with a
list of values. | Returns a dictionary where each key is associated with a
list of values. | [
"Returns",
"a",
"dictionary",
"where",
"each",
"key",
"is",
"associated",
"with",
"a",
"list",
"of",
"values",
"."
] | def dict_of_lists(self):
"""
Returns a dictionary where each key is associated with a
list of values.
"""
unicode_dict = {}
for key, value in six.iteritems(self.multi.dict_of_lists()):
value = [self._decode_value(value) for value in value]
unicode_dict[self._decode_key(key)] = value
return unicode_dict | [
"def",
"dict_of_lists",
"(",
"self",
")",
":",
"unicode_dict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"multi",
".",
"dict_of_lists",
"(",
")",
")",
":",
"value",
"=",
"[",
"self",
".",
"_decode_value",
"(",
"value",
")",
"for",
"value",
"in",
"value",
"]",
"unicode_dict",
"[",
"self",
".",
"_decode_key",
"(",
"key",
")",
"]",
"=",
"value",
"return",
"unicode_dict"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/Paste/paste/util/multidict.py#L327-L336 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/traitlets/py2/traitlets/config/loader.py | python | JSONFileConfigLoader.load_config | (self) | return self.config | Load the config from a file and return it as a Config object. | Load the config from a file and return it as a Config object. | [
"Load",
"the",
"config",
"from",
"a",
"file",
"and",
"return",
"it",
"as",
"a",
"Config",
"object",
"."
] | def load_config(self):
"""Load the config from a file and return it as a Config object."""
self.clear()
try:
self._find_file()
except IOError as e:
raise ConfigFileNotFound(str(e))
dct = self._read_file_as_dict()
self.config = self._convert_to_config(dct)
return self.config | [
"def",
"load_config",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"try",
":",
"self",
".",
"_find_file",
"(",
")",
"except",
"IOError",
"as",
"e",
":",
"raise",
"ConfigFileNotFound",
"(",
"str",
"(",
"e",
")",
")",
"dct",
"=",
"self",
".",
"_read_file_as_dict",
"(",
")",
"self",
".",
"config",
"=",
"self",
".",
"_convert_to_config",
"(",
"dct",
")",
"return",
"self",
".",
"config"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py2/traitlets/config/loader.py#L399-L408 | |
Kitware/TeleSculptor | 84821cabd2fd60c5fbfeaf61a1948cbced716641 | plugins/blender/io_import_krtd_camera.py | python | readCameraPath | (context, files, scale) | Read a camera path from a sequence KRTD files | Read a camera path from a sequence KRTD files | [
"Read",
"a",
"camera",
"path",
"from",
"a",
"sequence",
"KRTD",
"files"
] | def readCameraPath(context, files, scale):
"""Read a camera path from a sequence KRTD files
"""
cam = bpy.data.cameras.new("camera_KRTD")
cam_ob = bpy.data.objects.new("KRTD", cam)
bpy.context.scene.objects.link(cam_ob)
bpy.context.scene.frame_start = 0
bpy.context.scene.frame_end = len(files)
for fnum, filepath in enumerate(files):
with open(filepath, 'r') as f:
(K, R, t, d) = parseCameraKrtd(f)
t = scale * t
cam_ob.matrix_world = mathutils.Matrix.Translation(t) * R.to_4x4()
if K[0][2] != 0.0:
cam_ob.data.lens = K[0][0] / (2.0 * K[0][2]) \
* cam_ob.data.sensor_width
cam_ob.data.sensor_fit = 'HORIZONTAL'
bpy.context.scene.render.resolution_x = 2.0 * K[0][2]
bpy.context.scene.render.resolution_y = 2.0 * K[1][2]
cam.keyframe_insert("lens", frame=fnum)
cam_ob.keyframe_insert("location", frame=fnum)
cam_ob.keyframe_insert("rotation_euler", frame=fnum) | [
"def",
"readCameraPath",
"(",
"context",
",",
"files",
",",
"scale",
")",
":",
"cam",
"=",
"bpy",
".",
"data",
".",
"cameras",
".",
"new",
"(",
"\"camera_KRTD\"",
")",
"cam_ob",
"=",
"bpy",
".",
"data",
".",
"objects",
".",
"new",
"(",
"\"KRTD\"",
",",
"cam",
")",
"bpy",
".",
"context",
".",
"scene",
".",
"objects",
".",
"link",
"(",
"cam_ob",
")",
"bpy",
".",
"context",
".",
"scene",
".",
"frame_start",
"=",
"0",
"bpy",
".",
"context",
".",
"scene",
".",
"frame_end",
"=",
"len",
"(",
"files",
")",
"for",
"fnum",
",",
"filepath",
"in",
"enumerate",
"(",
"files",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"'r'",
")",
"as",
"f",
":",
"(",
"K",
",",
"R",
",",
"t",
",",
"d",
")",
"=",
"parseCameraKrtd",
"(",
"f",
")",
"t",
"=",
"scale",
"*",
"t",
"cam_ob",
".",
"matrix_world",
"=",
"mathutils",
".",
"Matrix",
".",
"Translation",
"(",
"t",
")",
"*",
"R",
".",
"to_4x4",
"(",
")",
"if",
"K",
"[",
"0",
"]",
"[",
"2",
"]",
"!=",
"0.0",
":",
"cam_ob",
".",
"data",
".",
"lens",
"=",
"K",
"[",
"0",
"]",
"[",
"0",
"]",
"/",
"(",
"2.0",
"*",
"K",
"[",
"0",
"]",
"[",
"2",
"]",
")",
"*",
"cam_ob",
".",
"data",
".",
"sensor_width",
"cam_ob",
".",
"data",
".",
"sensor_fit",
"=",
"'HORIZONTAL'",
"bpy",
".",
"context",
".",
"scene",
".",
"render",
".",
"resolution_x",
"=",
"2.0",
"*",
"K",
"[",
"0",
"]",
"[",
"2",
"]",
"bpy",
".",
"context",
".",
"scene",
".",
"render",
".",
"resolution_y",
"=",
"2.0",
"*",
"K",
"[",
"1",
"]",
"[",
"2",
"]",
"cam",
".",
"keyframe_insert",
"(",
"\"lens\"",
",",
"frame",
"=",
"fnum",
")",
"cam_ob",
".",
"keyframe_insert",
"(",
"\"location\"",
",",
"frame",
"=",
"fnum",
")",
"cam_ob",
".",
"keyframe_insert",
"(",
"\"rotation_euler\"",
",",
"frame",
"=",
"fnum",
")"
] | https://github.com/Kitware/TeleSculptor/blob/84821cabd2fd60c5fbfeaf61a1948cbced716641/plugins/blender/io_import_krtd_camera.py#L100-L121 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | native_client_sdk/src/build_tools/nacl_sdk_scons/nacl_utils.py | python | GetJSONFromNexeSpec | (nexe_spec) | return nmf_json | Generate a JSON string that represents the architecture-to-nexe mapping
in |nexe_spec|.
The nexe spec is a simple dictionary, whose keys are architecture names and
values are the nexe files that should be loaded for the corresponding
architecture. For example:
{'x86-32': 'hello_world_x86_32.nexe',
'x86-64': 'hello_world_x86_64.nexe',
'arm': 'hello_world_ARM.nexe'}
Args:
nexe_spec: The dictionary that maps architectures to .nexe files.
Returns:
A JSON string representing |nexe_spec|. | Generate a JSON string that represents the architecture-to-nexe mapping
in |nexe_spec|. | [
"Generate",
"a",
"JSON",
"string",
"that",
"represents",
"the",
"architecture",
"-",
"to",
"-",
"nexe",
"mapping",
"in",
"|nexe_spec|",
"."
] | def GetJSONFromNexeSpec(nexe_spec):
'''Generate a JSON string that represents the architecture-to-nexe mapping
in |nexe_spec|.
The nexe spec is a simple dictionary, whose keys are architecture names and
values are the nexe files that should be loaded for the corresponding
architecture. For example:
{'x86-32': 'hello_world_x86_32.nexe',
'x86-64': 'hello_world_x86_64.nexe',
'arm': 'hello_world_ARM.nexe'}
Args:
nexe_spec: The dictionary that maps architectures to .nexe files.
Returns:
A JSON string representing |nexe_spec|.
'''
nmf_json = '{\n'
nmf_json += ' "program": {\n'
# Add an entry in the JSON for each specified architecture. Note that this
# loop emits a trailing ',' for every line but the last one.
if nexe_spec and len(nexe_spec):
line_count = len(nexe_spec)
for arch_key in nexe_spec:
line_count -= 1
eol_char = ',' if line_count > 0 else ''
nmf_json += ' "%s": {"url": "%s"}%s\n' % (arch_key,
nexe_spec[arch_key],
eol_char)
nmf_json += ' }\n'
nmf_json += '}\n'
return nmf_json | [
"def",
"GetJSONFromNexeSpec",
"(",
"nexe_spec",
")",
":",
"nmf_json",
"=",
"'{\\n'",
"nmf_json",
"+=",
"' \"program\": {\\n'",
"# Add an entry in the JSON for each specified architecture. Note that this",
"# loop emits a trailing ',' for every line but the last one.",
"if",
"nexe_spec",
"and",
"len",
"(",
"nexe_spec",
")",
":",
"line_count",
"=",
"len",
"(",
"nexe_spec",
")",
"for",
"arch_key",
"in",
"nexe_spec",
":",
"line_count",
"-=",
"1",
"eol_char",
"=",
"','",
"if",
"line_count",
">",
"0",
"else",
"''",
"nmf_json",
"+=",
"' \"%s\": {\"url\": \"%s\"}%s\\n'",
"%",
"(",
"arch_key",
",",
"nexe_spec",
"[",
"arch_key",
"]",
",",
"eol_char",
")",
"nmf_json",
"+=",
"' }\\n'",
"nmf_json",
"+=",
"'}\\n'",
"return",
"nmf_json"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/native_client_sdk/src/build_tools/nacl_sdk_scons/nacl_utils.py#L227-L259 | |
Sigil-Ebook/Sigil | 0d145d3a4874b4a26f7aabd68dbd9d18a2402e52 | src/Resource_Files/plugin_launchers/python/sigil_bs4/diagnose.py | python | rsentence | (length=4) | return " ".join(rword(random.randint(4,9)) for i in range(length)) | Generate a random sentence-like string. | Generate a random sentence-like string. | [
"Generate",
"a",
"random",
"sentence",
"-",
"like",
"string",
"."
] | def rsentence(length=4):
"Generate a random sentence-like string."
return " ".join(rword(random.randint(4,9)) for i in range(length)) | [
"def",
"rsentence",
"(",
"length",
"=",
"4",
")",
":",
"return",
"\" \"",
".",
"join",
"(",
"rword",
"(",
"random",
".",
"randint",
"(",
"4",
",",
"9",
")",
")",
"for",
"i",
"in",
"range",
"(",
"length",
")",
")"
] | https://github.com/Sigil-Ebook/Sigil/blob/0d145d3a4874b4a26f7aabd68dbd9d18a2402e52/src/Resource_Files/plugin_launchers/python/sigil_bs4/diagnose.py#L147-L149 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scikit-learn/py3/sklearn/preprocessing/_label.py | python | MultiLabelBinarizer.inverse_transform | (self, yt) | Transform the given indicator matrix into label sets
Parameters
----------
yt : array or sparse matrix of shape (n_samples, n_classes)
A matrix containing only 1s ands 0s.
Returns
-------
y : list of tuples
The set of labels for each sample such that `y[i]` consists of
`classes_[j]` for each `yt[i, j] == 1`. | Transform the given indicator matrix into label sets | [
"Transform",
"the",
"given",
"indicator",
"matrix",
"into",
"label",
"sets"
] | def inverse_transform(self, yt):
"""Transform the given indicator matrix into label sets
Parameters
----------
yt : array or sparse matrix of shape (n_samples, n_classes)
A matrix containing only 1s ands 0s.
Returns
-------
y : list of tuples
The set of labels for each sample such that `y[i]` consists of
`classes_[j]` for each `yt[i, j] == 1`.
"""
check_is_fitted(self)
if yt.shape[1] != len(self.classes_):
raise ValueError('Expected indicator for {0} classes, but got {1}'
.format(len(self.classes_), yt.shape[1]))
if sp.issparse(yt):
yt = yt.tocsr()
if len(yt.data) != 0 and len(np.setdiff1d(yt.data, [0, 1])) > 0:
raise ValueError('Expected only 0s and 1s in label indicator.')
return [tuple(self.classes_.take(yt.indices[start:end]))
for start, end in zip(yt.indptr[:-1], yt.indptr[1:])]
else:
unexpected = np.setdiff1d(yt, [0, 1])
if len(unexpected) > 0:
raise ValueError('Expected only 0s and 1s in label indicator. '
'Also got {0}'.format(unexpected))
return [tuple(self.classes_.compress(indicators)) for indicators
in yt] | [
"def",
"inverse_transform",
"(",
"self",
",",
"yt",
")",
":",
"check_is_fitted",
"(",
"self",
")",
"if",
"yt",
".",
"shape",
"[",
"1",
"]",
"!=",
"len",
"(",
"self",
".",
"classes_",
")",
":",
"raise",
"ValueError",
"(",
"'Expected indicator for {0} classes, but got {1}'",
".",
"format",
"(",
"len",
"(",
"self",
".",
"classes_",
")",
",",
"yt",
".",
"shape",
"[",
"1",
"]",
")",
")",
"if",
"sp",
".",
"issparse",
"(",
"yt",
")",
":",
"yt",
"=",
"yt",
".",
"tocsr",
"(",
")",
"if",
"len",
"(",
"yt",
".",
"data",
")",
"!=",
"0",
"and",
"len",
"(",
"np",
".",
"setdiff1d",
"(",
"yt",
".",
"data",
",",
"[",
"0",
",",
"1",
"]",
")",
")",
">",
"0",
":",
"raise",
"ValueError",
"(",
"'Expected only 0s and 1s in label indicator.'",
")",
"return",
"[",
"tuple",
"(",
"self",
".",
"classes_",
".",
"take",
"(",
"yt",
".",
"indices",
"[",
"start",
":",
"end",
"]",
")",
")",
"for",
"start",
",",
"end",
"in",
"zip",
"(",
"yt",
".",
"indptr",
"[",
":",
"-",
"1",
"]",
",",
"yt",
".",
"indptr",
"[",
"1",
":",
"]",
")",
"]",
"else",
":",
"unexpected",
"=",
"np",
".",
"setdiff1d",
"(",
"yt",
",",
"[",
"0",
",",
"1",
"]",
")",
"if",
"len",
"(",
"unexpected",
")",
">",
"0",
":",
"raise",
"ValueError",
"(",
"'Expected only 0s and 1s in label indicator. '",
"'Also got {0}'",
".",
"format",
"(",
"unexpected",
")",
")",
"return",
"[",
"tuple",
"(",
"self",
".",
"classes_",
".",
"compress",
"(",
"indicators",
")",
")",
"for",
"indicators",
"in",
"yt",
"]"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/preprocessing/_label.py#L993-L1025 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/external/boost/boost_1_68_0/tools/build/src/build/feature.py | python | enumerate | () | return __all_features.iteritems () | Returns an iterator to the features map. | Returns an iterator to the features map. | [
"Returns",
"an",
"iterator",
"to",
"the",
"features",
"map",
"."
] | def enumerate ():
""" Returns an iterator to the features map.
"""
return __all_features.iteritems () | [
"def",
"enumerate",
"(",
")",
":",
"return",
"__all_features",
".",
"iteritems",
"(",
")"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/tools/build/src/build/feature.py#L120-L123 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/lib/nanfunctions.py | python | nanmin | (a, axis=None, out=None, keepdims=np._NoValue) | return res | Return minimum of an array or minimum along an axis, ignoring any NaNs.
When all-NaN slices are encountered a ``RuntimeWarning`` is raised and
Nan is returned for that slice.
Parameters
----------
a : array_like
Array containing numbers whose minimum is desired. If `a` is not an
array, a conversion is attempted.
axis : {int, tuple of int, None}, optional
Axis or axes along which the minimum is computed. The default is to compute
the minimum of the flattened array.
out : ndarray, optional
Alternate output array in which to place the result. The default
is ``None``; if provided, it must have the same shape as the
expected output, but the type will be cast if necessary. See
:ref:`ufuncs-output-type` for more details.
.. versionadded:: 1.8.0
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
If the value is anything but the default, then
`keepdims` will be passed through to the `min` method
of sub-classes of `ndarray`. If the sub-classes methods
does not implement `keepdims` any exceptions will be raised.
.. versionadded:: 1.8.0
Returns
-------
nanmin : ndarray
An array with the same shape as `a`, with the specified axis
removed. If `a` is a 0-d array, or if axis is None, an ndarray
scalar is returned. The same dtype as `a` is returned.
See Also
--------
nanmax :
The maximum value of an array along a given axis, ignoring any NaNs.
amin :
The minimum value of an array along a given axis, propagating any NaNs.
fmin :
Element-wise minimum of two arrays, ignoring any NaNs.
minimum :
Element-wise minimum of two arrays, propagating any NaNs.
isnan :
Shows which elements are Not a Number (NaN).
isfinite:
Shows which elements are neither NaN nor infinity.
amax, fmax, maximum
Notes
-----
NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754). This means that Not a Number is not equivalent to infinity.
Positive infinity is treated as a very large number and negative
infinity is treated as a very small (i.e. negative) number.
If the input has a integer type the function is equivalent to np.min.
Examples
--------
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nanmin(a)
1.0
>>> np.nanmin(a, axis=0)
array([1., 2.])
>>> np.nanmin(a, axis=1)
array([1., 3.])
When positive infinity and negative infinity are present:
>>> np.nanmin([1, 2, np.nan, np.inf])
1.0
>>> np.nanmin([1, 2, np.nan, np.NINF])
-inf | Return minimum of an array or minimum along an axis, ignoring any NaNs.
When all-NaN slices are encountered a ``RuntimeWarning`` is raised and
Nan is returned for that slice. | [
"Return",
"minimum",
"of",
"an",
"array",
"or",
"minimum",
"along",
"an",
"axis",
"ignoring",
"any",
"NaNs",
".",
"When",
"all",
"-",
"NaN",
"slices",
"are",
"encountered",
"a",
"RuntimeWarning",
"is",
"raised",
"and",
"Nan",
"is",
"returned",
"for",
"that",
"slice",
"."
] | def nanmin(a, axis=None, out=None, keepdims=np._NoValue):
"""
Return minimum of an array or minimum along an axis, ignoring any NaNs.
When all-NaN slices are encountered a ``RuntimeWarning`` is raised and
Nan is returned for that slice.
Parameters
----------
a : array_like
Array containing numbers whose minimum is desired. If `a` is not an
array, a conversion is attempted.
axis : {int, tuple of int, None}, optional
Axis or axes along which the minimum is computed. The default is to compute
the minimum of the flattened array.
out : ndarray, optional
Alternate output array in which to place the result. The default
is ``None``; if provided, it must have the same shape as the
expected output, but the type will be cast if necessary. See
:ref:`ufuncs-output-type` for more details.
.. versionadded:: 1.8.0
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
If the value is anything but the default, then
`keepdims` will be passed through to the `min` method
of sub-classes of `ndarray`. If the sub-classes methods
does not implement `keepdims` any exceptions will be raised.
.. versionadded:: 1.8.0
Returns
-------
nanmin : ndarray
An array with the same shape as `a`, with the specified axis
removed. If `a` is a 0-d array, or if axis is None, an ndarray
scalar is returned. The same dtype as `a` is returned.
See Also
--------
nanmax :
The maximum value of an array along a given axis, ignoring any NaNs.
amin :
The minimum value of an array along a given axis, propagating any NaNs.
fmin :
Element-wise minimum of two arrays, ignoring any NaNs.
minimum :
Element-wise minimum of two arrays, propagating any NaNs.
isnan :
Shows which elements are Not a Number (NaN).
isfinite:
Shows which elements are neither NaN nor infinity.
amax, fmax, maximum
Notes
-----
NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754). This means that Not a Number is not equivalent to infinity.
Positive infinity is treated as a very large number and negative
infinity is treated as a very small (i.e. negative) number.
If the input has a integer type the function is equivalent to np.min.
Examples
--------
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nanmin(a)
1.0
>>> np.nanmin(a, axis=0)
array([1., 2.])
>>> np.nanmin(a, axis=1)
array([1., 3.])
When positive infinity and negative infinity are present:
>>> np.nanmin([1, 2, np.nan, np.inf])
1.0
>>> np.nanmin([1, 2, np.nan, np.NINF])
-inf
"""
kwargs = {}
if keepdims is not np._NoValue:
kwargs['keepdims'] = keepdims
if type(a) is np.ndarray and a.dtype != np.object_:
# Fast, but not safe for subclasses of ndarray, or object arrays,
# which do not implement isnan (gh-9009), or fmin correctly (gh-8975)
res = np.fmin.reduce(a, axis=axis, out=out, **kwargs)
if np.isnan(res).any():
warnings.warn("All-NaN slice encountered", RuntimeWarning,
stacklevel=3)
else:
# Slow, but safe for subclasses of ndarray
a, mask = _replace_nan(a, +np.inf)
res = np.amin(a, axis=axis, out=out, **kwargs)
if mask is None:
return res
# Check for all-NaN axis
mask = np.all(mask, axis=axis, **kwargs)
if np.any(mask):
res = _copyto(res, np.nan, mask)
warnings.warn("All-NaN axis encountered", RuntimeWarning,
stacklevel=3)
return res | [
"def",
"nanmin",
"(",
"a",
",",
"axis",
"=",
"None",
",",
"out",
"=",
"None",
",",
"keepdims",
"=",
"np",
".",
"_NoValue",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"keepdims",
"is",
"not",
"np",
".",
"_NoValue",
":",
"kwargs",
"[",
"'keepdims'",
"]",
"=",
"keepdims",
"if",
"type",
"(",
"a",
")",
"is",
"np",
".",
"ndarray",
"and",
"a",
".",
"dtype",
"!=",
"np",
".",
"object_",
":",
"# Fast, but not safe for subclasses of ndarray, or object arrays,",
"# which do not implement isnan (gh-9009), or fmin correctly (gh-8975)",
"res",
"=",
"np",
".",
"fmin",
".",
"reduce",
"(",
"a",
",",
"axis",
"=",
"axis",
",",
"out",
"=",
"out",
",",
"*",
"*",
"kwargs",
")",
"if",
"np",
".",
"isnan",
"(",
"res",
")",
".",
"any",
"(",
")",
":",
"warnings",
".",
"warn",
"(",
"\"All-NaN slice encountered\"",
",",
"RuntimeWarning",
",",
"stacklevel",
"=",
"3",
")",
"else",
":",
"# Slow, but safe for subclasses of ndarray",
"a",
",",
"mask",
"=",
"_replace_nan",
"(",
"a",
",",
"+",
"np",
".",
"inf",
")",
"res",
"=",
"np",
".",
"amin",
"(",
"a",
",",
"axis",
"=",
"axis",
",",
"out",
"=",
"out",
",",
"*",
"*",
"kwargs",
")",
"if",
"mask",
"is",
"None",
":",
"return",
"res",
"# Check for all-NaN axis",
"mask",
"=",
"np",
".",
"all",
"(",
"mask",
",",
"axis",
"=",
"axis",
",",
"*",
"*",
"kwargs",
")",
"if",
"np",
".",
"any",
"(",
"mask",
")",
":",
"res",
"=",
"_copyto",
"(",
"res",
",",
"np",
".",
"nan",
",",
"mask",
")",
"warnings",
".",
"warn",
"(",
"\"All-NaN axis encountered\"",
",",
"RuntimeWarning",
",",
"stacklevel",
"=",
"3",
")",
"return",
"res"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/nanfunctions.py#L229-L336 | |
Cantera/cantera | 0119484b261967ccb55a0066c020599cacc312e4 | interfaces/cython/cantera/onedim.py | python | CounterflowPremixedFlame.__init__ | (self, gas, grid=None, width=None) | :param gas:
`Solution` (using the IdealGas thermodynamic model) used to
evaluate all gas properties and reaction rates.
:param grid:
Array of initial grid points. Not recommended unless solving only on
a fixed grid; Use the `width` parameter instead.
:param width:
Defines a grid on the interval [0, width] with internal points
determined automatically by the solver.
A domain of class `IdealGasFlow` named ``flame`` will be created to
represent the flame and set to axisymmetric stagnation flow. The three
domains comprising the stack are stored as ``self.reactants``,
``self.flame``, and ``self.products``. | :param gas:
`Solution` (using the IdealGas thermodynamic model) used to
evaluate all gas properties and reaction rates.
:param grid:
Array of initial grid points. Not recommended unless solving only on
a fixed grid; Use the `width` parameter instead.
:param width:
Defines a grid on the interval [0, width] with internal points
determined automatically by the solver. | [
":",
"param",
"gas",
":",
"Solution",
"(",
"using",
"the",
"IdealGas",
"thermodynamic",
"model",
")",
"used",
"to",
"evaluate",
"all",
"gas",
"properties",
"and",
"reaction",
"rates",
".",
":",
"param",
"grid",
":",
"Array",
"of",
"initial",
"grid",
"points",
".",
"Not",
"recommended",
"unless",
"solving",
"only",
"on",
"a",
"fixed",
"grid",
";",
"Use",
"the",
"width",
"parameter",
"instead",
".",
":",
"param",
"width",
":",
"Defines",
"a",
"grid",
"on",
"the",
"interval",
"[",
"0",
"width",
"]",
"with",
"internal",
"points",
"determined",
"automatically",
"by",
"the",
"solver",
"."
] | def __init__(self, gas, grid=None, width=None):
"""
:param gas:
`Solution` (using the IdealGas thermodynamic model) used to
evaluate all gas properties and reaction rates.
:param grid:
Array of initial grid points. Not recommended unless solving only on
a fixed grid; Use the `width` parameter instead.
:param width:
Defines a grid on the interval [0, width] with internal points
determined automatically by the solver.
A domain of class `IdealGasFlow` named ``flame`` will be created to
represent the flame and set to axisymmetric stagnation flow. The three
domains comprising the stack are stored as ``self.reactants``,
``self.flame``, and ``self.products``.
"""
self.reactants = Inlet1D(name='reactants', phase=gas)
self.reactants.T = gas.T
self.products = Inlet1D(name='products', phase=gas)
self.products.T = gas.T
self.flame = IdealGasFlow(gas, name='flame')
self.flame.set_axisymmetric_flow()
if width is not None:
# Create grid points aligned with initial guess profile
grid = np.array([0.0, 0.3, 0.5, 0.7, 1.0]) * width
super().__init__((self.reactants, self.flame, self.products), gas, grid)
# Setting X needs to be deferred until linked to the flow domain
self.reactants.X = gas.X | [
"def",
"__init__",
"(",
"self",
",",
"gas",
",",
"grid",
"=",
"None",
",",
"width",
"=",
"None",
")",
":",
"self",
".",
"reactants",
"=",
"Inlet1D",
"(",
"name",
"=",
"'reactants'",
",",
"phase",
"=",
"gas",
")",
"self",
".",
"reactants",
".",
"T",
"=",
"gas",
".",
"T",
"self",
".",
"products",
"=",
"Inlet1D",
"(",
"name",
"=",
"'products'",
",",
"phase",
"=",
"gas",
")",
"self",
".",
"products",
".",
"T",
"=",
"gas",
".",
"T",
"self",
".",
"flame",
"=",
"IdealGasFlow",
"(",
"gas",
",",
"name",
"=",
"'flame'",
")",
"self",
".",
"flame",
".",
"set_axisymmetric_flow",
"(",
")",
"if",
"width",
"is",
"not",
"None",
":",
"# Create grid points aligned with initial guess profile",
"grid",
"=",
"np",
".",
"array",
"(",
"[",
"0.0",
",",
"0.3",
",",
"0.5",
",",
"0.7",
",",
"1.0",
"]",
")",
"*",
"width",
"super",
"(",
")",
".",
"__init__",
"(",
"(",
"self",
".",
"reactants",
",",
"self",
".",
"flame",
",",
"self",
".",
"products",
")",
",",
"gas",
",",
"grid",
")",
"# Setting X needs to be deferred until linked to the flow domain",
"self",
".",
"reactants",
".",
"X",
"=",
"gas",
".",
"X"
] | https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/onedim.py#L1504-L1537 | ||
stan-dev/math | 5fd79f89933269a4ca4d8dd1fde2a36d53d4768c | lib/boost_1.75.0/tools/build/src/build/project.py | python | ProjectRegistry.target | (self, project_module) | return self.module2target[project_module] | Returns the project target corresponding to the 'project-module'. | Returns the project target corresponding to the 'project-module'. | [
"Returns",
"the",
"project",
"target",
"corresponding",
"to",
"the",
"project",
"-",
"module",
"."
] | def target(self, project_module):
"""Returns the project target corresponding to the 'project-module'."""
assert isinstance(project_module, basestring)
if project_module not in self.module2target:
self.module2target[project_module] = \
b2.build.targets.ProjectTarget(project_module, project_module,
self.attribute(project_module, "requirements"))
return self.module2target[project_module] | [
"def",
"target",
"(",
"self",
",",
"project_module",
")",
":",
"assert",
"isinstance",
"(",
"project_module",
",",
"basestring",
")",
"if",
"project_module",
"not",
"in",
"self",
".",
"module2target",
":",
"self",
".",
"module2target",
"[",
"project_module",
"]",
"=",
"b2",
".",
"build",
".",
"targets",
".",
"ProjectTarget",
"(",
"project_module",
",",
"project_module",
",",
"self",
".",
"attribute",
"(",
"project_module",
",",
"\"requirements\"",
")",
")",
"return",
"self",
".",
"module2target",
"[",
"project_module",
"]"
] | https://github.com/stan-dev/math/blob/5fd79f89933269a4ca4d8dd1fde2a36d53d4768c/lib/boost_1.75.0/tools/build/src/build/project.py#L611-L619 | |
hifiberry/hifiberry-os | 88c05213fb3e6230645cb4bf8eb8fceda8bd07d4 | buildroot/package/audiocontrol2/src/mpris.py | python | MPRISController.retrievePlayers | (self) | return [name for name in self.bus.list_names()
if name.startswith("org.mpris")] | Returns a list of all MPRIS enabled players that are active in
the system | Returns a list of all MPRIS enabled players that are active in
the system | [
"Returns",
"a",
"list",
"of",
"all",
"MPRIS",
"enabled",
"players",
"that",
"are",
"active",
"in",
"the",
"system"
] | def retrievePlayers(self):
"""
Returns a list of all MPRIS enabled players that are active in
the system
"""
return [name for name in self.bus.list_names()
if name.startswith("org.mpris")] | [
"def",
"retrievePlayers",
"(",
"self",
")",
":",
"return",
"[",
"name",
"for",
"name",
"in",
"self",
".",
"bus",
".",
"list_names",
"(",
")",
"if",
"name",
".",
"startswith",
"(",
"\"org.mpris\"",
")",
"]"
] | https://github.com/hifiberry/hifiberry-os/blob/88c05213fb3e6230645cb4bf8eb8fceda8bd07d4/buildroot/package/audiocontrol2/src/mpris.py#L70-L76 | |
nasa/trick | 7b85aa66329d62fe8816462627c09a353aac8299 | share/trick/trickops/WorkflowCommon.py | python | WorkflowCommon.execute_jobs | (self, jobs, max_concurrent=None, header=None) | return any(job.get_status() is not job.Status.SUCCESS for job in jobs) | Run jobs, blocking until all have returned.
Parameters
----------
jobs : iterable of Job
The jobs to run.
max_concurrent : int
The maximum number of jobs to execute simultaneously.
header : str
Header text.
Returns
-------
bool
True if any job failed or was not run.
False if all jobs completed successfully. | Run jobs, blocking until all have returned. | [
"Run",
"jobs",
"blocking",
"until",
"all",
"have",
"returned",
"."
] | def execute_jobs(self, jobs, max_concurrent=None, header=None):
"""
Run jobs, blocking until all have returned.
Parameters
----------
jobs : iterable of Job
The jobs to run.
max_concurrent : int
The maximum number of jobs to execute simultaneously.
header : str
Header text.
Returns
-------
bool
True if any job failed or was not run.
False if all jobs completed successfully.
"""
if not os.environ.get('TERM') and not self.quiet:
tprint(
'The TERM environment variable must be set when the command\n'
'line option --quiet is not used. This is usually set by one\n'
"of the shell's configuration files (.profile, .cshrc, etc).\n"
'However, if this was executed via a non-interactive,\n'
"non-login shell (for instance: ssh <machine> '<command>'), it\n"
'may not be automatically set.', 'DARK_RED')
return True
num_jobs = len(jobs)
if max_concurrent is None or max_concurrent < 1:
max_concurrent = num_jobs
if header:
header += '\n'
else:
header = ''
header += (
'Executing {0} total jobs, running up to {1} simultaneously.\n'
.format(num_jobs, max_concurrent) +
'Press CTRL+C to terminate early.\n')
logging.info(header)
# Define the meat of this function in an inner function.
# This inner function will be called via curses.wrapper if
# status output is enabled. Otherwise, it will be called
# directly. See below.
def execute(stdscr=None):
# stdscr is passed via curses.wrapper
if stdscr:
# Turn off the cursor. Not all terminals may support
# this.
try:
curses.curs_set(False)
except curses.error:
pass
# Configure colors. Not all terminals may support
# this.
try:
curses.start_color()
curses.use_default_colors()
curses.init_pair(1, curses.COLOR_RED, -1)
curses.init_pair(2, curses.COLOR_GREEN, -1)
use_colors = True
except curses.error:
use_colors = False
# Cause getch to be non-blocking. The arrow keys and
# mouse wheel are used to scroll the pad. We don't
# want to hang if the user doesn't type anything.
stdscr.timeout(0)
# Nothing will be displayed without an initial call
# to refresh.
stdscr.refresh()
# Create a pad for the header. It must have enough
# lines to contain all the content we intend to
# write. Text longer than the width wraps, consuming
# extra lines, so pick a realy big width that isn't
# likely to cause wrapping. We also need a final
# additional line for the cursor to end on.
header_pad = curses.newpad(header.count('\n') + 1, 1000)
header_pad.addstr(header)
# Create a pad for the status.
# The total line count is:
# all job status strings
# + a line for each job name
# + a blank line after each status string
# + a final line for the cursor to end on
status_pad = curses.newpad(
sum(job.get_status_string_line_count() for job in jobs) +
2 * len(jobs) + 1,
1000)
# The top visible status pad line.
# Used for scrolling.
top_line = 0
header_height = header_pad.getmaxyx()[0]
status_height = status_pad.getmaxyx()[0]
while any(job.get_status() in
[job.Status.NOT_STARTED, job.Status.RUNNING]
for job in jobs):
# Start waiting jobs if cpus are available
waitingJobs = [job for job in jobs
if job.get_status() is job.Status.NOT_STARTED]
if waitingJobs:
available_cpus = max_concurrent - sum(1 for job in jobs
if job.get_status() is job.Status.RUNNING)
for i in range(min(len(waitingJobs), available_cpus)):
waitingJobs[i].start()
# display the status if enabled
if stdscr:
status_pad.erase()
for i, job in enumerate(jobs):
# print the name
status_pad.addstr('Job {0:{width}d}/{1}: '.format(
i + 1, num_jobs, width=len(str(num_jobs))))
status_pad.addstr(job.name + '\n', curses.A_BOLD)
# print the status string
if use_colors:
# color the status string
status = job.get_status()
if status is job.Status.FAILED:
color = curses.color_pair(1)
elif status is job.Status.SUCCESS:
color = curses.color_pair(2)
else:
color = curses.color_pair(0)
status_pad.addstr(
job.get_status_string() + '\n\n', color)
else:
status_pad.addstr(
job.get_status_string() + '\n\n')
# handle scrolling
while True:
key = stdscr.getch()
if key == -1:
# no input
break
if key == curses.KEY_UP:
top_line -= 1
elif key == curses.KEY_DOWN:
top_line += 1
# prevent scrolling beyond the bounds of status_pad
screen_height, screen_width = stdscr.getmaxyx()
top_line = max(
0,
min(top_line,
status_height - 2 - (screen_height - header_height)))
# Resizing the terminal can cause the actual
# screen width or height to become smaller than
# what we already got from getmaxyx, resulting
# in a curses.error in these calls. Note that
# even calling getmaxyx again right here isn't
# fool-proof. Resizing is asynchronous (curses
# responds to it via a signal handler), so the
# size can always change between when we get it
# and when we use it. Best to just use what we
# have and ignore errors.
try:
header_pad.noutrefresh(
0, 0, 0, 0, screen_height - 1, screen_width - 1)
status_pad.noutrefresh(
top_line, 0, header_height, 0,
screen_height - 1, screen_width - 1)
except curses.error:
pass
curses.doupdate()
# take a nap
time.sleep(0.1)
# When done clear everything, without this subsequent calls
# to execute_jobs can show previous status bars if the number
# of jobs is less on the subsequent executions
if not self.quiet:
stdscr.clear()
try:
if not self.quiet:
# wrapper takes care of initializing the terminal and
# restores it to a useable state regardless of how
# execute exits (even via exception)
curses.wrapper(execute)
else:
# not using curses, just call execute
execute()
except BaseException as exception:
logging.exception('')
tprint(
'An exception occurred. See the log for details.\n\n'
' ' + repr(exception) + "\n\n"
'Terminating all jobs. Please wait for cleanup to finish. '
'CTRL+C may leave orphaned processes.', 'DARK_RED',
'ERROR')
# kill all the jobs
for job in jobs:
job.die()
tprint('All jobs terminated.\n', 'DARK_RED')
# print summary
summary = 'Job Summary\n'
for i, job in enumerate(jobs):
summary += 'Job {0:{width}d}/{1}: {2}\n{3}\n'.format(
i + 1, num_jobs, job.name, job.get_status_string(),
width=len(str(num_jobs)))
logging.info(summary)
for job in jobs:
text, color = {
job.Status.NOT_STARTED: ('was not run', 'GREY40'),
job.Status.SUCCESS: ('succeeded', 'DARK_GREEN'),
job.Status.FAILED: ('failed', 'DARK_RED')
}[job.get_status()]
text = job.name + ' ' + text
# Print the summary status even if self.quiet is True
tprint(text, color)
return any(job.get_status() is not job.Status.SUCCESS for job in jobs) | [
"def",
"execute_jobs",
"(",
"self",
",",
"jobs",
",",
"max_concurrent",
"=",
"None",
",",
"header",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"environ",
".",
"get",
"(",
"'TERM'",
")",
"and",
"not",
"self",
".",
"quiet",
":",
"tprint",
"(",
"'The TERM environment variable must be set when the command\\n'",
"'line option --quiet is not used. This is usually set by one\\n'",
"\"of the shell's configuration files (.profile, .cshrc, etc).\\n\"",
"'However, if this was executed via a non-interactive,\\n'",
"\"non-login shell (for instance: ssh <machine> '<command>'), it\\n\"",
"'may not be automatically set.'",
",",
"'DARK_RED'",
")",
"return",
"True",
"num_jobs",
"=",
"len",
"(",
"jobs",
")",
"if",
"max_concurrent",
"is",
"None",
"or",
"max_concurrent",
"<",
"1",
":",
"max_concurrent",
"=",
"num_jobs",
"if",
"header",
":",
"header",
"+=",
"'\\n'",
"else",
":",
"header",
"=",
"''",
"header",
"+=",
"(",
"'Executing {0} total jobs, running up to {1} simultaneously.\\n'",
".",
"format",
"(",
"num_jobs",
",",
"max_concurrent",
")",
"+",
"'Press CTRL+C to terminate early.\\n'",
")",
"logging",
".",
"info",
"(",
"header",
")",
"# Define the meat of this function in an inner function.",
"# This inner function will be called via curses.wrapper if",
"# status output is enabled. Otherwise, it will be called",
"# directly. See below.",
"def",
"execute",
"(",
"stdscr",
"=",
"None",
")",
":",
"# stdscr is passed via curses.wrapper",
"if",
"stdscr",
":",
"# Turn off the cursor. Not all terminals may support",
"# this.",
"try",
":",
"curses",
".",
"curs_set",
"(",
"False",
")",
"except",
"curses",
".",
"error",
":",
"pass",
"# Configure colors. Not all terminals may support",
"# this.",
"try",
":",
"curses",
".",
"start_color",
"(",
")",
"curses",
".",
"use_default_colors",
"(",
")",
"curses",
".",
"init_pair",
"(",
"1",
",",
"curses",
".",
"COLOR_RED",
",",
"-",
"1",
")",
"curses",
".",
"init_pair",
"(",
"2",
",",
"curses",
".",
"COLOR_GREEN",
",",
"-",
"1",
")",
"use_colors",
"=",
"True",
"except",
"curses",
".",
"error",
":",
"use_colors",
"=",
"False",
"# Cause getch to be non-blocking. The arrow keys and",
"# mouse wheel are used to scroll the pad. We don't",
"# want to hang if the user doesn't type anything.",
"stdscr",
".",
"timeout",
"(",
"0",
")",
"# Nothing will be displayed without an initial call",
"# to refresh.",
"stdscr",
".",
"refresh",
"(",
")",
"# Create a pad for the header. It must have enough",
"# lines to contain all the content we intend to",
"# write. Text longer than the width wraps, consuming",
"# extra lines, so pick a realy big width that isn't",
"# likely to cause wrapping. We also need a final",
"# additional line for the cursor to end on.",
"header_pad",
"=",
"curses",
".",
"newpad",
"(",
"header",
".",
"count",
"(",
"'\\n'",
")",
"+",
"1",
",",
"1000",
")",
"header_pad",
".",
"addstr",
"(",
"header",
")",
"# Create a pad for the status.",
"# The total line count is:",
"# all job status strings",
"# + a line for each job name",
"# + a blank line after each status string",
"# + a final line for the cursor to end on",
"status_pad",
"=",
"curses",
".",
"newpad",
"(",
"sum",
"(",
"job",
".",
"get_status_string_line_count",
"(",
")",
"for",
"job",
"in",
"jobs",
")",
"+",
"2",
"*",
"len",
"(",
"jobs",
")",
"+",
"1",
",",
"1000",
")",
"# The top visible status pad line.",
"# Used for scrolling.",
"top_line",
"=",
"0",
"header_height",
"=",
"header_pad",
".",
"getmaxyx",
"(",
")",
"[",
"0",
"]",
"status_height",
"=",
"status_pad",
".",
"getmaxyx",
"(",
")",
"[",
"0",
"]",
"while",
"any",
"(",
"job",
".",
"get_status",
"(",
")",
"in",
"[",
"job",
".",
"Status",
".",
"NOT_STARTED",
",",
"job",
".",
"Status",
".",
"RUNNING",
"]",
"for",
"job",
"in",
"jobs",
")",
":",
"# Start waiting jobs if cpus are available",
"waitingJobs",
"=",
"[",
"job",
"for",
"job",
"in",
"jobs",
"if",
"job",
".",
"get_status",
"(",
")",
"is",
"job",
".",
"Status",
".",
"NOT_STARTED",
"]",
"if",
"waitingJobs",
":",
"available_cpus",
"=",
"max_concurrent",
"-",
"sum",
"(",
"1",
"for",
"job",
"in",
"jobs",
"if",
"job",
".",
"get_status",
"(",
")",
"is",
"job",
".",
"Status",
".",
"RUNNING",
")",
"for",
"i",
"in",
"range",
"(",
"min",
"(",
"len",
"(",
"waitingJobs",
")",
",",
"available_cpus",
")",
")",
":",
"waitingJobs",
"[",
"i",
"]",
".",
"start",
"(",
")",
"# display the status if enabled",
"if",
"stdscr",
":",
"status_pad",
".",
"erase",
"(",
")",
"for",
"i",
",",
"job",
"in",
"enumerate",
"(",
"jobs",
")",
":",
"# print the name",
"status_pad",
".",
"addstr",
"(",
"'Job {0:{width}d}/{1}: '",
".",
"format",
"(",
"i",
"+",
"1",
",",
"num_jobs",
",",
"width",
"=",
"len",
"(",
"str",
"(",
"num_jobs",
")",
")",
")",
")",
"status_pad",
".",
"addstr",
"(",
"job",
".",
"name",
"+",
"'\\n'",
",",
"curses",
".",
"A_BOLD",
")",
"# print the status string",
"if",
"use_colors",
":",
"# color the status string",
"status",
"=",
"job",
".",
"get_status",
"(",
")",
"if",
"status",
"is",
"job",
".",
"Status",
".",
"FAILED",
":",
"color",
"=",
"curses",
".",
"color_pair",
"(",
"1",
")",
"elif",
"status",
"is",
"job",
".",
"Status",
".",
"SUCCESS",
":",
"color",
"=",
"curses",
".",
"color_pair",
"(",
"2",
")",
"else",
":",
"color",
"=",
"curses",
".",
"color_pair",
"(",
"0",
")",
"status_pad",
".",
"addstr",
"(",
"job",
".",
"get_status_string",
"(",
")",
"+",
"'\\n\\n'",
",",
"color",
")",
"else",
":",
"status_pad",
".",
"addstr",
"(",
"job",
".",
"get_status_string",
"(",
")",
"+",
"'\\n\\n'",
")",
"# handle scrolling",
"while",
"True",
":",
"key",
"=",
"stdscr",
".",
"getch",
"(",
")",
"if",
"key",
"==",
"-",
"1",
":",
"# no input",
"break",
"if",
"key",
"==",
"curses",
".",
"KEY_UP",
":",
"top_line",
"-=",
"1",
"elif",
"key",
"==",
"curses",
".",
"KEY_DOWN",
":",
"top_line",
"+=",
"1",
"# prevent scrolling beyond the bounds of status_pad",
"screen_height",
",",
"screen_width",
"=",
"stdscr",
".",
"getmaxyx",
"(",
")",
"top_line",
"=",
"max",
"(",
"0",
",",
"min",
"(",
"top_line",
",",
"status_height",
"-",
"2",
"-",
"(",
"screen_height",
"-",
"header_height",
")",
")",
")",
"# Resizing the terminal can cause the actual",
"# screen width or height to become smaller than",
"# what we already got from getmaxyx, resulting",
"# in a curses.error in these calls. Note that",
"# even calling getmaxyx again right here isn't",
"# fool-proof. Resizing is asynchronous (curses",
"# responds to it via a signal handler), so the",
"# size can always change between when we get it",
"# and when we use it. Best to just use what we",
"# have and ignore errors.",
"try",
":",
"header_pad",
".",
"noutrefresh",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"screen_height",
"-",
"1",
",",
"screen_width",
"-",
"1",
")",
"status_pad",
".",
"noutrefresh",
"(",
"top_line",
",",
"0",
",",
"header_height",
",",
"0",
",",
"screen_height",
"-",
"1",
",",
"screen_width",
"-",
"1",
")",
"except",
"curses",
".",
"error",
":",
"pass",
"curses",
".",
"doupdate",
"(",
")",
"# take a nap",
"time",
".",
"sleep",
"(",
"0.1",
")",
"# When done clear everything, without this subsequent calls",
"# to execute_jobs can show previous status bars if the number",
"# of jobs is less on the subsequent executions",
"if",
"not",
"self",
".",
"quiet",
":",
"stdscr",
".",
"clear",
"(",
")",
"try",
":",
"if",
"not",
"self",
".",
"quiet",
":",
"# wrapper takes care of initializing the terminal and",
"# restores it to a useable state regardless of how",
"# execute exits (even via exception)",
"curses",
".",
"wrapper",
"(",
"execute",
")",
"else",
":",
"# not using curses, just call execute",
"execute",
"(",
")",
"except",
"BaseException",
"as",
"exception",
":",
"logging",
".",
"exception",
"(",
"''",
")",
"tprint",
"(",
"'An exception occurred. See the log for details.\\n\\n'",
"' '",
"+",
"repr",
"(",
"exception",
")",
"+",
"\"\\n\\n\"",
"'Terminating all jobs. Please wait for cleanup to finish. '",
"'CTRL+C may leave orphaned processes.'",
",",
"'DARK_RED'",
",",
"'ERROR'",
")",
"# kill all the jobs",
"for",
"job",
"in",
"jobs",
":",
"job",
".",
"die",
"(",
")",
"tprint",
"(",
"'All jobs terminated.\\n'",
",",
"'DARK_RED'",
")",
"# print summary",
"summary",
"=",
"'Job Summary\\n'",
"for",
"i",
",",
"job",
"in",
"enumerate",
"(",
"jobs",
")",
":",
"summary",
"+=",
"'Job {0:{width}d}/{1}: {2}\\n{3}\\n'",
".",
"format",
"(",
"i",
"+",
"1",
",",
"num_jobs",
",",
"job",
".",
"name",
",",
"job",
".",
"get_status_string",
"(",
")",
",",
"width",
"=",
"len",
"(",
"str",
"(",
"num_jobs",
")",
")",
")",
"logging",
".",
"info",
"(",
"summary",
")",
"for",
"job",
"in",
"jobs",
":",
"text",
",",
"color",
"=",
"{",
"job",
".",
"Status",
".",
"NOT_STARTED",
":",
"(",
"'was not run'",
",",
"'GREY40'",
")",
",",
"job",
".",
"Status",
".",
"SUCCESS",
":",
"(",
"'succeeded'",
",",
"'DARK_GREEN'",
")",
",",
"job",
".",
"Status",
".",
"FAILED",
":",
"(",
"'failed'",
",",
"'DARK_RED'",
")",
"}",
"[",
"job",
".",
"get_status",
"(",
")",
"]",
"text",
"=",
"job",
".",
"name",
"+",
"' '",
"+",
"text",
"# Print the summary status even if self.quiet is True",
"tprint",
"(",
"text",
",",
"color",
")",
"return",
"any",
"(",
"job",
".",
"get_status",
"(",
")",
"is",
"not",
"job",
".",
"Status",
".",
"SUCCESS",
"for",
"job",
"in",
"jobs",
")"
] | https://github.com/nasa/trick/blob/7b85aa66329d62fe8816462627c09a353aac8299/share/trick/trickops/WorkflowCommon.py#L574-L811 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/adapters.py | python | HTTPAdapter.init_poolmanager | (self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs) | Initializes a urllib3 PoolManager.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param connections: The number of urllib3 connection pools to cache.
:param maxsize: The maximum number of connections to save in the pool.
:param block: Block when no free connections are available.
:param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager. | Initializes a urllib3 PoolManager. | [
"Initializes",
"a",
"urllib3",
"PoolManager",
"."
] | def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
"""Initializes a urllib3 PoolManager.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param connections: The number of urllib3 connection pools to cache.
:param maxsize: The maximum number of connections to save in the pool.
:param block: Block when no free connections are available.
:param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
"""
# save these values for pickling
self._pool_connections = connections
self._pool_maxsize = maxsize
self._pool_block = block
self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize,
block=block, strict=True, **pool_kwargs) | [
"def",
"init_poolmanager",
"(",
"self",
",",
"connections",
",",
"maxsize",
",",
"block",
"=",
"DEFAULT_POOLBLOCK",
",",
"*",
"*",
"pool_kwargs",
")",
":",
"# save these values for pickling",
"self",
".",
"_pool_connections",
"=",
"connections",
"self",
".",
"_pool_maxsize",
"=",
"maxsize",
"self",
".",
"_pool_block",
"=",
"block",
"self",
".",
"poolmanager",
"=",
"PoolManager",
"(",
"num_pools",
"=",
"connections",
",",
"maxsize",
"=",
"maxsize",
",",
"block",
"=",
"block",
",",
"strict",
"=",
"True",
",",
"*",
"*",
"pool_kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/adapters.py#L146-L164 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/Inelastic/CrystalField/fitting.py | python | CrystalField.getSpectrum | (self, i=0, workspace=None, ws_index=0) | return self._calcSpectrum(i, wksp, 0) | Get the i-th spectrum calculated with the current field and peak parameters.
Alternatively can be called getSpectrum(workspace, ws_index). Spectrum index i is assumed zero.
Examples:
cf.getSpectrum() # Return the first spectrum calculated on a generated set of x-values.
cf.getSpectrum(1, ws, 5) # Calculate the second spectrum using the x-values from the 6th spectrum
# in workspace ws.
cf.getSpectrum(ws) # Calculate the first spectrum using the x-values from the 1st spectrum
# in workspace ws.
cf.getSpectrum(ws, 3) # Calculate the first spectrum using the x-values from the 4th spectrum
# in workspace ws.
@param i: Index of a spectrum to get.
@param workspace: A workspace to base on. If not given the x-values of the output spectrum will be
generated.
@param ws_index: An index of a spectrum from workspace to use.
@return: A tuple of (x, y) arrays | Get the i-th spectrum calculated with the current field and peak parameters. | [
"Get",
"the",
"i",
"-",
"th",
"spectrum",
"calculated",
"with",
"the",
"current",
"field",
"and",
"peak",
"parameters",
"."
] | def getSpectrum(self, i=0, workspace=None, ws_index=0):
"""
Get the i-th spectrum calculated with the current field and peak parameters.
Alternatively can be called getSpectrum(workspace, ws_index). Spectrum index i is assumed zero.
Examples:
cf.getSpectrum() # Return the first spectrum calculated on a generated set of x-values.
cf.getSpectrum(1, ws, 5) # Calculate the second spectrum using the x-values from the 6th spectrum
# in workspace ws.
cf.getSpectrum(ws) # Calculate the first spectrum using the x-values from the 1st spectrum
# in workspace ws.
cf.getSpectrum(ws, 3) # Calculate the first spectrum using the x-values from the 4th spectrum
# in workspace ws.
@param i: Index of a spectrum to get.
@param workspace: A workspace to base on. If not given the x-values of the output spectrum will be
generated.
@param ws_index: An index of a spectrum from workspace to use.
@return: A tuple of (x, y) arrays
"""
wksp = workspace
# Allow to call getSpectrum with a workspace as the first argument.
if not isinstance(i, int):
if wksp is not None:
if not isinstance(wksp, int):
raise RuntimeError('Spectrum index is expected to be int. Got %s' % i.__class__.__name__)
ws_index = wksp
wksp = i
i = 0
if (self.Temperature[i] if islistlike(self.Temperature) else self.Temperature) < 0:
raise RuntimeError('You must first define a temperature for the spectrum')
# Workspace is given, always calculate
if wksp is None:
xArray = None
elif isinstance(wksp, list) or isinstance(wksp, np.ndarray):
xArray = wksp
else:
return self._calcSpectrum(i, wksp, ws_index)
if xArray is None:
x_min, x_max = self.calc_xmin_xmax(i)
xArray = np.linspace(x_min, x_max, self.default_spectrum_size)
yArray = np.zeros_like(xArray)
wksp = makeWorkspace(xArray, yArray)
return self._calcSpectrum(i, wksp, 0) | [
"def",
"getSpectrum",
"(",
"self",
",",
"i",
"=",
"0",
",",
"workspace",
"=",
"None",
",",
"ws_index",
"=",
"0",
")",
":",
"wksp",
"=",
"workspace",
"# Allow to call getSpectrum with a workspace as the first argument.",
"if",
"not",
"isinstance",
"(",
"i",
",",
"int",
")",
":",
"if",
"wksp",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"wksp",
",",
"int",
")",
":",
"raise",
"RuntimeError",
"(",
"'Spectrum index is expected to be int. Got %s'",
"%",
"i",
".",
"__class__",
".",
"__name__",
")",
"ws_index",
"=",
"wksp",
"wksp",
"=",
"i",
"i",
"=",
"0",
"if",
"(",
"self",
".",
"Temperature",
"[",
"i",
"]",
"if",
"islistlike",
"(",
"self",
".",
"Temperature",
")",
"else",
"self",
".",
"Temperature",
")",
"<",
"0",
":",
"raise",
"RuntimeError",
"(",
"'You must first define a temperature for the spectrum'",
")",
"# Workspace is given, always calculate",
"if",
"wksp",
"is",
"None",
":",
"xArray",
"=",
"None",
"elif",
"isinstance",
"(",
"wksp",
",",
"list",
")",
"or",
"isinstance",
"(",
"wksp",
",",
"np",
".",
"ndarray",
")",
":",
"xArray",
"=",
"wksp",
"else",
":",
"return",
"self",
".",
"_calcSpectrum",
"(",
"i",
",",
"wksp",
",",
"ws_index",
")",
"if",
"xArray",
"is",
"None",
":",
"x_min",
",",
"x_max",
"=",
"self",
".",
"calc_xmin_xmax",
"(",
"i",
")",
"xArray",
"=",
"np",
".",
"linspace",
"(",
"x_min",
",",
"x_max",
",",
"self",
".",
"default_spectrum_size",
")",
"yArray",
"=",
"np",
".",
"zeros_like",
"(",
"xArray",
")",
"wksp",
"=",
"makeWorkspace",
"(",
"xArray",
",",
"yArray",
")",
"return",
"self",
".",
"_calcSpectrum",
"(",
"i",
",",
"wksp",
",",
"0",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/CrystalField/fitting.py#L718-L767 | |
apache/mesos | 97d9a4063332aae3825d78de71611657e05cf5e2 | src/python/interface/src/mesos/interface/__init__.py | python | SchedulerDriver.join | (self) | Waits for the driver to be stopped or aborted, possibly blocking the
current thread indefinitely. The return status of this function can
be used to determine if the driver was aborted (see mesos.proto for a
description of Status). | Waits for the driver to be stopped or aborted, possibly blocking the
current thread indefinitely. The return status of this function can
be used to determine if the driver was aborted (see mesos.proto for a
description of Status). | [
"Waits",
"for",
"the",
"driver",
"to",
"be",
"stopped",
"or",
"aborted",
"possibly",
"blocking",
"the",
"current",
"thread",
"indefinitely",
".",
"The",
"return",
"status",
"of",
"this",
"function",
"can",
"be",
"used",
"to",
"determine",
"if",
"the",
"driver",
"was",
"aborted",
"(",
"see",
"mesos",
".",
"proto",
"for",
"a",
"description",
"of",
"Status",
")",
"."
] | def join(self):
"""
Waits for the driver to be stopped or aborted, possibly blocking the
current thread indefinitely. The return status of this function can
be used to determine if the driver was aborted (see mesos.proto for a
description of Status).
""" | [
"def",
"join",
"(",
"self",
")",
":"
] | https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/src/python/interface/src/mesos/interface/__init__.py#L171-L177 | ||
Komnomnomnom/swigibpy | cfd307fdbfaffabc69a2dc037538d7e34a8b8daf | swigibpy.py | python | EClient.calculateImpliedVolatility | (self, reqId, contract, optionPrice, underPrice) | return _swigibpy.EClient_calculateImpliedVolatility(self, reqId, contract, optionPrice, underPrice) | calculateImpliedVolatility(EClient self, TickerId reqId, Contract contract, double optionPrice, double underPrice) | calculateImpliedVolatility(EClient self, TickerId reqId, Contract contract, double optionPrice, double underPrice) | [
"calculateImpliedVolatility",
"(",
"EClient",
"self",
"TickerId",
"reqId",
"Contract",
"contract",
"double",
"optionPrice",
"double",
"underPrice",
")"
] | def calculateImpliedVolatility(self, reqId, contract, optionPrice, underPrice):
"""calculateImpliedVolatility(EClient self, TickerId reqId, Contract contract, double optionPrice, double underPrice)"""
return _swigibpy.EClient_calculateImpliedVolatility(self, reqId, contract, optionPrice, underPrice) | [
"def",
"calculateImpliedVolatility",
"(",
"self",
",",
"reqId",
",",
"contract",
",",
"optionPrice",
",",
"underPrice",
")",
":",
"return",
"_swigibpy",
".",
"EClient_calculateImpliedVolatility",
"(",
"self",
",",
"reqId",
",",
"contract",
",",
"optionPrice",
",",
"underPrice",
")"
] | https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L1270-L1272 | |
fengbingchun/NN_Test | d6305825d5273e4569ccd1eda9ffa2a9c72e18d2 | src/tiny-dnn/third_party/cpplint.py | python | CheckIncludeLine | (filename, clean_lines, linenum, include_state, error) | Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found. | Check rules that are applicable to #include lines. | [
"Check",
"rules",
"that",
"are",
"applicable",
"to",
"#include",
"lines",
"."
] | def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
"""Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found.
"""
fileinfo = FileInfo(filename)
line = clean_lines.lines[linenum]
# "include" should use the new style "foo/bar.h" instead of just "bar.h"
# Only do this check if the included header follows google naming
# conventions. If not, assume that it's a 3rd party API that
# requires special include conventions.
#
# We also make an exception for Lua headers, which follow google
# naming convention but not the include convention.
match = Match(r'#include\s*"([^/]+\.h)"', line)
if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
error(filename, linenum, 'build/include_subdir', 4,
'Include the directory when naming .h files')
# we shouldn't include a file more than once. actually, there are a
# handful of instances where doing so is okay, but in general it's
# not.
match = _RE_PATTERN_INCLUDE.search(line)
if match:
include = match.group(2)
is_system = (match.group(1) == '<')
duplicate_line = include_state.FindHeader(include)
if duplicate_line >= 0:
error(filename, linenum, 'build/include', 4,
'"%s" already included at %s:%s' %
(include, filename, duplicate_line))
return
for extension in GetNonHeaderExtensions():
if (include.endswith('.' + extension) and
os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
error(filename, linenum, 'build/include', 4,
'Do not include .' + extension + ' files from other packages')
return
if not _THIRD_PARTY_HEADERS_PATTERN.match(include):
include_state.include_list[-1].append((include, linenum))
# We want to ensure that headers appear in the right order:
# 1) for foo.cc, foo.h (preferred location)
# 2) c system files
# 3) cpp system files
# 4) for foo.cc, foo.h (deprecated location)
# 5) other google headers
#
# We classify each include statement as one of those 5 types
# using a number of techniques. The include_state object keeps
# track of the highest type seen, and complains if we see a
# lower type after that.
error_message = include_state.CheckNextIncludeOrder(
_ClassifyInclude(fileinfo, include, is_system))
if error_message:
error(filename, linenum, 'build/include_order', 4,
'%s. Should be: %s.h, c system, c++ system, other.' %
(error_message, fileinfo.BaseName()))
canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
if not include_state.IsInAlphabeticalOrder(
clean_lines, linenum, canonical_include):
error(filename, linenum, 'build/include_alpha', 4,
'Include "%s" not in alphabetical order' % include)
include_state.SetLastHeader(canonical_include) | [
"def",
"CheckIncludeLine",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"include_state",
",",
"error",
")",
":",
"fileinfo",
"=",
"FileInfo",
"(",
"filename",
")",
"line",
"=",
"clean_lines",
".",
"lines",
"[",
"linenum",
"]",
"# \"include\" should use the new style \"foo/bar.h\" instead of just \"bar.h\"",
"# Only do this check if the included header follows google naming",
"# conventions. If not, assume that it's a 3rd party API that",
"# requires special include conventions.",
"#",
"# We also make an exception for Lua headers, which follow google",
"# naming convention but not the include convention.",
"match",
"=",
"Match",
"(",
"r'#include\\s*\"([^/]+\\.h)\"'",
",",
"line",
")",
"if",
"match",
"and",
"not",
"_THIRD_PARTY_HEADERS_PATTERN",
".",
"match",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include_subdir'",
",",
"4",
",",
"'Include the directory when naming .h files'",
")",
"# we shouldn't include a file more than once. actually, there are a",
"# handful of instances where doing so is okay, but in general it's",
"# not.",
"match",
"=",
"_RE_PATTERN_INCLUDE",
".",
"search",
"(",
"line",
")",
"if",
"match",
":",
"include",
"=",
"match",
".",
"group",
"(",
"2",
")",
"is_system",
"=",
"(",
"match",
".",
"group",
"(",
"1",
")",
"==",
"'<'",
")",
"duplicate_line",
"=",
"include_state",
".",
"FindHeader",
"(",
"include",
")",
"if",
"duplicate_line",
">=",
"0",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include'",
",",
"4",
",",
"'\"%s\" already included at %s:%s'",
"%",
"(",
"include",
",",
"filename",
",",
"duplicate_line",
")",
")",
"return",
"for",
"extension",
"in",
"GetNonHeaderExtensions",
"(",
")",
":",
"if",
"(",
"include",
".",
"endswith",
"(",
"'.'",
"+",
"extension",
")",
"and",
"os",
".",
"path",
".",
"dirname",
"(",
"fileinfo",
".",
"RepositoryName",
"(",
")",
")",
"!=",
"os",
".",
"path",
".",
"dirname",
"(",
"include",
")",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include'",
",",
"4",
",",
"'Do not include .'",
"+",
"extension",
"+",
"' files from other packages'",
")",
"return",
"if",
"not",
"_THIRD_PARTY_HEADERS_PATTERN",
".",
"match",
"(",
"include",
")",
":",
"include_state",
".",
"include_list",
"[",
"-",
"1",
"]",
".",
"append",
"(",
"(",
"include",
",",
"linenum",
")",
")",
"# We want to ensure that headers appear in the right order:",
"# 1) for foo.cc, foo.h (preferred location)",
"# 2) c system files",
"# 3) cpp system files",
"# 4) for foo.cc, foo.h (deprecated location)",
"# 5) other google headers",
"#",
"# We classify each include statement as one of those 5 types",
"# using a number of techniques. The include_state object keeps",
"# track of the highest type seen, and complains if we see a",
"# lower type after that.",
"error_message",
"=",
"include_state",
".",
"CheckNextIncludeOrder",
"(",
"_ClassifyInclude",
"(",
"fileinfo",
",",
"include",
",",
"is_system",
")",
")",
"if",
"error_message",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include_order'",
",",
"4",
",",
"'%s. Should be: %s.h, c system, c++ system, other.'",
"%",
"(",
"error_message",
",",
"fileinfo",
".",
"BaseName",
"(",
")",
")",
")",
"canonical_include",
"=",
"include_state",
".",
"CanonicalizeAlphabeticalOrder",
"(",
"include",
")",
"if",
"not",
"include_state",
".",
"IsInAlphabeticalOrder",
"(",
"clean_lines",
",",
"linenum",
",",
"canonical_include",
")",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/include_alpha'",
",",
"4",
",",
"'Include \"%s\" not in alphabetical order'",
"%",
"include",
")",
"include_state",
".",
"SetLastHeader",
"(",
"canonical_include",
")"
] | https://github.com/fengbingchun/NN_Test/blob/d6305825d5273e4569ccd1eda9ffa2a9c72e18d2/src/tiny-dnn/third_party/cpplint.py#L4673-L4748 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/utils.py | python | _parse_content_type_header | (header) | return content_type, params_dict | Returns content type and parameters from given header
:param header: string
:return: tuple containing content type and dictionary of
parameters | Returns content type and parameters from given header | [
"Returns",
"content",
"type",
"and",
"parameters",
"from",
"given",
"header"
] | def _parse_content_type_header(header):
"""Returns content type and parameters from given header
:param header: string
:return: tuple containing content type and dictionary of
parameters
"""
tokens = header.split(';')
content_type, params = tokens[0].strip(), tokens[1:]
params_dict = {}
items_to_strip = "\"' "
for param in params:
param = param.strip()
if param:
key, value = param, True
index_of_equals = param.find("=")
if index_of_equals != -1:
key = param[:index_of_equals].strip(items_to_strip)
value = param[index_of_equals + 1:].strip(items_to_strip)
params_dict[key.lower()] = value
return content_type, params_dict | [
"def",
"_parse_content_type_header",
"(",
"header",
")",
":",
"tokens",
"=",
"header",
".",
"split",
"(",
"';'",
")",
"content_type",
",",
"params",
"=",
"tokens",
"[",
"0",
"]",
".",
"strip",
"(",
")",
",",
"tokens",
"[",
"1",
":",
"]",
"params_dict",
"=",
"{",
"}",
"items_to_strip",
"=",
"\"\\\"' \"",
"for",
"param",
"in",
"params",
":",
"param",
"=",
"param",
".",
"strip",
"(",
")",
"if",
"param",
":",
"key",
",",
"value",
"=",
"param",
",",
"True",
"index_of_equals",
"=",
"param",
".",
"find",
"(",
"\"=\"",
")",
"if",
"index_of_equals",
"!=",
"-",
"1",
":",
"key",
"=",
"param",
"[",
":",
"index_of_equals",
"]",
".",
"strip",
"(",
"items_to_strip",
")",
"value",
"=",
"param",
"[",
"index_of_equals",
"+",
"1",
":",
"]",
".",
"strip",
"(",
"items_to_strip",
")",
"params_dict",
"[",
"key",
".",
"lower",
"(",
")",
"]",
"=",
"value",
"return",
"content_type",
",",
"params_dict"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/requests/utils.py#L921-L965 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/propgrid.py | python | PropertyGridEvent.CanVeto | (*args, **kwargs) | return _propgrid.PropertyGridEvent_CanVeto(*args, **kwargs) | CanVeto(self) -> bool | CanVeto(self) -> bool | [
"CanVeto",
"(",
"self",
")",
"-",
">",
"bool"
] | def CanVeto(*args, **kwargs):
"""CanVeto(self) -> bool"""
return _propgrid.PropertyGridEvent_CanVeto(*args, **kwargs) | [
"def",
"CanVeto",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridEvent_CanVeto",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L2525-L2527 | |
priyankchheda/algorithms | c361aa9071573fa9966d5b02d05e524815abcf2b | linked_list/library/circular_linked_list.py | python | CircularLinkedList.print | (self) | prints entire linked list without changing underlying data | prints entire linked list without changing underlying data | [
"prints",
"entire",
"linked",
"list",
"without",
"changing",
"underlying",
"data"
] | def print(self):
""" prints entire linked list without changing underlying data """
current = self.head
while current is not None:
print(" ->", current.data, end="")
current = current.next
if current == self.head:
break
print(end=" -> ...")
print() | [
"def",
"print",
"(",
"self",
")",
":",
"current",
"=",
"self",
".",
"head",
"while",
"current",
"is",
"not",
"None",
":",
"print",
"(",
"\" ->\"",
",",
"current",
".",
"data",
",",
"end",
"=",
"\"\"",
")",
"current",
"=",
"current",
".",
"next",
"if",
"current",
"==",
"self",
".",
"head",
":",
"break",
"print",
"(",
"end",
"=",
"\" -> ...\"",
")",
"print",
"(",
")"
] | https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/linked_list/library/circular_linked_list.py#L83-L92 | ||
pyne/pyne | 0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3 | pyne/xs/data_source.py | python | DataSource.discretize | (self, nuc, rx, temp=300.0, src_phi_g=None, dst_phi_g=None) | return dst_sigma | Discretizes the reaction channel from the source group structure to that
of the destination weighted by the group fluxes. This implemenation is only
valid for multi-group data sources. Non-multigroup data source should also
override this method.
Parameters
----------
nuc : int or str
A nuclide.
rx : int or str
Reaction id or name.
temp : float, optional
Temperature [K] of material, defaults to 300.0.
src_phi_g : array-like, optional
Group fluxes for this data source, length src_ngroups.
dst_phi_g : array-like, optional
Group fluxes for the destiniation structure, length dst_ngroups.
Returns
-------
dst_sigma : ndarray
Destination cross section data, length dst_ngroups. | Discretizes the reaction channel from the source group structure to that
of the destination weighted by the group fluxes. This implemenation is only
valid for multi-group data sources. Non-multigroup data source should also
override this method. | [
"Discretizes",
"the",
"reaction",
"channel",
"from",
"the",
"source",
"group",
"structure",
"to",
"that",
"of",
"the",
"destination",
"weighted",
"by",
"the",
"group",
"fluxes",
".",
"This",
"implemenation",
"is",
"only",
"valid",
"for",
"multi",
"-",
"group",
"data",
"sources",
".",
"Non",
"-",
"multigroup",
"data",
"source",
"should",
"also",
"override",
"this",
"method",
"."
] | def discretize(self, nuc, rx, temp=300.0, src_phi_g=None, dst_phi_g=None):
"""Discretizes the reaction channel from the source group structure to that
of the destination weighted by the group fluxes. This implemenation is only
valid for multi-group data sources. Non-multigroup data source should also
override this method.
Parameters
----------
nuc : int or str
A nuclide.
rx : int or str
Reaction id or name.
temp : float, optional
Temperature [K] of material, defaults to 300.0.
src_phi_g : array-like, optional
Group fluxes for this data source, length src_ngroups.
dst_phi_g : array-like, optional
Group fluxes for the destiniation structure, length dst_ngroups.
Returns
-------
dst_sigma : ndarray
Destination cross section data, length dst_ngroups.
"""
src_phi_g = self.src_phi_g if src_phi_g is None else np.asarray(src_phi_g)
src_sigma = self.reaction(nuc, rx, temp)
dst_sigma = None if src_sigma is None else group_collapse(src_sigma,
src_phi_g, dst_phi_g,
self._src_to_dst_matrix)
return dst_sigma | [
"def",
"discretize",
"(",
"self",
",",
"nuc",
",",
"rx",
",",
"temp",
"=",
"300.0",
",",
"src_phi_g",
"=",
"None",
",",
"dst_phi_g",
"=",
"None",
")",
":",
"src_phi_g",
"=",
"self",
".",
"src_phi_g",
"if",
"src_phi_g",
"is",
"None",
"else",
"np",
".",
"asarray",
"(",
"src_phi_g",
")",
"src_sigma",
"=",
"self",
".",
"reaction",
"(",
"nuc",
",",
"rx",
",",
"temp",
")",
"dst_sigma",
"=",
"None",
"if",
"src_sigma",
"is",
"None",
"else",
"group_collapse",
"(",
"src_sigma",
",",
"src_phi_g",
",",
"dst_phi_g",
",",
"self",
".",
"_src_to_dst_matrix",
")",
"return",
"dst_sigma"
] | https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/xs/data_source.py#L194-L224 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/seacas/scripts/exodus3.in.py | python | exodus.get_variable_values | (self, objType, entityId, name, step) | return values | get list of `objType` variable values for a specified object id
block, variable name, and time step
>>> evar_vals = exo.get_variable_values('EX_ELEM_BLOCK', elem_blk_id,
... evar_name, time_step)
Parameters
----------
objType : ex_entity_type
type of object being queried
entityId : int
id of the entity (block, set) *ID* (not *INDEX*)
name : string
name of variable
time_step : int
1-based index of time step
Returns
-------
if array_type == 'ctype':
<list<ctypes.c_double>> evar_vals
if array_type == 'numpy':
<np_array<double>> evar_vals | get list of `objType` variable values for a specified object id
block, variable name, and time step | [
"get",
"list",
"of",
"objType",
"variable",
"values",
"for",
"a",
"specified",
"object",
"id",
"block",
"variable",
"name",
"and",
"time",
"step"
] | def get_variable_values(self, objType, entityId, name, step):
"""
get list of `objType` variable values for a specified object id
block, variable name, and time step
>>> evar_vals = exo.get_variable_values('EX_ELEM_BLOCK', elem_blk_id,
... evar_name, time_step)
Parameters
----------
objType : ex_entity_type
type of object being queried
entityId : int
id of the entity (block, set) *ID* (not *INDEX*)
name : string
name of variable
time_step : int
1-based index of time step
Returns
-------
if array_type == 'ctype':
<list<ctypes.c_double>> evar_vals
if array_type == 'numpy':
<np_array<double>> evar_vals
"""
names = self.get_variable_names(objType)
var_id = names.index(name) + 1
numVals = 0
if objType == 'EX_NODAL':
numVals = self.num_nodes()
elif objType == 'EX_ELEM_BLOCK':
numVals = self.num_elems_in_blk(entityId)
elif objType == 'EX_NODE_SET':
(numVals, _numDistFactInSet) = self.__ex_get_set_param(objType, entityId)
elif objType == 'EX_EDGE_SET':
(numVals, _numDistFactInSet) = self.__ex_get_set_param(objType, entityId)
elif objType == 'EX_FACE_SET':
(numVals, _numDistFactInSet) = self.__ex_get_set_param(objType, entityId)
elif objType == 'EX_SIDE_SET':
(numVals, _numDistFactInSet) = self.__ex_get_set_param(objType, entityId)
values = self.__ex_get_var(step, objType, var_id, entityId, numVals)
if self.use_numpy:
values = ctype_to_numpy(self, values)
return values | [
"def",
"get_variable_values",
"(",
"self",
",",
"objType",
",",
"entityId",
",",
"name",
",",
"step",
")",
":",
"names",
"=",
"self",
".",
"get_variable_names",
"(",
"objType",
")",
"var_id",
"=",
"names",
".",
"index",
"(",
"name",
")",
"+",
"1",
"numVals",
"=",
"0",
"if",
"objType",
"==",
"'EX_NODAL'",
":",
"numVals",
"=",
"self",
".",
"num_nodes",
"(",
")",
"elif",
"objType",
"==",
"'EX_ELEM_BLOCK'",
":",
"numVals",
"=",
"self",
".",
"num_elems_in_blk",
"(",
"entityId",
")",
"elif",
"objType",
"==",
"'EX_NODE_SET'",
":",
"(",
"numVals",
",",
"_numDistFactInSet",
")",
"=",
"self",
".",
"__ex_get_set_param",
"(",
"objType",
",",
"entityId",
")",
"elif",
"objType",
"==",
"'EX_EDGE_SET'",
":",
"(",
"numVals",
",",
"_numDistFactInSet",
")",
"=",
"self",
".",
"__ex_get_set_param",
"(",
"objType",
",",
"entityId",
")",
"elif",
"objType",
"==",
"'EX_FACE_SET'",
":",
"(",
"numVals",
",",
"_numDistFactInSet",
")",
"=",
"self",
".",
"__ex_get_set_param",
"(",
"objType",
",",
"entityId",
")",
"elif",
"objType",
"==",
"'EX_SIDE_SET'",
":",
"(",
"numVals",
",",
"_numDistFactInSet",
")",
"=",
"self",
".",
"__ex_get_set_param",
"(",
"objType",
",",
"entityId",
")",
"values",
"=",
"self",
".",
"__ex_get_var",
"(",
"step",
",",
"objType",
",",
"var_id",
",",
"entityId",
",",
"numVals",
")",
"if",
"self",
".",
"use_numpy",
":",
"values",
"=",
"ctype_to_numpy",
"(",
"self",
",",
"values",
")",
"return",
"values"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus3.in.py#L2162-L2209 | |
giuspen/cherrytree | 84712f206478fcf9acf30174009ad28c648c6344 | pygtk2/modules/support.py | python | clean_from_chars_not_for_filename | (filename_in) | return filename_out.replace(cons.CHAR_SPACE, cons.CHAR_USCORE) | Clean a string from chars not good for filename | Clean a string from chars not good for filename | [
"Clean",
"a",
"string",
"from",
"chars",
"not",
"good",
"for",
"filename"
] | def clean_from_chars_not_for_filename(filename_in):
"""Clean a string from chars not good for filename"""
filename_out = filename_in.replace(cons.CHAR_SLASH, cons.CHAR_MINUS).replace(cons.CHAR_BSLASH, cons.CHAR_MINUS)
filename_out = filename_out.replace(cons.CHAR_STAR, "").replace(cons.CHAR_QUESTION, "").replace(cons.CHAR_COLON, "")
filename_out = filename_out.replace(cons.CHAR_LESSER, "").replace(cons.CHAR_GREATER, "")
filename_out = filename_out.replace(cons.CHAR_PIPE, "").replace(cons.CHAR_DQUOTE, "")
filename_out = filename_out.replace(cons.CHAR_NEWLINE, "").replace(cons.CHAR_CR, "").strip()
return filename_out.replace(cons.CHAR_SPACE, cons.CHAR_USCORE) | [
"def",
"clean_from_chars_not_for_filename",
"(",
"filename_in",
")",
":",
"filename_out",
"=",
"filename_in",
".",
"replace",
"(",
"cons",
".",
"CHAR_SLASH",
",",
"cons",
".",
"CHAR_MINUS",
")",
".",
"replace",
"(",
"cons",
".",
"CHAR_BSLASH",
",",
"cons",
".",
"CHAR_MINUS",
")",
"filename_out",
"=",
"filename_out",
".",
"replace",
"(",
"cons",
".",
"CHAR_STAR",
",",
"\"\"",
")",
".",
"replace",
"(",
"cons",
".",
"CHAR_QUESTION",
",",
"\"\"",
")",
".",
"replace",
"(",
"cons",
".",
"CHAR_COLON",
",",
"\"\"",
")",
"filename_out",
"=",
"filename_out",
".",
"replace",
"(",
"cons",
".",
"CHAR_LESSER",
",",
"\"\"",
")",
".",
"replace",
"(",
"cons",
".",
"CHAR_GREATER",
",",
"\"\"",
")",
"filename_out",
"=",
"filename_out",
".",
"replace",
"(",
"cons",
".",
"CHAR_PIPE",
",",
"\"\"",
")",
".",
"replace",
"(",
"cons",
".",
"CHAR_DQUOTE",
",",
"\"\"",
")",
"filename_out",
"=",
"filename_out",
".",
"replace",
"(",
"cons",
".",
"CHAR_NEWLINE",
",",
"\"\"",
")",
".",
"replace",
"(",
"cons",
".",
"CHAR_CR",
",",
"\"\"",
")",
".",
"strip",
"(",
")",
"return",
"filename_out",
".",
"replace",
"(",
"cons",
".",
"CHAR_SPACE",
",",
"cons",
".",
"CHAR_USCORE",
")"
] | https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/support.py#L636-L643 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/fixer_base.py | python | BaseFix.compile_pattern | (self) | Compiles self.PATTERN into self.pattern.
Subclass may override if it doesn't want to use
self.{pattern,PATTERN} in .match(). | Compiles self.PATTERN into self.pattern. | [
"Compiles",
"self",
".",
"PATTERN",
"into",
"self",
".",
"pattern",
"."
] | def compile_pattern(self):
"""Compiles self.PATTERN into self.pattern.
Subclass may override if it doesn't want to use
self.{pattern,PATTERN} in .match().
"""
if self.PATTERN is not None:
PC = PatternCompiler()
self.pattern, self.pattern_tree = PC.compile_pattern(self.PATTERN,
with_tree=True) | [
"def",
"compile_pattern",
"(",
"self",
")",
":",
"if",
"self",
".",
"PATTERN",
"is",
"not",
"None",
":",
"PC",
"=",
"PatternCompiler",
"(",
")",
"self",
".",
"pattern",
",",
"self",
".",
"pattern_tree",
"=",
"PC",
".",
"compile_pattern",
"(",
"self",
".",
"PATTERN",
",",
"with_tree",
"=",
"True",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/fixer_base.py#L61-L70 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py | python | TarInfo._proc_gnulong | (self, tarfile) | return next | Process the blocks that hold a GNU longname
or longlink member. | Process the blocks that hold a GNU longname
or longlink member. | [
"Process",
"the",
"blocks",
"that",
"hold",
"a",
"GNU",
"longname",
"or",
"longlink",
"member",
"."
] | def _proc_gnulong(self, tarfile):
"""Process the blocks that hold a GNU longname
or longlink member.
"""
buf = tarfile.fileobj.read(self._block(self.size))
# Fetch the next header and process it.
try:
next = self.fromtarfile(tarfile)
except HeaderError:
raise SubsequentHeaderError("missing or bad subsequent header")
# Patch the TarInfo object from the next header with
# the longname information.
next.offset = self.offset
if self.type == GNUTYPE_LONGNAME:
next.name = nts(buf, tarfile.encoding, tarfile.errors)
elif self.type == GNUTYPE_LONGLINK:
next.linkname = nts(buf, tarfile.encoding, tarfile.errors)
return next | [
"def",
"_proc_gnulong",
"(",
"self",
",",
"tarfile",
")",
":",
"buf",
"=",
"tarfile",
".",
"fileobj",
".",
"read",
"(",
"self",
".",
"_block",
"(",
"self",
".",
"size",
")",
")",
"# Fetch the next header and process it.",
"try",
":",
"next",
"=",
"self",
".",
"fromtarfile",
"(",
"tarfile",
")",
"except",
"HeaderError",
":",
"raise",
"SubsequentHeaderError",
"(",
"\"missing or bad subsequent header\"",
")",
"# Patch the TarInfo object from the next header with",
"# the longname information.",
"next",
".",
"offset",
"=",
"self",
".",
"offset",
"if",
"self",
".",
"type",
"==",
"GNUTYPE_LONGNAME",
":",
"next",
".",
"name",
"=",
"nts",
"(",
"buf",
",",
"tarfile",
".",
"encoding",
",",
"tarfile",
".",
"errors",
")",
"elif",
"self",
".",
"type",
"==",
"GNUTYPE_LONGLINK",
":",
"next",
".",
"linkname",
"=",
"nts",
"(",
"buf",
",",
"tarfile",
".",
"encoding",
",",
"tarfile",
".",
"errors",
")",
"return",
"next"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py#L1333-L1353 | |
Kitware/VTK | 5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8 | Wrapping/Python/vtkmodules/numpy_interface/internal_algorithms.py | python | area | (dataset) | return _cell_quality(dataset, "area") | Returns the surface area of each cell in a mesh. | Returns the surface area of each cell in a mesh. | [
"Returns",
"the",
"surface",
"area",
"of",
"each",
"cell",
"in",
"a",
"mesh",
"."
] | def area (dataset) :
"Returns the surface area of each cell in a mesh."
return _cell_quality(dataset, "area") | [
"def",
"area",
"(",
"dataset",
")",
":",
"return",
"_cell_quality",
"(",
"dataset",
",",
"\"area\"",
")"
] | https://github.com/Kitware/VTK/blob/5b4df4d90a4f31194d97d3c639dd38ea8f81e8b8/Wrapping/Python/vtkmodules/numpy_interface/internal_algorithms.py#L184-L186 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/imputil.py | python | ImportManager._determine_import_context | (self, globals) | return parent | Returns the context in which a module should be imported.
The context could be a loaded (package) module and the imported module
will be looked for within that package. The context could also be None,
meaning there is no context -- the module should be looked for as a
"top-level" module. | Returns the context in which a module should be imported. | [
"Returns",
"the",
"context",
"in",
"which",
"a",
"module",
"should",
"be",
"imported",
"."
] | def _determine_import_context(self, globals):
"""Returns the context in which a module should be imported.
The context could be a loaded (package) module and the imported module
will be looked for within that package. The context could also be None,
meaning there is no context -- the module should be looked for as a
"top-level" module.
"""
if not globals or not globals.get('__importer__'):
# globals does not refer to one of our modules or packages. That
# implies there is no relative import context (as far as we are
# concerned), and it should just pick it off the standard path.
return None
# The globals refer to a module or package of ours. It will define
# the context of the new import. Get the module/package fqname.
parent_fqname = globals['__name__']
# if a package is performing the import, then return itself (imports
# refer to pkg contents)
if globals['__ispkg__']:
parent = sys.modules[parent_fqname]
assert globals is parent.__dict__
return parent
i = parent_fqname.rfind('.')
# a module outside of a package has no particular import context
if i == -1:
return None
# if a module in a package is performing the import, then return the
# package (imports refer to siblings)
parent_fqname = parent_fqname[:i]
parent = sys.modules[parent_fqname]
assert parent.__name__ == parent_fqname
return parent | [
"def",
"_determine_import_context",
"(",
"self",
",",
"globals",
")",
":",
"if",
"not",
"globals",
"or",
"not",
"globals",
".",
"get",
"(",
"'__importer__'",
")",
":",
"# globals does not refer to one of our modules or packages. That",
"# implies there is no relative import context (as far as we are",
"# concerned), and it should just pick it off the standard path.",
"return",
"None",
"# The globals refer to a module or package of ours. It will define",
"# the context of the new import. Get the module/package fqname.",
"parent_fqname",
"=",
"globals",
"[",
"'__name__'",
"]",
"# if a package is performing the import, then return itself (imports",
"# refer to pkg contents)",
"if",
"globals",
"[",
"'__ispkg__'",
"]",
":",
"parent",
"=",
"sys",
".",
"modules",
"[",
"parent_fqname",
"]",
"assert",
"globals",
"is",
"parent",
".",
"__dict__",
"return",
"parent",
"i",
"=",
"parent_fqname",
".",
"rfind",
"(",
"'.'",
")",
"# a module outside of a package has no particular import context",
"if",
"i",
"==",
"-",
"1",
":",
"return",
"None",
"# if a module in a package is performing the import, then return the",
"# package (imports refer to siblings)",
"parent_fqname",
"=",
"parent_fqname",
"[",
":",
"i",
"]",
"parent",
"=",
"sys",
".",
"modules",
"[",
"parent_fqname",
"]",
"assert",
"parent",
".",
"__name__",
"==",
"parent_fqname",
"return",
"parent"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/imputil.py#L149-L186 | |
cryfs/cryfs | 5f908c641cd5854b8a347f842b996bfe76a64577 | src/gitversion/versioneer.py | python | do_vcs_install | (manifest_in, versionfile_source, ipy) | Git-specific installation logic for Versioneer.
For Git, this means creating/changing .gitattributes to mark _version.py
for export-time keyword substitution. | Git-specific installation logic for Versioneer. | [
"Git",
"-",
"specific",
"installation",
"logic",
"for",
"Versioneer",
"."
] | def do_vcs_install(manifest_in, versionfile_source, ipy):
"""Git-specific installation logic for Versioneer.
For Git, this means creating/changing .gitattributes to mark _version.py
for export-time keyword substitution.
"""
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
files = [manifest_in, versionfile_source]
if ipy:
files.append(ipy)
try:
me = __file__
if me.endswith(".pyc") or me.endswith(".pyo"):
me = os.path.splitext(me)[0] + ".py"
versioneer_file = os.path.relpath(me)
except NameError:
versioneer_file = "versioneer.py"
files.append(versioneer_file)
present = False
try:
f = open(".gitattributes", "r")
for line in f.readlines():
if line.strip().startswith(versionfile_source):
if "export-subst" in line.strip().split()[1:]:
present = True
f.close()
except EnvironmentError:
pass
if not present:
f = open(".gitattributes", "a+")
f.write("%s export-subst\n" % versionfile_source)
f.close()
files.append(".gitattributes")
run_command(GITS, ["add", "--"] + files) | [
"def",
"do_vcs_install",
"(",
"manifest_in",
",",
"versionfile_source",
",",
"ipy",
")",
":",
"GITS",
"=",
"[",
"\"git\"",
"]",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"GITS",
"=",
"[",
"\"git.cmd\"",
",",
"\"git.exe\"",
"]",
"files",
"=",
"[",
"manifest_in",
",",
"versionfile_source",
"]",
"if",
"ipy",
":",
"files",
".",
"append",
"(",
"ipy",
")",
"try",
":",
"me",
"=",
"__file__",
"if",
"me",
".",
"endswith",
"(",
"\".pyc\"",
")",
"or",
"me",
".",
"endswith",
"(",
"\".pyo\"",
")",
":",
"me",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"me",
")",
"[",
"0",
"]",
"+",
"\".py\"",
"versioneer_file",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"me",
")",
"except",
"NameError",
":",
"versioneer_file",
"=",
"\"versioneer.py\"",
"files",
".",
"append",
"(",
"versioneer_file",
")",
"present",
"=",
"False",
"try",
":",
"f",
"=",
"open",
"(",
"\".gitattributes\"",
",",
"\"r\"",
")",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"if",
"line",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"versionfile_source",
")",
":",
"if",
"\"export-subst\"",
"in",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"[",
"1",
":",
"]",
":",
"present",
"=",
"True",
"f",
".",
"close",
"(",
")",
"except",
"EnvironmentError",
":",
"pass",
"if",
"not",
"present",
":",
"f",
"=",
"open",
"(",
"\".gitattributes\"",
",",
"\"a+\"",
")",
"f",
".",
"write",
"(",
"\"%s export-subst\\n\"",
"%",
"versionfile_source",
")",
"f",
".",
"close",
"(",
")",
"files",
".",
"append",
"(",
"\".gitattributes\"",
")",
"run_command",
"(",
"GITS",
",",
"[",
"\"add\"",
",",
"\"--\"",
"]",
"+",
"files",
")"
] | https://github.com/cryfs/cryfs/blob/5f908c641cd5854b8a347f842b996bfe76a64577/src/gitversion/versioneer.py#L1129-L1164 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexing.py | python | _NDFrameIndexer._validate_key | (self, key, axis: int) | Ensure that key is valid for current indexer.
Parameters
----------
key : scalar, slice or list-like
Key requested.
axis : int
Dimension on which the indexing is being made.
Raises
------
TypeError
If the key (or some element of it) has wrong type.
IndexError
If the key (or some element of it) is out of bounds.
KeyError
If the key was not found. | Ensure that key is valid for current indexer. | [
"Ensure",
"that",
"key",
"is",
"valid",
"for",
"current",
"indexer",
"."
] | def _validate_key(self, key, axis: int):
"""
Ensure that key is valid for current indexer.
Parameters
----------
key : scalar, slice or list-like
Key requested.
axis : int
Dimension on which the indexing is being made.
Raises
------
TypeError
If the key (or some element of it) has wrong type.
IndexError
If the key (or some element of it) is out of bounds.
KeyError
If the key was not found.
"""
raise AbstractMethodError(self) | [
"def",
"_validate_key",
"(",
"self",
",",
"key",
",",
"axis",
":",
"int",
")",
":",
"raise",
"AbstractMethodError",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/indexing.py#L673-L693 | ||
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/numarray/numerictypes.py | python | getType | (type) | Return the numeric type object for type
type may be the name of a type object or the actual object | Return the numeric type object for type | [
"Return",
"the",
"numeric",
"type",
"object",
"for",
"type"
] | def getType(type):
"""Return the numeric type object for type
type may be the name of a type object or the actual object
"""
if isinstance(type, NumericType):
return type
try:
return typeDict[type]
except KeyError:
raise TypeError("Not a numeric type") | [
"def",
"getType",
"(",
"type",
")",
":",
"if",
"isinstance",
"(",
"type",
",",
"NumericType",
")",
":",
"return",
"type",
"try",
":",
"return",
"typeDict",
"[",
"type",
"]",
"except",
"KeyError",
":",
"raise",
"TypeError",
"(",
"\"Not a numeric type\"",
")"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/numarray/numerictypes.py#L501-L511 | ||
tangzhenyu/Scene-Text-Understanding | 0f7ffc7aea5971a50cdc03d33d0a41075285948b | ctpn_crnn_ocr/crnn/util.py | python | strLabelConverter.encode | (self, text, depth=0) | return (torch.IntTensor(text), torch.IntTensor(length)) | Support batch or single str. | Support batch or single str. | [
"Support",
"batch",
"or",
"single",
"str",
"."
] | def encode(self, text, depth=0):
"""Support batch or single str."""
length = []
result=[]
for str in text:
str = unicode(str,"utf8")
length.append(len(str))
for char in str:
#print(char)
index = self.dict[char]
result.append(index)
text = result
return (torch.IntTensor(text), torch.IntTensor(length)) | [
"def",
"encode",
"(",
"self",
",",
"text",
",",
"depth",
"=",
"0",
")",
":",
"length",
"=",
"[",
"]",
"result",
"=",
"[",
"]",
"for",
"str",
"in",
"text",
":",
"str",
"=",
"unicode",
"(",
"str",
",",
"\"utf8\"",
")",
"length",
".",
"append",
"(",
"len",
"(",
"str",
")",
")",
"for",
"char",
"in",
"str",
":",
"#print(char)",
"index",
"=",
"self",
".",
"dict",
"[",
"char",
"]",
"result",
".",
"append",
"(",
"index",
")",
"text",
"=",
"result",
"return",
"(",
"torch",
".",
"IntTensor",
"(",
"text",
")",
",",
"torch",
".",
"IntTensor",
"(",
"length",
")",
")"
] | https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/ctpn_crnn_ocr/crnn/util.py#L17-L29 | |
LLNL/lbann | 26083e6c86050302ce33148aea70f62e61cacb92 | python/lbann/contrib/lc/launcher.py | python | run | (*args, **kwargs) | Run LBANN with LC-specific optimizations (deprecated).
This is deprecated. Use `lbann.contrib.launcher.run` instead. | Run LBANN with LC-specific optimizations (deprecated). | [
"Run",
"LBANN",
"with",
"LC",
"-",
"specific",
"optimizations",
"(",
"deprecated",
")",
"."
] | def run(*args, **kwargs):
"""Run LBANN with LC-specific optimizations (deprecated).
This is deprecated. Use `lbann.contrib.launcher.run` instead.
"""
import warnings
warnings.warn(
'Using deprecated function `lbann.contrib.lc.launcher.run`. '
'Use `lbann.contrib.launcher.run` instead.'
)
from ..launcher import run as _run
_run(*args, **kwargs) | [
"def",
"run",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"'Using deprecated function `lbann.contrib.lc.launcher.run`. '",
"'Use `lbann.contrib.launcher.run` instead.'",
")",
"from",
".",
".",
"launcher",
"import",
"run",
"as",
"_run",
"_run",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/python/lbann/contrib/lc/launcher.py#L6-L19 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/macostools.py | python | copytree | (src, dst, copydates=1) | Copy a complete file tree to a new destination | Copy a complete file tree to a new destination | [
"Copy",
"a",
"complete",
"file",
"tree",
"to",
"a",
"new",
"destination"
] | def copytree(src, dst, copydates=1):
"""Copy a complete file tree to a new destination"""
if os.path.isdir(src):
mkdirs(dst)
files = os.listdir(src)
for f in files:
copytree(os.path.join(src, f), os.path.join(dst, f), copydates)
else:
copy(src, dst, 1, copydates) | [
"def",
"copytree",
"(",
"src",
",",
"dst",
",",
"copydates",
"=",
"1",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"src",
")",
":",
"mkdirs",
"(",
"dst",
")",
"files",
"=",
"os",
".",
"listdir",
"(",
"src",
")",
"for",
"f",
"in",
"files",
":",
"copytree",
"(",
"os",
".",
"path",
".",
"join",
"(",
"src",
",",
"f",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"f",
")",
",",
"copydates",
")",
"else",
":",
"copy",
"(",
"src",
",",
"dst",
",",
"1",
",",
"copydates",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/macostools.py#L130-L138 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/src/robotsim.py | python | Simulator.getJointForces | (self, link: "RobotModelLink") | return _robotsim.Simulator_getJointForces(self, link) | r"""
getJointForces(Simulator self, RobotModelLink link)
Returns the joint force and torque local to the link, as would be read by a
force-torque sensor mounted at the given link's origin.
Returns:
6 entries of the wrench (fx,fy,fz,mx,my,mz) | r"""
getJointForces(Simulator self, RobotModelLink link) | [
"r",
"getJointForces",
"(",
"Simulator",
"self",
"RobotModelLink",
"link",
")"
] | def getJointForces(self, link: "RobotModelLink") -> "void":
r"""
getJointForces(Simulator self, RobotModelLink link)
Returns the joint force and torque local to the link, as would be read by a
force-torque sensor mounted at the given link's origin.
Returns:
6 entries of the wrench (fx,fy,fz,mx,my,mz)
"""
return _robotsim.Simulator_getJointForces(self, link) | [
"def",
"getJointForces",
"(",
"self",
",",
"link",
":",
"\"RobotModelLink\"",
")",
"->",
"\"void\"",
":",
"return",
"_robotsim",
".",
"Simulator_getJointForces",
"(",
"self",
",",
"link",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L8506-L8519 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py | python | pyparsing_common.convertToDate | (fmt="%Y-%m-%d") | return cvt_fn | Helper to create a parse action for converting parsed date string to Python datetime.date
Params -
- fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``)
Example::
date_expr = pyparsing_common.iso8601_date.copy()
date_expr.setParseAction(pyparsing_common.convertToDate())
print(date_expr.parseString("1999-12-31"))
prints::
[datetime.date(1999, 12, 31)] | Helper to create a parse action for converting parsed date string to Python datetime.date | [
"Helper",
"to",
"create",
"a",
"parse",
"action",
"for",
"converting",
"parsed",
"date",
"string",
"to",
"Python",
"datetime",
".",
"date"
] | def convertToDate(fmt="%Y-%m-%d"):
"""
Helper to create a parse action for converting parsed date string to Python datetime.date
Params -
- fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``)
Example::
date_expr = pyparsing_common.iso8601_date.copy()
date_expr.setParseAction(pyparsing_common.convertToDate())
print(date_expr.parseString("1999-12-31"))
prints::
[datetime.date(1999, 12, 31)]
"""
def cvt_fn(s, l, t):
try:
return datetime.strptime(t[0], fmt).date()
except ValueError as ve:
raise ParseException(s, l, str(ve))
return cvt_fn | [
"def",
"convertToDate",
"(",
"fmt",
"=",
"\"%Y-%m-%d\"",
")",
":",
"def",
"cvt_fn",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"try",
":",
"return",
"datetime",
".",
"strptime",
"(",
"t",
"[",
"0",
"]",
",",
"fmt",
")",
".",
"date",
"(",
")",
"except",
"ValueError",
"as",
"ve",
":",
"raise",
"ParseException",
"(",
"s",
",",
"l",
",",
"str",
"(",
"ve",
")",
")",
"return",
"cvt_fn"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L6605-L6627 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py | python | Tk.report_callback_exception | (self, exc, val, tb) | Report callback exception on sys.stderr.
Applications may want to override this internal function, and
should when sys.stderr is None. | Report callback exception on sys.stderr. | [
"Report",
"callback",
"exception",
"on",
"sys",
".",
"stderr",
"."
] | def report_callback_exception(self, exc, val, tb):
"""Report callback exception on sys.stderr.
Applications may want to override this internal function, and
should when sys.stderr is None."""
import traceback
print("Exception in Tkinter callback", file=sys.stderr)
sys.last_type = exc
sys.last_value = val
sys.last_traceback = tb
traceback.print_exception(exc, val, tb) | [
"def",
"report_callback_exception",
"(",
"self",
",",
"exc",
",",
"val",
",",
"tb",
")",
":",
"import",
"traceback",
"print",
"(",
"\"Exception in Tkinter callback\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"last_type",
"=",
"exc",
"sys",
".",
"last_value",
"=",
"val",
"sys",
".",
"last_traceback",
"=",
"tb",
"traceback",
".",
"print_exception",
"(",
"exc",
",",
"val",
",",
"tb",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L2088-L2098 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/offline_debug/dbg_services.py | python | TensorData.shape | (self) | return self.instance.get_shape() | Function to receive TensorData shape.
Returns:
shape of TensorData instance (list).
Examples:
>>> from mindspore.ccsrc.debug.debugger.offline_debug import dbg_services
>>> tensor_data = dbg_services.TensorData(data_ptr=b'\xba\xd0\xba\xd0',
... data_size=4,
... dtype=0,
... shape=[2, 2])
>>> shape = tensor_data.shape | Function to receive TensorData shape. | [
"Function",
"to",
"receive",
"TensorData",
"shape",
"."
] | def shape(self):
"""
Function to receive TensorData shape.
Returns:
shape of TensorData instance (list).
Examples:
>>> from mindspore.ccsrc.debug.debugger.offline_debug import dbg_services
>>> tensor_data = dbg_services.TensorData(data_ptr=b'\xba\xd0\xba\xd0',
... data_size=4,
... dtype=0,
... shape=[2, 2])
>>> shape = tensor_data.shape
"""
return self.instance.get_shape() | [
"def",
"shape",
"(",
"self",
")",
":",
"return",
"self",
".",
"instance",
".",
"get_shape",
"(",
")"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/offline_debug/dbg_services.py#L600-L615 | |
devsisters/libquic | 8954789a056d8e7d5fcb6452fd1572ca57eb5c4e | src/third_party/protobuf/python/google/protobuf/json_format.py | python | _ConvertValueMessage | (value, message) | Convert a JSON representation into Value message. | Convert a JSON representation into Value message. | [
"Convert",
"a",
"JSON",
"representation",
"into",
"Value",
"message",
"."
] | def _ConvertValueMessage(value, message):
"""Convert a JSON representation into Value message."""
if isinstance(value, dict):
_ConvertStructMessage(value, message.struct_value)
elif isinstance(value, list):
_ConvertListValueMessage(value, message.list_value)
elif value is None:
message.null_value = 0
elif isinstance(value, bool):
message.bool_value = value
elif isinstance(value, six.string_types):
message.string_value = value
elif isinstance(value, _INT_OR_FLOAT):
message.number_value = value
else:
raise ParseError('Unexpected type for Value message.') | [
"def",
"_ConvertValueMessage",
"(",
"value",
",",
"message",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"_ConvertStructMessage",
"(",
"value",
",",
"message",
".",
"struct_value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"_ConvertListValueMessage",
"(",
"value",
",",
"message",
".",
"list_value",
")",
"elif",
"value",
"is",
"None",
":",
"message",
".",
"null_value",
"=",
"0",
"elif",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"message",
".",
"bool_value",
"=",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"message",
".",
"string_value",
"=",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"_INT_OR_FLOAT",
")",
":",
"message",
".",
"number_value",
"=",
"value",
"else",
":",
"raise",
"ParseError",
"(",
"'Unexpected type for Value message.'",
")"
] | https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/google/protobuf/json_format.py#L459-L474 | ||
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | gpu/command_buffer/build_gles2_cmd_buffer.py | python | CWriter.__WriteLine | (self, line, ends_with_eol) | Given a signle line, writes it to a file, splitting if it's > 80 chars | Given a signle line, writes it to a file, splitting if it's > 80 chars | [
"Given",
"a",
"signle",
"line",
"writes",
"it",
"to",
"a",
"file",
"splitting",
"if",
"it",
"s",
">",
"80",
"chars"
] | def __WriteLine(self, line, ends_with_eol):
"""Given a signle line, writes it to a file, splitting if it's > 80 chars"""
if len(line) >= 80:
i = self.__FindSplit(line)
if i > 0:
line1 = line[0:i + 1]
if line1[-1] == ' ':
line1 = line1[:-1]
lineend = ''
if line1[0] == '#':
lineend = ' \\'
nolint = ''
if len(line1) > 80:
nolint = ' // NOLINT'
self.__AddLine(line1 + nolint + lineend + '\n')
match = re.match("( +)", line1)
indent = ""
if match:
indent = match.group(1)
splitter = line[i]
if not splitter == ',':
indent = " " + indent
self.__WriteLine(indent + line[i + 1:].lstrip(), True)
return
nolint = ''
if len(line) > 80:
nolint = ' // NOLINT'
self.__AddLine(line + nolint)
if ends_with_eol:
self.__AddLine('\n') | [
"def",
"__WriteLine",
"(",
"self",
",",
"line",
",",
"ends_with_eol",
")",
":",
"if",
"len",
"(",
"line",
")",
">=",
"80",
":",
"i",
"=",
"self",
".",
"__FindSplit",
"(",
"line",
")",
"if",
"i",
">",
"0",
":",
"line1",
"=",
"line",
"[",
"0",
":",
"i",
"+",
"1",
"]",
"if",
"line1",
"[",
"-",
"1",
"]",
"==",
"' '",
":",
"line1",
"=",
"line1",
"[",
":",
"-",
"1",
"]",
"lineend",
"=",
"''",
"if",
"line1",
"[",
"0",
"]",
"==",
"'#'",
":",
"lineend",
"=",
"' \\\\'",
"nolint",
"=",
"''",
"if",
"len",
"(",
"line1",
")",
">",
"80",
":",
"nolint",
"=",
"' // NOLINT'",
"self",
".",
"__AddLine",
"(",
"line1",
"+",
"nolint",
"+",
"lineend",
"+",
"'\\n'",
")",
"match",
"=",
"re",
".",
"match",
"(",
"\"( +)\"",
",",
"line1",
")",
"indent",
"=",
"\"\"",
"if",
"match",
":",
"indent",
"=",
"match",
".",
"group",
"(",
"1",
")",
"splitter",
"=",
"line",
"[",
"i",
"]",
"if",
"not",
"splitter",
"==",
"','",
":",
"indent",
"=",
"\" \"",
"+",
"indent",
"self",
".",
"__WriteLine",
"(",
"indent",
"+",
"line",
"[",
"i",
"+",
"1",
":",
"]",
".",
"lstrip",
"(",
")",
",",
"True",
")",
"return",
"nolint",
"=",
"''",
"if",
"len",
"(",
"line",
")",
">",
"80",
":",
"nolint",
"=",
"' // NOLINT'",
"self",
".",
"__AddLine",
"(",
"line",
"+",
"nolint",
")",
"if",
"ends_with_eol",
":",
"self",
".",
"__AddLine",
"(",
"'\\n'",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L1775-L1804 | ||
ycm-core/ycmd | fc0fb7e5e15176cc5a2a30c80956335988c6b59a | ycmd/completers/cpp/clang_completer.py | python | GetIncompleteIncludeValue | ( line ) | return ( line[ include_start : separator_char_pos + 1 ],
quoted_include,
separator_char_pos + 2 ) | Returns the tuple |include_value|, |quoted_include|, and |start_codepoint|
where:
- |include_value| is the string starting from the opening quote or bracket of
the include statement in |line|. None if no include statement is found;
- |quoted_include| is True if the statement is a quoted include, False
otherwise;
- |start_column| is the 1-based column where the completion should start (i.e.
at the last path separator '/' or at the opening quote or bracket). None if
no include statement is matched. | Returns the tuple |include_value|, |quoted_include|, and |start_codepoint|
where:
- |include_value| is the string starting from the opening quote or bracket of
the include statement in |line|. None if no include statement is found;
- |quoted_include| is True if the statement is a quoted include, False
otherwise;
- |start_column| is the 1-based column where the completion should start (i.e.
at the last path separator '/' or at the opening quote or bracket). None if
no include statement is matched. | [
"Returns",
"the",
"tuple",
"|include_value|",
"|quoted_include|",
"and",
"|start_codepoint|",
"where",
":",
"-",
"|include_value|",
"is",
"the",
"string",
"starting",
"from",
"the",
"opening",
"quote",
"or",
"bracket",
"of",
"the",
"include",
"statement",
"in",
"|line|",
".",
"None",
"if",
"no",
"include",
"statement",
"is",
"found",
";",
"-",
"|quoted_include|",
"is",
"True",
"if",
"the",
"statement",
"is",
"a",
"quoted",
"include",
"False",
"otherwise",
";",
"-",
"|start_column|",
"is",
"the",
"1",
"-",
"based",
"column",
"where",
"the",
"completion",
"should",
"start",
"(",
"i",
".",
"e",
".",
"at",
"the",
"last",
"path",
"separator",
"/",
"or",
"at",
"the",
"opening",
"quote",
"or",
"bracket",
")",
".",
"None",
"if",
"no",
"include",
"statement",
"is",
"matched",
"."
] | def GetIncompleteIncludeValue( line ):
"""Returns the tuple |include_value|, |quoted_include|, and |start_codepoint|
where:
- |include_value| is the string starting from the opening quote or bracket of
the include statement in |line|. None if no include statement is found;
- |quoted_include| is True if the statement is a quoted include, False
otherwise;
- |start_column| is the 1-based column where the completion should start (i.e.
at the last path separator '/' or at the opening quote or bracket). None if
no include statement is matched."""
match = INCLUDE_REGEX.match( line )
if not match:
return None, False, None
include_start = match.end( 1 ) + 1
quoted_include = ( line[ include_start - 1 ] == '"' )
separator_char = '/'
separator_char_pos = line.rfind( separator_char, match.end( 1 ) )
if separator_char_pos == -1:
return '', quoted_include, include_start + 1
return ( line[ include_start : separator_char_pos + 1 ],
quoted_include,
separator_char_pos + 2 ) | [
"def",
"GetIncompleteIncludeValue",
"(",
"line",
")",
":",
"match",
"=",
"INCLUDE_REGEX",
".",
"match",
"(",
"line",
")",
"if",
"not",
"match",
":",
"return",
"None",
",",
"False",
",",
"None",
"include_start",
"=",
"match",
".",
"end",
"(",
"1",
")",
"+",
"1",
"quoted_include",
"=",
"(",
"line",
"[",
"include_start",
"-",
"1",
"]",
"==",
"'\"'",
")",
"separator_char",
"=",
"'/'",
"separator_char_pos",
"=",
"line",
".",
"rfind",
"(",
"separator_char",
",",
"match",
".",
"end",
"(",
"1",
")",
")",
"if",
"separator_char_pos",
"==",
"-",
"1",
":",
"return",
"''",
",",
"quoted_include",
",",
"include_start",
"+",
"1",
"return",
"(",
"line",
"[",
"include_start",
":",
"separator_char_pos",
"+",
"1",
"]",
",",
"quoted_include",
",",
"separator_char_pos",
"+",
"2",
")"
] | https://github.com/ycm-core/ycmd/blob/fc0fb7e5e15176cc5a2a30c80956335988c6b59a/ycmd/completers/cpp/clang_completer.py#L590-L612 | |
apache/incubator-mxnet | f03fb23f1d103fec9541b5ae59ee06b1734a51d9 | python/mxnet/numpy/multiarray.py | python | bitwise_left_shift | (x1, x2, out=None) | return _mx_nd_np.bitwise_left_shift(x1, x2, out) | r"""
Shift the bits of and integer to the left. Bits are shifted to the left by
appending x2 0s at the right of x1. Since the internal representation of numbers
is in binary format, this operation is equivalent to ``x1 * 2**x2``
Parameters
----------
x1 : ndarray or scalar
Input values.
x2 : ndarray or scalar
Number of zeros to append to x1. Has to be non-negative. If x1.shape != x2.shape,
they must be broadcastable to a common shape (which becomes the shape of the output).
out : ndarray, optional
A location into which the result is stored. If provided, it must have a shape that the
inputs broadcast to. If not provided or None, a freshly-allocated array is returned.
Returns
-------
out : ndarray
Result.
Examples
--------
>>> np.binary_repr(5)
'101'
>>> np.left_shift(5, 2)
20
>>> np.binary_repr(20)
'10100' | r"""
Shift the bits of and integer to the left. Bits are shifted to the left by
appending x2 0s at the right of x1. Since the internal representation of numbers
is in binary format, this operation is equivalent to ``x1 * 2**x2`` | [
"r",
"Shift",
"the",
"bits",
"of",
"and",
"integer",
"to",
"the",
"left",
".",
"Bits",
"are",
"shifted",
"to",
"the",
"left",
"by",
"appending",
"x2",
"0s",
"at",
"the",
"right",
"of",
"x1",
".",
"Since",
"the",
"internal",
"representation",
"of",
"numbers",
"is",
"in",
"binary",
"format",
"this",
"operation",
"is",
"equivalent",
"to",
"x1",
"*",
"2",
"**",
"x2"
] | def bitwise_left_shift(x1, x2, out=None):
r"""
Shift the bits of and integer to the left. Bits are shifted to the left by
appending x2 0s at the right of x1. Since the internal representation of numbers
is in binary format, this operation is equivalent to ``x1 * 2**x2``
Parameters
----------
x1 : ndarray or scalar
Input values.
x2 : ndarray or scalar
Number of zeros to append to x1. Has to be non-negative. If x1.shape != x2.shape,
they must be broadcastable to a common shape (which becomes the shape of the output).
out : ndarray, optional
A location into which the result is stored. If provided, it must have a shape that the
inputs broadcast to. If not provided or None, a freshly-allocated array is returned.
Returns
-------
out : ndarray
Result.
Examples
--------
>>> np.binary_repr(5)
'101'
>>> np.left_shift(5, 2)
20
>>> np.binary_repr(20)
'10100'
"""
return _mx_nd_np.bitwise_left_shift(x1, x2, out) | [
"def",
"bitwise_left_shift",
"(",
"x1",
",",
"x2",
",",
"out",
"=",
"None",
")",
":",
"return",
"_mx_nd_np",
".",
"bitwise_left_shift",
"(",
"x1",
",",
"x2",
",",
"out",
")"
] | https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/numpy/multiarray.py#L13229-L13260 | |
tensorflow/deepmath | b5b721f54de1d5d6a02d78f5da5995237f9995f9 | deepmath/deephol/utilities/proof_analysis.py | python | _thm_string | (thm: proof_assistant_pb2.Theorem) | return '|:|'.join([str(hyp) for hyp in thm.hypotheses] +
[str(thm.conclusion)]) | Turn theorem into a string for unique representation.
Args:
thm: Theorem to be turned into a string.
Returns:
string: Joined hypotheses and conclusion. | Turn theorem into a string for unique representation. | [
"Turn",
"theorem",
"into",
"a",
"string",
"for",
"unique",
"representation",
"."
] | def _thm_string(thm: proof_assistant_pb2.Theorem) -> Text:
"""Turn theorem into a string for unique representation.
Args:
thm: Theorem to be turned into a string.
Returns:
string: Joined hypotheses and conclusion.
"""
return '|:|'.join([str(hyp) for hyp in thm.hypotheses] +
[str(thm.conclusion)]) | [
"def",
"_thm_string",
"(",
"thm",
":",
"proof_assistant_pb2",
".",
"Theorem",
")",
"->",
"Text",
":",
"return",
"'|:|'",
".",
"join",
"(",
"[",
"str",
"(",
"hyp",
")",
"for",
"hyp",
"in",
"thm",
".",
"hypotheses",
"]",
"+",
"[",
"str",
"(",
"thm",
".",
"conclusion",
")",
"]",
")"
] | https://github.com/tensorflow/deepmath/blob/b5b721f54de1d5d6a02d78f5da5995237f9995f9/deepmath/deephol/utilities/proof_analysis.py#L24-L34 | |
pytorch/pytorch | 7176c92687d3cc847cc046bf002269c6949a21c2 | torch/jit/_passes/_property_propagation.py | python | apply_input_props_using_example | (graph: Graph, example_input: List[Any]) | Applies properties for each tensor in the graph inputs
using the example supplied. | Applies properties for each tensor in the graph inputs
using the example supplied. | [
"Applies",
"properties",
"for",
"each",
"tensor",
"in",
"the",
"graph",
"inputs",
"using",
"the",
"example",
"supplied",
"."
] | def apply_input_props_using_example(graph: Graph, example_input: List[Any]):
"""
Applies properties for each tensor in the graph inputs
using the example supplied.
"""
graph_inputs = list(graph.inputs())
if len(graph_inputs) == 0:
return
# Strip self args off for methods
in_0 = graph_inputs[0]
if isinstance(in_0.type(), torch._C.ClassType) and in_0.debugName() == "self":
graph_inputs = graph_inputs[1:]
if not len(graph_inputs) == len(example_input):
raise RuntimeError(
"Number of inputs in graph does not match number of inputs in the example")
for i, (graph_i, example_i) in enumerate(zip(graph_inputs, example_input)):
if example_i is None:
continue # Skip the type check
if isinstance(example_i, torch.Tensor) != isinstance(graph_i.type(), TensorType):
raise RuntimeError(f"Input {i} does not match type of example", graph_i, example_i)
if isinstance(example_i, torch.Tensor):
graph_i.setType(TensorType.create_from_tensor(example_i)) | [
"def",
"apply_input_props_using_example",
"(",
"graph",
":",
"Graph",
",",
"example_input",
":",
"List",
"[",
"Any",
"]",
")",
":",
"graph_inputs",
"=",
"list",
"(",
"graph",
".",
"inputs",
"(",
")",
")",
"if",
"len",
"(",
"graph_inputs",
")",
"==",
"0",
":",
"return",
"# Strip self args off for methods",
"in_0",
"=",
"graph_inputs",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"in_0",
".",
"type",
"(",
")",
",",
"torch",
".",
"_C",
".",
"ClassType",
")",
"and",
"in_0",
".",
"debugName",
"(",
")",
"==",
"\"self\"",
":",
"graph_inputs",
"=",
"graph_inputs",
"[",
"1",
":",
"]",
"if",
"not",
"len",
"(",
"graph_inputs",
")",
"==",
"len",
"(",
"example_input",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Number of inputs in graph does not match number of inputs in the example\"",
")",
"for",
"i",
",",
"(",
"graph_i",
",",
"example_i",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"graph_inputs",
",",
"example_input",
")",
")",
":",
"if",
"example_i",
"is",
"None",
":",
"continue",
"# Skip the type check",
"if",
"isinstance",
"(",
"example_i",
",",
"torch",
".",
"Tensor",
")",
"!=",
"isinstance",
"(",
"graph_i",
".",
"type",
"(",
")",
",",
"TensorType",
")",
":",
"raise",
"RuntimeError",
"(",
"f\"Input {i} does not match type of example\"",
",",
"graph_i",
",",
"example_i",
")",
"if",
"isinstance",
"(",
"example_i",
",",
"torch",
".",
"Tensor",
")",
":",
"graph_i",
".",
"setType",
"(",
"TensorType",
".",
"create_from_tensor",
"(",
"example_i",
")",
")"
] | https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/jit/_passes/_property_propagation.py#L15-L41 | ||
Samsung/veles | 95ed733c2e49bc011ad98ccf2416ecec23fbf352 | veles/external/pydot.py | python | Graph.get_subgraph_list | (self) | return sgraph_objs | Get the list of Subgraph instances.
This method returns the list of Subgraph instances
in the graph. | Get the list of Subgraph instances.
This method returns the list of Subgraph instances
in the graph. | [
"Get",
"the",
"list",
"of",
"Subgraph",
"instances",
".",
"This",
"method",
"returns",
"the",
"list",
"of",
"Subgraph",
"instances",
"in",
"the",
"graph",
"."
] | def get_subgraph_list(self):
"""Get the list of Subgraph instances.
This method returns the list of Subgraph instances
in the graph.
"""
sgraph_objs = list()
for sgraph, obj_dict_list in self.obj_dict['subgraphs'].items():
sgraph_objs.extend([ Subgraph(obj_dict=obj_d) for obj_d in obj_dict_list ])
return sgraph_objs | [
"def",
"get_subgraph_list",
"(",
"self",
")",
":",
"sgraph_objs",
"=",
"list",
"(",
")",
"for",
"sgraph",
",",
"obj_dict_list",
"in",
"self",
".",
"obj_dict",
"[",
"'subgraphs'",
"]",
".",
"items",
"(",
")",
":",
"sgraph_objs",
".",
"extend",
"(",
"[",
"Subgraph",
"(",
"obj_dict",
"=",
"obj_d",
")",
"for",
"obj_d",
"in",
"obj_dict_list",
"]",
")",
"return",
"sgraph_objs"
] | https://github.com/Samsung/veles/blob/95ed733c2e49bc011ad98ccf2416ecec23fbf352/veles/external/pydot.py#L1531-L1543 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/layers/legacy_rnn/rnn_cell_wrapper_impl.py | python | _parse_config_to_function | (config, custom_objects, func_attr_name,
func_type_attr_name, module_attr_name) | return function | Reconstruct the function from the config. | Reconstruct the function from the config. | [
"Reconstruct",
"the",
"function",
"from",
"the",
"config",
"."
] | def _parse_config_to_function(config, custom_objects, func_attr_name,
func_type_attr_name, module_attr_name):
"""Reconstruct the function from the config."""
globs = globals()
module = config.pop(module_attr_name, None)
if module in sys.modules:
globs.update(sys.modules[module].__dict__)
elif module is not None:
# Note: we don't know the name of the function if it's a lambda.
warnings.warn("{} is not loaded, but a layer uses it. "
"It may cause errors.".format(module), UserWarning)
if custom_objects:
globs.update(custom_objects)
function_type = config.pop(func_type_attr_name)
if function_type == "function":
# Simple lookup in custom objects
function = generic_utils.deserialize_keras_object(
config[func_attr_name],
custom_objects=custom_objects,
printable_module_name="function in wrapper")
elif function_type == "lambda":
# Unsafe deserialization from bytecode
function = generic_utils.func_load(
config[func_attr_name], globs=globs)
else:
raise TypeError("Unknown function type:", function_type)
return function | [
"def",
"_parse_config_to_function",
"(",
"config",
",",
"custom_objects",
",",
"func_attr_name",
",",
"func_type_attr_name",
",",
"module_attr_name",
")",
":",
"globs",
"=",
"globals",
"(",
")",
"module",
"=",
"config",
".",
"pop",
"(",
"module_attr_name",
",",
"None",
")",
"if",
"module",
"in",
"sys",
".",
"modules",
":",
"globs",
".",
"update",
"(",
"sys",
".",
"modules",
"[",
"module",
"]",
".",
"__dict__",
")",
"elif",
"module",
"is",
"not",
"None",
":",
"# Note: we don't know the name of the function if it's a lambda.",
"warnings",
".",
"warn",
"(",
"\"{} is not loaded, but a layer uses it. \"",
"\"It may cause errors.\"",
".",
"format",
"(",
"module",
")",
",",
"UserWarning",
")",
"if",
"custom_objects",
":",
"globs",
".",
"update",
"(",
"custom_objects",
")",
"function_type",
"=",
"config",
".",
"pop",
"(",
"func_type_attr_name",
")",
"if",
"function_type",
"==",
"\"function\"",
":",
"# Simple lookup in custom objects",
"function",
"=",
"generic_utils",
".",
"deserialize_keras_object",
"(",
"config",
"[",
"func_attr_name",
"]",
",",
"custom_objects",
"=",
"custom_objects",
",",
"printable_module_name",
"=",
"\"function in wrapper\"",
")",
"elif",
"function_type",
"==",
"\"lambda\"",
":",
"# Unsafe deserialization from bytecode",
"function",
"=",
"generic_utils",
".",
"func_load",
"(",
"config",
"[",
"func_attr_name",
"]",
",",
"globs",
"=",
"globs",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Unknown function type:\"",
",",
"function_type",
")",
"return",
"function"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/layers/legacy_rnn/rnn_cell_wrapper_impl.py#L464-L490 | |
neoml-lib/neoml | a0d370fba05269a1b2258cef126f77bbd2054a3e | NeoML/Python/neoml/Dnn/Crf.py | python | Crf.free_terms | (self) | return self._internal.get_free_terms() | Gets the hidden layer free terms. The blob size is class_count. | Gets the hidden layer free terms. The blob size is class_count. | [
"Gets",
"the",
"hidden",
"layer",
"free",
"terms",
".",
"The",
"blob",
"size",
"is",
"class_count",
"."
] | def free_terms(self):
"""Gets the hidden layer free terms. The blob size is class_count.
"""
return self._internal.get_free_terms() | [
"def",
"free_terms",
"(",
"self",
")",
":",
"return",
"self",
".",
"_internal",
".",
"get_free_terms",
"(",
")"
] | https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Crf.py#L177-L180 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | Process.Redirect | (*args, **kwargs) | return _misc_.Process_Redirect(*args, **kwargs) | Redirect(self) | Redirect(self) | [
"Redirect",
"(",
"self",
")"
] | def Redirect(*args, **kwargs):
"""Redirect(self)"""
return _misc_.Process_Redirect(*args, **kwargs) | [
"def",
"Redirect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"Process_Redirect",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L2007-L2009 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/model/subrobot.py | python | SubRobotModel.sensor | (self,index) | Returns the SimSensorModel corresponding to index. Note however that
you can't set the "link" setting according to this SubRobotModel.
Args:
index (int or str) | Returns the SimSensorModel corresponding to index. Note however that
you can't set the "link" setting according to this SubRobotModel. | [
"Returns",
"the",
"SimSensorModel",
"corresponding",
"to",
"index",
".",
"Note",
"however",
"that",
"you",
"can",
"t",
"set",
"the",
"link",
"setting",
"according",
"to",
"this",
"SubRobotModel",
"."
] | def sensor(self,index):
"""Returns the SimSensorModel corresponding to index. Note however that
you can't set the "link" setting according to this SubRobotModel.
Args:
index (int or str)
"""
if isinstance(index,str):
return self._robot.sensor(index)
else:
return self._robot.sensor(self.tofull(index)) | [
"def",
"sensor",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"str",
")",
":",
"return",
"self",
".",
"_robot",
".",
"sensor",
"(",
"index",
")",
"else",
":",
"return",
"self",
".",
"_robot",
".",
"sensor",
"(",
"self",
".",
"tofull",
"(",
"index",
")",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/model/subrobot.py#L364-L374 | ||
facebookincubator/katran | 192eb988c398afc673620254097defb7035d669e | build/fbcode_builder/shell_quoting.py | python | ShellQuoted.format | (self, **kwargs) | return ShellQuoted(
self.do_not_use_raw_str.format(
**dict(
(k, shell_quote(v).do_not_use_raw_str) for k, v in kwargs.items()
)
)
) | Use instead of str.format() when the arguments are either
`ShellQuoted()` or raw strings needing to be `shell_quote()`d.
Positional args are deliberately not supported since they are more
error-prone. | [] | def format(self, **kwargs):
"""
Use instead of str.format() when the arguments are either
`ShellQuoted()` or raw strings needing to be `shell_quote()`d.
Positional args are deliberately not supported since they are more
error-prone.
"""
return ShellQuoted(
self.do_not_use_raw_str.format(
**dict(
(k, shell_quote(v).do_not_use_raw_str) for k, v in kwargs.items()
)
)
) | [
"def",
"format",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"ShellQuoted",
"(",
"self",
".",
"do_not_use_raw_str",
".",
"format",
"(",
"*",
"*",
"dict",
"(",
"(",
"k",
",",
"shell_quote",
"(",
"v",
")",
".",
"do_not_use_raw_str",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
")",
")",
")"
] | https://github.com/facebookincubator/katran/blob/192eb988c398afc673620254097defb7035d669e/build/fbcode_builder/shell_quoting.py#L49-L65 | ||
alexgkendall/caffe-posenet | 62aafbd7c45df91acdba14f5d1406d8295c2bc6f | examples/finetune_flickr_style/assemble_data.py | python | download_image | (args_tuple) | For use with multiprocessing map. Returns filename on fail. | For use with multiprocessing map. Returns filename on fail. | [
"For",
"use",
"with",
"multiprocessing",
"map",
".",
"Returns",
"filename",
"on",
"fail",
"."
] | def download_image(args_tuple):
"For use with multiprocessing map. Returns filename on fail."
try:
url, filename = args_tuple
if not os.path.exists(filename):
urllib.urlretrieve(url, filename)
with open(filename) as f:
assert hashlib.sha1(f.read()).hexdigest() != MISSING_IMAGE_SHA1
test_read_image = io.imread(filename)
return True
except KeyboardInterrupt:
raise Exception() # multiprocessing doesn't catch keyboard exceptions
except:
return False | [
"def",
"download_image",
"(",
"args_tuple",
")",
":",
"try",
":",
"url",
",",
"filename",
"=",
"args_tuple",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"urllib",
".",
"urlretrieve",
"(",
"url",
",",
"filename",
")",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"assert",
"hashlib",
".",
"sha1",
"(",
"f",
".",
"read",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"!=",
"MISSING_IMAGE_SHA1",
"test_read_image",
"=",
"io",
".",
"imread",
"(",
"filename",
")",
"return",
"True",
"except",
"KeyboardInterrupt",
":",
"raise",
"Exception",
"(",
")",
"# multiprocessing doesn't catch keyboard exceptions",
"except",
":",
"return",
"False"
] | https://github.com/alexgkendall/caffe-posenet/blob/62aafbd7c45df91acdba14f5d1406d8295c2bc6f/examples/finetune_flickr_style/assemble_data.py#L23-L36 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags_validators.py | python | SimpleValidator.__init__ | (self, flag_name, checker, message) | Constructor.
Args:
flag_name: string, name of the flag.
checker: function to verify the validator.
input - value of the corresponding flag (string, boolean, etc).
output - Boolean. Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise Error.
message: string, error message to be shown to the user if validator's
condition is not satisfied | Constructor. | [
"Constructor",
"."
] | def __init__(self, flag_name, checker, message):
"""Constructor.
Args:
flag_name: string, name of the flag.
checker: function to verify the validator.
input - value of the corresponding flag (string, boolean, etc).
output - Boolean. Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise Error.
message: string, error message to be shown to the user if validator's
condition is not satisfied
"""
super(SimpleValidator, self).__init__(checker, message)
self.flag_name = flag_name | [
"def",
"__init__",
"(",
"self",
",",
"flag_name",
",",
"checker",
",",
"message",
")",
":",
"super",
"(",
"SimpleValidator",
",",
"self",
")",
".",
"__init__",
"(",
"checker",
",",
"message",
")",
"self",
".",
"flag_name",
"=",
"flag_name"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags_validators.py#L111-L125 | ||
gem5/gem5 | 141cc37c2d4b93959d4c249b8f7e6a8b2ef75338 | ext/ply/example/GardenSnake/GardenSnake.py | python | t_WS | (t) | r' [ ]+ | r' [ ]+ | [
"r",
"[",
"]",
"+"
] | def t_WS(t):
r' [ ]+ '
if t.lexer.at_line_start and t.lexer.paren_count == 0:
return t | [
"def",
"t_WS",
"(",
"t",
")",
":",
"if",
"t",
".",
"lexer",
".",
"at_line_start",
"and",
"t",
".",
"lexer",
".",
"paren_count",
"==",
"0",
":",
"return",
"t"
] | https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/GardenSnake/GardenSnake.py#L120-L123 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/fit_function_options_view.py | python | FitFunctionOptionsView.update_function_browser_parameters | (self, is_simultaneous_fit: bool, fit_function: IFunction,
global_parameters: list = []) | Updates the parameters in the function browser. | Updates the parameters in the function browser. | [
"Updates",
"the",
"parameters",
"in",
"the",
"function",
"browser",
"."
] | def update_function_browser_parameters(self, is_simultaneous_fit: bool, fit_function: IFunction,
global_parameters: list = []) -> None:
"""Updates the parameters in the function browser."""
self.function_browser.blockSignals(True)
if fit_function is None:
self.function_browser.setFunction("")
elif is_simultaneous_fit:
self.function_browser.updateMultiDatasetParameters(fit_function.clone())
self.global_parameters = global_parameters
else:
self.function_browser.updateParameters(fit_function)
self.function_browser.blockSignals(False)
self.function_browser.setErrorsEnabled(True) | [
"def",
"update_function_browser_parameters",
"(",
"self",
",",
"is_simultaneous_fit",
":",
"bool",
",",
"fit_function",
":",
"IFunction",
",",
"global_parameters",
":",
"list",
"=",
"[",
"]",
")",
"->",
"None",
":",
"self",
".",
"function_browser",
".",
"blockSignals",
"(",
"True",
")",
"if",
"fit_function",
"is",
"None",
":",
"self",
".",
"function_browser",
".",
"setFunction",
"(",
"\"\"",
")",
"elif",
"is_simultaneous_fit",
":",
"self",
".",
"function_browser",
".",
"updateMultiDatasetParameters",
"(",
"fit_function",
".",
"clone",
"(",
")",
")",
"self",
".",
"global_parameters",
"=",
"global_parameters",
"else",
":",
"self",
".",
"function_browser",
".",
"updateParameters",
"(",
"fit_function",
")",
"self",
".",
"function_browser",
".",
"blockSignals",
"(",
"False",
")",
"self",
".",
"function_browser",
".",
"setErrorsEnabled",
"(",
"True",
")"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/fit_function_options_view.py#L187-L201 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_windows.py | python | PrintPreview.DetermineScaling | (*args, **kwargs) | return _windows_.PrintPreview_DetermineScaling(*args, **kwargs) | DetermineScaling(self) | DetermineScaling(self) | [
"DetermineScaling",
"(",
"self",
")"
] | def DetermineScaling(*args, **kwargs):
"""DetermineScaling(self)"""
return _windows_.PrintPreview_DetermineScaling(*args, **kwargs) | [
"def",
"DetermineScaling",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PrintPreview_DetermineScaling",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L5654-L5656 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/pubsub/core/topicobj.py | python | Topic.hasListener | (self, listener) | return listener in self.__listeners | Return true if listener is subscribed to this topic. | Return true if listener is subscribed to this topic. | [
"Return",
"true",
"if",
"listener",
"is",
"subscribed",
"to",
"this",
"topic",
"."
] | def hasListener(self, listener):
"""Return true if listener is subscribed to this topic."""
return listener in self.__listeners | [
"def",
"hasListener",
"(",
"self",
",",
"listener",
")",
":",
"return",
"listener",
"in",
"self",
".",
"__listeners"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pubsub/core/topicobj.py#L253-L255 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_controls.py | python | TreeCtrl.Collapse | (*args, **kwargs) | return _controls_.TreeCtrl_Collapse(*args, **kwargs) | Collapse(self, TreeItemId item) | Collapse(self, TreeItemId item) | [
"Collapse",
"(",
"self",
"TreeItemId",
"item",
")"
] | def Collapse(*args, **kwargs):
"""Collapse(self, TreeItemId item)"""
return _controls_.TreeCtrl_Collapse(*args, **kwargs) | [
"def",
"Collapse",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_controls_",
".",
"TreeCtrl_Collapse",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L5475-L5477 | |
GoSSIP-SJTU/Armariris | ad5d868482956b2194a77b39c8d543c7c2318200 | tools/clang/bindings/python/clang/cindex.py | python | Cursor.underlying_typedef_type | (self) | return self._underlying_type | Return the underlying type of a typedef declaration.
Returns a Type for the typedef this cursor is a declaration for. If
the current cursor is not a typedef, this raises. | Return the underlying type of a typedef declaration. | [
"Return",
"the",
"underlying",
"type",
"of",
"a",
"typedef",
"declaration",
"."
] | def underlying_typedef_type(self):
"""Return the underlying type of a typedef declaration.
Returns a Type for the typedef this cursor is a declaration for. If
the current cursor is not a typedef, this raises.
"""
if not hasattr(self, '_underlying_type'):
assert self.kind.is_declaration()
self._underlying_type = \
conf.lib.clang_getTypedefDeclUnderlyingType(self)
return self._underlying_type | [
"def",
"underlying_typedef_type",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_underlying_type'",
")",
":",
"assert",
"self",
".",
"kind",
".",
"is_declaration",
"(",
")",
"self",
".",
"_underlying_type",
"=",
"conf",
".",
"lib",
".",
"clang_getTypedefDeclUnderlyingType",
"(",
"self",
")",
"return",
"self",
".",
"_underlying_type"
] | https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/tools/clang/bindings/python/clang/cindex.py#L1380-L1391 | |
verilog-to-routing/vtr-verilog-to-routing | d9719cf7374821156c3cee31d66991cb85578562 | libs/EXTERNAL/libcatch2/tools/scripts/updateDocumentToC.py | python | createToc | (headlines, hyperlink=True, top_link=False, no_toc_header=False) | return processed | Creates the table of contents from the headline list
that was returned by the tagAndCollect function.
Keyword Arguments:
headlines: list of lists
e.g., ['Some header lvl3', 'some-header-lvl3', 3]
hyperlink: Creates hyperlinks in Markdown format if True,
e.g., '- [Some header lvl1](#some-header-lvl1)'
top_link: if True, add a id tag for linking the table
of contents itself (for the back-to-top-links)
no_toc_header: suppresses TOC header if True.
Returns a list of headlines for a table of contents
in Markdown format,
e.g., [' - [Some header lvl3](#some-header-lvl3)', ...] | Creates the table of contents from the headline list
that was returned by the tagAndCollect function. | [
"Creates",
"the",
"table",
"of",
"contents",
"from",
"the",
"headline",
"list",
"that",
"was",
"returned",
"by",
"the",
"tagAndCollect",
"function",
"."
] | def createToc(headlines, hyperlink=True, top_link=False, no_toc_header=False):
"""
Creates the table of contents from the headline list
that was returned by the tagAndCollect function.
Keyword Arguments:
headlines: list of lists
e.g., ['Some header lvl3', 'some-header-lvl3', 3]
hyperlink: Creates hyperlinks in Markdown format if True,
e.g., '- [Some header lvl1](#some-header-lvl1)'
top_link: if True, add a id tag for linking the table
of contents itself (for the back-to-top-links)
no_toc_header: suppresses TOC header if True.
Returns a list of headlines for a table of contents
in Markdown format,
e.g., [' - [Some header lvl3](#some-header-lvl3)', ...]
"""
processed = []
if not no_toc_header:
if top_link:
processed.append('<a class="mk-toclify" id="table-of-contents"></a>\n')
processed.append(contentTitle + '<br>')
for line in headlines:
if hyperlink:
item = '[%s](#%s)' % (line[0], line[1])
else:
item = '%s- %s' % ((line[2]-1)*' ', line[0])
processed.append(item + '<br>')
processed.append('\n')
return processed | [
"def",
"createToc",
"(",
"headlines",
",",
"hyperlink",
"=",
"True",
",",
"top_link",
"=",
"False",
",",
"no_toc_header",
"=",
"False",
")",
":",
"processed",
"=",
"[",
"]",
"if",
"not",
"no_toc_header",
":",
"if",
"top_link",
":",
"processed",
".",
"append",
"(",
"'<a class=\"mk-toclify\" id=\"table-of-contents\"></a>\\n'",
")",
"processed",
".",
"append",
"(",
"contentTitle",
"+",
"'<br>'",
")",
"for",
"line",
"in",
"headlines",
":",
"if",
"hyperlink",
":",
"item",
"=",
"'[%s](#%s)'",
"%",
"(",
"line",
"[",
"0",
"]",
",",
"line",
"[",
"1",
"]",
")",
"else",
":",
"item",
"=",
"'%s- %s'",
"%",
"(",
"(",
"line",
"[",
"2",
"]",
"-",
"1",
")",
"*",
"' '",
",",
"line",
"[",
"0",
"]",
")",
"processed",
".",
"append",
"(",
"item",
"+",
"'<br>'",
")",
"processed",
".",
"append",
"(",
"'\\n'",
")",
"return",
"processed"
] | https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/libs/EXTERNAL/libcatch2/tools/scripts/updateDocumentToC.py#L193-L225 | |
BitMEX/api-connectors | 37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812 | auto-generated/python/swagger_client/models/instrument.py | python | Instrument.funding_premium_symbol | (self, funding_premium_symbol) | Sets the funding_premium_symbol of this Instrument.
:param funding_premium_symbol: The funding_premium_symbol of this Instrument. # noqa: E501
:type: str | Sets the funding_premium_symbol of this Instrument. | [
"Sets",
"the",
"funding_premium_symbol",
"of",
"this",
"Instrument",
"."
] | def funding_premium_symbol(self, funding_premium_symbol):
"""Sets the funding_premium_symbol of this Instrument.
:param funding_premium_symbol: The funding_premium_symbol of this Instrument. # noqa: E501
:type: str
"""
self._funding_premium_symbol = funding_premium_symbol | [
"def",
"funding_premium_symbol",
"(",
"self",
",",
"funding_premium_symbol",
")",
":",
"self",
".",
"_funding_premium_symbol",
"=",
"funding_premium_symbol"
] | https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/instrument.py#L1622-L1630 | ||
h0x91b/redis-v8 | ac8b9d49701d75bcee3719892a2a6a50b437e47a | redis/deps/v8/tools/grokdump.py | python | InspectionPadawan.FindMap | (self, tagged_address) | When used as a mixin in place of V8Heap. | When used as a mixin in place of V8Heap. | [
"When",
"used",
"as",
"a",
"mixin",
"in",
"place",
"of",
"V8Heap",
"."
] | def FindMap(self, tagged_address):
"""When used as a mixin in place of V8Heap."""
raise NotImplementedError | [
"def",
"FindMap",
"(",
"self",
",",
"tagged_address",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/h0x91b/redis-v8/blob/ac8b9d49701d75bcee3719892a2a6a50b437e47a/redis/deps/v8/tools/grokdump.py#L1631-L1633 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py | python | Decimal._islogical | (self) | return True | Return True if self is a logical operand.
For being logical, it must be a finite number with a sign of 0,
an exponent of 0, and a coefficient whose digits must all be
either 0 or 1. | Return True if self is a logical operand. | [
"Return",
"True",
"if",
"self",
"is",
"a",
"logical",
"operand",
"."
] | def _islogical(self):
"""Return True if self is a logical operand.
For being logical, it must be a finite number with a sign of 0,
an exponent of 0, and a coefficient whose digits must all be
either 0 or 1.
"""
if self._sign != 0 or self._exp != 0:
return False
for dig in self._int:
if dig not in '01':
return False
return True | [
"def",
"_islogical",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sign",
"!=",
"0",
"or",
"self",
".",
"_exp",
"!=",
"0",
":",
"return",
"False",
"for",
"dig",
"in",
"self",
".",
"_int",
":",
"if",
"dig",
"not",
"in",
"'01'",
":",
"return",
"False",
"return",
"True"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py#L3353-L3365 | |
apple/swift | 469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893 | utils/swift_build_support/swift_build_support/products/tsan_libdispatch.py | python | TSanLibDispatch.build | (self, host_target) | Build TSan runtime (compiler-rt). | Build TSan runtime (compiler-rt). | [
"Build",
"TSan",
"runtime",
"(",
"compiler",
"-",
"rt",
")",
"."
] | def build(self, host_target):
"""Build TSan runtime (compiler-rt)."""
rt_source_dir = join_path(
self.source_dir, os.pardir,
'llvm-project', 'compiler-rt')
toolchain_path = join_path(self.args.install_destdir, 'usr')
clang = join_path(toolchain_path, 'bin', 'clang')
clangxx = join_path(toolchain_path, 'bin', 'clang++')
config_cmd = [
self.toolchain.cmake,
'-GNinja',
'-DCMAKE_PREFIX_PATH=%s' % toolchain_path,
'-DCMAKE_C_COMPILER=%s' % clang,
'-DCMAKE_CXX_COMPILER=%s' % clangxx,
'-DCMAKE_BUILD_TYPE=Release',
'-DLLVM_ENABLE_ASSERTIONS=ON',
'-DCOMPILER_RT_INCLUDE_TESTS=ON',
'-DCOMPILER_RT_BUILD_XRAY=OFF',
'-DCOMPILER_RT_INTERCEPT_LIBDISPATCH=ON',
'-DCOMPILER_RT_LIBDISPATCH_INSTALL_PATH=%s' % toolchain_path,
rt_source_dir]
build_cmd = ['ninja', 'tsan']
# Always rebuild TSan runtime
shell.rmtree(self.build_dir)
shell.makedirs(self.build_dir)
with shell.pushd(self.build_dir):
shell.call(config_cmd)
shell.call(build_cmd) | [
"def",
"build",
"(",
"self",
",",
"host_target",
")",
":",
"rt_source_dir",
"=",
"join_path",
"(",
"self",
".",
"source_dir",
",",
"os",
".",
"pardir",
",",
"'llvm-project'",
",",
"'compiler-rt'",
")",
"toolchain_path",
"=",
"join_path",
"(",
"self",
".",
"args",
".",
"install_destdir",
",",
"'usr'",
")",
"clang",
"=",
"join_path",
"(",
"toolchain_path",
",",
"'bin'",
",",
"'clang'",
")",
"clangxx",
"=",
"join_path",
"(",
"toolchain_path",
",",
"'bin'",
",",
"'clang++'",
")",
"config_cmd",
"=",
"[",
"self",
".",
"toolchain",
".",
"cmake",
",",
"'-GNinja'",
",",
"'-DCMAKE_PREFIX_PATH=%s'",
"%",
"toolchain_path",
",",
"'-DCMAKE_C_COMPILER=%s'",
"%",
"clang",
",",
"'-DCMAKE_CXX_COMPILER=%s'",
"%",
"clangxx",
",",
"'-DCMAKE_BUILD_TYPE=Release'",
",",
"'-DLLVM_ENABLE_ASSERTIONS=ON'",
",",
"'-DCOMPILER_RT_INCLUDE_TESTS=ON'",
",",
"'-DCOMPILER_RT_BUILD_XRAY=OFF'",
",",
"'-DCOMPILER_RT_INTERCEPT_LIBDISPATCH=ON'",
",",
"'-DCOMPILER_RT_LIBDISPATCH_INSTALL_PATH=%s'",
"%",
"toolchain_path",
",",
"rt_source_dir",
"]",
"build_cmd",
"=",
"[",
"'ninja'",
",",
"'tsan'",
"]",
"# Always rebuild TSan runtime",
"shell",
".",
"rmtree",
"(",
"self",
".",
"build_dir",
")",
"shell",
".",
"makedirs",
"(",
"self",
".",
"build_dir",
")",
"with",
"shell",
".",
"pushd",
"(",
"self",
".",
"build_dir",
")",
":",
"shell",
".",
"call",
"(",
"config_cmd",
")",
"shell",
".",
"call",
"(",
"build_cmd",
")"
] | https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/swift_build_support/swift_build_support/products/tsan_libdispatch.py#L49-L79 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_gdi.py | python | GraphicsFont.__init__ | (self, *args, **kwargs) | __init__(self) -> GraphicsFont
A `wx.GraphicsFont` is a native representation of a font (including
text colour). The contents are specific an private to the respective
renderer. The only way to get a valid instance is via a CreateFont
call on the graphics context or the renderer instance. | __init__(self) -> GraphicsFont | [
"__init__",
"(",
"self",
")",
"-",
">",
"GraphicsFont"
] | def __init__(self, *args, **kwargs):
"""
__init__(self) -> GraphicsFont
A `wx.GraphicsFont` is a native representation of a font (including
text colour). The contents are specific an private to the respective
renderer. The only way to get a valid instance is via a CreateFont
call on the graphics context or the renderer instance.
"""
_gdi_.GraphicsFont_swiginit(self,_gdi_.new_GraphicsFont(*args, **kwargs)) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_gdi_",
".",
"GraphicsFont_swiginit",
"(",
"self",
",",
"_gdi_",
".",
"new_GraphicsFont",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L5569-L5578 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | v8_7_5/tools/stats-viewer.py | python | Main | (data_file, name_filter) | Run the stats counter.
Args:
data_file: The counters file to monitor.
name_filter: The regexp filter to apply to counter names. | Run the stats counter. | [
"Run",
"the",
"stats",
"counter",
"."
] | def Main(data_file, name_filter):
"""Run the stats counter.
Args:
data_file: The counters file to monitor.
name_filter: The regexp filter to apply to counter names.
"""
StatsViewer(data_file, name_filter).Run() | [
"def",
"Main",
"(",
"data_file",
",",
"name_filter",
")",
":",
"StatsViewer",
"(",
"data_file",
",",
"name_filter",
")",
".",
"Run",
"(",
")"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/v8_7_5/tools/stats-viewer.py#L454-L461 | ||
FreeCAD/FreeCAD | ba42231b9c6889b89e064d6d563448ed81e376ec | src/Mod/Arch/ArchSite.py | python | _Site.execute | (self,obj) | Method run when the object is recomputed.
If the site has no Shape or Terrain property assigned, do nothing.
Perform additions and subtractions on terrain, and assign to the site's
Shape. | Method run when the object is recomputed. | [
"Method",
"run",
"when",
"the",
"object",
"is",
"recomputed",
"."
] | def execute(self,obj):
"""Method run when the object is recomputed.
If the site has no Shape or Terrain property assigned, do nothing.
Perform additions and subtractions on terrain, and assign to the site's
Shape.
"""
if not hasattr(obj,'Shape'): # old-style Site
return
pl = obj.Placement
shape = None
if obj.Terrain:
if hasattr(obj.Terrain,'Shape'):
if obj.Terrain.Shape:
if not obj.Terrain.Shape.isNull():
shape = obj.Terrain.Shape.copy()
if shape:
shells = []
for sub in obj.Subtractions:
if hasattr(sub,'Shape'):
if sub.Shape:
if sub.Shape.Solids:
for sol in sub.Shape.Solids:
rest = shape.cut(sol)
shells.append(sol.Shells[0].common(shape.extrude(obj.ExtrusionVector)))
shape = rest
for sub in obj.Additions:
if hasattr(sub,'Shape'):
if sub.Shape:
if sub.Shape.Solids:
for sol in sub.Shape.Solids:
rest = shape.cut(sol)
shells.append(sol.Shells[0].cut(shape.extrude(obj.ExtrusionVector)))
shape = rest
if not shape.isNull():
if shape.isValid():
for shell in shells:
shape = shape.fuse(shell)
if obj.RemoveSplitter:
shape = shape.removeSplitter()
obj.Shape = shape
if not pl.isNull():
obj.Placement = pl
self.computeAreas(obj) | [
"def",
"execute",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'Shape'",
")",
":",
"# old-style Site",
"return",
"pl",
"=",
"obj",
".",
"Placement",
"shape",
"=",
"None",
"if",
"obj",
".",
"Terrain",
":",
"if",
"hasattr",
"(",
"obj",
".",
"Terrain",
",",
"'Shape'",
")",
":",
"if",
"obj",
".",
"Terrain",
".",
"Shape",
":",
"if",
"not",
"obj",
".",
"Terrain",
".",
"Shape",
".",
"isNull",
"(",
")",
":",
"shape",
"=",
"obj",
".",
"Terrain",
".",
"Shape",
".",
"copy",
"(",
")",
"if",
"shape",
":",
"shells",
"=",
"[",
"]",
"for",
"sub",
"in",
"obj",
".",
"Subtractions",
":",
"if",
"hasattr",
"(",
"sub",
",",
"'Shape'",
")",
":",
"if",
"sub",
".",
"Shape",
":",
"if",
"sub",
".",
"Shape",
".",
"Solids",
":",
"for",
"sol",
"in",
"sub",
".",
"Shape",
".",
"Solids",
":",
"rest",
"=",
"shape",
".",
"cut",
"(",
"sol",
")",
"shells",
".",
"append",
"(",
"sol",
".",
"Shells",
"[",
"0",
"]",
".",
"common",
"(",
"shape",
".",
"extrude",
"(",
"obj",
".",
"ExtrusionVector",
")",
")",
")",
"shape",
"=",
"rest",
"for",
"sub",
"in",
"obj",
".",
"Additions",
":",
"if",
"hasattr",
"(",
"sub",
",",
"'Shape'",
")",
":",
"if",
"sub",
".",
"Shape",
":",
"if",
"sub",
".",
"Shape",
".",
"Solids",
":",
"for",
"sol",
"in",
"sub",
".",
"Shape",
".",
"Solids",
":",
"rest",
"=",
"shape",
".",
"cut",
"(",
"sol",
")",
"shells",
".",
"append",
"(",
"sol",
".",
"Shells",
"[",
"0",
"]",
".",
"cut",
"(",
"shape",
".",
"extrude",
"(",
"obj",
".",
"ExtrusionVector",
")",
")",
")",
"shape",
"=",
"rest",
"if",
"not",
"shape",
".",
"isNull",
"(",
")",
":",
"if",
"shape",
".",
"isValid",
"(",
")",
":",
"for",
"shell",
"in",
"shells",
":",
"shape",
"=",
"shape",
".",
"fuse",
"(",
"shell",
")",
"if",
"obj",
".",
"RemoveSplitter",
":",
"shape",
"=",
"shape",
".",
"removeSplitter",
"(",
")",
"obj",
".",
"Shape",
"=",
"shape",
"if",
"not",
"pl",
".",
"isNull",
"(",
")",
":",
"obj",
".",
"Placement",
"=",
"pl",
"self",
".",
"computeAreas",
"(",
"obj",
")"
] | https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchSite.py#L649-L696 | ||
OkCupid/okws | 1c337392c676ccb4e9a4c92d11d5d2fada6427d2 | contrib/pub3-upgrade.py | python | Pub1Parser.p_env | (self, p) | env : DLBRACE blocks DRBRACE | env : DLBRACE blocks DRBRACE | [
"env",
":",
"DLBRACE",
"blocks",
"DRBRACE"
] | def p_env (self, p):
'''env : DLBRACE blocks DRBRACE'''
p[0] = NestedHtml (HtmlBlock (p[2])) | [
"def",
"p_env",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"NestedHtml",
"(",
"HtmlBlock",
"(",
"p",
"[",
"2",
"]",
")",
")"
] | https://github.com/OkCupid/okws/blob/1c337392c676ccb4e9a4c92d11d5d2fada6427d2/contrib/pub3-upgrade.py#L1035-L1037 | ||
verilog-to-routing/vtr-verilog-to-routing | d9719cf7374821156c3cee31d66991cb85578562 | vtr_flow/scripts/benchtracker/interface_db.py | python | connect_db | (dbname="results.db") | return db | Attempt a database connection, exiting with 1 if dbname does not exist, else return with db connection | Attempt a database connection, exiting with 1 if dbname does not exist, else return with db connection | [
"Attempt",
"a",
"database",
"connection",
"exiting",
"with",
"1",
"if",
"dbname",
"does",
"not",
"exist",
"else",
"return",
"with",
"db",
"connection"
] | def connect_db(dbname="results.db"):
"""Attempt a database connection, exiting with 1 if dbname does not exist, else return with db connection"""
if not os.path.isfile(dbname):
print("{} does not exist".format(dbname))
raise IOError(dbname)
db = sqlite3.connect(dbname)
db.row_factory = sqlite3.Row
return db | [
"def",
"connect_db",
"(",
"dbname",
"=",
"\"results.db\"",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"dbname",
")",
":",
"print",
"(",
"\"{} does not exist\"",
".",
"format",
"(",
"dbname",
")",
")",
"raise",
"IOError",
"(",
"dbname",
")",
"db",
"=",
"sqlite3",
".",
"connect",
"(",
"dbname",
")",
"db",
".",
"row_factory",
"=",
"sqlite3",
".",
"Row",
"return",
"db"
] | https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/benchtracker/interface_db.py#L190-L197 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_core.py | python | TextEntryBase.CanUndo | (*args, **kwargs) | return _core_.TextEntryBase_CanUndo(*args, **kwargs) | CanUndo(self) -> bool
Returns True if the text field is editable and the last edit can be
undone. | CanUndo(self) -> bool | [
"CanUndo",
"(",
"self",
")",
"-",
">",
"bool"
] | def CanUndo(*args, **kwargs):
"""
CanUndo(self) -> bool
Returns True if the text field is editable and the last edit can be
undone.
"""
return _core_.TextEntryBase_CanUndo(*args, **kwargs) | [
"def",
"CanUndo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"TextEntryBase_CanUndo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L13227-L13234 | |
ApolloAuto/apollo-platform | 86d9dc6743b496ead18d597748ebabd34a513289 | ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/shape_base.py | python | atleast_3d | (*arys) | View inputs as arrays with at least three dimensions.
Parameters
----------
arys1, arys2, ... : array_like
One or more array-like sequences. Non-array inputs are converted to
arrays. Arrays that already have three or more dimensions are
preserved.
Returns
-------
res1, res2, ... : ndarray
An array, or tuple of arrays, each with ``a.ndim >= 3``. Copies are
avoided where possible, and views with three or more dimensions are
returned. For example, a 1-D array of shape ``(N,)`` becomes a view
of shape ``(1, N, 1)``, and a 2-D array of shape ``(M, N)`` becomes a
view of shape ``(M, N, 1)``.
See Also
--------
atleast_1d, atleast_2d
Examples
--------
>>> np.atleast_3d(3.0)
array([[[ 3.]]])
>>> x = np.arange(3.0)
>>> np.atleast_3d(x).shape
(1, 3, 1)
>>> x = np.arange(12.0).reshape(4,3)
>>> np.atleast_3d(x).shape
(4, 3, 1)
>>> np.atleast_3d(x).base is x
True
>>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]):
... print arr, arr.shape
...
[[[1]
[2]]] (1, 2, 1)
[[[1]
[2]]] (1, 2, 1)
[[[1 2]]] (1, 1, 2) | View inputs as arrays with at least three dimensions. | [
"View",
"inputs",
"as",
"arrays",
"with",
"at",
"least",
"three",
"dimensions",
"."
] | def atleast_3d(*arys):
"""
View inputs as arrays with at least three dimensions.
Parameters
----------
arys1, arys2, ... : array_like
One or more array-like sequences. Non-array inputs are converted to
arrays. Arrays that already have three or more dimensions are
preserved.
Returns
-------
res1, res2, ... : ndarray
An array, or tuple of arrays, each with ``a.ndim >= 3``. Copies are
avoided where possible, and views with three or more dimensions are
returned. For example, a 1-D array of shape ``(N,)`` becomes a view
of shape ``(1, N, 1)``, and a 2-D array of shape ``(M, N)`` becomes a
view of shape ``(M, N, 1)``.
See Also
--------
atleast_1d, atleast_2d
Examples
--------
>>> np.atleast_3d(3.0)
array([[[ 3.]]])
>>> x = np.arange(3.0)
>>> np.atleast_3d(x).shape
(1, 3, 1)
>>> x = np.arange(12.0).reshape(4,3)
>>> np.atleast_3d(x).shape
(4, 3, 1)
>>> np.atleast_3d(x).base is x
True
>>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]):
... print arr, arr.shape
...
[[[1]
[2]]] (1, 2, 1)
[[[1]
[2]]] (1, 2, 1)
[[[1 2]]] (1, 1, 2)
"""
res = []
for ary in arys:
ary = asanyarray(ary)
if len(ary.shape) == 0:
result = ary.reshape(1, 1, 1)
elif len(ary.shape) == 1:
result = ary[newaxis,:, newaxis]
elif len(ary.shape) == 2:
result = ary[:,:, newaxis]
else:
result = ary
res.append(result)
if len(res) == 1:
return res[0]
else:
return res | [
"def",
"atleast_3d",
"(",
"*",
"arys",
")",
":",
"res",
"=",
"[",
"]",
"for",
"ary",
"in",
"arys",
":",
"ary",
"=",
"asanyarray",
"(",
"ary",
")",
"if",
"len",
"(",
"ary",
".",
"shape",
")",
"==",
"0",
":",
"result",
"=",
"ary",
".",
"reshape",
"(",
"1",
",",
"1",
",",
"1",
")",
"elif",
"len",
"(",
"ary",
".",
"shape",
")",
"==",
"1",
":",
"result",
"=",
"ary",
"[",
"newaxis",
",",
":",
",",
"newaxis",
"]",
"elif",
"len",
"(",
"ary",
".",
"shape",
")",
"==",
"2",
":",
"result",
"=",
"ary",
"[",
":",
",",
":",
",",
"newaxis",
"]",
"else",
":",
"result",
"=",
"ary",
"res",
".",
"append",
"(",
"result",
")",
"if",
"len",
"(",
"res",
")",
"==",
"1",
":",
"return",
"res",
"[",
"0",
"]",
"else",
":",
"return",
"res"
] | https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/core/shape_base.py#L112-L176 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/framework/tensor_shape.py | python | TensorShape.__getitem__ | (self, key) | Returns the value of a dimension or a shape, depending on the key.
Args:
key: If `key` is an integer, returns the dimension at that index;
otherwise if `key` is a slice, returns a TensorShape whose
dimensions are those selected by the slice from `self`.
Returns:
A dimension if `key` is an integer, or a `TensorShape` if `key` is a
slice.
Raises:
ValueError: If `key` is a slice, and any of its elements are negative, or
if `self` is completely unknown and the step is set. | Returns the value of a dimension or a shape, depending on the key. | [
"Returns",
"the",
"value",
"of",
"a",
"dimension",
"or",
"a",
"shape",
"depending",
"on",
"the",
"key",
"."
] | def __getitem__(self, key):
"""Returns the value of a dimension or a shape, depending on the key.
Args:
key: If `key` is an integer, returns the dimension at that index;
otherwise if `key` is a slice, returns a TensorShape whose
dimensions are those selected by the slice from `self`.
Returns:
A dimension if `key` is an integer, or a `TensorShape` if `key` is a
slice.
Raises:
ValueError: If `key` is a slice, and any of its elements are negative, or
if `self` is completely unknown and the step is set.
"""
if self._dims is not None:
if isinstance(key, slice):
return TensorShape(self._dims[key])
else:
return self._dims[key]
else:
if isinstance(key, slice):
start = key.start if key.start is not None else 0
stop = key.stop
if key.step is not None:
# TODO(mrry): Handle these maybe.
raise ValueError("Steps are not yet handled")
if stop is None:
# NOTE(mrry): This implies that TensorShape(None) is compatible with
# TensorShape(None)[1:], which is obviously not true. It would be
# possible to track the number of dimensions symbolically,
# and perhaps we should do that.
return unknown_shape()
elif start < 0 or stop < 0:
# TODO(mrry): Handle this better, as it will be useful for handling
# suffixes of otherwise unknown shapes.
return unknown_shape()
else:
return unknown_shape(ndims=stop - start)
else:
return Dimension(None) | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"if",
"self",
".",
"_dims",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"key",
",",
"slice",
")",
":",
"return",
"TensorShape",
"(",
"self",
".",
"_dims",
"[",
"key",
"]",
")",
"else",
":",
"return",
"self",
".",
"_dims",
"[",
"key",
"]",
"else",
":",
"if",
"isinstance",
"(",
"key",
",",
"slice",
")",
":",
"start",
"=",
"key",
".",
"start",
"if",
"key",
".",
"start",
"is",
"not",
"None",
"else",
"0",
"stop",
"=",
"key",
".",
"stop",
"if",
"key",
".",
"step",
"is",
"not",
"None",
":",
"# TODO(mrry): Handle these maybe.",
"raise",
"ValueError",
"(",
"\"Steps are not yet handled\"",
")",
"if",
"stop",
"is",
"None",
":",
"# NOTE(mrry): This implies that TensorShape(None) is compatible with",
"# TensorShape(None)[1:], which is obviously not true. It would be",
"# possible to track the number of dimensions symbolically,",
"# and perhaps we should do that.",
"return",
"unknown_shape",
"(",
")",
"elif",
"start",
"<",
"0",
"or",
"stop",
"<",
"0",
":",
"# TODO(mrry): Handle this better, as it will be useful for handling",
"# suffixes of otherwise unknown shapes.",
"return",
"unknown_shape",
"(",
")",
"else",
":",
"return",
"unknown_shape",
"(",
"ndims",
"=",
"stop",
"-",
"start",
")",
"else",
":",
"return",
"Dimension",
"(",
"None",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/tensor_shape.py#L501-L543 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | Framework/PythonInterface/plugins/functions/GuinierPorod.py | python | GuinierPorod._boundary_conditions | (self, dummy_qval) | return False | Check boundary constraints and return True if we
are out of bounds.
@param dummy_qval: q-value to evaluate at | Check boundary constraints and return True if we
are out of bounds. | [
"Check",
"boundary",
"constraints",
"and",
"return",
"True",
"if",
"we",
"are",
"out",
"of",
"bounds",
"."
] | def _boundary_conditions(self, dummy_qval):
"""
Check boundary constraints and return True if we
are out of bounds.
@param dummy_qval: q-value to evaluate at
"""
s = self.getParameterValue('Dimension')
Rg = self.getParameterValue('Rg')
m = self.getParameterValue('M')
if Rg <= 0:
return True
if m < s:
return True
if s > 3.0:
return True
return False | [
"def",
"_boundary_conditions",
"(",
"self",
",",
"dummy_qval",
")",
":",
"s",
"=",
"self",
".",
"getParameterValue",
"(",
"'Dimension'",
")",
"Rg",
"=",
"self",
".",
"getParameterValue",
"(",
"'Rg'",
")",
"m",
"=",
"self",
".",
"getParameterValue",
"(",
"'M'",
")",
"if",
"Rg",
"<=",
"0",
":",
"return",
"True",
"if",
"m",
"<",
"s",
":",
"return",
"True",
"if",
"s",
">",
"3.0",
":",
"return",
"True",
"return",
"False"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/functions/GuinierPorod.py#L35-L50 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/random.py | python | Random.sample | (self, population, k) | return result | Chooses k unique random elements from a population sequence or set.
Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.
To choose a sample in a range of integers, use range as an argument.
This is especially fast and space efficient for sampling from a
large population: sample(range(10000000), 60) | Chooses k unique random elements from a population sequence or set. | [
"Chooses",
"k",
"unique",
"random",
"elements",
"from",
"a",
"population",
"sequence",
"or",
"set",
"."
] | def sample(self, population, k):
"""Chooses k unique random elements from a population sequence or set.
Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.
To choose a sample in a range of integers, use range as an argument.
This is especially fast and space efficient for sampling from a
large population: sample(range(10000000), 60)
"""
# Sampling without replacement entails tracking either potential
# selections (the pool) in a list or previous selections in a set.
# When the number of selections is small compared to the
# population, then tracking selections is efficient, requiring
# only a small set and an occasional reselection. For
# a larger number of selections, the pool tracking method is
# preferred since the list takes less space than the
# set and it doesn't suffer from frequent reselections.
if isinstance(population, _Set):
population = tuple(population)
if not isinstance(population, _Sequence):
raise TypeError("Population must be a sequence or set. For dicts, use list(d).")
randbelow = self._randbelow
n = len(population)
if not 0 <= k <= n:
raise ValueError("Sample larger than population or is negative")
result = [None] * k
setsize = 21 # size of a small set minus size of an empty list
if k > 5:
setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
if n <= setsize:
# An n-length list is smaller than a k-length set
pool = list(population)
for i in range(k): # invariant: non-selected at [0,n-i)
j = randbelow(n-i)
result[i] = pool[j]
pool[j] = pool[n-i-1] # move non-selected item into vacancy
else:
selected = set()
selected_add = selected.add
for i in range(k):
j = randbelow(n)
while j in selected:
j = randbelow(n)
selected_add(j)
result[i] = population[j]
return result | [
"def",
"sample",
"(",
"self",
",",
"population",
",",
"k",
")",
":",
"# Sampling without replacement entails tracking either potential",
"# selections (the pool) in a list or previous selections in a set.",
"# When the number of selections is small compared to the",
"# population, then tracking selections is efficient, requiring",
"# only a small set and an occasional reselection. For",
"# a larger number of selections, the pool tracking method is",
"# preferred since the list takes less space than the",
"# set and it doesn't suffer from frequent reselections.",
"if",
"isinstance",
"(",
"population",
",",
"_Set",
")",
":",
"population",
"=",
"tuple",
"(",
"population",
")",
"if",
"not",
"isinstance",
"(",
"population",
",",
"_Sequence",
")",
":",
"raise",
"TypeError",
"(",
"\"Population must be a sequence or set. For dicts, use list(d).\"",
")",
"randbelow",
"=",
"self",
".",
"_randbelow",
"n",
"=",
"len",
"(",
"population",
")",
"if",
"not",
"0",
"<=",
"k",
"<=",
"n",
":",
"raise",
"ValueError",
"(",
"\"Sample larger than population or is negative\"",
")",
"result",
"=",
"[",
"None",
"]",
"*",
"k",
"setsize",
"=",
"21",
"# size of a small set minus size of an empty list",
"if",
"k",
">",
"5",
":",
"setsize",
"+=",
"4",
"**",
"_ceil",
"(",
"_log",
"(",
"k",
"*",
"3",
",",
"4",
")",
")",
"# table size for big sets",
"if",
"n",
"<=",
"setsize",
":",
"# An n-length list is smaller than a k-length set",
"pool",
"=",
"list",
"(",
"population",
")",
"for",
"i",
"in",
"range",
"(",
"k",
")",
":",
"# invariant: non-selected at [0,n-i)",
"j",
"=",
"randbelow",
"(",
"n",
"-",
"i",
")",
"result",
"[",
"i",
"]",
"=",
"pool",
"[",
"j",
"]",
"pool",
"[",
"j",
"]",
"=",
"pool",
"[",
"n",
"-",
"i",
"-",
"1",
"]",
"# move non-selected item into vacancy",
"else",
":",
"selected",
"=",
"set",
"(",
")",
"selected_add",
"=",
"selected",
".",
"add",
"for",
"i",
"in",
"range",
"(",
"k",
")",
":",
"j",
"=",
"randbelow",
"(",
"n",
")",
"while",
"j",
"in",
"selected",
":",
"j",
"=",
"randbelow",
"(",
"n",
")",
"selected_add",
"(",
"j",
")",
"result",
"[",
"i",
"]",
"=",
"population",
"[",
"j",
"]",
"return",
"result"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/random.py#L286-L342 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py | python | MaskedArray.tobytes | (self, fill_value=None, order='C') | return self.filled(fill_value).tobytes(order=order) | Return the array data as a string containing the raw bytes in the array.
The array is filled with a fill value before the string conversion.
.. versionadded:: 1.9.0
Parameters
----------
fill_value : scalar, optional
Value used to fill in the masked values. Default is None, in which
case `MaskedArray.fill_value` is used.
order : {'C','F','A'}, optional
Order of the data item in the copy. Default is 'C'.
- 'C' -- C order (row major).
- 'F' -- Fortran order (column major).
- 'A' -- Any, current order of array.
- None -- Same as 'A'.
See Also
--------
numpy.ndarray.tobytes
tolist, tofile
Notes
-----
As for `ndarray.tobytes`, information about the shape, dtype, etc.,
but also about `fill_value`, will be lost.
Examples
--------
>>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
>>> x.tobytes()
b'\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00' | Return the array data as a string containing the raw bytes in the array. | [
"Return",
"the",
"array",
"data",
"as",
"a",
"string",
"containing",
"the",
"raw",
"bytes",
"in",
"the",
"array",
"."
] | def tobytes(self, fill_value=None, order='C'):
"""
Return the array data as a string containing the raw bytes in the array.
The array is filled with a fill value before the string conversion.
.. versionadded:: 1.9.0
Parameters
----------
fill_value : scalar, optional
Value used to fill in the masked values. Default is None, in which
case `MaskedArray.fill_value` is used.
order : {'C','F','A'}, optional
Order of the data item in the copy. Default is 'C'.
- 'C' -- C order (row major).
- 'F' -- Fortran order (column major).
- 'A' -- Any, current order of array.
- None -- Same as 'A'.
See Also
--------
numpy.ndarray.tobytes
tolist, tofile
Notes
-----
As for `ndarray.tobytes`, information about the shape, dtype, etc.,
but also about `fill_value`, will be lost.
Examples
--------
>>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
>>> x.tobytes()
b'\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00'
"""
return self.filled(fill_value).tobytes(order=order) | [
"def",
"tobytes",
"(",
"self",
",",
"fill_value",
"=",
"None",
",",
"order",
"=",
"'C'",
")",
":",
"return",
"self",
".",
"filled",
"(",
"fill_value",
")",
".",
"tobytes",
"(",
"order",
"=",
"order",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py#L5981-L6019 | |
cmu-db/noisepage | 79276e68fe83322f1249e8a8be96bd63c583ae56 | script/self_driving/model_server.py | python | ForecastModel.infer | (self, data: Dict) | return {0: result}, True, "" | Do inference on the model, give the data file, and the model_map_path
:param data: {
input_path: PATH_TO_TRACE, or None
input_sequence: Input sequence data, or None
model_path: model path
model_names: [LSTM...]
models_config: PATH_TO_JSON model config file
interval_micro_sec: Interval duration for aggregation in microseconds
sequence_length: Number of intervals in a data sequence
horizon_length: Number of intervals ahead for the planning horizon
}
:return: {Dict<cluster, Dict<query>, List<preds>>, if inference succeeds, error message} | Do inference on the model, give the data file, and the model_map_path
:param data: {
input_path: PATH_TO_TRACE, or None
input_sequence: Input sequence data, or None
model_path: model path
model_names: [LSTM...]
models_config: PATH_TO_JSON model config file
interval_micro_sec: Interval duration for aggregation in microseconds
sequence_length: Number of intervals in a data sequence
horizon_length: Number of intervals ahead for the planning horizon
}
:return: {Dict<cluster, Dict<query>, List<preds>>, if inference succeeds, error message} | [
"Do",
"inference",
"on",
"the",
"model",
"give",
"the",
"data",
"file",
"and",
"the",
"model_map_path",
":",
"param",
"data",
":",
"{",
"input_path",
":",
"PATH_TO_TRACE",
"or",
"None",
"input_sequence",
":",
"Input",
"sequence",
"data",
"or",
"None",
"model_path",
":",
"model",
"path",
"model_names",
":",
"[",
"LSTM",
"...",
"]",
"models_config",
":",
"PATH_TO_JSON",
"model",
"config",
"file",
"interval_micro_sec",
":",
"Interval",
"duration",
"for",
"aggregation",
"in",
"microseconds",
"sequence_length",
":",
"Number",
"of",
"intervals",
"in",
"a",
"data",
"sequence",
"horizon_length",
":",
"Number",
"of",
"intervals",
"ahead",
"for",
"the",
"planning",
"horizon",
"}",
":",
"return",
":",
"{",
"Dict<cluster",
"Dict<query",
">",
"List<preds",
">>",
"if",
"inference",
"succeeds",
"error",
"message",
"}"
] | def infer(self, data: Dict) -> Tuple[Any, bool, str]:
"""
Do inference on the model, give the data file, and the model_map_path
:param data: {
input_path: PATH_TO_TRACE, or None
input_sequence: Input sequence data, or None
model_path: model path
model_names: [LSTM...]
models_config: PATH_TO_JSON model config file
interval_micro_sec: Interval duration for aggregation in microseconds
sequence_length: Number of intervals in a data sequence
horizon_length: Number of intervals ahead for the planning horizon
}
:return: {Dict<cluster, Dict<query>, List<preds>>, if inference succeeds, error message}
"""
input_path = data["input_path"] if "input_path" in data else None
input_sequence = data["input_sequence"] if "input_sequence" in data else None
model_names = data["model_names"]
models_config = data.get("models_config")
interval = data["interval_micro_sec"]
seq_length = data["sequence_length"]
horizon_length = data["horizon_length"]
model_path = data["model_path"]
# Load the trained models
models = self._load_model(model_path)
if models is None:
logging.error(
f"Models at {str(model_path)} has not been trained")
return [], False, "MODELS_NOT_TRAINED"
if input_path is None and input_sequence is None:
return [], False, "NO_INPUT_PROVIDED"
if input_path is not None and input_sequence is not None:
return [], False, "BOTH_INPUT_PATH_AND_SEQUENCE_SPECIFIED"
forecaster = Forecaster(
trace_file=input_path,
trace_sequence=input_sequence,
test_mode=True,
interval_us=interval,
seq_len=seq_length,
eval_size=seq_length + 2 * horizon_length,
horizon_len=horizon_length)
# FIXME:
# Assuming all the queries in the current trace file are from
# the same cluster for now
# Only forecast with first element of model_names
result = {}
query_pred = forecaster.predict(0, models[0][model_names[0]])
for qid, ts in query_pred.items():
result[int(qid)] = ts
return {0: result}, True, "" | [
"def",
"infer",
"(",
"self",
",",
"data",
":",
"Dict",
")",
"->",
"Tuple",
"[",
"Any",
",",
"bool",
",",
"str",
"]",
":",
"input_path",
"=",
"data",
"[",
"\"input_path\"",
"]",
"if",
"\"input_path\"",
"in",
"data",
"else",
"None",
"input_sequence",
"=",
"data",
"[",
"\"input_sequence\"",
"]",
"if",
"\"input_sequence\"",
"in",
"data",
"else",
"None",
"model_names",
"=",
"data",
"[",
"\"model_names\"",
"]",
"models_config",
"=",
"data",
".",
"get",
"(",
"\"models_config\"",
")",
"interval",
"=",
"data",
"[",
"\"interval_micro_sec\"",
"]",
"seq_length",
"=",
"data",
"[",
"\"sequence_length\"",
"]",
"horizon_length",
"=",
"data",
"[",
"\"horizon_length\"",
"]",
"model_path",
"=",
"data",
"[",
"\"model_path\"",
"]",
"# Load the trained models",
"models",
"=",
"self",
".",
"_load_model",
"(",
"model_path",
")",
"if",
"models",
"is",
"None",
":",
"logging",
".",
"error",
"(",
"f\"Models at {str(model_path)} has not been trained\"",
")",
"return",
"[",
"]",
",",
"False",
",",
"\"MODELS_NOT_TRAINED\"",
"if",
"input_path",
"is",
"None",
"and",
"input_sequence",
"is",
"None",
":",
"return",
"[",
"]",
",",
"False",
",",
"\"NO_INPUT_PROVIDED\"",
"if",
"input_path",
"is",
"not",
"None",
"and",
"input_sequence",
"is",
"not",
"None",
":",
"return",
"[",
"]",
",",
"False",
",",
"\"BOTH_INPUT_PATH_AND_SEQUENCE_SPECIFIED\"",
"forecaster",
"=",
"Forecaster",
"(",
"trace_file",
"=",
"input_path",
",",
"trace_sequence",
"=",
"input_sequence",
",",
"test_mode",
"=",
"True",
",",
"interval_us",
"=",
"interval",
",",
"seq_len",
"=",
"seq_length",
",",
"eval_size",
"=",
"seq_length",
"+",
"2",
"*",
"horizon_length",
",",
"horizon_len",
"=",
"horizon_length",
")",
"# FIXME:",
"# Assuming all the queries in the current trace file are from",
"# the same cluster for now",
"# Only forecast with first element of model_names",
"result",
"=",
"{",
"}",
"query_pred",
"=",
"forecaster",
".",
"predict",
"(",
"0",
",",
"models",
"[",
"0",
"]",
"[",
"model_names",
"[",
"0",
"]",
"]",
")",
"for",
"qid",
",",
"ts",
"in",
"query_pred",
".",
"items",
"(",
")",
":",
"result",
"[",
"int",
"(",
"qid",
")",
"]",
"=",
"ts",
"return",
"{",
"0",
":",
"result",
"}",
",",
"True",
",",
"\"\""
] | https://github.com/cmu-db/noisepage/blob/79276e68fe83322f1249e8a8be96bd63c583ae56/script/self_driving/model_server.py#L539-L594 | |
hughperkins/tf-coriander | 970d3df6c11400ad68405f22b0c42a52374e94ca | tensorflow/python/training/saver.py | python | BaseSaverBuilder._AddSaveOps | (self, filename_tensor, saveables) | return control_flow_ops.with_dependencies([save], filename_tensor) | Add ops to save variables that are on the same shard.
Args:
filename_tensor: String Tensor.
saveables: A list of SaveableObject objects.
Returns:
A tensor with the filename used to save. | Add ops to save variables that are on the same shard. | [
"Add",
"ops",
"to",
"save",
"variables",
"that",
"are",
"on",
"the",
"same",
"shard",
"."
] | def _AddSaveOps(self, filename_tensor, saveables):
"""Add ops to save variables that are on the same shard.
Args:
filename_tensor: String Tensor.
saveables: A list of SaveableObject objects.
Returns:
A tensor with the filename used to save.
"""
save = self.save_op(filename_tensor, saveables)
return control_flow_ops.with_dependencies([save], filename_tensor) | [
"def",
"_AddSaveOps",
"(",
"self",
",",
"filename_tensor",
",",
"saveables",
")",
":",
"save",
"=",
"self",
".",
"save_op",
"(",
"filename_tensor",
",",
"saveables",
")",
"return",
"control_flow_ops",
".",
"with_dependencies",
"(",
"[",
"save",
"]",
",",
"filename_tensor",
")"
] | https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/saver.py#L220-L231 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/quantize/python/graph_matcher.py | python | GraphMatcher._match_pattern | (self, pattern, op, tensor) | return True | Returns whether an TF expression rooted at `op` matches `pattern`.
If there is a match, adds to `self._match_result` the matching op and tensor
with key `pattern`.
Args:
pattern: An `Pattern`.
op: A `tf.Operation` to match against the pattern.
tensor: the output `tf.Tensor` of `op` that is used by the matching op of
`pattern`'s parent. Can be None if `pattern` is already the root of the
pattern tree.
Returns:
True if an TF expression rooted at `op` matches `pattern`. | Returns whether an TF expression rooted at `op` matches `pattern`. | [
"Returns",
"whether",
"an",
"TF",
"expression",
"rooted",
"at",
"op",
"matches",
"pattern",
"."
] | def _match_pattern(self, pattern, op, tensor):
"""Returns whether an TF expression rooted at `op` matches `pattern`.
If there is a match, adds to `self._match_result` the matching op and tensor
with key `pattern`.
Args:
pattern: An `Pattern`.
op: A `tf.Operation` to match against the pattern.
tensor: the output `tf.Tensor` of `op` that is used by the matching op of
`pattern`'s parent. Can be None if `pattern` is already the root of the
pattern tree.
Returns:
True if an TF expression rooted at `op` matches `pattern`.
"""
match_result = pattern.match(op, tensor)
if match_result is None:
return False
self._match_result.merge_from(match_result)
return True | [
"def",
"_match_pattern",
"(",
"self",
",",
"pattern",
",",
"op",
",",
"tensor",
")",
":",
"match_result",
"=",
"pattern",
".",
"match",
"(",
"op",
",",
"tensor",
")",
"if",
"match_result",
"is",
"None",
":",
"return",
"False",
"self",
".",
"_match_result",
".",
"merge_from",
"(",
"match_result",
")",
"return",
"True"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/quantize/python/graph_matcher.py#L213-L233 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/ops/conv2d_benchmark.py | python | build_graph | (device, dtype, data_format, input_shape, filter_shape, strides,
padding, num_iters, warmup_iters) | builds a graph containing a sequence of conv2d operations.
Args:
device: String, the device to run on.
dtype: Data type for the convolution.
data_format: A string from: "NHWC" or "NCHW". Data format for input and
output data.
input_shape: Shape of the input tensor.
filter_shape: Shape of the filter tensor.
strides: A list of ints. 1-D of length 4. The stride of sliding
window for each dimension of input.
padding: A string from: "SAME", "VALID". The type of padding
algorithm to use.
num_iters: number of iterations to run conv2d.
warmup_iters: number of iterations for warmup runs.
Returns:
An array of tensors to run() | builds a graph containing a sequence of conv2d operations. | [
"builds",
"a",
"graph",
"containing",
"a",
"sequence",
"of",
"conv2d",
"operations",
"."
] | def build_graph(device, dtype, data_format, input_shape, filter_shape, strides,
padding, num_iters, warmup_iters):
"""builds a graph containing a sequence of conv2d operations.
Args:
device: String, the device to run on.
dtype: Data type for the convolution.
data_format: A string from: "NHWC" or "NCHW". Data format for input and
output data.
input_shape: Shape of the input tensor.
filter_shape: Shape of the filter tensor.
strides: A list of ints. 1-D of length 4. The stride of sliding
window for each dimension of input.
padding: A string from: "SAME", "VALID". The type of padding
algorithm to use.
num_iters: number of iterations to run conv2d.
warmup_iters: number of iterations for warmup runs.
Returns:
An array of tensors to run()
"""
with ops.device("/%s:0" % device):
inp = variables.VariableV1(
random_ops.truncated_normal(input_shape, dtype=dtype))
filt = variables.VariableV1(
random_ops.truncated_normal(filter_shape, dtype=dtype))
outputs = []
conv2d_op = nn_ops.conv2d(
inp, filt, strides, padding, data_format=data_format)
outputs.append(conv2d_op)
for _ in range(1, num_iters):
with ops.control_dependencies([conv2d_op]):
conv2d_op = nn_ops.conv2d(
inp, filt, strides, padding, data_format=data_format)
outputs.append(conv2d_op)
warmup_groups = []
warmup_conv2d_op = nn_ops.conv2d(
inp, filt, strides, padding, data_format=data_format)
warmup_groups.append(warmup_conv2d_op)
for _ in range(1, warmup_iters):
with ops.control_dependencies([warmup_conv2d_op]):
warmup_conv2d_op = nn_ops.conv2d(
inp, filt, strides, padding, data_format=data_format)
warmup_groups.append(warmup_conv2d_op)
return control_flow_ops.group(*warmup_groups), control_flow_ops.group(
*outputs) | [
"def",
"build_graph",
"(",
"device",
",",
"dtype",
",",
"data_format",
",",
"input_shape",
",",
"filter_shape",
",",
"strides",
",",
"padding",
",",
"num_iters",
",",
"warmup_iters",
")",
":",
"with",
"ops",
".",
"device",
"(",
"\"/%s:0\"",
"%",
"device",
")",
":",
"inp",
"=",
"variables",
".",
"VariableV1",
"(",
"random_ops",
".",
"truncated_normal",
"(",
"input_shape",
",",
"dtype",
"=",
"dtype",
")",
")",
"filt",
"=",
"variables",
".",
"VariableV1",
"(",
"random_ops",
".",
"truncated_normal",
"(",
"filter_shape",
",",
"dtype",
"=",
"dtype",
")",
")",
"outputs",
"=",
"[",
"]",
"conv2d_op",
"=",
"nn_ops",
".",
"conv2d",
"(",
"inp",
",",
"filt",
",",
"strides",
",",
"padding",
",",
"data_format",
"=",
"data_format",
")",
"outputs",
".",
"append",
"(",
"conv2d_op",
")",
"for",
"_",
"in",
"range",
"(",
"1",
",",
"num_iters",
")",
":",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"conv2d_op",
"]",
")",
":",
"conv2d_op",
"=",
"nn_ops",
".",
"conv2d",
"(",
"inp",
",",
"filt",
",",
"strides",
",",
"padding",
",",
"data_format",
"=",
"data_format",
")",
"outputs",
".",
"append",
"(",
"conv2d_op",
")",
"warmup_groups",
"=",
"[",
"]",
"warmup_conv2d_op",
"=",
"nn_ops",
".",
"conv2d",
"(",
"inp",
",",
"filt",
",",
"strides",
",",
"padding",
",",
"data_format",
"=",
"data_format",
")",
"warmup_groups",
".",
"append",
"(",
"warmup_conv2d_op",
")",
"for",
"_",
"in",
"range",
"(",
"1",
",",
"warmup_iters",
")",
":",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"warmup_conv2d_op",
"]",
")",
":",
"warmup_conv2d_op",
"=",
"nn_ops",
".",
"conv2d",
"(",
"inp",
",",
"filt",
",",
"strides",
",",
"padding",
",",
"data_format",
"=",
"data_format",
")",
"warmup_groups",
".",
"append",
"(",
"warmup_conv2d_op",
")",
"return",
"control_flow_ops",
".",
"group",
"(",
"*",
"warmup_groups",
")",
",",
"control_flow_ops",
".",
"group",
"(",
"*",
"outputs",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/conv2d_benchmark.py#L40-L87 | ||
danmar/cppcheck | 78228599da0dfce3763a90a130b14fa2d614ab9f | addons/misra.py | python | MisraChecker.isRuleSuppressed | (self, file_path, linenr, ruleNum) | return ruleIsSuppressed | Check to see if a rule is suppressed.
:param ruleNum: is the rule number in hundreds format
:param file_path: File path of checked location
:param linenr: Line number of checked location
If the rule exists in the dict then check for a filename
If the filename is None then rule is suppressed globally
for all files.
If the filename exists then look for list of
line number, symbol name tuples. If the list is None then
the rule is suppressed for the entire file
If the list of tuples exists then search the list looking for
matching line numbers. Symbol names are currently ignored
because they can include regular expressions.
TODO: Support symbol names and expression matching. | Check to see if a rule is suppressed. | [
"Check",
"to",
"see",
"if",
"a",
"rule",
"is",
"suppressed",
"."
] | def isRuleSuppressed(self, file_path, linenr, ruleNum):
"""
Check to see if a rule is suppressed.
:param ruleNum: is the rule number in hundreds format
:param file_path: File path of checked location
:param linenr: Line number of checked location
If the rule exists in the dict then check for a filename
If the filename is None then rule is suppressed globally
for all files.
If the filename exists then look for list of
line number, symbol name tuples. If the list is None then
the rule is suppressed for the entire file
If the list of tuples exists then search the list looking for
matching line numbers. Symbol names are currently ignored
because they can include regular expressions.
TODO: Support symbol names and expression matching.
"""
ruleIsSuppressed = False
# Remove any prefix listed in command arguments from the filename.
filename = None
if file_path is not None:
if self.filePrefix is not None:
filename = remove_file_prefix(file_path, self.filePrefix)
else:
filename = os.path.basename(file_path)
if ruleNum in self.suppressedRules:
fileDict = self.suppressedRules[ruleNum]
# a file name entry of None means that the rule is suppressed
# globally
if None in fileDict:
ruleIsSuppressed = True
else:
# Does the filename match one of the names in
# the file list
if filename in fileDict:
# Get the list of ruleItems
ruleItemList = fileDict[filename]
if None in ruleItemList:
# Entry of None in the ruleItemList means the rule is
# suppressed for all lines in the filename
ruleIsSuppressed = True
else:
# Iterate though the the list of line numbers
# and symbols looking for a match of the line
# number. Matching the symbol is a TODO:
for each in ruleItemList:
if each is not None:
if each[0] == linenr:
ruleIsSuppressed = True
return ruleIsSuppressed | [
"def",
"isRuleSuppressed",
"(",
"self",
",",
"file_path",
",",
"linenr",
",",
"ruleNum",
")",
":",
"ruleIsSuppressed",
"=",
"False",
"# Remove any prefix listed in command arguments from the filename.",
"filename",
"=",
"None",
"if",
"file_path",
"is",
"not",
"None",
":",
"if",
"self",
".",
"filePrefix",
"is",
"not",
"None",
":",
"filename",
"=",
"remove_file_prefix",
"(",
"file_path",
",",
"self",
".",
"filePrefix",
")",
"else",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"file_path",
")",
"if",
"ruleNum",
"in",
"self",
".",
"suppressedRules",
":",
"fileDict",
"=",
"self",
".",
"suppressedRules",
"[",
"ruleNum",
"]",
"# a file name entry of None means that the rule is suppressed",
"# globally",
"if",
"None",
"in",
"fileDict",
":",
"ruleIsSuppressed",
"=",
"True",
"else",
":",
"# Does the filename match one of the names in",
"# the file list",
"if",
"filename",
"in",
"fileDict",
":",
"# Get the list of ruleItems",
"ruleItemList",
"=",
"fileDict",
"[",
"filename",
"]",
"if",
"None",
"in",
"ruleItemList",
":",
"# Entry of None in the ruleItemList means the rule is",
"# suppressed for all lines in the filename",
"ruleIsSuppressed",
"=",
"True",
"else",
":",
"# Iterate though the the list of line numbers",
"# and symbols looking for a match of the line",
"# number. Matching the symbol is a TODO:",
"for",
"each",
"in",
"ruleItemList",
":",
"if",
"each",
"is",
"not",
"None",
":",
"if",
"each",
"[",
"0",
"]",
"==",
"linenr",
":",
"ruleIsSuppressed",
"=",
"True",
"return",
"ruleIsSuppressed"
] | https://github.com/danmar/cppcheck/blob/78228599da0dfce3763a90a130b14fa2d614ab9f/addons/misra.py#L3916-L3973 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/grid.py | python | Grid.GetGridLineColour | (*args, **kwargs) | return _grid.Grid_GetGridLineColour(*args, **kwargs) | GetGridLineColour(self) -> Colour | GetGridLineColour(self) -> Colour | [
"GetGridLineColour",
"(",
"self",
")",
"-",
">",
"Colour"
] | def GetGridLineColour(*args, **kwargs):
"""GetGridLineColour(self) -> Colour"""
return _grid.Grid_GetGridLineColour(*args, **kwargs) | [
"def",
"GetGridLineColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"Grid_GetGridLineColour",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1694-L1696 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/symsrc/pefile.py | python | Structure.all_zeroes | (self) | return self._all_zeroes | Returns true is the unpacked data is all zeroes. | Returns true is the unpacked data is all zeroes. | [
"Returns",
"true",
"is",
"the",
"unpacked",
"data",
"is",
"all",
"zeroes",
"."
] | def all_zeroes(self):
"""Returns true is the unpacked data is all zeroes."""
return self._all_zeroes | [
"def",
"all_zeroes",
"(",
"self",
")",
":",
"return",
"self",
".",
"_all_zeroes"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/symsrc/pefile.py#L697-L700 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/datasets/base.py | python | load_csv_with_header | (filename,
target_dtype,
features_dtype,
target_column=-1) | return Dataset(data=data, target=target) | Load dataset from CSV file with a header row. | Load dataset from CSV file with a header row. | [
"Load",
"dataset",
"from",
"CSV",
"file",
"with",
"a",
"header",
"row",
"."
] | def load_csv_with_header(filename,
target_dtype,
features_dtype,
target_column=-1):
"""Load dataset from CSV file with a header row."""
with gfile.Open(filename) as csv_file:
data_file = csv.reader(csv_file)
header = next(data_file)
n_samples = int(header[0])
n_features = int(header[1])
data = np.zeros((n_samples, n_features), dtype=features_dtype)
target = np.zeros((n_samples,), dtype=target_dtype)
for i, row in enumerate(data_file):
target[i] = np.asarray(row.pop(target_column), dtype=target_dtype)
data[i] = np.asarray(row, dtype=features_dtype)
return Dataset(data=data, target=target) | [
"def",
"load_csv_with_header",
"(",
"filename",
",",
"target_dtype",
",",
"features_dtype",
",",
"target_column",
"=",
"-",
"1",
")",
":",
"with",
"gfile",
".",
"Open",
"(",
"filename",
")",
"as",
"csv_file",
":",
"data_file",
"=",
"csv",
".",
"reader",
"(",
"csv_file",
")",
"header",
"=",
"next",
"(",
"data_file",
")",
"n_samples",
"=",
"int",
"(",
"header",
"[",
"0",
"]",
")",
"n_features",
"=",
"int",
"(",
"header",
"[",
"1",
"]",
")",
"data",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_samples",
",",
"n_features",
")",
",",
"dtype",
"=",
"features_dtype",
")",
"target",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_samples",
",",
")",
",",
"dtype",
"=",
"target_dtype",
")",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"data_file",
")",
":",
"target",
"[",
"i",
"]",
"=",
"np",
".",
"asarray",
"(",
"row",
".",
"pop",
"(",
"target_column",
")",
",",
"dtype",
"=",
"target_dtype",
")",
"data",
"[",
"i",
"]",
"=",
"np",
".",
"asarray",
"(",
"row",
",",
"dtype",
"=",
"features_dtype",
")",
"return",
"Dataset",
"(",
"data",
"=",
"data",
",",
"target",
"=",
"target",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/datasets/base.py#L46-L62 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/lite/python/lite.py | python | TFLiteConverterBase._get_base_converter_args | (self) | return args | Returns the base converter args.
Returns:
{key str: val} | Returns the base converter args. | [
"Returns",
"the",
"base",
"converter",
"args",
"."
] | def _get_base_converter_args(self):
"""Returns the base converter args.
Returns:
{key str: val}
"""
args = {
"input_format":
constants.TENSORFLOW_GRAPHDEF,
"allow_custom_ops":
self.allow_custom_ops,
"debug_info":
self._debug_info,
"target_ops":
self.target_spec.supported_ops,
"enable_mlir_converter":
self.experimental_new_converter,
"select_user_tf_ops":
self.target_spec.experimental_select_user_tf_ops,
"supported_backends":
self.target_spec.experimental_supported_backends,
"unfold_batchmatmul":
not self._experimental_disable_batchmatmul_unfold,
"lower_tensor_list_ops":
self._experimental_lower_tensor_list_ops,
"unfold_large_splat_constant":
self._experimental_unfold_large_splat_constant,
"default_to_single_batch_in_tensor_list_ops":
self._experimental_default_to_single_batch_in_tensor_list_ops,
"tf_quantization_mode":
self._experimental_tf_quantization_mode,
"experimental_enable_resource_variables":
self.experimental_enable_resource_variables,
}
if self.saved_model_dir:
args.update({
"saved_model_dir": self.saved_model_dir,
"saved_model_version": self._saved_model_version,
"saved_model_tags": self._saved_model_tags,
"saved_model_exported_names": self._saved_model_exported_names,
})
return args | [
"def",
"_get_base_converter_args",
"(",
"self",
")",
":",
"args",
"=",
"{",
"\"input_format\"",
":",
"constants",
".",
"TENSORFLOW_GRAPHDEF",
",",
"\"allow_custom_ops\"",
":",
"self",
".",
"allow_custom_ops",
",",
"\"debug_info\"",
":",
"self",
".",
"_debug_info",
",",
"\"target_ops\"",
":",
"self",
".",
"target_spec",
".",
"supported_ops",
",",
"\"enable_mlir_converter\"",
":",
"self",
".",
"experimental_new_converter",
",",
"\"select_user_tf_ops\"",
":",
"self",
".",
"target_spec",
".",
"experimental_select_user_tf_ops",
",",
"\"supported_backends\"",
":",
"self",
".",
"target_spec",
".",
"experimental_supported_backends",
",",
"\"unfold_batchmatmul\"",
":",
"not",
"self",
".",
"_experimental_disable_batchmatmul_unfold",
",",
"\"lower_tensor_list_ops\"",
":",
"self",
".",
"_experimental_lower_tensor_list_ops",
",",
"\"unfold_large_splat_constant\"",
":",
"self",
".",
"_experimental_unfold_large_splat_constant",
",",
"\"default_to_single_batch_in_tensor_list_ops\"",
":",
"self",
".",
"_experimental_default_to_single_batch_in_tensor_list_ops",
",",
"\"tf_quantization_mode\"",
":",
"self",
".",
"_experimental_tf_quantization_mode",
",",
"\"experimental_enable_resource_variables\"",
":",
"self",
".",
"experimental_enable_resource_variables",
",",
"}",
"if",
"self",
".",
"saved_model_dir",
":",
"args",
".",
"update",
"(",
"{",
"\"saved_model_dir\"",
":",
"self",
".",
"saved_model_dir",
",",
"\"saved_model_version\"",
":",
"self",
".",
"_saved_model_version",
",",
"\"saved_model_tags\"",
":",
"self",
".",
"_saved_model_tags",
",",
"\"saved_model_exported_names\"",
":",
"self",
".",
"_saved_model_exported_names",
",",
"}",
")",
"return",
"args"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/python/lite.py#L637-L680 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/contrib/data/python/ops/dataset_ops.py | python | Dataset.dense_to_sparse_batch | (self, batch_size, row_shape) | return self.apply(batching.dense_to_sparse_batch(batch_size, row_shape)) | Use: `Dataset.apply(tf.contrib.data.dense_to_sparse_batch(...))`. | Use: `Dataset.apply(tf.contrib.data.dense_to_sparse_batch(...))`. | [
"Use",
":",
"Dataset",
".",
"apply",
"(",
"tf",
".",
"contrib",
".",
"data",
".",
"dense_to_sparse_batch",
"(",
"...",
"))",
"."
] | def dense_to_sparse_batch(self, batch_size, row_shape):
"""Use: `Dataset.apply(tf.contrib.data.dense_to_sparse_batch(...))`."""
return self.apply(batching.dense_to_sparse_batch(batch_size, row_shape)) | [
"def",
"dense_to_sparse_batch",
"(",
"self",
",",
"batch_size",
",",
"row_shape",
")",
":",
"return",
"self",
".",
"apply",
"(",
"batching",
".",
"dense_to_sparse_batch",
"(",
"batch_size",
",",
"row_shape",
")",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/data/python/ops/dataset_ops.py#L461-L464 | |
qt/qtwebkit | ab1bd15209abaf7effc51dbc2f272c5681af7223 | Source/JavaScriptCore/disassembler/udis86/ud_opcode.py | python | UdOpcodeTables.mergeSSENONE | (self) | Merge sse tables with only one entry for /sse=none | Merge sse tables with only one entry for /sse=none | [
"Merge",
"sse",
"tables",
"with",
"only",
"one",
"entry",
"for",
"/",
"sse",
"=",
"none"
] | def mergeSSENONE(self):
"""Merge sse tables with only one entry for /sse=none
"""
for table in self._tables:
for k, e in table.entries():
if isinstance(e, UdOpcodeTable) and e.typ() == '/sse':
if e.numEntries() == 1:
sse = e.lookup("/sse=none")
if sse:
table.setEntryAt(k, sse)
uniqTables = {}
def genTableList(tbl):
if tbl not in uniqTables:
self._tables.append(tbl)
uniqTables[tbl] = 1
for k, e in tbl.entries():
if isinstance(e, UdOpcodeTable):
genTableList(e)
self._tables = []
genTableList(self.root) | [
"def",
"mergeSSENONE",
"(",
"self",
")",
":",
"for",
"table",
"in",
"self",
".",
"_tables",
":",
"for",
"k",
",",
"e",
"in",
"table",
".",
"entries",
"(",
")",
":",
"if",
"isinstance",
"(",
"e",
",",
"UdOpcodeTable",
")",
"and",
"e",
".",
"typ",
"(",
")",
"==",
"'/sse'",
":",
"if",
"e",
".",
"numEntries",
"(",
")",
"==",
"1",
":",
"sse",
"=",
"e",
".",
"lookup",
"(",
"\"/sse=none\"",
")",
"if",
"sse",
":",
"table",
".",
"setEntryAt",
"(",
"k",
",",
"sse",
")",
"uniqTables",
"=",
"{",
"}",
"def",
"genTableList",
"(",
"tbl",
")",
":",
"if",
"tbl",
"not",
"in",
"uniqTables",
":",
"self",
".",
"_tables",
".",
"append",
"(",
"tbl",
")",
"uniqTables",
"[",
"tbl",
"]",
"=",
"1",
"for",
"k",
",",
"e",
"in",
"tbl",
".",
"entries",
"(",
")",
":",
"if",
"isinstance",
"(",
"e",
",",
"UdOpcodeTable",
")",
":",
"genTableList",
"(",
"e",
")",
"self",
".",
"_tables",
"=",
"[",
"]",
"genTableList",
"(",
"self",
".",
"root",
")"
] | https://github.com/qt/qtwebkit/blob/ab1bd15209abaf7effc51dbc2f272c5681af7223/Source/JavaScriptCore/disassembler/udis86/ud_opcode.py#L337-L356 | ||
RobotLocomotion/drake | 0e18a34604c45ed65bc9018a54f7610f91cdad5b | bindings/pydrake/systems/planar_scenegraph_visualizer.py | python | PlanarSceneGraphVisualizer.draw | (self, context) | Overrides base with the implementation. | Overrides base with the implementation. | [
"Overrides",
"base",
"with",
"the",
"implementation",
"."
] | def draw(self, context):
"""Overrides base with the implementation."""
query_object = self._geometry_query_input_port.Eval(context)
inspector = query_object.inspector()
view_dir = np.cross(self._T_VW[0, :3], self._T_VW[1, :3])
for frame_id in inspector.GetAllFrameIds():
frame_name = self.frame_name(frame_id, inspector)
if frame_name not in self._patch_Blist:
continue
X_WB = query_object.GetPoseInWorld(frame_id)
patch_Wlist, _ = self._get_view_patches(frame_name, X_WB)
for i, patch_W in enumerate(patch_Wlist):
# Project the object vertices from 3d in world frame W to 2d in
# view frame V (keeps homogeneous portion, removing it later).
patch_V = self._project_patch(patch_W)
body_fill = self._body_fill_dict[frame_name][i]
# Use the latest vertices to update the body_fill.
self._update_body_fill_verts(body_fill, patch_V)
body_fill.zorder = X_WB.translation() @ view_dir
self.ax.set_title('t = {:.1f}'.format(context.get_time())) | [
"def",
"draw",
"(",
"self",
",",
"context",
")",
":",
"query_object",
"=",
"self",
".",
"_geometry_query_input_port",
".",
"Eval",
"(",
"context",
")",
"inspector",
"=",
"query_object",
".",
"inspector",
"(",
")",
"view_dir",
"=",
"np",
".",
"cross",
"(",
"self",
".",
"_T_VW",
"[",
"0",
",",
":",
"3",
"]",
",",
"self",
".",
"_T_VW",
"[",
"1",
",",
":",
"3",
"]",
")",
"for",
"frame_id",
"in",
"inspector",
".",
"GetAllFrameIds",
"(",
")",
":",
"frame_name",
"=",
"self",
".",
"frame_name",
"(",
"frame_id",
",",
"inspector",
")",
"if",
"frame_name",
"not",
"in",
"self",
".",
"_patch_Blist",
":",
"continue",
"X_WB",
"=",
"query_object",
".",
"GetPoseInWorld",
"(",
"frame_id",
")",
"patch_Wlist",
",",
"_",
"=",
"self",
".",
"_get_view_patches",
"(",
"frame_name",
",",
"X_WB",
")",
"for",
"i",
",",
"patch_W",
"in",
"enumerate",
"(",
"patch_Wlist",
")",
":",
"# Project the object vertices from 3d in world frame W to 2d in",
"# view frame V (keeps homogeneous portion, removing it later).",
"patch_V",
"=",
"self",
".",
"_project_patch",
"(",
"patch_W",
")",
"body_fill",
"=",
"self",
".",
"_body_fill_dict",
"[",
"frame_name",
"]",
"[",
"i",
"]",
"# Use the latest vertices to update the body_fill.",
"self",
".",
"_update_body_fill_verts",
"(",
"body_fill",
",",
"patch_V",
")",
"body_fill",
".",
"zorder",
"=",
"X_WB",
".",
"translation",
"(",
")",
"@",
"view_dir",
"self",
".",
"ax",
".",
"set_title",
"(",
"'t = {:.1f}'",
".",
"format",
"(",
"context",
".",
"get_time",
"(",
")",
")",
")"
] | https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/bindings/pydrake/systems/planar_scenegraph_visualizer.py#L383-L404 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/numpy/py3/numpy/lib/utils.py | python | who | (vardict=None) | return | Print the NumPy arrays in the given dictionary.
If there is no dictionary passed in or `vardict` is None then returns
NumPy arrays in the globals() dictionary (all NumPy arrays in the
namespace).
Parameters
----------
vardict : dict, optional
A dictionary possibly containing ndarrays. Default is globals().
Returns
-------
out : None
Returns 'None'.
Notes
-----
Prints out the name, shape, bytes and type of all of the ndarrays
present in `vardict`.
Examples
--------
>>> a = np.arange(10)
>>> b = np.ones(20)
>>> np.who()
Name Shape Bytes Type
===========================================================
a 10 80 int64
b 20 160 float64
Upper bound on total bytes = 240
>>> d = {'x': np.arange(2.0), 'y': np.arange(3.0), 'txt': 'Some str',
... 'idx':5}
>>> np.who(d)
Name Shape Bytes Type
===========================================================
x 2 16 float64
y 3 24 float64
Upper bound on total bytes = 40 | Print the NumPy arrays in the given dictionary. | [
"Print",
"the",
"NumPy",
"arrays",
"in",
"the",
"given",
"dictionary",
"."
] | def who(vardict=None):
"""
Print the NumPy arrays in the given dictionary.
If there is no dictionary passed in or `vardict` is None then returns
NumPy arrays in the globals() dictionary (all NumPy arrays in the
namespace).
Parameters
----------
vardict : dict, optional
A dictionary possibly containing ndarrays. Default is globals().
Returns
-------
out : None
Returns 'None'.
Notes
-----
Prints out the name, shape, bytes and type of all of the ndarrays
present in `vardict`.
Examples
--------
>>> a = np.arange(10)
>>> b = np.ones(20)
>>> np.who()
Name Shape Bytes Type
===========================================================
a 10 80 int64
b 20 160 float64
Upper bound on total bytes = 240
>>> d = {'x': np.arange(2.0), 'y': np.arange(3.0), 'txt': 'Some str',
... 'idx':5}
>>> np.who(d)
Name Shape Bytes Type
===========================================================
x 2 16 float64
y 3 24 float64
Upper bound on total bytes = 40
"""
if vardict is None:
frame = sys._getframe().f_back
vardict = frame.f_globals
sta = []
cache = {}
for name in vardict.keys():
if isinstance(vardict[name], ndarray):
var = vardict[name]
idv = id(var)
if idv in cache.keys():
namestr = name + " (%s)" % cache[idv]
original = 0
else:
cache[idv] = name
namestr = name
original = 1
shapestr = " x ".join(map(str, var.shape))
bytestr = str(var.nbytes)
sta.append([namestr, shapestr, bytestr, var.dtype.name,
original])
maxname = 0
maxshape = 0
maxbyte = 0
totalbytes = 0
for k in range(len(sta)):
val = sta[k]
if maxname < len(val[0]):
maxname = len(val[0])
if maxshape < len(val[1]):
maxshape = len(val[1])
if maxbyte < len(val[2]):
maxbyte = len(val[2])
if val[4]:
totalbytes += int(val[2])
if len(sta) > 0:
sp1 = max(10, maxname)
sp2 = max(10, maxshape)
sp3 = max(10, maxbyte)
prval = "Name %s Shape %s Bytes %s Type" % (sp1*' ', sp2*' ', sp3*' ')
print(prval + "\n" + "="*(len(prval)+5) + "\n")
for k in range(len(sta)):
val = sta[k]
print("%s %s %s %s %s %s %s" % (val[0], ' '*(sp1-len(val[0])+4),
val[1], ' '*(sp2-len(val[1])+5),
val[2], ' '*(sp3-len(val[2])+5),
val[3]))
print("\nUpper bound on total bytes = %d" % totalbytes)
return | [
"def",
"who",
"(",
"vardict",
"=",
"None",
")",
":",
"if",
"vardict",
"is",
"None",
":",
"frame",
"=",
"sys",
".",
"_getframe",
"(",
")",
".",
"f_back",
"vardict",
"=",
"frame",
".",
"f_globals",
"sta",
"=",
"[",
"]",
"cache",
"=",
"{",
"}",
"for",
"name",
"in",
"vardict",
".",
"keys",
"(",
")",
":",
"if",
"isinstance",
"(",
"vardict",
"[",
"name",
"]",
",",
"ndarray",
")",
":",
"var",
"=",
"vardict",
"[",
"name",
"]",
"idv",
"=",
"id",
"(",
"var",
")",
"if",
"idv",
"in",
"cache",
".",
"keys",
"(",
")",
":",
"namestr",
"=",
"name",
"+",
"\" (%s)\"",
"%",
"cache",
"[",
"idv",
"]",
"original",
"=",
"0",
"else",
":",
"cache",
"[",
"idv",
"]",
"=",
"name",
"namestr",
"=",
"name",
"original",
"=",
"1",
"shapestr",
"=",
"\" x \"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"var",
".",
"shape",
")",
")",
"bytestr",
"=",
"str",
"(",
"var",
".",
"nbytes",
")",
"sta",
".",
"append",
"(",
"[",
"namestr",
",",
"shapestr",
",",
"bytestr",
",",
"var",
".",
"dtype",
".",
"name",
",",
"original",
"]",
")",
"maxname",
"=",
"0",
"maxshape",
"=",
"0",
"maxbyte",
"=",
"0",
"totalbytes",
"=",
"0",
"for",
"k",
"in",
"range",
"(",
"len",
"(",
"sta",
")",
")",
":",
"val",
"=",
"sta",
"[",
"k",
"]",
"if",
"maxname",
"<",
"len",
"(",
"val",
"[",
"0",
"]",
")",
":",
"maxname",
"=",
"len",
"(",
"val",
"[",
"0",
"]",
")",
"if",
"maxshape",
"<",
"len",
"(",
"val",
"[",
"1",
"]",
")",
":",
"maxshape",
"=",
"len",
"(",
"val",
"[",
"1",
"]",
")",
"if",
"maxbyte",
"<",
"len",
"(",
"val",
"[",
"2",
"]",
")",
":",
"maxbyte",
"=",
"len",
"(",
"val",
"[",
"2",
"]",
")",
"if",
"val",
"[",
"4",
"]",
":",
"totalbytes",
"+=",
"int",
"(",
"val",
"[",
"2",
"]",
")",
"if",
"len",
"(",
"sta",
")",
">",
"0",
":",
"sp1",
"=",
"max",
"(",
"10",
",",
"maxname",
")",
"sp2",
"=",
"max",
"(",
"10",
",",
"maxshape",
")",
"sp3",
"=",
"max",
"(",
"10",
",",
"maxbyte",
")",
"prval",
"=",
"\"Name %s Shape %s Bytes %s Type\"",
"%",
"(",
"sp1",
"*",
"' '",
",",
"sp2",
"*",
"' '",
",",
"sp3",
"*",
"' '",
")",
"print",
"(",
"prval",
"+",
"\"\\n\"",
"+",
"\"=\"",
"*",
"(",
"len",
"(",
"prval",
")",
"+",
"5",
")",
"+",
"\"\\n\"",
")",
"for",
"k",
"in",
"range",
"(",
"len",
"(",
"sta",
")",
")",
":",
"val",
"=",
"sta",
"[",
"k",
"]",
"print",
"(",
"\"%s %s %s %s %s %s %s\"",
"%",
"(",
"val",
"[",
"0",
"]",
",",
"' '",
"*",
"(",
"sp1",
"-",
"len",
"(",
"val",
"[",
"0",
"]",
")",
"+",
"4",
")",
",",
"val",
"[",
"1",
"]",
",",
"' '",
"*",
"(",
"sp2",
"-",
"len",
"(",
"val",
"[",
"1",
"]",
")",
"+",
"5",
")",
",",
"val",
"[",
"2",
"]",
",",
"' '",
"*",
"(",
"sp3",
"-",
"len",
"(",
"val",
"[",
"2",
"]",
")",
"+",
"5",
")",
",",
"val",
"[",
"3",
"]",
")",
")",
"print",
"(",
"\"\\nUpper bound on total bytes = %d\"",
"%",
"totalbytes",
")",
"return"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/lib/utils.py#L285-L379 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/tensor/creation.py | python | empty_like | (x, dtype=None, name=None) | return out | This Op returns a Tensor with uninitialized data which has identical shape of ``x`` and ``dtype``.
If the ``dtype`` is None, the data type of Tensor is same with ``x``.
Args:
x(Tensor): The input tensor which specifies shape and data type. The data type can be bool, float16, float32, float64, int32, int64.
dtype(np.dtype|str, optional): The data type of output. The data type can be one
of bool, float16, float32, float64, int32, int64. The default value is None, which means the output
data type is the same as input.
name(str, optional): The default value is None. Normally there is no need for user to set this
property. For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor: Tensor which is created according to ``x`` and ``dtype``, and is uninitialized.
Examples:
.. code-block:: python
import paddle
import numpy as np
paddle.set_device("cpu") # and use cpu device
x = paddle.randn([2, 3], 'float32')
output = paddle.empty_like(x)
#[[1.8491974e+20 1.8037303e+28 1.7443726e+28] # uninitialized
# [4.9640171e+28 3.0186127e+32 5.6715899e-11]] # uninitialized | This Op returns a Tensor with uninitialized data which has identical shape of ``x`` and ``dtype``.
If the ``dtype`` is None, the data type of Tensor is same with ``x``.
Args:
x(Tensor): The input tensor which specifies shape and data type. The data type can be bool, float16, float32, float64, int32, int64.
dtype(np.dtype|str, optional): The data type of output. The data type can be one
of bool, float16, float32, float64, int32, int64. The default value is None, which means the output
data type is the same as input.
name(str, optional): The default value is None. Normally there is no need for user to set this
property. For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor: Tensor which is created according to ``x`` and ``dtype``, and is uninitialized. | [
"This",
"Op",
"returns",
"a",
"Tensor",
"with",
"uninitialized",
"data",
"which",
"has",
"identical",
"shape",
"of",
"x",
"and",
"dtype",
".",
"If",
"the",
"dtype",
"is",
"None",
"the",
"data",
"type",
"of",
"Tensor",
"is",
"same",
"with",
"x",
".",
"Args",
":",
"x",
"(",
"Tensor",
")",
":",
"The",
"input",
"tensor",
"which",
"specifies",
"shape",
"and",
"data",
"type",
".",
"The",
"data",
"type",
"can",
"be",
"bool",
"float16",
"float32",
"float64",
"int32",
"int64",
".",
"dtype",
"(",
"np",
".",
"dtype|str",
"optional",
")",
":",
"The",
"data",
"type",
"of",
"output",
".",
"The",
"data",
"type",
"can",
"be",
"one",
"of",
"bool",
"float16",
"float32",
"float64",
"int32",
"int64",
".",
"The",
"default",
"value",
"is",
"None",
"which",
"means",
"the",
"output",
"data",
"type",
"is",
"the",
"same",
"as",
"input",
".",
"name",
"(",
"str",
"optional",
")",
":",
"The",
"default",
"value",
"is",
"None",
".",
"Normally",
"there",
"is",
"no",
"need",
"for",
"user",
"to",
"set",
"this",
"property",
".",
"For",
"more",
"information",
"please",
"refer",
"to",
":",
"ref",
":",
"api_guide_Name",
".",
"Returns",
":",
"Tensor",
":",
"Tensor",
"which",
"is",
"created",
"according",
"to",
"x",
"and",
"dtype",
"and",
"is",
"uninitialized",
"."
] | def empty_like(x, dtype=None, name=None):
"""
This Op returns a Tensor with uninitialized data which has identical shape of ``x`` and ``dtype``.
If the ``dtype`` is None, the data type of Tensor is same with ``x``.
Args:
x(Tensor): The input tensor which specifies shape and data type. The data type can be bool, float16, float32, float64, int32, int64.
dtype(np.dtype|str, optional): The data type of output. The data type can be one
of bool, float16, float32, float64, int32, int64. The default value is None, which means the output
data type is the same as input.
name(str, optional): The default value is None. Normally there is no need for user to set this
property. For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor: Tensor which is created according to ``x`` and ``dtype``, and is uninitialized.
Examples:
.. code-block:: python
import paddle
import numpy as np
paddle.set_device("cpu") # and use cpu device
x = paddle.randn([2, 3], 'float32')
output = paddle.empty_like(x)
#[[1.8491974e+20 1.8037303e+28 1.7443726e+28] # uninitialized
# [4.9640171e+28 3.0186127e+32 5.6715899e-11]] # uninitialized
"""
if dtype is None:
dtype = x.dtype
dtype = convert_dtype(dtype)
if in_dygraph_mode():
out = _C_ops.empty('shape', x.shape, 'dtype',
convert_np_dtype_to_dtype_(dtype))
out.stop_gradient = True
return out
helper = LayerHelper("empty_like", **locals())
check_variable_and_dtype(
x, 'x', ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'],
'empty_like')
check_dtype(dtype, 'dtype',
['bool', 'float16', 'float32', 'float64', 'int32', 'int64'],
'empty_like')
out = helper.create_variable_for_type_inference(dtype=dtype)
inputs = {}
attrs = {}
attrs['dtype'] = convert_np_dtype_to_dtype_(dtype)
shape = paddle.shape(x)
utils.get_shape_tensor_inputs(
inputs=inputs, attrs=attrs, shape=shape, op_type='empty_like')
helper.append_op(
type='empty',
inputs=inputs,
outputs={'Out': [out]},
attrs=attrs,
stop_gradient=True)
out.stop_gradient = True
return out | [
"def",
"empty_like",
"(",
"x",
",",
"dtype",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"x",
".",
"dtype",
"dtype",
"=",
"convert_dtype",
"(",
"dtype",
")",
"if",
"in_dygraph_mode",
"(",
")",
":",
"out",
"=",
"_C_ops",
".",
"empty",
"(",
"'shape'",
",",
"x",
".",
"shape",
",",
"'dtype'",
",",
"convert_np_dtype_to_dtype_",
"(",
"dtype",
")",
")",
"out",
".",
"stop_gradient",
"=",
"True",
"return",
"out",
"helper",
"=",
"LayerHelper",
"(",
"\"empty_like\"",
",",
"*",
"*",
"locals",
"(",
")",
")",
"check_variable_and_dtype",
"(",
"x",
",",
"'x'",
",",
"[",
"'bool'",
",",
"'float16'",
",",
"'float32'",
",",
"'float64'",
",",
"'int32'",
",",
"'int64'",
"]",
",",
"'empty_like'",
")",
"check_dtype",
"(",
"dtype",
",",
"'dtype'",
",",
"[",
"'bool'",
",",
"'float16'",
",",
"'float32'",
",",
"'float64'",
",",
"'int32'",
",",
"'int64'",
"]",
",",
"'empty_like'",
")",
"out",
"=",
"helper",
".",
"create_variable_for_type_inference",
"(",
"dtype",
"=",
"dtype",
")",
"inputs",
"=",
"{",
"}",
"attrs",
"=",
"{",
"}",
"attrs",
"[",
"'dtype'",
"]",
"=",
"convert_np_dtype_to_dtype_",
"(",
"dtype",
")",
"shape",
"=",
"paddle",
".",
"shape",
"(",
"x",
")",
"utils",
".",
"get_shape_tensor_inputs",
"(",
"inputs",
"=",
"inputs",
",",
"attrs",
"=",
"attrs",
",",
"shape",
"=",
"shape",
",",
"op_type",
"=",
"'empty_like'",
")",
"helper",
".",
"append_op",
"(",
"type",
"=",
"'empty'",
",",
"inputs",
"=",
"inputs",
",",
"outputs",
"=",
"{",
"'Out'",
":",
"[",
"out",
"]",
"}",
",",
"attrs",
"=",
"attrs",
",",
"stop_gradient",
"=",
"True",
")",
"out",
".",
"stop_gradient",
"=",
"True",
"return",
"out"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/tensor/creation.py#L1092-L1155 | |
CRYTEK/CRYENGINE | 232227c59a220cbbd311576f0fbeba7bb53b2a8c | Code/Tools/waf-1.7.13/waflib/Tools/c_config.py | python | have_define | (self, key) | return (self.env.HAVE_PAT or 'HAVE_%s') % Utils.quote_define_name(key) | :param key: define name
:type key: string
:return: the input key prefixed by *HAVE_* and substitute any invalid characters.
:rtype: string | :param key: define name
:type key: string
:return: the input key prefixed by *HAVE_* and substitute any invalid characters.
:rtype: string | [
":",
"param",
"key",
":",
"define",
"name",
":",
"type",
"key",
":",
"string",
":",
"return",
":",
"the",
"input",
"key",
"prefixed",
"by",
"*",
"HAVE_",
"*",
"and",
"substitute",
"any",
"invalid",
"characters",
".",
":",
"rtype",
":",
"string"
] | def have_define(self, key):
"""
:param key: define name
:type key: string
:return: the input key prefixed by *HAVE_* and substitute any invalid characters.
:rtype: string
"""
return (self.env.HAVE_PAT or 'HAVE_%s') % Utils.quote_define_name(key) | [
"def",
"have_define",
"(",
"self",
",",
"key",
")",
":",
"return",
"(",
"self",
".",
"env",
".",
"HAVE_PAT",
"or",
"'HAVE_%s'",
")",
"%",
"Utils",
".",
"quote_define_name",
"(",
"key",
")"
] | https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/c_config.py#L906-L913 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextCtrl.GetPreDrag | (*args, **kwargs) | return _richtext.RichTextCtrl_GetPreDrag(*args, **kwargs) | GetPreDrag(self) -> bool | GetPreDrag(self) -> bool | [
"GetPreDrag",
"(",
"self",
")",
"-",
">",
"bool"
] | def GetPreDrag(*args, **kwargs):
"""GetPreDrag(self) -> bool"""
return _richtext.RichTextCtrl_GetPreDrag(*args, **kwargs) | [
"def",
"GetPreDrag",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_GetPreDrag",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L3037-L3039 | |
HyeonwooNoh/caffe | d9e8494a2832d67b25dee37194c7bcb9d52d0e42 | scripts/cpp_lint.py | python | ProcessFile | (filename, vlevel, extra_check_functions=[]) | Does google-lint on a single file.
Args:
filename: The name of the file to parse.
vlevel: The level of errors to report. Every error of confidence
>= verbose_level will be reported. 0 is a good default.
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error | Does google-lint on a single file. | [
"Does",
"google",
"-",
"lint",
"on",
"a",
"single",
"file",
"."
] | def ProcessFile(filename, vlevel, extra_check_functions=[]):
"""Does google-lint on a single file.
Args:
filename: The name of the file to parse.
vlevel: The level of errors to report. Every error of confidence
>= verbose_level will be reported. 0 is a good default.
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
_SetVerboseLevel(vlevel)
try:
# Support the UNIX convention of using "-" for stdin. Note that
# we are not opening the file with universal newline support
# (which codecs doesn't support anyway), so the resulting lines do
# contain trailing '\r' characters if we are reading a file that
# has CRLF endings.
# If after the split a trailing '\r' is present, it is removed
# below. If it is not expected to be present (i.e. os.linesep !=
# '\r\n' as in Windows), a warning is issued below if this file
# is processed.
if filename == '-':
lines = codecs.StreamReaderWriter(sys.stdin,
codecs.getreader('utf8'),
codecs.getwriter('utf8'),
'replace').read().split('\n')
else:
lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
carriage_return_found = False
# Remove trailing '\r'.
for linenum in range(len(lines)):
if lines[linenum].endswith('\r'):
lines[linenum] = lines[linenum].rstrip('\r')
carriage_return_found = True
except IOError:
sys.stderr.write(
"Skipping input '%s': Can't open for reading\n" % filename)
return
# Note, if no dot is found, this will give the entire filename as the ext.
file_extension = filename[filename.rfind('.') + 1:]
# When reading from stdin, the extension is unknown, so no cpplint tests
# should rely on the extension.
if filename != '-' and file_extension not in _valid_extensions:
sys.stderr.write('Ignoring %s; not a valid file name '
'(%s)\n' % (filename, ', '.join(_valid_extensions)))
else:
ProcessFileData(filename, file_extension, lines, Error,
extra_check_functions)
if carriage_return_found and os.linesep != '\r\n':
# Use 0 for linenum since outputting only one error for potentially
# several lines.
Error(filename, 0, 'whitespace/newline', 1,
'One or more unexpected \\r (^M) found;'
'better to use only a \\n')
sys.stderr.write('Done processing %s\n' % filename) | [
"def",
"ProcessFile",
"(",
"filename",
",",
"vlevel",
",",
"extra_check_functions",
"=",
"[",
"]",
")",
":",
"_SetVerboseLevel",
"(",
"vlevel",
")",
"try",
":",
"# Support the UNIX convention of using \"-\" for stdin. Note that",
"# we are not opening the file with universal newline support",
"# (which codecs doesn't support anyway), so the resulting lines do",
"# contain trailing '\\r' characters if we are reading a file that",
"# has CRLF endings.",
"# If after the split a trailing '\\r' is present, it is removed",
"# below. If it is not expected to be present (i.e. os.linesep !=",
"# '\\r\\n' as in Windows), a warning is issued below if this file",
"# is processed.",
"if",
"filename",
"==",
"'-'",
":",
"lines",
"=",
"codecs",
".",
"StreamReaderWriter",
"(",
"sys",
".",
"stdin",
",",
"codecs",
".",
"getreader",
"(",
"'utf8'",
")",
",",
"codecs",
".",
"getwriter",
"(",
"'utf8'",
")",
",",
"'replace'",
")",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"else",
":",
"lines",
"=",
"codecs",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"'utf8'",
",",
"'replace'",
")",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"carriage_return_found",
"=",
"False",
"# Remove trailing '\\r'.",
"for",
"linenum",
"in",
"range",
"(",
"len",
"(",
"lines",
")",
")",
":",
"if",
"lines",
"[",
"linenum",
"]",
".",
"endswith",
"(",
"'\\r'",
")",
":",
"lines",
"[",
"linenum",
"]",
"=",
"lines",
"[",
"linenum",
"]",
".",
"rstrip",
"(",
"'\\r'",
")",
"carriage_return_found",
"=",
"True",
"except",
"IOError",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Skipping input '%s': Can't open for reading\\n\"",
"%",
"filename",
")",
"return",
"# Note, if no dot is found, this will give the entire filename as the ext.",
"file_extension",
"=",
"filename",
"[",
"filename",
".",
"rfind",
"(",
"'.'",
")",
"+",
"1",
":",
"]",
"# When reading from stdin, the extension is unknown, so no cpplint tests",
"# should rely on the extension.",
"if",
"filename",
"!=",
"'-'",
"and",
"file_extension",
"not",
"in",
"_valid_extensions",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Ignoring %s; not a valid file name '",
"'(%s)\\n'",
"%",
"(",
"filename",
",",
"', '",
".",
"join",
"(",
"_valid_extensions",
")",
")",
")",
"else",
":",
"ProcessFileData",
"(",
"filename",
",",
"file_extension",
",",
"lines",
",",
"Error",
",",
"extra_check_functions",
")",
"if",
"carriage_return_found",
"and",
"os",
".",
"linesep",
"!=",
"'\\r\\n'",
":",
"# Use 0 for linenum since outputting only one error for potentially",
"# several lines.",
"Error",
"(",
"filename",
",",
"0",
",",
"'whitespace/newline'",
",",
"1",
",",
"'One or more unexpected \\\\r (^M) found;'",
"'better to use only a \\\\n'",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Done processing %s\\n'",
"%",
"filename",
")"
] | https://github.com/HyeonwooNoh/caffe/blob/d9e8494a2832d67b25dee37194c7bcb9d52d0e42/scripts/cpp_lint.py#L4689-L4754 | ||
qt/qt | 0a2f2382541424726168804be2c90b91381608c6 | src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/generator/make.py | python | Target | (filename) | return os.path.splitext(filename)[0] + '.o' | Translate a compilable filename to its .o target. | Translate a compilable filename to its .o target. | [
"Translate",
"a",
"compilable",
"filename",
"to",
"its",
".",
"o",
"target",
"."
] | def Target(filename):
"""Translate a compilable filename to its .o target."""
return os.path.splitext(filename)[0] + '.o' | [
"def",
"Target",
"(",
"filename",
")",
":",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"0",
"]",
"+",
"'.o'"
] | https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/webkit/Source/ThirdParty/gyp/pylib/gyp/generator/make.py#L442-L444 | |
SequoiaDB/SequoiaDB | 2894ed7e5bd6fe57330afc900cf76d0ff0df9f64 | driver/python/pysequoiadb/lob.py | python | lob.write | (self, data, length) | write data into lob.
Parameters:
Name Type Info:
data str The data to be written
length int The length of data to be written
Exceptions:
pysequoiadb.error.SDBBaseError | write data into lob. | [
"write",
"data",
"into",
"lob",
"."
] | def write(self, data, length):
"""write data into lob.
Parameters:
Name Type Info:
data str The data to be written
length int The length of data to be written
Exceptions:
pysequoiadb.error.SDBBaseError
"""
if not isinstance(data, str_type):
raise SDBTypeError("data should be byte or string")
rc = sdb.lob_write(self._handle, data, length)
raise_if_error(rc, "Failed to write data to lob") | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"length",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"str_type",
")",
":",
"raise",
"SDBTypeError",
"(",
"\"data should be byte or string\"",
")",
"rc",
"=",
"sdb",
".",
"lob_write",
"(",
"self",
".",
"_handle",
",",
"data",
",",
"length",
")",
"raise_if_error",
"(",
"rc",
",",
"\"Failed to write data to lob\"",
")"
] | https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/driver/python/pysequoiadb/lob.py#L180-L194 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.