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
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/factorization/python/ops/gmm_ops.py
python
GmmAlgorithm._define_full_covariance_probs
(self, shard_id, shard)
Defines the full covariance probabilities per example in a class. Updates a matrix with dimension num_examples X num_classes. Args: shard_id: id of the current shard. shard: current data shard, 1 X num_examples X dimensions.
Defines the full covariance probabilities per example in a class.
[ "Defines", "the", "full", "covariance", "probabilities", "per", "example", "in", "a", "class", "." ]
def _define_full_covariance_probs(self, shard_id, shard): """Defines the full covariance probabilities per example in a class. Updates a matrix with dimension num_examples X num_classes. Args: shard_id: id of the current shard. shard: current data shard, 1 X num_examples X dimensions. """ diff = shard - self._means cholesky = linalg_ops.cholesky(self._covs + self._min_var) log_det_covs = 2.0 * math_ops.reduce_sum( math_ops.log(array_ops.matrix_diag_part(cholesky)), 1) x_mu_cov = math_ops.square( linalg_ops.matrix_triangular_solve( cholesky, array_ops.transpose( diff, perm=[0, 2, 1]), lower=True)) diag_m = array_ops.transpose(math_ops.reduce_sum(x_mu_cov, 1)) self._probs[shard_id] = ( -0.5 * (diag_m + math_ops.cast(self._dimensions, dtypes.float32) * math_ops.log(2 * np.pi) + log_det_covs))
[ "def", "_define_full_covariance_probs", "(", "self", ",", "shard_id", ",", "shard", ")", ":", "diff", "=", "shard", "-", "self", ".", "_means", "cholesky", "=", "linalg_ops", ".", "cholesky", "(", "self", ".", "_covs", "+", "self", ".", "_min_var", ")", "log_det_covs", "=", "2.0", "*", "math_ops", ".", "reduce_sum", "(", "math_ops", ".", "log", "(", "array_ops", ".", "matrix_diag_part", "(", "cholesky", ")", ")", ",", "1", ")", "x_mu_cov", "=", "math_ops", ".", "square", "(", "linalg_ops", ".", "matrix_triangular_solve", "(", "cholesky", ",", "array_ops", ".", "transpose", "(", "diff", ",", "perm", "=", "[", "0", ",", "2", ",", "1", "]", ")", ",", "lower", "=", "True", ")", ")", "diag_m", "=", "array_ops", ".", "transpose", "(", "math_ops", ".", "reduce_sum", "(", "x_mu_cov", ",", "1", ")", ")", "self", ".", "_probs", "[", "shard_id", "]", "=", "(", "-", "0.5", "*", "(", "diag_m", "+", "math_ops", ".", "cast", "(", "self", ".", "_dimensions", ",", "dtypes", ".", "float32", ")", "*", "math_ops", ".", "log", "(", "2", "*", "np", ".", "pi", ")", "+", "log_det_covs", ")", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/factorization/python/ops/gmm_ops.py#L282-L302
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py
python
_MaskedPrintOption.__init__
(self, display)
Create the masked_print_option object.
Create the masked_print_option object.
[ "Create", "the", "masked_print_option", "object", "." ]
def __init__(self, display): """ Create the masked_print_option object. """ self._display = display self._enabled = True
[ "def", "__init__", "(", "self", ",", "display", ")", ":", "self", ".", "_display", "=", "display", "self", ".", "_enabled", "=", "True" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/ma/core.py#L2395-L2401
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/polynomial/_polybase.py
python
ABCPolyBase._generate_string
(self, term_method)
return out
Generate the full string representation of the polynomial, using ``term_method`` to generate each polynomial term.
Generate the full string representation of the polynomial, using ``term_method`` to generate each polynomial term.
[ "Generate", "the", "full", "string", "representation", "of", "the", "polynomial", "using", "term_method", "to", "generate", "each", "polynomial", "term", "." ]
def _generate_string(self, term_method): """ Generate the full string representation of the polynomial, using ``term_method`` to generate each polynomial term. """ # Get configuration for line breaks linewidth = np.get_printoptions().get('linewidth', 75) if linewidth < 1: linewidth = 1 out = f"{self.coef[0]}" for i, coef in enumerate(self.coef[1:]): out += " " power = str(i + 1) # Polynomial coefficient # The coefficient array can be an object array with elements that # will raise a TypeError with >= 0 (e.g. strings or Python # complex). In this case, represent the coeficient as-is. try: if coef >= 0: next_term = f"+ {coef}" else: next_term = f"- {-coef}" except TypeError: next_term = f"+ {coef}" # Polynomial term next_term += term_method(power, "x") # Length of the current line with next term added line_len = len(out.split('\n')[-1]) + len(next_term) # If not the last term in the polynomial, it will be two # characters longer due to the +/- with the next term if i < len(self.coef[1:]) - 1: line_len += 2 # Handle linebreaking if line_len >= linewidth: next_term = next_term.replace(" ", "\n", 1) out += next_term return out
[ "def", "_generate_string", "(", "self", ",", "term_method", ")", ":", "# Get configuration for line breaks", "linewidth", "=", "np", ".", "get_printoptions", "(", ")", ".", "get", "(", "'linewidth'", ",", "75", ")", "if", "linewidth", "<", "1", ":", "linewidth", "=", "1", "out", "=", "f\"{self.coef[0]}\"", "for", "i", ",", "coef", "in", "enumerate", "(", "self", ".", "coef", "[", "1", ":", "]", ")", ":", "out", "+=", "\" \"", "power", "=", "str", "(", "i", "+", "1", ")", "# Polynomial coefficient", "# The coefficient array can be an object array with elements that", "# will raise a TypeError with >= 0 (e.g. strings or Python", "# complex). In this case, represent the coeficient as-is.", "try", ":", "if", "coef", ">=", "0", ":", "next_term", "=", "f\"+ {coef}\"", "else", ":", "next_term", "=", "f\"- {-coef}\"", "except", "TypeError", ":", "next_term", "=", "f\"+ {coef}\"", "# Polynomial term", "next_term", "+=", "term_method", "(", "power", ",", "\"x\"", ")", "# Length of the current line with next term added", "line_len", "=", "len", "(", "out", ".", "split", "(", "'\\n'", ")", "[", "-", "1", "]", ")", "+", "len", "(", "next_term", ")", "# If not the last term in the polynomial, it will be two", "# characters longer due to the +/- with the next term", "if", "i", "<", "len", "(", "self", ".", "coef", "[", "1", ":", "]", ")", "-", "1", ":", "line_len", "+=", "2", "# Handle linebreaking", "if", "line_len", ">=", "linewidth", ":", "next_term", "=", "next_term", ".", "replace", "(", "\" \"", ",", "\"\\n\"", ",", "1", ")", "out", "+=", "next_term", "return", "out" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/_polybase.py#L331-L367
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/codecs.py
python
IncrementalEncoder.reset
(self)
Resets the encoder to the initial state.
Resets the encoder to the initial state.
[ "Resets", "the", "encoder", "to", "the", "initial", "state", "." ]
def reset(self): """ Resets the encoder to the initial state. """
[ "def", "reset", "(", "self", ")", ":" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/codecs.py#L203-L206
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/hpmc/external/wall.py
python
wall.set_volume
(self, volume)
R"""Set the volume associated with the intersection of all walls in the system. # noqa This number will subsequently change when the box is resized and walls are scaled appropriately. Example:: mc = hpmc.integrate.sphere(seed = 415236); ext_wall = hpmc.compute.wall(mc); ext_wall.add_sphere_wall(radius = 1.0, origin = [0, 0, 0], inside = True); ext_wall.set_volume(4./3.*np.pi);
R"""Set the volume associated with the intersection of all walls in the system. # noqa
[ "R", "Set", "the", "volume", "associated", "with", "the", "intersection", "of", "all", "walls", "in", "the", "system", ".", "#", "noqa" ]
def set_volume(self, volume): R"""Set the volume associated with the intersection of all walls in the system. # noqa This number will subsequently change when the box is resized and walls are scaled appropriately. Example:: mc = hpmc.integrate.sphere(seed = 415236); ext_wall = hpmc.compute.wall(mc); ext_wall.add_sphere_wall(radius = 1.0, origin = [0, 0, 0], inside = True); ext_wall.set_volume(4./3.*np.pi); """ self.cpp_compute.setVolume(volume)
[ "def", "set_volume", "(", "self", ",", "volume", ")", ":", "self", ".", "cpp_compute", ".", "setVolume", "(", "volume", ")" ]
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/hpmc/external/wall.py#L415-L428
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/nanops.py
python
nanmean
(values, axis=None, skipna=True, mask=None)
return _wrap_results(the_mean, dtype)
Compute the mean of the element along an axis ignoring NaNs Parameters ---------- values : ndarray axis: int, optional skipna : bool, default True mask : ndarray[bool], optional nan-mask if known Returns ------- result : float Unless input is a float array, in which case use the same precision as the input array. Examples -------- >>> import pandas.core.nanops as nanops >>> s = pd.Series([1, 2, np.nan]) >>> nanops.nanmean(s) 1.5
Compute the mean of the element along an axis ignoring NaNs
[ "Compute", "the", "mean", "of", "the", "element", "along", "an", "axis", "ignoring", "NaNs" ]
def nanmean(values, axis=None, skipna=True, mask=None): """ Compute the mean of the element along an axis ignoring NaNs Parameters ---------- values : ndarray axis: int, optional skipna : bool, default True mask : ndarray[bool], optional nan-mask if known Returns ------- result : float Unless input is a float array, in which case use the same precision as the input array. Examples -------- >>> import pandas.core.nanops as nanops >>> s = pd.Series([1, 2, np.nan]) >>> nanops.nanmean(s) 1.5 """ values, mask, dtype, dtype_max, _ = _get_values( values, skipna, fill_value=0, mask=mask ) dtype_sum = dtype_max dtype_count = np.float64 if ( is_integer_dtype(dtype) or is_timedelta64_dtype(dtype) or is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype) ): dtype_sum = np.float64 elif is_float_dtype(dtype): dtype_sum = dtype dtype_count = dtype count = _get_counts(values.shape, mask, axis, dtype=dtype_count) the_sum = _ensure_numeric(values.sum(axis, dtype=dtype_sum)) if axis is not None and getattr(the_sum, "ndim", False): with np.errstate(all="ignore"): # suppress division by zero warnings the_mean = the_sum / count ct_mask = count == 0 if ct_mask.any(): the_mean[ct_mask] = np.nan else: the_mean = the_sum / count if count > 0 else np.nan return _wrap_results(the_mean, dtype)
[ "def", "nanmean", "(", "values", ",", "axis", "=", "None", ",", "skipna", "=", "True", ",", "mask", "=", "None", ")", ":", "values", ",", "mask", ",", "dtype", ",", "dtype_max", ",", "_", "=", "_get_values", "(", "values", ",", "skipna", ",", "fill_value", "=", "0", ",", "mask", "=", "mask", ")", "dtype_sum", "=", "dtype_max", "dtype_count", "=", "np", ".", "float64", "if", "(", "is_integer_dtype", "(", "dtype", ")", "or", "is_timedelta64_dtype", "(", "dtype", ")", "or", "is_datetime64_dtype", "(", "dtype", ")", "or", "is_datetime64tz_dtype", "(", "dtype", ")", ")", ":", "dtype_sum", "=", "np", ".", "float64", "elif", "is_float_dtype", "(", "dtype", ")", ":", "dtype_sum", "=", "dtype", "dtype_count", "=", "dtype", "count", "=", "_get_counts", "(", "values", ".", "shape", ",", "mask", ",", "axis", ",", "dtype", "=", "dtype_count", ")", "the_sum", "=", "_ensure_numeric", "(", "values", ".", "sum", "(", "axis", ",", "dtype", "=", "dtype_sum", ")", ")", "if", "axis", "is", "not", "None", "and", "getattr", "(", "the_sum", ",", "\"ndim\"", ",", "False", ")", ":", "with", "np", ".", "errstate", "(", "all", "=", "\"ignore\"", ")", ":", "# suppress division by zero warnings", "the_mean", "=", "the_sum", "/", "count", "ct_mask", "=", "count", "==", "0", "if", "ct_mask", ".", "any", "(", ")", ":", "the_mean", "[", "ct_mask", "]", "=", "np", ".", "nan", "else", ":", "the_mean", "=", "the_sum", "/", "count", "if", "count", ">", "0", "else", "np", ".", "nan", "return", "_wrap_results", "(", "the_mean", ",", "dtype", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/nanops.py#L501-L554
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/turtle.py
python
RawTurtle.begin_fill
(self)
Called just before drawing a shape to be filled. No argument. Example (for a Turtle instance named turtle): >>> turtle.color("black", "red") >>> turtle.begin_fill() >>> turtle.circle(60) >>> turtle.end_fill()
Called just before drawing a shape to be filled.
[ "Called", "just", "before", "drawing", "a", "shape", "to", "be", "filled", "." ]
def begin_fill(self): """Called just before drawing a shape to be filled. No argument. Example (for a Turtle instance named turtle): >>> turtle.color("black", "red") >>> turtle.begin_fill() >>> turtle.circle(60) >>> turtle.end_fill() """ if not self.filling(): self._fillitem = self.screen._createpoly() self.items.append(self._fillitem) self._fillpath = [self._position] self._newLine() if self.undobuffer: self.undobuffer.push(("beginfill", self._fillitem)) self._update()
[ "def", "begin_fill", "(", "self", ")", ":", "if", "not", "self", ".", "filling", "(", ")", ":", "self", ".", "_fillitem", "=", "self", ".", "screen", ".", "_createpoly", "(", ")", "self", ".", "items", ".", "append", "(", "self", ".", "_fillitem", ")", "self", ".", "_fillpath", "=", "[", "self", ".", "_position", "]", "self", ".", "_newLine", "(", ")", "if", "self", ".", "undobuffer", ":", "self", ".", "undobuffer", ".", "push", "(", "(", "\"beginfill\"", ",", "self", ".", "_fillitem", ")", ")", "self", ".", "_update", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/turtle.py#L3310-L3328
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/smtplib.py
python
SMTP.auth_cram_md5
(self, challenge=None)
return self.user + " " + hmac.HMAC( self.password.encode('ascii'), challenge, 'md5').hexdigest()
Authobject to use with CRAM-MD5 authentication. Requires self.user and self.password to be set.
Authobject to use with CRAM-MD5 authentication. Requires self.user and self.password to be set.
[ "Authobject", "to", "use", "with", "CRAM", "-", "MD5", "authentication", ".", "Requires", "self", ".", "user", "and", "self", ".", "password", "to", "be", "set", "." ]
def auth_cram_md5(self, challenge=None): """ Authobject to use with CRAM-MD5 authentication. Requires self.user and self.password to be set.""" # CRAM-MD5 does not support initial-response. if challenge is None: return None return self.user + " " + hmac.HMAC( self.password.encode('ascii'), challenge, 'md5').hexdigest()
[ "def", "auth_cram_md5", "(", "self", ",", "challenge", "=", "None", ")", ":", "# CRAM-MD5 does not support initial-response.", "if", "challenge", "is", "None", ":", "return", "None", "return", "self", ".", "user", "+", "\" \"", "+", "hmac", ".", "HMAC", "(", "self", ".", "password", ".", "encode", "(", "'ascii'", ")", ",", "challenge", ",", "'md5'", ")", ".", "hexdigest", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/smtplib.py#L644-L651
baidu/bigflow
449245016c0df7d1252e85581e588bfc60cefad3
bigflow_python/python/bigflow/rpc/requests.py
python
launch
(pipeline_id, logical_plan_message, resource_message, commit_args=None, context=None)
Send the rpc command to the other end to launch the logical plan Args: Raises: error.BigflowRPCException: if any error happened
Send the rpc command to the other end to launch the logical plan
[ "Send", "the", "rpc", "command", "to", "the", "other", "end", "to", "launch", "the", "logical", "plan" ]
def launch(pipeline_id, logical_plan_message, resource_message, commit_args=None, context=None): """ Send the rpc command to the other end to launch the logical plan Args: Raises: error.BigflowRPCException: if any error happened """ request = service_pb2.LaunchRequest() request.pipeline_id = pipeline_id request.logical_plan.CopyFrom(logical_plan_message) request.resource.CopyFrom(resource_message) if commit_args is not None: request.hadoop_commit_args.extend(commit_args) if context is not None: assert isinstance(context, str) request.pipeline_context = context response = _service.request(request, "launch") import google.protobuf.json_format as json_format res = json_format.Parse(response, service_pb2.VoidResponse()) #logger.info(res) if not res.status.success: backend_log_path = os.getenv("BIGFLOW_LOG_FILE_BACKEND", "") error_message = "Job ran failed" if len(_message) > 0: error_message += ", possible_reason: \n" + "".join(_message) if backend_log_path: error_message += "Please check backend log['%s.log'] for details" % backend_log_path raise error.BigflowRuntimeException(error_message)
[ "def", "launch", "(", "pipeline_id", ",", "logical_plan_message", ",", "resource_message", ",", "commit_args", "=", "None", ",", "context", "=", "None", ")", ":", "request", "=", "service_pb2", ".", "LaunchRequest", "(", ")", "request", ".", "pipeline_id", "=", "pipeline_id", "request", ".", "logical_plan", ".", "CopyFrom", "(", "logical_plan_message", ")", "request", ".", "resource", ".", "CopyFrom", "(", "resource_message", ")", "if", "commit_args", "is", "not", "None", ":", "request", ".", "hadoop_commit_args", ".", "extend", "(", "commit_args", ")", "if", "context", "is", "not", "None", ":", "assert", "isinstance", "(", "context", ",", "str", ")", "request", ".", "pipeline_context", "=", "context", "response", "=", "_service", ".", "request", "(", "request", ",", "\"launch\"", ")", "import", "google", ".", "protobuf", ".", "json_format", "as", "json_format", "res", "=", "json_format", ".", "Parse", "(", "response", ",", "service_pb2", ".", "VoidResponse", "(", ")", ")", "#logger.info(res)", "if", "not", "res", ".", "status", ".", "success", ":", "backend_log_path", "=", "os", ".", "getenv", "(", "\"BIGFLOW_LOG_FILE_BACKEND\"", ",", "\"\"", ")", "error_message", "=", "\"Job ran failed\"", "if", "len", "(", "_message", ")", ">", "0", ":", "error_message", "+=", "\", possible_reason: \\n\"", "+", "\"\"", ".", "join", "(", "_message", ")", "if", "backend_log_path", ":", "error_message", "+=", "\"Please check backend log['%s.log'] for details\"", "%", "backend_log_path", "raise", "error", ".", "BigflowRuntimeException", "(", "error_message", ")" ]
https://github.com/baidu/bigflow/blob/449245016c0df7d1252e85581e588bfc60cefad3/bigflow_python/python/bigflow/rpc/requests.py#L77-L113
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/io/formats/format.py
python
DataFrameFormatter._is_in_terminal
(self)
return bool(self.max_cols == 0 or self.max_rows == 0)
Check if the output is to be shown in terminal.
Check if the output is to be shown in terminal.
[ "Check", "if", "the", "output", "is", "to", "be", "shown", "in", "terminal", "." ]
def _is_in_terminal(self) -> bool: """Check if the output is to be shown in terminal.""" return bool(self.max_cols == 0 or self.max_rows == 0)
[ "def", "_is_in_terminal", "(", "self", ")", "->", "bool", ":", "return", "bool", "(", "self", ".", "max_cols", "==", "0", "or", "self", ".", "max_rows", "==", "0", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/io/formats/format.py#L690-L692
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/mantid/fitfunctions.py
python
FunctionWrapper.fix
(self, name)
Fix a parameter. :param name: name of parameter to be fixed
Fix a parameter.
[ "Fix", "a", "parameter", "." ]
def fix(self, name): """ Fix a parameter. :param name: name of parameter to be fixed """ self.fun.fixParameter(name)
[ "def", "fix", "(", "self", ",", "name", ")", ":", "self", ".", "fun", ".", "fixParameter", "(", "name", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/mantid/fitfunctions.py#L291-L297
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/v8/third_party/jinja2/utils.py
python
LRUCache.get
(self, key, default=None)
Return an item from the cache dict or `default`
Return an item from the cache dict or `default`
[ "Return", "an", "item", "from", "the", "cache", "dict", "or", "default" ]
def get(self, key, default=None): """Return an item from the cache dict or `default`""" try: return self[key] except KeyError: return default
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "try", ":", "return", "self", "[", "key", "]", "except", "KeyError", ":", "return", "default" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/third_party/jinja2/utils.py#L348-L353
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
llvm/bindings/python/llvm/object.py
python
Section.size
(self)
return lib.LLVMGetSectionSize(self)
The size of the section, in long bytes.
The size of the section, in long bytes.
[ "The", "size", "of", "the", "section", "in", "long", "bytes", "." ]
def size(self): """The size of the section, in long bytes.""" if self.expired: raise Exception('Section instance has expired.') return lib.LLVMGetSectionSize(self)
[ "def", "size", "(", "self", ")", ":", "if", "self", ".", "expired", ":", "raise", "Exception", "(", "'Section instance has expired.'", ")", "return", "lib", ".", "LLVMGetSectionSize", "(", "self", ")" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/llvm/bindings/python/llvm/object.py#L204-L209
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/ma/extras.py
python
mask_cols
(a, axis=None)
return mask_rowcols(a, 1)
Mask columns of a 2D array that contain masked values. This function is a shortcut to ``mask_rowcols`` with `axis` equal to 1. See Also -------- mask_rowcols : Mask rows and/or columns of a 2D array. masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.zeros((3, 3), dtype=np.int) >>> a[1, 1] = 1 >>> a array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) >>> a = ma.masked_equal(a, 1) >>> a masked_array(data = [[0 0 0] [0 -- 0] [0 0 0]], mask = [[False False False] [False True False] [False False False]], fill_value=999999) >>> ma.mask_cols(a) masked_array(data = [[0 -- 0] [0 -- 0] [0 -- 0]], mask = [[False True False] [False True False] [False True False]], fill_value=999999)
Mask columns of a 2D array that contain masked values.
[ "Mask", "columns", "of", "a", "2D", "array", "that", "contain", "masked", "values", "." ]
def mask_cols(a, axis=None): """ Mask columns of a 2D array that contain masked values. This function is a shortcut to ``mask_rowcols`` with `axis` equal to 1. See Also -------- mask_rowcols : Mask rows and/or columns of a 2D array. masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.zeros((3, 3), dtype=np.int) >>> a[1, 1] = 1 >>> a array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) >>> a = ma.masked_equal(a, 1) >>> a masked_array(data = [[0 0 0] [0 -- 0] [0 0 0]], mask = [[False False False] [False True False] [False False False]], fill_value=999999) >>> ma.mask_cols(a) masked_array(data = [[0 -- 0] [0 -- 0] [0 -- 0]], mask = [[False True False] [False True False] [False True False]], fill_value=999999) """ return mask_rowcols(a, 1)
[ "def", "mask_cols", "(", "a", ",", "axis", "=", "None", ")", ":", "return", "mask_rowcols", "(", "a", ",", "1", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/ma/extras.py#L903-L946
Xilinx/XRT
dd071c90309df61d3ecdd92dca39f43804915c99
.github/scripts/clang-tidy-review.py
python
get_line_ranges
(diff, files)
return json.dumps(line_filter_json, separators=(",", ":"))
Return the line ranges of added lines in diff, suitable for the line-filter argument of clang-tidy
Return the line ranges of added lines in diff, suitable for the line-filter argument of clang-tidy
[ "Return", "the", "line", "ranges", "of", "added", "lines", "in", "diff", "suitable", "for", "the", "line", "-", "filter", "argument", "of", "clang", "-", "tidy" ]
def get_line_ranges(diff, files): """Return the line ranges of added lines in diff, suitable for the line-filter argument of clang-tidy """ lines_by_file = {} for filename in diff: if filename.target_file[2:] not in files: continue added_lines = [] for hunk in filename: for line in hunk: if line.is_added: added_lines.append(line.target_line_no) for _, group in itertools.groupby( enumerate(added_lines), lambda ix: ix[0] - ix[1] ): groups = list(map(itemgetter(1), group)) lines_by_file.setdefault(filename.target_file[2:], []).append( [groups[0], groups[-1]] ) line_filter_json = [] for name, lines in lines_by_file.items(): line_filter_json.append(str({"name": name, "lines": lines})) return json.dumps(line_filter_json, separators=(",", ":"))
[ "def", "get_line_ranges", "(", "diff", ",", "files", ")", ":", "lines_by_file", "=", "{", "}", "for", "filename", "in", "diff", ":", "if", "filename", ".", "target_file", "[", "2", ":", "]", "not", "in", "files", ":", "continue", "added_lines", "=", "[", "]", "for", "hunk", "in", "filename", ":", "for", "line", "in", "hunk", ":", "if", "line", ".", "is_added", ":", "added_lines", ".", "append", "(", "line", ".", "target_line_no", ")", "for", "_", ",", "group", "in", "itertools", ".", "groupby", "(", "enumerate", "(", "added_lines", ")", ",", "lambda", "ix", ":", "ix", "[", "0", "]", "-", "ix", "[", "1", "]", ")", ":", "groups", "=", "list", "(", "map", "(", "itemgetter", "(", "1", ")", ",", "group", ")", ")", "lines_by_file", ".", "setdefault", "(", "filename", ".", "target_file", "[", "2", ":", "]", ",", "[", "]", ")", ".", "append", "(", "[", "groups", "[", "0", "]", ",", "groups", "[", "-", "1", "]", "]", ")", "line_filter_json", "=", "[", "]", "for", "name", ",", "lines", "in", "lines_by_file", ".", "items", "(", ")", ":", "line_filter_json", ".", "append", "(", "str", "(", "{", "\"name\"", ":", "name", ",", "\"lines\"", ":", "lines", "}", ")", ")", "return", "json", ".", "dumps", "(", "line_filter_json", ",", "separators", "=", "(", "\",\"", ",", "\":\"", ")", ")" ]
https://github.com/Xilinx/XRT/blob/dd071c90309df61d3ecdd92dca39f43804915c99/.github/scripts/clang-tidy-review.py#L118-L145
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/traceback.py
python
format_tb
(tb, limit = None)
return format_list(extract_tb(tb, limit))
A shorthand for 'format_list(extract_stack(f, limit)).
A shorthand for 'format_list(extract_stack(f, limit)).
[ "A", "shorthand", "for", "format_list", "(", "extract_stack", "(", "f", "limit", "))", "." ]
def format_tb(tb, limit = None): """A shorthand for 'format_list(extract_stack(f, limit)).""" return format_list(extract_tb(tb, limit))
[ "def", "format_tb", "(", "tb", ",", "limit", "=", "None", ")", ":", "return", "format_list", "(", "extract_tb", "(", "tb", ",", "limit", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/traceback.py#L74-L76
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/idl/idl/parser.py
python
_parse_chained_types
(ctxt, node)
return chained_items
Parse a chained types section in a struct in the IDL file.
Parse a chained types section in a struct in the IDL file.
[ "Parse", "a", "chained", "types", "section", "in", "a", "struct", "in", "the", "IDL", "file", "." ]
def _parse_chained_types(ctxt, node): # type: (errors.ParserContext, yaml.nodes.MappingNode) -> List[syntax.ChainedType] """Parse a chained types section in a struct in the IDL file.""" chained_items = [] field_name_set = set() # type: Set[str] for [first_node, second_node] in node.value: first_name = first_node.value if first_name in field_name_set: ctxt.add_duplicate_error(first_node, first_name) continue # Simple Scalar if second_node.id == "scalar": chain = syntax.ChainedType(ctxt.file_name, node.start_mark.line, node.start_mark.column) chain.name = first_name chain.cpp_name = second_node.value chained_items.append(chain) else: chain = _parse_chained_type(ctxt, first_name, second_node) chained_items.append(chain) field_name_set.add(first_name) return chained_items
[ "def", "_parse_chained_types", "(", "ctxt", ",", "node", ")", ":", "# type: (errors.ParserContext, yaml.nodes.MappingNode) -> List[syntax.ChainedType]", "chained_items", "=", "[", "]", "field_name_set", "=", "set", "(", ")", "# type: Set[str]", "for", "[", "first_node", ",", "second_node", "]", "in", "node", ".", "value", ":", "first_name", "=", "first_node", ".", "value", "if", "first_name", "in", "field_name_set", ":", "ctxt", ".", "add_duplicate_error", "(", "first_node", ",", "first_name", ")", "continue", "# Simple Scalar", "if", "second_node", ".", "id", "==", "\"scalar\"", ":", "chain", "=", "syntax", ".", "ChainedType", "(", "ctxt", ".", "file_name", ",", "node", ".", "start_mark", ".", "line", ",", "node", ".", "start_mark", ".", "column", ")", "chain", ".", "name", "=", "first_name", "chain", ".", "cpp_name", "=", "second_node", ".", "value", "chained_items", ".", "append", "(", "chain", ")", "else", ":", "chain", "=", "_parse_chained_type", "(", "ctxt", ",", "first_name", ",", "second_node", ")", "chained_items", ".", "append", "(", "chain", ")", "field_name_set", ".", "add", "(", "first_name", ")", "return", "chained_items" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/idl/idl/parser.py#L249-L275
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/keras/_impl/keras/backend.py
python
set_image_data_format
(data_format)
Sets the value of the image data format convention. Arguments: data_format: string. `'channels_first'` or `'channels_last'`. Example: ```python >>> from keras import backend as K >>> K.image_data_format() 'channels_first' >>> K.set_image_data_format('channels_last') >>> K.image_data_format() 'channels_last' ``` Raises: ValueError: In case of invalid `data_format` value.
Sets the value of the image data format convention.
[ "Sets", "the", "value", "of", "the", "image", "data", "format", "convention", "." ]
def set_image_data_format(data_format): """Sets the value of the image data format convention. Arguments: data_format: string. `'channels_first'` or `'channels_last'`. Example: ```python >>> from keras import backend as K >>> K.image_data_format() 'channels_first' >>> K.set_image_data_format('channels_last') >>> K.image_data_format() 'channels_last' ``` Raises: ValueError: In case of invalid `data_format` value. """ global _IMAGE_DATA_FORMAT if data_format not in {'channels_last', 'channels_first'}: raise ValueError('Unknown data_format:', data_format) _IMAGE_DATA_FORMAT = str(data_format)
[ "def", "set_image_data_format", "(", "data_format", ")", ":", "global", "_IMAGE_DATA_FORMAT", "if", "data_format", "not", "in", "{", "'channels_last'", ",", "'channels_first'", "}", ":", "raise", "ValueError", "(", "'Unknown data_format:'", ",", "data_format", ")", "_IMAGE_DATA_FORMAT", "=", "str", "(", "data_format", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/backend.py#L223-L245
sofa-framework/sofa
70628e35a44fcc258cf8250109b5e4eba8c5abe9
applications/plugins/PSL/python/pslparserhjson.py
python
treeToString
(node, space)
return res
Converts a Sofa node and its children & objects into an h-json representation
Converts a Sofa node and its children & objects into an h-json representation
[ "Converts", "a", "Sofa", "node", "and", "its", "children", "&", "objects", "into", "an", "h", "-", "json", "representation" ]
def treeToString(node, space): '''Converts a Sofa node and its children & objects into an h-json representation''' nspace=space+" " res = "" instanceof = node.getData("psl_instanceof") if instanceof != None: res += space+str(node.psl_instanceof)+" : {"+ "\n" for k,v in eval(node.psl_properties): res += space+" "+k+" : "+str(v)+ "\n" res += space+"}"+ "\n" return res res += space+"Node : {" ores = "" for datafield in node.getListOfDataFields(): if datafield.isPersistant(): if datafield.hasParent(): ores += "\n" + nspace + datafield.name + ' : "' + datafield.getParentPath() + '"' else: ores += "\n" + nspace + datafield.name + " : \"" + datafield.getValueString() + "\"" for link in node.getListOfLinks(): if link.isPersistant(): ores += "\n" + nspace + link.name + " : \"" + link.getValueString() + "\"" if ores != "": ores += "\n" dres = "" for object in node.getObjects(): dres += objectToString(object, space+" ") cres = "" for child in node.getChildren(): cres += treeToString(child, space+" ") ores = ores + dres + cres res += ores if ores == "": res += "}\n" else: res += space+"}\n" return res
[ "def", "treeToString", "(", "node", ",", "space", ")", ":", "nspace", "=", "space", "+", "\" \"", "res", "=", "\"\"", "instanceof", "=", "node", ".", "getData", "(", "\"psl_instanceof\"", ")", "if", "instanceof", "!=", "None", ":", "res", "+=", "space", "+", "str", "(", "node", ".", "psl_instanceof", ")", "+", "\" : {\"", "+", "\"\\n\"", "for", "k", ",", "v", "in", "eval", "(", "node", ".", "psl_properties", ")", ":", "res", "+=", "space", "+", "\" \"", "+", "k", "+", "\" : \"", "+", "str", "(", "v", ")", "+", "\"\\n\"", "res", "+=", "space", "+", "\"}\"", "+", "\"\\n\"", "return", "res", "res", "+=", "space", "+", "\"Node : {\"", "ores", "=", "\"\"", "for", "datafield", "in", "node", ".", "getListOfDataFields", "(", ")", ":", "if", "datafield", ".", "isPersistant", "(", ")", ":", "if", "datafield", ".", "hasParent", "(", ")", ":", "ores", "+=", "\"\\n\"", "+", "nspace", "+", "datafield", ".", "name", "+", "' : \"'", "+", "datafield", ".", "getParentPath", "(", ")", "+", "'\"'", "else", ":", "ores", "+=", "\"\\n\"", "+", "nspace", "+", "datafield", ".", "name", "+", "\" : \\\"\"", "+", "datafield", ".", "getValueString", "(", ")", "+", "\"\\\"\"", "for", "link", "in", "node", ".", "getListOfLinks", "(", ")", ":", "if", "link", ".", "isPersistant", "(", ")", ":", "ores", "+=", "\"\\n\"", "+", "nspace", "+", "link", ".", "name", "+", "\" : \\\"\"", "+", "link", ".", "getValueString", "(", ")", "+", "\"\\\"\"", "if", "ores", "!=", "\"\"", ":", "ores", "+=", "\"\\n\"", "dres", "=", "\"\"", "for", "object", "in", "node", ".", "getObjects", "(", ")", ":", "dres", "+=", "objectToString", "(", "object", ",", "space", "+", "\" \"", ")", "cres", "=", "\"\"", "for", "child", "in", "node", ".", "getChildren", "(", ")", ":", "cres", "+=", "treeToString", "(", "child", ",", "space", "+", "\" \"", ")", "ores", "=", "ores", "+", "dres", "+", "cres", "res", "+=", "ores", "if", "ores", "==", "\"\"", ":", "res", "+=", "\"}\\n\"", "else", ":", "res", "+=", "space", "+", "\"}\\n\"", "return", "res" ]
https://github.com/sofa-framework/sofa/blob/70628e35a44fcc258cf8250109b5e4eba8c5abe9/applications/plugins/PSL/python/pslparserhjson.py#L71-L113
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_view.py
python
BasicFittingView.set_workspace_combo_box_label
(self, text: str)
Sets the label text next to the workspace selector combobox.
Sets the label text next to the workspace selector combobox.
[ "Sets", "the", "label", "text", "next", "to", "the", "workspace", "selector", "combobox", "." ]
def set_workspace_combo_box_label(self, text: str) -> None: """Sets the label text next to the workspace selector combobox.""" self.workspace_selector.set_data_combo_box_label(text)
[ "def", "set_workspace_combo_box_label", "(", "self", ",", "text", ":", "str", ")", "->", "None", ":", "self", ".", "workspace_selector", ".", "set_data_combo_box_label", "(", "text", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_view.py#L132-L134
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Source/bindings/scripts/v8_interface.py
python
effective_overload_set
(F)
return S
Returns the effective overload set of an overloaded function. An effective overload set is the set of overloaded functions + signatures (type list of arguments, with optional and variadic arguments included or not), and is used in the overload resolution algorithm. For example, given input [f1(optional long x), f2(DOMString s)], the output is informally [f1(), f1(long), f2(DOMString)], and formally [(f1, [], []), (f1, [long], [optional]), (f2, [DOMString], [required])]. Currently the optionality list is a list of |is_optional| booleans (True means optional, False means required); to support variadics this needs to be tri-valued as required, optional, or variadic. Formally: An effective overload set represents the allowable invocations for a particular operation, constructor (specified with [Constructor] or [NamedConstructor]), legacy caller or callback function. An additional argument N (argument count) is needed when overloading variadics, but we don't use that currently. Spec: http://heycam.github.io/webidl/#dfn-effective-overload-set Formally the input and output lists are sets, but methods are stored internally as dicts, which can't be stored in a set because they are not hashable, so we use lists instead. Arguments: F: list of overloads for a given callable name. Returns: S: list of tuples of the form (callable, type list, optionality list).
Returns the effective overload set of an overloaded function.
[ "Returns", "the", "effective", "overload", "set", "of", "an", "overloaded", "function", "." ]
def effective_overload_set(F): """Returns the effective overload set of an overloaded function. An effective overload set is the set of overloaded functions + signatures (type list of arguments, with optional and variadic arguments included or not), and is used in the overload resolution algorithm. For example, given input [f1(optional long x), f2(DOMString s)], the output is informally [f1(), f1(long), f2(DOMString)], and formally [(f1, [], []), (f1, [long], [optional]), (f2, [DOMString], [required])]. Currently the optionality list is a list of |is_optional| booleans (True means optional, False means required); to support variadics this needs to be tri-valued as required, optional, or variadic. Formally: An effective overload set represents the allowable invocations for a particular operation, constructor (specified with [Constructor] or [NamedConstructor]), legacy caller or callback function. An additional argument N (argument count) is needed when overloading variadics, but we don't use that currently. Spec: http://heycam.github.io/webidl/#dfn-effective-overload-set Formally the input and output lists are sets, but methods are stored internally as dicts, which can't be stored in a set because they are not hashable, so we use lists instead. Arguments: F: list of overloads for a given callable name. Returns: S: list of tuples of the form (callable, type list, optionality list). """ # Code closely follows the algorithm in the spec, for clarity and # correctness, and hence is not very Pythonic. # 1. Initialize S to ∅. # (We use a list because we can't use a set, as noted above.) S = [] # 2. Let F be a set with elements as follows, according to the kind of # effective overload set: # (Passed as argument, nothing to do.) # 3. & 4. (maxarg, m) are only needed for variadics, not used. # 5. For each operation, extended attribute or callback function X in F: for X in F: # X is the "callable", F is the overloads. arguments = X['arguments'] # 1. Let n be the number of arguments X is declared to take. n = len(arguments) # 2. Let t0..n−1 be a list of types, where ti is the type of X’s # argument at index i. # (“type list”) t = tuple(argument['idl_type_object'] for argument in arguments) # 3. Let o0..n−1 be a list of optionality values, where oi is “variadic” # if X’s argument at index i is a final, variadic argument, “optional” # if the argument is optional, and “required” otherwise. # (“optionality list”) # (We’re just using a boolean for optional/variadic vs. required.) o = tuple(argument['is_optional'] or argument['is_variadic'] for argument in arguments) # 4. Add to S the tuple <X, t0..n−1, o0..n−1>. S.append((X, t, o)) # 5. If X is declared to be variadic, then: # (Not used, so not implemented.) # 6. Initialize i to n−1. i = n - 1 # 7. While i ≥ 0: # Spec bug (fencepost error); should be “While i > 0:” # https://www.w3.org/Bugs/Public/show_bug.cgi?id=25590 while i > 0: # 1. If argument i of X is not optional, then break this loop. if not o[i]: break # 2. Otherwise, add to S the tuple <X, t0..i−1, o0..i−1>. S.append((X, t[:i], o[:i])) # 3. Set i to i−1. i = i - 1 # 8. If n > 0 and all arguments of X are optional, then add to S the # tuple <X, (), ()> (where “()” represents the empty list). if n > 0 and all(oi for oi in o): S.append((X, [], [])) # 6. The effective overload set is S. return S
[ "def", "effective_overload_set", "(", "F", ")", ":", "# Code closely follows the algorithm in the spec, for clarity and", "# correctness, and hence is not very Pythonic.", "# 1. Initialize S to ∅.", "# (We use a list because we can't use a set, as noted above.)", "S", "=", "[", "]", "# 2. Let F be a set with elements as follows, according to the kind of", "# effective overload set:", "# (Passed as argument, nothing to do.)", "# 3. & 4. (maxarg, m) are only needed for variadics, not used.", "# 5. For each operation, extended attribute or callback function X in F:", "for", "X", "in", "F", ":", "# X is the \"callable\", F is the overloads.", "arguments", "=", "X", "[", "'arguments'", "]", "# 1. Let n be the number of arguments X is declared to take.", "n", "=", "len", "(", "arguments", ")", "# 2. Let t0..n−1 be a list of types, where ti is the type of X’s", "# argument at index i.", "# (“type list”)", "t", "=", "tuple", "(", "argument", "[", "'idl_type_object'", "]", "for", "argument", "in", "arguments", ")", "# 3. Let o0..n−1 be a list of optionality values, where oi is “variadic”", "# if X’s argument at index i is a final, variadic argument, “optional”", "# if the argument is optional, and “required” otherwise.", "# (“optionality list”)", "# (We’re just using a boolean for optional/variadic vs. required.)", "o", "=", "tuple", "(", "argument", "[", "'is_optional'", "]", "or", "argument", "[", "'is_variadic'", "]", "for", "argument", "in", "arguments", ")", "# 4. Add to S the tuple <X, t0..n−1, o0..n−1>.", "S", ".", "append", "(", "(", "X", ",", "t", ",", "o", ")", ")", "# 5. If X is declared to be variadic, then:", "# (Not used, so not implemented.)", "# 6. Initialize i to n−1.", "i", "=", "n", "-", "1", "# 7. While i ≥ 0:", "# Spec bug (fencepost error); should be “While i > 0:”", "# https://www.w3.org/Bugs/Public/show_bug.cgi?id=25590", "while", "i", ">", "0", ":", "# 1. If argument i of X is not optional, then break this loop.", "if", "not", "o", "[", "i", "]", ":", "break", "# 2. Otherwise, add to S the tuple <X, t0..i−1, o0..i−1>.", "S", ".", "append", "(", "(", "X", ",", "t", "[", ":", "i", "]", ",", "o", "[", ":", "i", "]", ")", ")", "# 3. Set i to i−1.", "i", "=", "i", "-", "1", "# 8. If n > 0 and all arguments of X are optional, then add to S the", "# tuple <X, (), ()> (where “()” represents the empty list).", "if", "n", ">", "0", "and", "all", "(", "oi", "for", "oi", "in", "o", ")", ":", "S", ".", "append", "(", "(", "X", ",", "[", "]", ",", "[", "]", ")", ")", "# 6. The effective overload set is S.", "return", "S" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Source/bindings/scripts/v8_interface.py#L776-L862
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/special/basic.py
python
jvp
(v, z, n=1)
Compute nth derivative of Bessel function Jv(z) with respect to `z`. Parameters ---------- v : float Order of Bessel function z : complex Argument at which to evaluate the derivative n : int, default 1 Order of derivative Notes ----- The derivative is computed using the relation DLFM 10.6.7 [2]_. References ---------- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special Functions", John Wiley and Sons, 1996, chapter 5. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html .. [2] NIST Digital Library of Mathematical Functions. https://dlmf.nist.gov/10.6.E7
Compute nth derivative of Bessel function Jv(z) with respect to `z`.
[ "Compute", "nth", "derivative", "of", "Bessel", "function", "Jv", "(", "z", ")", "with", "respect", "to", "z", "." ]
def jvp(v, z, n=1): """Compute nth derivative of Bessel function Jv(z) with respect to `z`. Parameters ---------- v : float Order of Bessel function z : complex Argument at which to evaluate the derivative n : int, default 1 Order of derivative Notes ----- The derivative is computed using the relation DLFM 10.6.7 [2]_. References ---------- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special Functions", John Wiley and Sons, 1996, chapter 5. https://people.sc.fsu.edu/~jburkardt/f_src/special_functions/special_functions.html .. [2] NIST Digital Library of Mathematical Functions. https://dlmf.nist.gov/10.6.E7 """ n = _nonneg_int_or_fail(n, 'n') if n == 0: return jv(v, z) else: return _bessel_diff_formula(v, z, n, jv, -1)
[ "def", "jvp", "(", "v", ",", "z", ",", "n", "=", "1", ")", ":", "n", "=", "_nonneg_int_or_fail", "(", "n", ",", "'n'", ")", "if", "n", "==", "0", ":", "return", "jv", "(", "v", ",", "z", ")", "else", ":", "return", "_bessel_diff_formula", "(", "v", ",", "z", ",", "n", ",", "jv", ",", "-", "1", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/special/basic.py#L436-L465
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/programs/scripts/internetcontent/nv_python_libs/xsltfunctions/cinemarv_api.py
python
xpathFunctions.cinemarvIsCustomHTML
(self, context, *args)
Check if the link is for a custom HTML Example call: mnvXpath:cinemarvIsCustomHTML(('dummy')) return True if the link does not starts with "http://" return False if the link starts with "http://"
Check if the link is for a custom HTML Example call: mnvXpath:cinemarvIsCustomHTML(('dummy')) return True if the link does not starts with "http://" return False if the link starts with "http://"
[ "Check", "if", "the", "link", "is", "for", "a", "custom", "HTML", "Example", "call", ":", "mnvXpath", ":", "cinemarvIsCustomHTML", "((", "dummy", "))", "return", "True", "if", "the", "link", "does", "not", "starts", "with", "http", ":", "//", "return", "False", "if", "the", "link", "starts", "with", "http", ":", "//" ]
def cinemarvIsCustomHTML(self, context, *args): '''Check if the link is for a custom HTML Example call: mnvXpath:cinemarvIsCustomHTML(('dummy')) return True if the link does not starts with "http://" return False if the link starts with "http://" ''' if self.persistence['cinemarvLinkGeneration'] is None: return False if self.persistence['cinemarvLinkGeneration'].startswith('http://'): return False else: return True
[ "def", "cinemarvIsCustomHTML", "(", "self", ",", "context", ",", "*", "args", ")", ":", "if", "self", ".", "persistence", "[", "'cinemarvLinkGeneration'", "]", "is", "None", ":", "return", "False", "if", "self", ".", "persistence", "[", "'cinemarvLinkGeneration'", "]", ".", "startswith", "(", "'http://'", ")", ":", "return", "False", "else", ":", "return", "True" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/internetcontent/nv_python_libs/xsltfunctions/cinemarv_api.py#L142-L154
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
CheckListBox.Create
(*args, **kwargs)
return _controls_.CheckListBox_Create(*args, **kwargs)
Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray, long style=0, Validator validator=DefaultValidator, String name=ListBoxNameStr) -> bool
Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray, long style=0, Validator validator=DefaultValidator, String name=ListBoxNameStr) -> bool
[ "Create", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "wxArrayString", "choices", "=", "wxPyEmptyStringArray", "long", "style", "=", "0", "Validator", "validator", "=", "DefaultValidator", "String", "name", "=", "ListBoxNameStr", ")", "-", ">", "bool" ]
def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray, long style=0, Validator validator=DefaultValidator, String name=ListBoxNameStr) -> bool """ return _controls_.CheckListBox_Create(*args, **kwargs)
[ "def", "Create", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "CheckListBox_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L1317-L1324
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/lib/polynomial.py
python
polyder
(p, m=1)
return val
Return the derivative of the specified order of a polynomial. Parameters ---------- p : poly1d or sequence Polynomial to differentiate. A sequence is interpreted as polynomial coefficients, see `poly1d`. m : int, optional Order of differentiation (default: 1) Returns ------- der : poly1d A new polynomial representing the derivative. See Also -------- polyint : Anti-derivative of a polynomial. poly1d : Class for one-dimensional polynomials. Examples -------- The derivative of the polynomial :math:`x^3 + x^2 + x^1 + 1` is: >>> p = np.poly1d([1,1,1,1]) >>> p2 = np.polyder(p) >>> p2 poly1d([3, 2, 1]) which evaluates to: >>> p2(2.) 17.0 We can verify this, approximating the derivative with ``(f(x + h) - f(x))/h``: >>> (p(2. + 0.001) - p(2.)) / 0.001 17.007000999997857 The fourth-order derivative of a 3rd-order polynomial is zero: >>> np.polyder(p, 2) poly1d([6, 2]) >>> np.polyder(p, 3) poly1d([6]) >>> np.polyder(p, 4) poly1d([ 0.])
Return the derivative of the specified order of a polynomial.
[ "Return", "the", "derivative", "of", "the", "specified", "order", "of", "a", "polynomial", "." ]
def polyder(p, m=1): """ Return the derivative of the specified order of a polynomial. Parameters ---------- p : poly1d or sequence Polynomial to differentiate. A sequence is interpreted as polynomial coefficients, see `poly1d`. m : int, optional Order of differentiation (default: 1) Returns ------- der : poly1d A new polynomial representing the derivative. See Also -------- polyint : Anti-derivative of a polynomial. poly1d : Class for one-dimensional polynomials. Examples -------- The derivative of the polynomial :math:`x^3 + x^2 + x^1 + 1` is: >>> p = np.poly1d([1,1,1,1]) >>> p2 = np.polyder(p) >>> p2 poly1d([3, 2, 1]) which evaluates to: >>> p2(2.) 17.0 We can verify this, approximating the derivative with ``(f(x + h) - f(x))/h``: >>> (p(2. + 0.001) - p(2.)) / 0.001 17.007000999997857 The fourth-order derivative of a 3rd-order polynomial is zero: >>> np.polyder(p, 2) poly1d([6, 2]) >>> np.polyder(p, 3) poly1d([6]) >>> np.polyder(p, 4) poly1d([ 0.]) """ m = int(m) if m < 0: raise ValueError, "Order of derivative must be positive (see polyint)" truepoly = isinstance(p, poly1d) p = NX.asarray(p) n = len(p) - 1 y = p[:-1] * NX.arange(n, 0, -1) if m == 0: val = p else: val = polyder(y, m - 1) if truepoly: val = poly1d(val) return val
[ "def", "polyder", "(", "p", ",", "m", "=", "1", ")", ":", "m", "=", "int", "(", "m", ")", "if", "m", "<", "0", ":", "raise", "ValueError", ",", "\"Order of derivative must be positive (see polyint)\"", "truepoly", "=", "isinstance", "(", "p", ",", "poly1d", ")", "p", "=", "NX", ".", "asarray", "(", "p", ")", "n", "=", "len", "(", "p", ")", "-", "1", "y", "=", "p", "[", ":", "-", "1", "]", "*", "NX", ".", "arange", "(", "n", ",", "0", ",", "-", "1", ")", "if", "m", "==", "0", ":", "val", "=", "p", "else", ":", "val", "=", "polyder", "(", "y", ",", "m", "-", "1", ")", "if", "truepoly", ":", "val", "=", "poly1d", "(", "val", ")", "return", "val" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/lib/polynomial.py#L326-L392
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_SelfTest_REQUEST.__init__
(self, fullTest = 0)
This command causes the TPM to perform a test of its capabilities. If the fullTest is YES, the TPM will test all functions. If fullTest = NO, the TPM will only test those functions that have not previously been tested. Attributes: fullTest (int): YES if full test to be performed NO if only test of untested functions required
This command causes the TPM to perform a test of its capabilities. If the fullTest is YES, the TPM will test all functions. If fullTest = NO, the TPM will only test those functions that have not previously been tested.
[ "This", "command", "causes", "the", "TPM", "to", "perform", "a", "test", "of", "its", "capabilities", ".", "If", "the", "fullTest", "is", "YES", "the", "TPM", "will", "test", "all", "functions", ".", "If", "fullTest", "=", "NO", "the", "TPM", "will", "only", "test", "those", "functions", "that", "have", "not", "previously", "been", "tested", "." ]
def __init__(self, fullTest = 0): """ This command causes the TPM to perform a test of its capabilities. If the fullTest is YES, the TPM will test all functions. If fullTest = NO, the TPM will only test those functions that have not previously been tested. Attributes: fullTest (int): YES if full test to be performed NO if only test of untested functions required """ self.fullTest = fullTest
[ "def", "__init__", "(", "self", ",", "fullTest", "=", "0", ")", ":", "self", ".", "fullTest", "=", "fullTest" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L9124-L9134
uber/neuropod
de304c40ec0634a868d7ef41ba7bf89ebc364f10
source/python/neuropod/utils/dtype_utils.py
python
get_dtype
(arg)
return np.dtype(arg)
Get numpy dtypes from strings in a python 2 and 3 compatible way
Get numpy dtypes from strings in a python 2 and 3 compatible way
[ "Get", "numpy", "dtypes", "from", "strings", "in", "a", "python", "2", "and", "3", "compatible", "way" ]
def get_dtype(arg): """ Get numpy dtypes from strings in a python 2 and 3 compatible way """ if arg == "string": arg = "str" return np.dtype(arg)
[ "def", "get_dtype", "(", "arg", ")", ":", "if", "arg", "==", "\"string\"", ":", "arg", "=", "\"str\"", "return", "np", ".", "dtype", "(", "arg", ")" ]
https://github.com/uber/neuropod/blob/de304c40ec0634a868d7ef41ba7bf89ebc364f10/source/python/neuropod/utils/dtype_utils.py#L18-L25
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/pexpect/screen.py
python
screen.cursor_restore_attrs
(self)
Restores cursor position after a Save Cursor.
Restores cursor position after a Save Cursor.
[ "Restores", "cursor", "position", "after", "a", "Save", "Cursor", "." ]
def cursor_restore_attrs (self): # <ESC>8 """Restores cursor position after a Save Cursor.""" self.cursor_home (self.cur_saved_r, self.cur_saved_c)
[ "def", "cursor_restore_attrs", "(", "self", ")", ":", "# <ESC>8", "self", ".", "cursor_home", "(", "self", ".", "cur_saved_r", ",", "self", ".", "cur_saved_c", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/pexpect/screen.py#L284-L288
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/syntax/_perl.py
python
KeywordString
(option=0)
Returns the specified Keyword String @note: not used by most modules
Returns the specified Keyword String @note: not used by most modules
[ "Returns", "the", "specified", "Keyword", "String", "@note", ":", "not", "used", "by", "most", "modules" ]
def KeywordString(option=0): """Returns the specified Keyword String @note: not used by most modules """ if option == synglob.ID_LANG_PERL: return PERL_KW[1] else: return u''
[ "def", "KeywordString", "(", "option", "=", "0", ")", ":", "if", "option", "==", "synglob", ".", "ID_LANG_PERL", ":", "return", "PERL_KW", "[", "1", "]", "else", ":", "return", "u''" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/_perl.py#L135-L143
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/agilepy/lib_base/arrayman.py
python
ArrayObjman.init_postload_external
(self)
Called after set state. Link internal states.
Called after set state. Link internal states.
[ "Called", "after", "set", "state", ".", "Link", "internal", "states", "." ]
def init_postload_external(self): """ Called after set state. Link internal states. """ TableMixin.init_postload_external(self) self._init_attributes() self._init_constants()
[ "def", "init_postload_external", "(", "self", ")", ":", "TableMixin", ".", "init_postload_external", "(", "self", ")", "self", ".", "_init_attributes", "(", ")", "self", ".", "_init_constants", "(", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_base/arrayman.py#L1233-L1240
DayBreak-u/yolo-face-with-landmark
29cc7454a578cc9a23d95a712af70d467f69fedd
utils/utils.py
python
box_iou
(box1, box2)
return inter / (area1[:, None] + area2 - inter)
Return intersection-over-union (Jaccard index) of boxes. Both sets of boxes are expected to be in (x1, y1, x2, y2) format. Arguments: box1 (Tensor[N, 4]) box2 (Tensor[M, 4]) Returns: iou (Tensor[N, M]): the NxM matrix containing the pairwise IoU values for every element in boxes1 and boxes2
Return intersection-over-union (Jaccard index) of boxes. Both sets of boxes are expected to be in (x1, y1, x2, y2) format. Arguments: box1 (Tensor[N, 4]) box2 (Tensor[M, 4]) Returns: iou (Tensor[N, M]): the NxM matrix containing the pairwise IoU values for every element in boxes1 and boxes2
[ "Return", "intersection", "-", "over", "-", "union", "(", "Jaccard", "index", ")", "of", "boxes", ".", "Both", "sets", "of", "boxes", "are", "expected", "to", "be", "in", "(", "x1", "y1", "x2", "y2", ")", "format", ".", "Arguments", ":", "box1", "(", "Tensor", "[", "N", "4", "]", ")", "box2", "(", "Tensor", "[", "M", "4", "]", ")", "Returns", ":", "iou", "(", "Tensor", "[", "N", "M", "]", ")", ":", "the", "NxM", "matrix", "containing", "the", "pairwise", "IoU", "values", "for", "every", "element", "in", "boxes1", "and", "boxes2" ]
def box_iou(box1, box2): # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py """ Return intersection-over-union (Jaccard index) of boxes. Both sets of boxes are expected to be in (x1, y1, x2, y2) format. Arguments: box1 (Tensor[N, 4]) box2 (Tensor[M, 4]) Returns: iou (Tensor[N, M]): the NxM matrix containing the pairwise IoU values for every element in boxes1 and boxes2 """ def box_area(box): # box = 4xn return (box[2] - box[0]) * (box[3] - box[1]) area1 = box_area(box1.t()) area2 = box_area(box2.t()) # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2) inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2) return inter / (area1[:, None] + area2 - inter)
[ "def", "box_iou", "(", "box1", ",", "box2", ")", ":", "# https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py", "def", "box_area", "(", "box", ")", ":", "# box = 4xn", "return", "(", "box", "[", "2", "]", "-", "box", "[", "0", "]", ")", "*", "(", "box", "[", "3", "]", "-", "box", "[", "1", "]", ")", "area1", "=", "box_area", "(", "box1", ".", "t", "(", ")", ")", "area2", "=", "box_area", "(", "box2", ".", "t", "(", ")", ")", "# inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)", "inter", "=", "(", "torch", ".", "min", "(", "box1", "[", ":", ",", "None", ",", "2", ":", "]", ",", "box2", "[", ":", ",", "2", ":", "]", ")", "-", "torch", ".", "max", "(", "box1", "[", ":", ",", "None", ",", ":", "2", "]", ",", "box2", "[", ":", ",", ":", "2", "]", ")", ")", ".", "clamp", "(", "0", ")", ".", "prod", "(", "2", ")", "return", "inter", "/", "(", "area1", "[", ":", ",", "None", "]", "+", "area2", "-", "inter", ")" ]
https://github.com/DayBreak-u/yolo-face-with-landmark/blob/29cc7454a578cc9a23d95a712af70d467f69fedd/utils/utils.py#L143-L165
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/jinja2/environment.py
python
Template.from_module_dict
(cls, environment, module_dict, globals)
return cls._from_namespace(environment, module_dict, globals)
Creates a template object from a module. This is used by the module loader to create a template object. .. versionadded:: 2.4
Creates a template object from a module. This is used by the module loader to create a template object.
[ "Creates", "a", "template", "object", "from", "a", "module", ".", "This", "is", "used", "by", "the", "module", "loader", "to", "create", "a", "template", "object", "." ]
def from_module_dict(cls, environment, module_dict, globals): """Creates a template object from a module. This is used by the module loader to create a template object. .. versionadded:: 2.4 """ return cls._from_namespace(environment, module_dict, globals)
[ "def", "from_module_dict", "(", "cls", ",", "environment", ",", "module_dict", ",", "globals", ")", ":", "return", "cls", ".", "_from_namespace", "(", "environment", ",", "module_dict", ",", "globals", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/environment.py#L923-L929
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py
python
CudnnParamsFormatConverterLSTM._cudnn_to_tf_weights
(self, *cu_weights)
r"""Stitching cudnn canonical weights to generate tf canonical weights.
r"""Stitching cudnn canonical weights to generate tf canonical weights.
[ "r", "Stitching", "cudnn", "canonical", "weights", "to", "generate", "tf", "canonical", "weights", "." ]
def _cudnn_to_tf_weights(self, *cu_weights): r"""Stitching cudnn canonical weights to generate tf canonical weights.""" if self._num_proj: w_i, w_f, w_c, w_o, r_i, r_f, r_c, r_o, pw = cu_weights else: w_i, w_f, w_c, w_o, r_i, r_f, r_c, r_o = cu_weights # pylint: disable=invalid-name W_i = array_ops.concat([w_i, r_i], axis=1) W_f = array_ops.concat([w_f, r_f], axis=1) W_c = array_ops.concat([w_c, r_c], axis=1) W_o = array_ops.concat([w_o, r_o], axis=1) # pylint: enable=invalid-name # Cudnn LSTM weights are in ifco order, other tf LSTMs are in icfo order. reordered = self._cudnn_to_tf_gate_params(*[W_i, W_f, W_c, W_o]) if self._num_proj: return (array_ops.transpose(array_ops.concat(reordered, axis=0)), array_ops.transpose(pw)) else: return (array_ops.transpose(array_ops.concat(reordered, axis=0)),)
[ "def", "_cudnn_to_tf_weights", "(", "self", ",", "*", "cu_weights", ")", ":", "if", "self", ".", "_num_proj", ":", "w_i", ",", "w_f", ",", "w_c", ",", "w_o", ",", "r_i", ",", "r_f", ",", "r_c", ",", "r_o", ",", "pw", "=", "cu_weights", "else", ":", "w_i", ",", "w_f", ",", "w_c", ",", "w_o", ",", "r_i", ",", "r_f", ",", "r_c", ",", "r_o", "=", "cu_weights", "# pylint: disable=invalid-name", "W_i", "=", "array_ops", ".", "concat", "(", "[", "w_i", ",", "r_i", "]", ",", "axis", "=", "1", ")", "W_f", "=", "array_ops", ".", "concat", "(", "[", "w_f", ",", "r_f", "]", ",", "axis", "=", "1", ")", "W_c", "=", "array_ops", ".", "concat", "(", "[", "w_c", ",", "r_c", "]", ",", "axis", "=", "1", ")", "W_o", "=", "array_ops", ".", "concat", "(", "[", "w_o", ",", "r_o", "]", ",", "axis", "=", "1", ")", "# pylint: enable=invalid-name", "# Cudnn LSTM weights are in ifco order, other tf LSTMs are in icfo order.", "reordered", "=", "self", ".", "_cudnn_to_tf_gate_params", "(", "*", "[", "W_i", ",", "W_f", ",", "W_c", ",", "W_o", "]", ")", "if", "self", ".", "_num_proj", ":", "return", "(", "array_ops", ".", "transpose", "(", "array_ops", ".", "concat", "(", "reordered", ",", "axis", "=", "0", ")", ")", ",", "array_ops", ".", "transpose", "(", "pw", ")", ")", "else", ":", "return", "(", "array_ops", ".", "transpose", "(", "array_ops", ".", "concat", "(", "reordered", ",", "axis", "=", "0", ")", ")", ",", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/cudnn_rnn/python/ops/cudnn_rnn_ops.py#L486-L505
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/basic_fitting_context.py
python
BasicFittingContext.chi_squared_for_undo
(self, chi_squared: list)
Sets the chi squared from previous fits used for single fitting.
Sets the chi squared from previous fits used for single fitting.
[ "Sets", "the", "chi", "squared", "from", "previous", "fits", "used", "for", "single", "fitting", "." ]
def chi_squared_for_undo(self, chi_squared: list) -> None: """Sets the chi squared from previous fits used for single fitting.""" self._chi_squared_for_undo = chi_squared
[ "def", "chi_squared_for_undo", "(", "self", ",", "chi_squared", ":", "list", ")", "->", "None", ":", "self", ".", "_chi_squared_for_undo", "=", "chi_squared" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/contexts/fitting_contexts/basic_fitting_context.py#L202-L204
google/tink
59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14
python/tink/jwt/_raw_jwt.py
python
RawJwt.json_payload
(self)
return _json_util.json_dumps(self._payload)
Returns the payload encoded as JSON string.
Returns the payload encoded as JSON string.
[ "Returns", "the", "payload", "encoded", "as", "JSON", "string", "." ]
def json_payload(self) -> str: """Returns the payload encoded as JSON string.""" return _json_util.json_dumps(self._payload)
[ "def", "json_payload", "(", "self", ")", "->", "str", ":", "return", "_json_util", ".", "json_dumps", "(", "self", ".", "_payload", ")" ]
https://github.com/google/tink/blob/59bb34495d1cb8f9d9dbc0f0a52c4f9e21491a14/python/tink/jwt/_raw_jwt.py#L167-L169
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/latex2mathml.py
python
parse_latex_math
(string, inline=True)
return tree
parse_latex_math(string [,inline]) -> MathML-tree Returns a MathML-tree parsed from string. inline=True is for inline math and inline=False is for displayed math. tree is the whole tree and node is the current element.
parse_latex_math(string [,inline]) -> MathML-tree
[ "parse_latex_math", "(", "string", "[", "inline", "]", ")", "-", ">", "MathML", "-", "tree" ]
def parse_latex_math(string, inline=True): """parse_latex_math(string [,inline]) -> MathML-tree Returns a MathML-tree parsed from string. inline=True is for inline math and inline=False is for displayed math. tree is the whole tree and node is the current element.""" # Normalize white-space: string = ' '.join(string.split()) if inline: node = mrow() tree = math(node, inline=True) else: node = mtd() tree = math(mtable(mtr(node)), inline=False) while len(string) > 0: n = len(string) c = string[0] skip = 1 # number of characters consumed if n > 1: c2 = string[1] else: c2 = '' ## print n, string, c, c2, node.__class__.__name__ if c == ' ': pass elif c == '\\': if c2 in '{}': node = node.append(mo(c2)) skip = 2 elif c2 == ' ': node = node.append(mspace()) skip = 2 elif c2 == ',': # TODO: small space node = node.append(mspace()) skip = 2 elif c2.isalpha(): # We have a LaTeX-name: i = 2 while i < n and string[i].isalpha(): i += 1 name = string[1:i] node, skip = handle_keyword(name, node, string[i:]) skip += i elif c2 == '\\': # End of a row: entry = mtd() row = mtr(entry) node.close().close().append(row) node = entry skip = 2 else: raise SyntaxError(ur'Syntax error: "%s%s"' % (c, c2)) elif c.isalpha(): node = node.append(mi(c)) elif c.isdigit(): node = node.append(mn(c)) elif c in "+-*/=()[]|<>,.!?':;@": node = node.append(mo(c)) elif c == '_': child = node.delete_child() if isinstance(child, msup): sub = msubsup(child.children, reversed=True) elif isinstance(child, mo) and child.data in sumintprod: sub = munder(child) else: sub = msub(child) node.append(sub) node = sub elif c == '^': child = node.delete_child() if isinstance(child, msub): sup = msubsup(child.children) elif isinstance(child, mo) and child.data in sumintprod: sup = mover(child) elif (isinstance(child, munder) and child.children[0].data in sumintprod): sup = munderover(child.children) else: sup = msup(child) node.append(sup) node = sup elif c == '{': row = mrow() node.append(row) node = row elif c == '}': node = node.close() elif c == '&': entry = mtd() node.close().append(entry) node = entry else: raise SyntaxError(ur'Illegal character: "%s"' % c) string = string[skip:] return tree
[ "def", "parse_latex_math", "(", "string", ",", "inline", "=", "True", ")", ":", "# Normalize white-space:", "string", "=", "' '", ".", "join", "(", "string", ".", "split", "(", ")", ")", "if", "inline", ":", "node", "=", "mrow", "(", ")", "tree", "=", "math", "(", "node", ",", "inline", "=", "True", ")", "else", ":", "node", "=", "mtd", "(", ")", "tree", "=", "math", "(", "mtable", "(", "mtr", "(", "node", ")", ")", ",", "inline", "=", "False", ")", "while", "len", "(", "string", ")", ">", "0", ":", "n", "=", "len", "(", "string", ")", "c", "=", "string", "[", "0", "]", "skip", "=", "1", "# number of characters consumed", "if", "n", ">", "1", ":", "c2", "=", "string", "[", "1", "]", "else", ":", "c2", "=", "''", "## print n, string, c, c2, node.__class__.__name__", "if", "c", "==", "' '", ":", "pass", "elif", "c", "==", "'\\\\'", ":", "if", "c2", "in", "'{}'", ":", "node", "=", "node", ".", "append", "(", "mo", "(", "c2", ")", ")", "skip", "=", "2", "elif", "c2", "==", "' '", ":", "node", "=", "node", ".", "append", "(", "mspace", "(", ")", ")", "skip", "=", "2", "elif", "c2", "==", "','", ":", "# TODO: small space", "node", "=", "node", ".", "append", "(", "mspace", "(", ")", ")", "skip", "=", "2", "elif", "c2", ".", "isalpha", "(", ")", ":", "# We have a LaTeX-name:", "i", "=", "2", "while", "i", "<", "n", "and", "string", "[", "i", "]", ".", "isalpha", "(", ")", ":", "i", "+=", "1", "name", "=", "string", "[", "1", ":", "i", "]", "node", ",", "skip", "=", "handle_keyword", "(", "name", ",", "node", ",", "string", "[", "i", ":", "]", ")", "skip", "+=", "i", "elif", "c2", "==", "'\\\\'", ":", "# End of a row:", "entry", "=", "mtd", "(", ")", "row", "=", "mtr", "(", "entry", ")", "node", ".", "close", "(", ")", ".", "close", "(", ")", ".", "append", "(", "row", ")", "node", "=", "entry", "skip", "=", "2", "else", ":", "raise", "SyntaxError", "(", "ur'Syntax error: \"%s%s\"'", "%", "(", "c", ",", "c2", ")", ")", "elif", "c", ".", "isalpha", "(", ")", ":", "node", "=", "node", ".", "append", "(", "mi", "(", "c", ")", ")", "elif", "c", ".", "isdigit", "(", ")", ":", "node", "=", "node", ".", "append", "(", "mn", "(", "c", ")", ")", "elif", "c", "in", "\"+-*/=()[]|<>,.!?':;@\"", ":", "node", "=", "node", ".", "append", "(", "mo", "(", "c", ")", ")", "elif", "c", "==", "'_'", ":", "child", "=", "node", ".", "delete_child", "(", ")", "if", "isinstance", "(", "child", ",", "msup", ")", ":", "sub", "=", "msubsup", "(", "child", ".", "children", ",", "reversed", "=", "True", ")", "elif", "isinstance", "(", "child", ",", "mo", ")", "and", "child", ".", "data", "in", "sumintprod", ":", "sub", "=", "munder", "(", "child", ")", "else", ":", "sub", "=", "msub", "(", "child", ")", "node", ".", "append", "(", "sub", ")", "node", "=", "sub", "elif", "c", "==", "'^'", ":", "child", "=", "node", ".", "delete_child", "(", ")", "if", "isinstance", "(", "child", ",", "msub", ")", ":", "sup", "=", "msubsup", "(", "child", ".", "children", ")", "elif", "isinstance", "(", "child", ",", "mo", ")", "and", "child", ".", "data", "in", "sumintprod", ":", "sup", "=", "mover", "(", "child", ")", "elif", "(", "isinstance", "(", "child", ",", "munder", ")", "and", "child", ".", "children", "[", "0", "]", ".", "data", "in", "sumintprod", ")", ":", "sup", "=", "munderover", "(", "child", ".", "children", ")", "else", ":", "sup", "=", "msup", "(", "child", ")", "node", ".", "append", "(", "sup", ")", "node", "=", "sup", "elif", "c", "==", "'{'", ":", "row", "=", "mrow", "(", ")", "node", ".", "append", "(", "row", ")", "node", "=", "row", "elif", "c", "==", "'}'", ":", "node", "=", "node", ".", "close", "(", ")", "elif", "c", "==", "'&'", ":", "entry", "=", "mtd", "(", ")", "node", ".", "close", "(", ")", ".", "append", "(", "entry", ")", "node", "=", "entry", "else", ":", "raise", "SyntaxError", "(", "ur'Illegal character: \"%s\"'", "%", "c", ")", "string", "=", "string", "[", "skip", ":", "]", "return", "tree" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/latex2mathml.py#L361-L459
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/graphviz/py2/graphviz/files.py
python
File.unflatten
(self, stagger=None, fanout=False, chain=None)
return Source(out, filename=self.filename, directory=self.directory, format=self._format, engine=self._engine, encoding=self._encoding)
Return a new :class:`.Source` instance with the source piped through the Graphviz *unflatten* preprocessor. Args: stagger (int): Stagger the minimum length of leaf edges between 1 and this small integer. fanout (bool): Fanout nodes with indegree = outdegree = 1 when staggering (requires ``stagger``). chain (int): Form disconnected nodes into chains of up to this many nodes. Returns: Source: Prepocessed DOT source code (improved layout aspect ratio). Raises: graphviz.RequiredArgumentError: If ``fanout`` is given but ``stagger`` is None. graphviz.ExecutableNotFound: If the Graphviz unflatten executable is not found. subprocess.CalledProcessError: If the exit status is non-zero. See also: https://www.graphviz.org/pdf/unflatten.1.pdf
Return a new :class:`.Source` instance with the source piped through the Graphviz *unflatten* preprocessor.
[ "Return", "a", "new", ":", "class", ":", ".", "Source", "instance", "with", "the", "source", "piped", "through", "the", "Graphviz", "*", "unflatten", "*", "preprocessor", "." ]
def unflatten(self, stagger=None, fanout=False, chain=None): """Return a new :class:`.Source` instance with the source piped through the Graphviz *unflatten* preprocessor. Args: stagger (int): Stagger the minimum length of leaf edges between 1 and this small integer. fanout (bool): Fanout nodes with indegree = outdegree = 1 when staggering (requires ``stagger``). chain (int): Form disconnected nodes into chains of up to this many nodes. Returns: Source: Prepocessed DOT source code (improved layout aspect ratio). Raises: graphviz.RequiredArgumentError: If ``fanout`` is given but ``stagger`` is None. graphviz.ExecutableNotFound: If the Graphviz unflatten executable is not found. subprocess.CalledProcessError: If the exit status is non-zero. See also: https://www.graphviz.org/pdf/unflatten.1.pdf """ out = backend.unflatten(self.source, stagger=stagger, fanout=fanout, chain=chain, encoding=self._encoding) return Source(out, filename=self.filename, directory=self.directory, format=self._format, engine=self._engine, encoding=self._encoding)
[ "def", "unflatten", "(", "self", ",", "stagger", "=", "None", ",", "fanout", "=", "False", ",", "chain", "=", "None", ")", ":", "out", "=", "backend", ".", "unflatten", "(", "self", ".", "source", ",", "stagger", "=", "stagger", ",", "fanout", "=", "fanout", ",", "chain", "=", "chain", ",", "encoding", "=", "self", ".", "_encoding", ")", "return", "Source", "(", "out", ",", "filename", "=", "self", ".", "filename", ",", "directory", "=", "self", ".", "directory", ",", "format", "=", "self", ".", "_format", ",", "engine", "=", "self", ".", "_engine", ",", "encoding", "=", "self", ".", "_encoding", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/graphviz/py2/graphviz/files.py#L116-L141
OAID/Caffe-HRT
aae71e498ab842c6f92bcc23fc668423615a4d65
scripts/cpp_lint.py
python
IsCppString
(line)
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant.
Does line terminate so, that the next symbol is in string constant.
[ "Does", "line", "terminate", "so", "that", "the", "next", "symbol", "is", "in", "string", "constant", "." ]
def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
[ "def", "IsCppString", "(", "line", ")", ":", "line", "=", "line", ".", "replace", "(", "r'\\\\'", ",", "'XX'", ")", "# after this, \\\\\" does not match to \\\"", "return", "(", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "r'\\\"'", ")", "-", "line", ".", "count", "(", "\"'\\\"'\"", ")", ")", "&", "1", ")", "==", "1" ]
https://github.com/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/scripts/cpp_lint.py#L1045-L1059
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/trade_bin.py
python
TradeBin.timestamp
(self, timestamp)
Sets the timestamp of this TradeBin. :param timestamp: The timestamp of this TradeBin. # noqa: E501 :type: datetime
Sets the timestamp of this TradeBin.
[ "Sets", "the", "timestamp", "of", "this", "TradeBin", "." ]
def timestamp(self, timestamp): """Sets the timestamp of this TradeBin. :param timestamp: The timestamp of this TradeBin. # noqa: E501 :type: datetime """ if timestamp is None: raise ValueError("Invalid value for `timestamp`, must not be `None`") # noqa: E501 self._timestamp = timestamp
[ "def", "timestamp", "(", "self", ",", "timestamp", ")", ":", "if", "timestamp", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `timestamp`, must not be `None`\"", ")", "# noqa: E501", "self", ".", "_timestamp", "=", "timestamp" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/trade_bin.py#L119-L129
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/etree/ElementTree.py
python
ProcessingInstruction
(target, text=None)
return element
Processing Instruction element factory. This function creates a special element which the standard serializer serializes as an XML comment. *target* is a string containing the processing instruction, *text* is a string containing the processing instruction contents, if any.
Processing Instruction element factory.
[ "Processing", "Instruction", "element", "factory", "." ]
def ProcessingInstruction(target, text=None): """Processing Instruction element factory. This function creates a special element which the standard serializer serializes as an XML comment. *target* is a string containing the processing instruction, *text* is a string containing the processing instruction contents, if any. """ element = Element(ProcessingInstruction) element.text = target if text: element.text = element.text + " " + text return element
[ "def", "ProcessingInstruction", "(", "target", ",", "text", "=", "None", ")", ":", "element", "=", "Element", "(", "ProcessingInstruction", ")", "element", ".", "text", "=", "target", "if", "text", ":", "element", ".", "text", "=", "element", ".", "text", "+", "\" \"", "+", "text", "return", "element" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/xml/etree/ElementTree.py#L476-L490
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/transforms.py
python
PassManagerBuilder.loop_vectorize
(self)
return ffi.lib.LLVMPY_PassManagerBuilderGetLoopVectorize(self)
If true, allow vectorizing loops.
If true, allow vectorizing loops.
[ "If", "true", "allow", "vectorizing", "loops", "." ]
def loop_vectorize(self): """ If true, allow vectorizing loops. """ return ffi.lib.LLVMPY_PassManagerBuilderGetLoopVectorize(self)
[ "def", "loop_vectorize", "(", "self", ")", ":", "return", "ffi", ".", "lib", ".", "LLVMPY_PassManagerBuilderGetLoopVectorize", "(", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/transforms.py#L65-L69
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/asyncio/protocols.py
python
BaseProtocol.connection_made
(self, transport)
Called when a connection is made. The argument is the transport representing the pipe connection. To receive data, wait for data_received() calls. When the connection is closed, connection_lost() is called.
Called when a connection is made.
[ "Called", "when", "a", "connection", "is", "made", "." ]
def connection_made(self, transport): """Called when a connection is made. The argument is the transport representing the pipe connection. To receive data, wait for data_received() calls. When the connection is closed, connection_lost() is called. """
[ "def", "connection_made", "(", "self", ",", "transport", ")", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/asyncio/protocols.py#L21-L27
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/tune/attr_tuner.py
python
ScaleSolver.solve_one
(self, tunable)
return False
Solve one step.
Solve one step.
[ "Solve", "one", "step", "." ]
def solve_one(self, tunable): """Solve one step.""" x, y, target = tunable.x, tunable.y, tunable.target if abs(y - target) <= self.tol: return True if y > 0: if self.correlation == 'positive': scale = (self.gamma + target) / (y + self.gamma) else: scale = (y + self.gamma) / (self.gamma + target) else: # y was zero. Try a value an order of magnitude smaller if self.correlation == 'positive': scale = 0.1 else: scale = 1.1 if (scale > self.max_scale): scale = self.max_scale # Ensures we stay within the tunable's domain (i.e. we don't take on # values to high or low). tunable.x = tunable.clamp_into_domain(scale * x) return False
[ "def", "solve_one", "(", "self", ",", "tunable", ")", ":", "x", ",", "y", ",", "target", "=", "tunable", ".", "x", ",", "tunable", ".", "y", ",", "tunable", ".", "target", "if", "abs", "(", "y", "-", "target", ")", "<=", "self", ".", "tol", ":", "return", "True", "if", "y", ">", "0", ":", "if", "self", ".", "correlation", "==", "'positive'", ":", "scale", "=", "(", "self", ".", "gamma", "+", "target", ")", "/", "(", "y", "+", "self", ".", "gamma", ")", "else", ":", "scale", "=", "(", "y", "+", "self", ".", "gamma", ")", "/", "(", "self", ".", "gamma", "+", "target", ")", "else", ":", "# y was zero. Try a value an order of magnitude smaller", "if", "self", ".", "correlation", "==", "'positive'", ":", "scale", "=", "0.1", "else", ":", "scale", "=", "1.1", "if", "(", "scale", ">", "self", ".", "max_scale", ")", ":", "scale", "=", "self", ".", "max_scale", "# Ensures we stay within the tunable's domain (i.e. we don't take on", "# values to high or low).", "tunable", ".", "x", "=", "tunable", ".", "clamp_into_domain", "(", "scale", "*", "x", ")", "return", "False" ]
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/tune/attr_tuner.py#L313-L336
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/webapp2/webapp2_extras/auth.py
python
AuthStore.get_session
(self, request)
return store.get_session(self.config['cookie_name'], backend=self.config['session_backend'])
Returns an auth session. :param request: A :class:`webapp2.Request` instance. :returns: A session dict.
Returns an auth session.
[ "Returns", "an", "auth", "session", "." ]
def get_session(self, request): """Returns an auth session. :param request: A :class:`webapp2.Request` instance. :returns: A session dict. """ store = sessions.get_store(request=request) return store.get_session(self.config['cookie_name'], backend=self.config['session_backend'])
[ "def", "get_session", "(", "self", ",", "request", ")", ":", "store", "=", "sessions", ".", "get_store", "(", "request", "=", "request", ")", "return", "store", ".", "get_session", "(", "self", ".", "config", "[", "'cookie_name'", "]", ",", "backend", "=", "self", ".", "config", "[", "'session_backend'", "]", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/webapp2/webapp2_extras/auth.py#L213-L223
KhronosGroup/SPIRV-LLVM
1eb85593f3fe2c39379b9a9b088d51eda4f42b8b
examples/Kaleidoscope/MCJIT/lazy/genk-timing.py
python
KScriptGenerator.setCallWeighting
(self, weight)
Sets the probably of generating a function call
Sets the probably of generating a function call
[ "Sets", "the", "probably", "of", "generating", "a", "function", "call" ]
def setCallWeighting(self, weight): """ Sets the probably of generating a function call""" self.callWeighting = weight
[ "def", "setCallWeighting", "(", "self", ",", "weight", ")", ":", "self", ".", "callWeighting", "=", "weight" ]
https://github.com/KhronosGroup/SPIRV-LLVM/blob/1eb85593f3fe2c39379b9a9b088d51eda4f42b8b/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py#L80-L82
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/dataview.py
python
DataViewChoiceRenderer.GetChoice
(*args, **kwargs)
return _dataview.DataViewChoiceRenderer_GetChoice(*args, **kwargs)
GetChoice(self, size_t index) -> String
GetChoice(self, size_t index) -> String
[ "GetChoice", "(", "self", "size_t", "index", ")", "-", ">", "String" ]
def GetChoice(*args, **kwargs): """GetChoice(self, size_t index) -> String""" return _dataview.DataViewChoiceRenderer_GetChoice(*args, **kwargs)
[ "def", "GetChoice", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewChoiceRenderer_GetChoice", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1394-L1396
yyzybb537/libgo
4af17b7c67643c4d54aa354dcc77963ea07847d0
third_party/boost.context/tools/build/src/build/type.py
python
reset
()
Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'.
Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'.
[ "Clear", "the", "module", "state", ".", "This", "is", "mainly", "for", "testing", "purposes", ".", "Note", "that", "this", "must", "be", "called", "_after_", "resetting", "the", "module", "feature", "." ]
def reset (): """ Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'. """ global __prefixes_suffixes, __suffixes_to_types, __types, __rule_names_to_types, __target_suffixes_cache __register_features () # Stores suffixes for generated targets. __prefixes_suffixes = [property.PropertyMap(), property.PropertyMap()] # Maps suffixes to types __suffixes_to_types = {} # A map with all the registered types, indexed by the type name # Each entry is a dictionary with following values: # 'base': the name of base type or None if type has no base # 'derived': a list of names of type which derive from this one # 'scanner': the scanner class registered for this type, if any __types = {} # Caches suffixes for targets with certain properties. __target_suffixes_cache = {}
[ "def", "reset", "(", ")", ":", "global", "__prefixes_suffixes", ",", "__suffixes_to_types", ",", "__types", ",", "__rule_names_to_types", ",", "__target_suffixes_cache", "__register_features", "(", ")", "# Stores suffixes for generated targets.", "__prefixes_suffixes", "=", "[", "property", ".", "PropertyMap", "(", ")", ",", "property", ".", "PropertyMap", "(", ")", "]", "# Maps suffixes to types", "__suffixes_to_types", "=", "{", "}", "# A map with all the registered types, indexed by the type name", "# Each entry is a dictionary with following values:", "# 'base': the name of base type or None if type has no base", "# 'derived': a list of names of type which derive from this one", "# 'scanner': the scanner class registered for this type, if any", "__types", "=", "{", "}", "# Caches suffixes for targets with certain properties.", "__target_suffixes_cache", "=", "{", "}" ]
https://github.com/yyzybb537/libgo/blob/4af17b7c67643c4d54aa354dcc77963ea07847d0/third_party/boost.context/tools/build/src/build/type.py#L32-L54
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/layers/utils.py
python
assert_same_structure
(nest1, nest2, check_types=True)
Confirm two nested structures with the same structure.
Confirm two nested structures with the same structure.
[ "Confirm", "two", "nested", "structures", "with", "the", "same", "structure", "." ]
def assert_same_structure(nest1, nest2, check_types=True): """ Confirm two nested structures with the same structure. """ len_nest1 = len(flatten(nest1)) if is_sequence(nest1) else 1 len_nest2 = len(flatten(nest2)) if is_sequence(nest2) else 1 if len_nest1 != len_nest2: raise ValueError("The two structures don't have the same number of " "elements.\n\nFirst structure (%i elements): %s\n\n" "Second structure (%i elements): %s" % (len_nest1, nest1, len_nest2, nest2)) _recursive_assert_same_structure(nest1, nest2, check_types)
[ "def", "assert_same_structure", "(", "nest1", ",", "nest2", ",", "check_types", "=", "True", ")", ":", "len_nest1", "=", "len", "(", "flatten", "(", "nest1", ")", ")", "if", "is_sequence", "(", "nest1", ")", "else", "1", "len_nest2", "=", "len", "(", "flatten", "(", "nest2", ")", ")", "if", "is_sequence", "(", "nest2", ")", "else", "1", "if", "len_nest1", "!=", "len_nest2", ":", "raise", "ValueError", "(", "\"The two structures don't have the same number of \"", "\"elements.\\n\\nFirst structure (%i elements): %s\\n\\n\"", "\"Second structure (%i elements): %s\"", "%", "(", "len_nest1", ",", "nest1", ",", "len_nest2", ",", "nest2", ")", ")", "_recursive_assert_same_structure", "(", "nest1", ",", "nest2", ",", "check_types", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/utils.py#L258-L269
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_PCR_Allocate_REQUEST.fromBytes
(buffer)
return TpmBuffer(buffer).createObj(TPM2_PCR_Allocate_REQUEST)
Returns new TPM2_PCR_Allocate_REQUEST object constructed from its marshaled representation in the given byte buffer
Returns new TPM2_PCR_Allocate_REQUEST object constructed from its marshaled representation in the given byte buffer
[ "Returns", "new", "TPM2_PCR_Allocate_REQUEST", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "byte", "buffer" ]
def fromBytes(buffer): """ Returns new TPM2_PCR_Allocate_REQUEST object constructed from its marshaled representation in the given byte buffer """ return TpmBuffer(buffer).createObj(TPM2_PCR_Allocate_REQUEST)
[ "def", "fromBytes", "(", "buffer", ")", ":", "return", "TpmBuffer", "(", "buffer", ")", ".", "createObj", "(", "TPM2_PCR_Allocate_REQUEST", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L13921-L13925
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/libmintsgshell.py
python
ShellInfo.ncartesian
(self)
return self.PYncartesian
Return the total number of functions if this shell was Cartesian
Return the total number of functions if this shell was Cartesian
[ "Return", "the", "total", "number", "of", "functions", "if", "this", "shell", "was", "Cartesian" ]
def ncartesian(self): """Return the total number of functions if this shell was Cartesian""" return self.PYncartesian
[ "def", "ncartesian", "(", "self", ")", ":", "return", "self", ".", "PYncartesian" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintsgshell.py#L274-L276
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/crypto.py
python
X509.to_cryptography
(self)
return _Certificate(backend, self._x509)
Export as a ``cryptography`` certificate. :rtype: ``cryptography.x509.Certificate`` .. versionadded:: 17.1.0
Export as a ``cryptography`` certificate.
[ "Export", "as", "a", "cryptography", "certificate", "." ]
def to_cryptography(self): """ Export as a ``cryptography`` certificate. :rtype: ``cryptography.x509.Certificate`` .. versionadded:: 17.1.0 """ from cryptography.hazmat.backends.openssl.x509 import _Certificate backend = _get_backend() return _Certificate(backend, self._x509)
[ "def", "to_cryptography", "(", "self", ")", ":", "from", "cryptography", ".", "hazmat", ".", "backends", ".", "openssl", ".", "x509", "import", "_Certificate", "backend", "=", "_get_backend", "(", ")", "return", "_Certificate", "(", "backend", ",", "self", ".", "_x509", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/crypto.py#L1071-L1081
HKUST-Aerial-Robotics/Fast-Planner
2ddd7793eecd573dbb5b47e2c985aa06606df3cf
uav_simulator/Utils/multi_map_server/quadrotor_msgs/build/catkin_generated/installspace/_setup_util.py
python
prepend_env_variables
(environ, env_var_subfolders, workspaces)
return lines
Generate shell code to prepend environment variables for the all workspaces.
Generate shell code to prepend environment variables for the all workspaces.
[ "Generate", "shell", "code", "to", "prepend", "environment", "variables", "for", "the", "all", "workspaces", "." ]
def prepend_env_variables(environ, env_var_subfolders, workspaces): ''' Generate shell code to prepend environment variables for the all workspaces. ''' lines = [] lines.append(comment('prepend folders of workspaces to environment variables')) paths = [path for path in workspaces.split(os.pathsep) if path] prefix = _prefix_env_variable(environ, 'CMAKE_PREFIX_PATH', paths, '') lines.append(prepend(environ, 'CMAKE_PREFIX_PATH', prefix)) for key in sorted([key for key in env_var_subfolders.keys() if key != 'CMAKE_PREFIX_PATH']): subfolder = env_var_subfolders[key] prefix = _prefix_env_variable(environ, key, paths, subfolder) lines.append(prepend(environ, key, prefix)) return lines
[ "def", "prepend_env_variables", "(", "environ", ",", "env_var_subfolders", ",", "workspaces", ")", ":", "lines", "=", "[", "]", "lines", ".", "append", "(", "comment", "(", "'prepend folders of workspaces to environment variables'", ")", ")", "paths", "=", "[", "path", "for", "path", "in", "workspaces", ".", "split", "(", "os", ".", "pathsep", ")", "if", "path", "]", "prefix", "=", "_prefix_env_variable", "(", "environ", ",", "'CMAKE_PREFIX_PATH'", ",", "paths", ",", "''", ")", "lines", ".", "append", "(", "prepend", "(", "environ", ",", "'CMAKE_PREFIX_PATH'", ",", "prefix", ")", ")", "for", "key", "in", "sorted", "(", "[", "key", "for", "key", "in", "env_var_subfolders", ".", "keys", "(", ")", "if", "key", "!=", "'CMAKE_PREFIX_PATH'", "]", ")", ":", "subfolder", "=", "env_var_subfolders", "[", "key", "]", "prefix", "=", "_prefix_env_variable", "(", "environ", ",", "key", ",", "paths", ",", "subfolder", ")", "lines", ".", "append", "(", "prepend", "(", "environ", ",", "key", ",", "prefix", ")", ")", "return", "lines" ]
https://github.com/HKUST-Aerial-Robotics/Fast-Planner/blob/2ddd7793eecd573dbb5b47e2c985aa06606df3cf/uav_simulator/Utils/multi_map_server/quadrotor_msgs/build/catkin_generated/installspace/_setup_util.py#L129-L146
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/ma/mrecords.py
python
_guessvartypes
(arr)
return vartypes
Tries to guess the dtypes of the str_ ndarray `arr`. Guesses by testing element-wise conversion. Returns a list of dtypes. The array is first converted to ndarray. If the array is 2D, the test is performed on the first line. An exception is raised if the file is 3D or more.
Tries to guess the dtypes of the str_ ndarray `arr`.
[ "Tries", "to", "guess", "the", "dtypes", "of", "the", "str_", "ndarray", "arr", "." ]
def _guessvartypes(arr): """ Tries to guess the dtypes of the str_ ndarray `arr`. Guesses by testing element-wise conversion. Returns a list of dtypes. The array is first converted to ndarray. If the array is 2D, the test is performed on the first line. An exception is raised if the file is 3D or more. """ vartypes = [] arr = np.asarray(arr) if arr.ndim == 2: arr = arr[0] elif arr.ndim > 2: raise ValueError("The array should be 2D at most!") # Start the conversion loop. for f in arr: try: int(f) except (ValueError, TypeError): try: float(f) except (ValueError, TypeError): try: complex(f) except (ValueError, TypeError): vartypes.append(arr.dtype) else: vartypes.append(np.dtype(complex)) else: vartypes.append(np.dtype(float)) else: vartypes.append(np.dtype(int)) return vartypes
[ "def", "_guessvartypes", "(", "arr", ")", ":", "vartypes", "=", "[", "]", "arr", "=", "np", ".", "asarray", "(", "arr", ")", "if", "arr", ".", "ndim", "==", "2", ":", "arr", "=", "arr", "[", "0", "]", "elif", "arr", ".", "ndim", ">", "2", ":", "raise", "ValueError", "(", "\"The array should be 2D at most!\"", ")", "# Start the conversion loop.", "for", "f", "in", "arr", ":", "try", ":", "int", "(", "f", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "try", ":", "float", "(", "f", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "try", ":", "complex", "(", "f", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "vartypes", ".", "append", "(", "arr", ".", "dtype", ")", "else", ":", "vartypes", ".", "append", "(", "np", ".", "dtype", "(", "complex", ")", ")", "else", ":", "vartypes", ".", "append", "(", "np", ".", "dtype", "(", "float", ")", ")", "else", ":", "vartypes", ".", "append", "(", "np", ".", "dtype", "(", "int", ")", ")", "return", "vartypes" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/ma/mrecords.py#L615-L649
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
xmlDoc.htmlSaveFile
(self, filename)
return ret
Dump an HTML document to a file. If @filename is "-" the stdout file is used.
Dump an HTML document to a file. If
[ "Dump", "an", "HTML", "document", "to", "a", "file", ".", "If" ]
def htmlSaveFile(self, filename): """Dump an HTML document to a file. If @filename is "-" the stdout file is used. """ ret = libxml2mod.htmlSaveFile(filename, self._o) return ret
[ "def", "htmlSaveFile", "(", "self", ",", "filename", ")", ":", "ret", "=", "libxml2mod", ".", "htmlSaveFile", "(", "filename", ",", "self", ".", "_o", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L3263-L3267
qbittorrent/qBittorrent
78eaa49cd6b3b59c064cd461fe6d30eceaeac770
src/searchengine/nova3/nova2.py
python
displayCapabilities
(supported_engines)
Display capabilities in XML format <capabilities> <engine_short_name> <name>long name</name> <url>http://example.com</url> <categories>movies music games</categories> </engine_short_name> </capabilities>
Display capabilities in XML format <capabilities> <engine_short_name> <name>long name</name> <url>http://example.com</url> <categories>movies music games</categories> </engine_short_name> </capabilities>
[ "Display", "capabilities", "in", "XML", "format", "<capabilities", ">", "<engine_short_name", ">", "<name", ">", "long", "name<", "/", "name", ">", "<url", ">", "http", ":", "//", "example", ".", "com<", "/", "url", ">", "<categories", ">", "movies", "music", "games<", "/", "categories", ">", "<", "/", "engine_short_name", ">", "<", "/", "capabilities", ">" ]
def displayCapabilities(supported_engines): """ Display capabilities in XML format <capabilities> <engine_short_name> <name>long name</name> <url>http://example.com</url> <categories>movies music games</categories> </engine_short_name> </capabilities> """ xml = "".join(("<capabilities>\n", "".join(engines_to_xml(supported_engines)), "</capabilities>")) print(xml)
[ "def", "displayCapabilities", "(", "supported_engines", ")", ":", "xml", "=", "\"\"", ".", "join", "(", "(", "\"<capabilities>\\n\"", ",", "\"\"", ".", "join", "(", "engines_to_xml", "(", "supported_engines", ")", ")", ",", "\"</capabilities>\"", ")", ")", "print", "(", "xml", ")" ]
https://github.com/qbittorrent/qBittorrent/blob/78eaa49cd6b3b59c064cd461fe6d30eceaeac770/src/searchengine/nova3/nova2.py#L105-L119
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/calendar.py
python
Calendar.yeardatescalendar
(self, year, width=3)
return [months[i:i+width] for i in range(0, len(months), width) ]
Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains upto width months. Each month contains between 4 and 6 weeks and each week contains 1-7 days. Days are datetime.date objects.
Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains upto width months. Each month contains between 4 and 6 weeks and each week contains 1-7 days. Days are datetime.date objects.
[ "Return", "the", "data", "for", "the", "specified", "year", "ready", "for", "formatting", ".", "The", "return", "value", "is", "a", "list", "of", "month", "rows", ".", "Each", "month", "row", "contains", "upto", "width", "months", ".", "Each", "month", "contains", "between", "4", "and", "6", "weeks", "and", "each", "week", "contains", "1", "-", "7", "days", ".", "Days", "are", "datetime", ".", "date", "objects", "." ]
def yeardatescalendar(self, year, width=3): """ Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains upto width months. Each month contains between 4 and 6 weeks and each week contains 1-7 days. Days are datetime.date objects. """ months = [ self.monthdatescalendar(year, i) for i in range(January, January+12) ] return [months[i:i+width] for i in range(0, len(months), width) ]
[ "def", "yeardatescalendar", "(", "self", ",", "year", ",", "width", "=", "3", ")", ":", "months", "=", "[", "self", ".", "monthdatescalendar", "(", "year", ",", "i", ")", "for", "i", "in", "range", "(", "January", ",", "January", "+", "12", ")", "]", "return", "[", "months", "[", "i", ":", "i", "+", "width", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "months", ")", ",", "width", ")", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/calendar.py#L220-L231
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Validation/RecoTrack/python/plotting/ntupleDataFormat.py
python
BeamSpot.__init__
(self, tree)
Constructor. Arguments: tree -- TTree object
Constructor.
[ "Constructor", "." ]
def __init__(self, tree): """Constructor. Arguments: tree -- TTree object """ super(BeamSpot, self).__init__() self._tree = tree self._prefix = "bsp"
[ "def", "__init__", "(", "self", ",", "tree", ")", ":", "super", "(", "BeamSpot", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "_tree", "=", "tree", "self", ".", "_prefix", "=", "\"bsp\"" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTrack/python/plotting/ntupleDataFormat.py#L529-L537
echronos/echronos
c996f1d2c8af6c6536205eb319c1bf1d4d84569c
external_tools/ply_info/example/BASIC/basparse.py
python
p_program
(p)
program : program statement | statement
program : program statement | statement
[ "program", ":", "program", "statement", "|", "statement" ]
def p_program(p): '''program : program statement | statement''' if len(p) == 2 and p[1]: p[0] = { } line,stat = p[1] p[0][line] = stat elif len(p) ==3: p[0] = p[1] if not p[0]: p[0] = { } if p[2]: line,stat = p[2] p[0][line] = stat
[ "def", "p_program", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", "and", "p", "[", "1", "]", ":", "p", "[", "0", "]", "=", "{", "}", "line", ",", "stat", "=", "p", "[", "1", "]", "p", "[", "0", "]", "[", "line", "]", "=", "stat", "elif", "len", "(", "p", ")", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "if", "not", "p", "[", "0", "]", ":", "p", "[", "0", "]", "=", "{", "}", "if", "p", "[", "2", "]", ":", "line", ",", "stat", "=", "p", "[", "2", "]", "p", "[", "0", "]", "[", "line", "]", "=", "stat" ]
https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/BASIC/basparse.py#L19-L32
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
getboolean
(s)
return _default_root.tk.getboolean(s)
Convert true and false to integer values 1 and 0.
Convert true and false to integer values 1 and 0.
[ "Convert", "true", "and", "false", "to", "integer", "values", "1", "and", "0", "." ]
def getboolean(s): """Convert true and false to integer values 1 and 0.""" return _default_root.tk.getboolean(s)
[ "def", "getboolean", "(", "s", ")", ":", "return", "_default_root", ".", "tk", ".", "getboolean", "(", "s", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib-tk/Tkinter.py#L367-L369
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pymcuprog/avr8target.py
python
TinyXAvrTarget.sib_read
(self)
return self.protocol.memory_read(Avr8Protocol.AVR8_MEMTYPE_SIB, 0, 32)
Reads the System Information Block :return: SIB bytes
Reads the System Information Block
[ "Reads", "the", "System", "Information", "Block" ]
def sib_read(self): """ Reads the System Information Block :return: SIB bytes """ return self.protocol.memory_read(Avr8Protocol.AVR8_MEMTYPE_SIB, 0, 32)
[ "def", "sib_read", "(", "self", ")", ":", "return", "self", ".", "protocol", ".", "memory_read", "(", "Avr8Protocol", ".", "AVR8_MEMTYPE_SIB", ",", "0", ",", "32", ")" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/avr8target.py#L206-L212
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
HardSigmoid.__init__
(self, alpha=0.2, gamma=0.5)
Args: alpha (float): Value of alpha. gamma (float): Value of beta.
Args: alpha (float): Value of alpha. gamma (float): Value of beta.
[ "Args", ":", "alpha", "(", "float", ")", ":", "Value", "of", "alpha", ".", "gamma", "(", "float", ")", ":", "Value", "of", "beta", "." ]
def __init__(self, alpha=0.2, gamma=0.5): """ Args: alpha (float): Value of alpha. gamma (float): Value of beta. """ super(HardSigmoid, self).__init__() self.alpha = alpha self.gamma = gamma
[ "def", "__init__", "(", "self", ",", "alpha", "=", "0.2", ",", "gamma", "=", "0.5", ")", ":", "super", "(", "HardSigmoid", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "alpha", "=", "alpha", "self", ".", "gamma", "=", "gamma" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L3172-L3180
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/optimizer/optimizer.py
python
Optimizer._get_lr
(self, index)
return self._get_lrs([index])[0]
Gets the learning rate given the index of the weight. Parameters ---------- index : int The index corresponding to the weight. Returns ------- lr : float Learning rate for this index.
Gets the learning rate given the index of the weight.
[ "Gets", "the", "learning", "rate", "given", "the", "index", "of", "the", "weight", "." ]
def _get_lr(self, index): """Gets the learning rate given the index of the weight. Parameters ---------- index : int The index corresponding to the weight. Returns ------- lr : float Learning rate for this index. """ return self._get_lrs([index])[0]
[ "def", "_get_lr", "(", "self", ",", "index", ")", ":", "return", "self", ".", "_get_lrs", "(", "[", "index", "]", ")", "[", "0", "]" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/optimizer/optimizer.py#L495-L508
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/model/trajectory.py
python
SO3Trajectory.getPointTrajectory
(self,localPt)
return Trajectory(self.times,[so3.apply(m,localPt) for m in self.milestones])
Returns a Trajectory describing the movement of the point localPt attached to this rotating frame.
Returns a Trajectory describing the movement of the point localPt attached to this rotating frame.
[ "Returns", "a", "Trajectory", "describing", "the", "movement", "of", "the", "point", "localPt", "attached", "to", "this", "rotating", "frame", "." ]
def getPointTrajectory(self,localPt): """Returns a Trajectory describing the movement of the point localPt attached to this rotating frame. """ return Trajectory(self.times,[so3.apply(m,localPt) for m in self.milestones])
[ "def", "getPointTrajectory", "(", "self", ",", "localPt", ")", ":", "return", "Trajectory", "(", "self", ".", "times", ",", "[", "so3", ".", "apply", "(", "m", ",", "localPt", ")", "for", "m", "in", "self", ".", "milestones", "]", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/model/trajectory.py#L658-L661
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/graph_editor/reroute.py
python
swap_inputs
(sgv0, sgv1)
return _reroute_sgv_inputs(sgv0, sgv1, _RerouteMode.swap)
Swap all the inputs of sgv0 and sgv1 (see reroute_inputs).
Swap all the inputs of sgv0 and sgv1 (see reroute_inputs).
[ "Swap", "all", "the", "inputs", "of", "sgv0", "and", "sgv1", "(", "see", "reroute_inputs", ")", "." ]
def swap_inputs(sgv0, sgv1): """Swap all the inputs of sgv0 and sgv1 (see reroute_inputs).""" return _reroute_sgv_inputs(sgv0, sgv1, _RerouteMode.swap)
[ "def", "swap_inputs", "(", "sgv0", ",", "sgv1", ")", ":", "return", "_reroute_sgv_inputs", "(", "sgv0", ",", "sgv1", ",", "_RerouteMode", ".", "swap", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/graph_editor/reroute.py#L398-L400
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
Function.WriteCmdComputeSize
(self, file)
Writes the ComputeSize function for the command.
Writes the ComputeSize function for the command.
[ "Writes", "the", "ComputeSize", "function", "for", "the", "command", "." ]
def WriteCmdComputeSize(self, file): """Writes the ComputeSize function for the command.""" file.Write(" static uint32 ComputeSize() {\n") file.Write( " return static_cast<uint32>(sizeof(ValueType)); // NOLINT\n") file.Write(" }\n") file.Write("\n")
[ "def", "WriteCmdComputeSize", "(", "self", ",", "file", ")", ":", "file", ".", "Write", "(", "\" static uint32 ComputeSize() {\\n\"", ")", "file", ".", "Write", "(", "\" return static_cast<uint32>(sizeof(ValueType)); // NOLINT\\n\"", ")", "file", ".", "Write", "(", "\" }\\n\"", ")", "file", ".", "Write", "(", "\"\\n\"", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L5280-L5286
twhui/LiteFlowNet
00925aebf2db9ac50f4b1666f718688b10dd10d1
scripts/cpp_lint.py
python
_FunctionState.End
(self)
Stop analyzing function body.
Stop analyzing function body.
[ "Stop", "analyzing", "function", "body", "." ]
def End(self): """Stop analyzing function body.""" self.in_a_function = False
[ "def", "End", "(", "self", ")", ":", "self", ".", "in_a_function", "=", "False" ]
https://github.com/twhui/LiteFlowNet/blob/00925aebf2db9ac50f4b1666f718688b10dd10d1/scripts/cpp_lint.py#L861-L863
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/sans/algorithm_detail/calculate_transmission_helper.py
python
apply_flat_background_correction_to_detectors
(workspace, flat_background_correction_start, flat_background_correction_stop)
return workspace
Applies the flat background correction to all detectors which are not monitors :param workspace: the workspace which contains detector spectra which will be corrected. :param flat_background_correction_start: the start of the flat background region :param flat_background_correction_stop: the end of the flat background region :return: a corrected workspace
Applies the flat background correction to all detectors which are not monitors
[ "Applies", "the", "flat", "background", "correction", "to", "all", "detectors", "which", "are", "not", "monitors" ]
def apply_flat_background_correction_to_detectors(workspace, flat_background_correction_start, flat_background_correction_stop): """ Applies the flat background correction to all detectors which are not monitors :param workspace: the workspace which contains detector spectra which will be corrected. :param flat_background_correction_start: the start of the flat background region :param flat_background_correction_stop: the end of the flat background region :return: a corrected workspace """ if flat_background_correction_start is not None and flat_background_correction_stop is not None: flat_name = "CalculateFlatBackground" flat_options = {"InputWorkspace": workspace, "Mode": "Mean", "StartX": flat_background_correction_start, "EndX": flat_background_correction_stop, "SkipMonitors": True} flat_alg = create_unmanaged_algorithm(flat_name, **flat_options) flat_alg.setPropertyValue("OutputWorkspace", EMPTY_NAME) flat_alg.setProperty("OutputWorkspace", workspace) flat_alg.execute() workspace = flat_alg.getProperty("OutputWorkspace").value return workspace
[ "def", "apply_flat_background_correction_to_detectors", "(", "workspace", ",", "flat_background_correction_start", ",", "flat_background_correction_stop", ")", ":", "if", "flat_background_correction_start", "is", "not", "None", "and", "flat_background_correction_stop", "is", "not", "None", ":", "flat_name", "=", "\"CalculateFlatBackground\"", "flat_options", "=", "{", "\"InputWorkspace\"", ":", "workspace", ",", "\"Mode\"", ":", "\"Mean\"", ",", "\"StartX\"", ":", "flat_background_correction_start", ",", "\"EndX\"", ":", "flat_background_correction_stop", ",", "\"SkipMonitors\"", ":", "True", "}", "flat_alg", "=", "create_unmanaged_algorithm", "(", "flat_name", ",", "*", "*", "flat_options", ")", "flat_alg", ".", "setPropertyValue", "(", "\"OutputWorkspace\"", ",", "EMPTY_NAME", ")", "flat_alg", ".", "setProperty", "(", "\"OutputWorkspace\"", ",", "workspace", ")", "flat_alg", ".", "execute", "(", ")", "workspace", "=", "flat_alg", ".", "getProperty", "(", "\"OutputWorkspace\"", ")", ".", "value", "return", "workspace" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/algorithm_detail/calculate_transmission_helper.py#L12-L34
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/bullet/minitaur_duck_gym_env.py
python
MinitaurBulletDuckEnv.__init__
( self, urdf_root=pybullet_data.getDataPath(), action_repeat=1, distance_weight=1.0, energy_weight=0.005, shake_weight=0.0, drift_weight=0.0, distance_limit=float("inf"), observation_noise_stdev=0.0, self_collision_enabled=True, motor_velocity_limit=np.inf, pd_control_enabled=False, #not needed to be true if accurate motor model is enabled (has its own better PD) leg_model_enabled=True, accurate_motor_model_enabled=True, motor_kp=1.0, motor_kd=0.02, torque_control_enabled=False, motor_overheat_protection=True, hard_reset=True, on_rack=False, render=False, kd_for_pd_controllers=0.3, env_randomizer=minitaur_env_randomizer.MinitaurEnvRandomizer())
Initialize the minitaur gym environment. Args: urdf_root: The path to the urdf data folder. action_repeat: The number of simulation steps before actions are applied. distance_weight: The weight of the distance term in the reward. energy_weight: The weight of the energy term in the reward. shake_weight: The weight of the vertical shakiness term in the reward. drift_weight: The weight of the sideways drift term in the reward. distance_limit: The maximum distance to terminate the episode. observation_noise_stdev: The standard deviation of observation noise. self_collision_enabled: Whether to enable self collision in the sim. motor_velocity_limit: The velocity limit of each motor. pd_control_enabled: Whether to use PD controller for each motor. leg_model_enabled: Whether to use a leg motor to reparameterize the action space. accurate_motor_model_enabled: Whether to use the accurate DC motor model. motor_kp: proportional gain for the accurate motor model. motor_kd: derivative gain for the accurate motor model. torque_control_enabled: Whether to use the torque control, if set to False, pose control will be used. motor_overheat_protection: Whether to shutdown the motor that has exerted large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time (OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in minitaur.py for more details. hard_reset: Whether to wipe the simulation and load everything when reset is called. If set to false, reset just place the minitaur back to start position and set its pose to initial configuration. on_rack: Whether to place the minitaur on rack. This is only used to debug the walking gait. In this mode, the minitaur's base is hanged midair so that its walking gait is clearer to visualize. render: Whether to render the simulation. kd_for_pd_controllers: kd value for the pd controllers of the motors env_randomizer: An EnvRandomizer to randomize the physical properties during reset().
Initialize the minitaur gym environment.
[ "Initialize", "the", "minitaur", "gym", "environment", "." ]
def __init__( self, urdf_root=pybullet_data.getDataPath(), action_repeat=1, distance_weight=1.0, energy_weight=0.005, shake_weight=0.0, drift_weight=0.0, distance_limit=float("inf"), observation_noise_stdev=0.0, self_collision_enabled=True, motor_velocity_limit=np.inf, pd_control_enabled=False, #not needed to be true if accurate motor model is enabled (has its own better PD) leg_model_enabled=True, accurate_motor_model_enabled=True, motor_kp=1.0, motor_kd=0.02, torque_control_enabled=False, motor_overheat_protection=True, hard_reset=True, on_rack=False, render=False, kd_for_pd_controllers=0.3, env_randomizer=minitaur_env_randomizer.MinitaurEnvRandomizer()): """Initialize the minitaur gym environment. Args: urdf_root: The path to the urdf data folder. action_repeat: The number of simulation steps before actions are applied. distance_weight: The weight of the distance term in the reward. energy_weight: The weight of the energy term in the reward. shake_weight: The weight of the vertical shakiness term in the reward. drift_weight: The weight of the sideways drift term in the reward. distance_limit: The maximum distance to terminate the episode. observation_noise_stdev: The standard deviation of observation noise. self_collision_enabled: Whether to enable self collision in the sim. motor_velocity_limit: The velocity limit of each motor. pd_control_enabled: Whether to use PD controller for each motor. leg_model_enabled: Whether to use a leg motor to reparameterize the action space. accurate_motor_model_enabled: Whether to use the accurate DC motor model. motor_kp: proportional gain for the accurate motor model. motor_kd: derivative gain for the accurate motor model. torque_control_enabled: Whether to use the torque control, if set to False, pose control will be used. motor_overheat_protection: Whether to shutdown the motor that has exerted large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time (OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in minitaur.py for more details. hard_reset: Whether to wipe the simulation and load everything when reset is called. If set to false, reset just place the minitaur back to start position and set its pose to initial configuration. on_rack: Whether to place the minitaur on rack. This is only used to debug the walking gait. In this mode, the minitaur's base is hanged midair so that its walking gait is clearer to visualize. render: Whether to render the simulation. kd_for_pd_controllers: kd value for the pd controllers of the motors env_randomizer: An EnvRandomizer to randomize the physical properties during reset(). """ self._time_step = 0.01 self._action_repeat = action_repeat self._num_bullet_solver_iterations = 300 self._urdf_root = urdf_root self._self_collision_enabled = self_collision_enabled self._motor_velocity_limit = motor_velocity_limit self._observation = [] self._env_step_counter = 0 self._is_render = render self._last_base_position = [0, 0, 0] self._distance_weight = distance_weight self._energy_weight = energy_weight self._drift_weight = drift_weight self._shake_weight = shake_weight self._distance_limit = distance_limit self._observation_noise_stdev = observation_noise_stdev self._action_bound = 1 self._pd_control_enabled = pd_control_enabled self._leg_model_enabled = leg_model_enabled self._accurate_motor_model_enabled = accurate_motor_model_enabled self._motor_kp = motor_kp self._motor_kd = motor_kd self._torque_control_enabled = torque_control_enabled self._motor_overheat_protection = motor_overheat_protection self._on_rack = on_rack self._cam_dist = 1.0 self._cam_yaw = 0 self._duckId = -1 self._cam_pitch = -30 self._hard_reset = True self._kd_for_pd_controllers = kd_for_pd_controllers self._last_frame_time = 0.0 print("urdf_root=" + self._urdf_root) self._env_randomizer = env_randomizer # PD control needs smaller time step for stability. if pd_control_enabled or accurate_motor_model_enabled: self._time_step /= NUM_SUBSTEPS self._num_bullet_solver_iterations /= NUM_SUBSTEPS self._action_repeat *= NUM_SUBSTEPS if self._is_render: self._pybullet_client = bc.BulletClient(connection_mode=pybullet.GUI) else: self._pybullet_client = bc.BulletClient() self.seed() self.reset() observation_high = (self.minitaur.GetObservationUpperBound() + OBSERVATION_EPS) observation_low = (self.minitaur.GetObservationLowerBound() - OBSERVATION_EPS) action_dim = 8 action_high = np.array([self._action_bound] * action_dim) self.action_space = spaces.Box(-action_high, action_high, dtype=np.float32) self.observation_space = spaces.Box(observation_low, observation_high, dtype=np.float32) self.viewer = None self._hard_reset = hard_reset
[ "def", "__init__", "(", "self", ",", "urdf_root", "=", "pybullet_data", ".", "getDataPath", "(", ")", ",", "action_repeat", "=", "1", ",", "distance_weight", "=", "1.0", ",", "energy_weight", "=", "0.005", ",", "shake_weight", "=", "0.0", ",", "drift_weight", "=", "0.0", ",", "distance_limit", "=", "float", "(", "\"inf\"", ")", ",", "observation_noise_stdev", "=", "0.0", ",", "self_collision_enabled", "=", "True", ",", "motor_velocity_limit", "=", "np", ".", "inf", ",", "pd_control_enabled", "=", "False", ",", "#not needed to be true if accurate motor model is enabled (has its own better PD)", "leg_model_enabled", "=", "True", ",", "accurate_motor_model_enabled", "=", "True", ",", "motor_kp", "=", "1.0", ",", "motor_kd", "=", "0.02", ",", "torque_control_enabled", "=", "False", ",", "motor_overheat_protection", "=", "True", ",", "hard_reset", "=", "True", ",", "on_rack", "=", "False", ",", "render", "=", "False", ",", "kd_for_pd_controllers", "=", "0.3", ",", "env_randomizer", "=", "minitaur_env_randomizer", ".", "MinitaurEnvRandomizer", "(", ")", ")", ":", "self", ".", "_time_step", "=", "0.01", "self", ".", "_action_repeat", "=", "action_repeat", "self", ".", "_num_bullet_solver_iterations", "=", "300", "self", ".", "_urdf_root", "=", "urdf_root", "self", ".", "_self_collision_enabled", "=", "self_collision_enabled", "self", ".", "_motor_velocity_limit", "=", "motor_velocity_limit", "self", ".", "_observation", "=", "[", "]", "self", ".", "_env_step_counter", "=", "0", "self", ".", "_is_render", "=", "render", "self", ".", "_last_base_position", "=", "[", "0", ",", "0", ",", "0", "]", "self", ".", "_distance_weight", "=", "distance_weight", "self", ".", "_energy_weight", "=", "energy_weight", "self", ".", "_drift_weight", "=", "drift_weight", "self", ".", "_shake_weight", "=", "shake_weight", "self", ".", "_distance_limit", "=", "distance_limit", "self", ".", "_observation_noise_stdev", "=", "observation_noise_stdev", "self", ".", "_action_bound", "=", "1", "self", ".", "_pd_control_enabled", "=", "pd_control_enabled", "self", ".", "_leg_model_enabled", "=", "leg_model_enabled", "self", ".", "_accurate_motor_model_enabled", "=", "accurate_motor_model_enabled", "self", ".", "_motor_kp", "=", "motor_kp", "self", ".", "_motor_kd", "=", "motor_kd", "self", ".", "_torque_control_enabled", "=", "torque_control_enabled", "self", ".", "_motor_overheat_protection", "=", "motor_overheat_protection", "self", ".", "_on_rack", "=", "on_rack", "self", ".", "_cam_dist", "=", "1.0", "self", ".", "_cam_yaw", "=", "0", "self", ".", "_duckId", "=", "-", "1", "self", ".", "_cam_pitch", "=", "-", "30", "self", ".", "_hard_reset", "=", "True", "self", ".", "_kd_for_pd_controllers", "=", "kd_for_pd_controllers", "self", ".", "_last_frame_time", "=", "0.0", "print", "(", "\"urdf_root=\"", "+", "self", ".", "_urdf_root", ")", "self", ".", "_env_randomizer", "=", "env_randomizer", "# PD control needs smaller time step for stability.", "if", "pd_control_enabled", "or", "accurate_motor_model_enabled", ":", "self", ".", "_time_step", "/=", "NUM_SUBSTEPS", "self", ".", "_num_bullet_solver_iterations", "/=", "NUM_SUBSTEPS", "self", ".", "_action_repeat", "*=", "NUM_SUBSTEPS", "if", "self", ".", "_is_render", ":", "self", ".", "_pybullet_client", "=", "bc", ".", "BulletClient", "(", "connection_mode", "=", "pybullet", ".", "GUI", ")", "else", ":", "self", ".", "_pybullet_client", "=", "bc", ".", "BulletClient", "(", ")", "self", ".", "seed", "(", ")", "self", ".", "reset", "(", ")", "observation_high", "=", "(", "self", ".", "minitaur", ".", "GetObservationUpperBound", "(", ")", "+", "OBSERVATION_EPS", ")", "observation_low", "=", "(", "self", ".", "minitaur", ".", "GetObservationLowerBound", "(", ")", "-", "OBSERVATION_EPS", ")", "action_dim", "=", "8", "action_high", "=", "np", ".", "array", "(", "[", "self", ".", "_action_bound", "]", "*", "action_dim", ")", "self", ".", "action_space", "=", "spaces", ".", "Box", "(", "-", "action_high", ",", "action_high", ",", "dtype", "=", "np", ".", "float32", ")", "self", ".", "observation_space", "=", "spaces", ".", "Box", "(", "observation_low", ",", "observation_high", ",", "dtype", "=", "np", ".", "float32", ")", "self", ".", "viewer", "=", "None", "self", ".", "_hard_reset", "=", "hard_reset" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/bullet/minitaur_duck_gym_env.py#L52-L166
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/cmd.py
python
Command.set_undefined_options
(self, src_cmd, *option_pairs)
Set the values of any "undefined" options from corresponding option values in some other command object. "Undefined" here means "is None", which is the convention used to indicate that an option has not been changed between 'initialize_options()' and 'finalize_options()'. Usually called from 'finalize_options()' for options that depend on some other command rather than another option of the same command. 'src_cmd' is the other command from which option values will be taken (a command object will be created for it if necessary); the remaining arguments are '(src_option,dst_option)' tuples which mean "take the value of 'src_option' in the 'src_cmd' command object, and copy it to 'dst_option' in the current command object".
Set the values of any "undefined" options from corresponding option values in some other command object. "Undefined" here means "is None", which is the convention used to indicate that an option has not been changed between 'initialize_options()' and 'finalize_options()'. Usually called from 'finalize_options()' for options that depend on some other command rather than another option of the same command. 'src_cmd' is the other command from which option values will be taken (a command object will be created for it if necessary); the remaining arguments are '(src_option,dst_option)' tuples which mean "take the value of 'src_option' in the 'src_cmd' command object, and copy it to 'dst_option' in the current command object".
[ "Set", "the", "values", "of", "any", "undefined", "options", "from", "corresponding", "option", "values", "in", "some", "other", "command", "object", ".", "Undefined", "here", "means", "is", "None", "which", "is", "the", "convention", "used", "to", "indicate", "that", "an", "option", "has", "not", "been", "changed", "between", "initialize_options", "()", "and", "finalize_options", "()", ".", "Usually", "called", "from", "finalize_options", "()", "for", "options", "that", "depend", "on", "some", "other", "command", "rather", "than", "another", "option", "of", "the", "same", "command", ".", "src_cmd", "is", "the", "other", "command", "from", "which", "option", "values", "will", "be", "taken", "(", "a", "command", "object", "will", "be", "created", "for", "it", "if", "necessary", ")", ";", "the", "remaining", "arguments", "are", "(", "src_option", "dst_option", ")", "tuples", "which", "mean", "take", "the", "value", "of", "src_option", "in", "the", "src_cmd", "command", "object", "and", "copy", "it", "to", "dst_option", "in", "the", "current", "command", "object", "." ]
def set_undefined_options(self, src_cmd, *option_pairs): """Set the values of any "undefined" options from corresponding option values in some other command object. "Undefined" here means "is None", which is the convention used to indicate that an option has not been changed between 'initialize_options()' and 'finalize_options()'. Usually called from 'finalize_options()' for options that depend on some other command rather than another option of the same command. 'src_cmd' is the other command from which option values will be taken (a command object will be created for it if necessary); the remaining arguments are '(src_option,dst_option)' tuples which mean "take the value of 'src_option' in the 'src_cmd' command object, and copy it to 'dst_option' in the current command object". """ # Option_pairs: list of (src_option, dst_option) tuples src_cmd_obj = self.distribution.get_command_obj(src_cmd) src_cmd_obj.ensure_finalized() for (src_option, dst_option) in option_pairs: if getattr(self, dst_option) is None: setattr(self, dst_option, getattr(src_cmd_obj, src_option))
[ "def", "set_undefined_options", "(", "self", ",", "src_cmd", ",", "*", "option_pairs", ")", ":", "# Option_pairs: list of (src_option, dst_option) tuples", "src_cmd_obj", "=", "self", ".", "distribution", ".", "get_command_obj", "(", "src_cmd", ")", "src_cmd_obj", ".", "ensure_finalized", "(", ")", "for", "(", "src_option", ",", "dst_option", ")", "in", "option_pairs", ":", "if", "getattr", "(", "self", ",", "dst_option", ")", "is", "None", ":", "setattr", "(", "self", ",", "dst_option", ",", "getattr", "(", "src_cmd_obj", ",", "src_option", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/distutils/cmd.py#L280-L302
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/config.py
python
BaseConfigurator.ext_convert
(self, value)
return self.resolve(value)
Default converter for the ext:// protocol.
Default converter for the ext:// protocol.
[ "Default", "converter", "for", "the", "ext", ":", "//", "protocol", "." ]
def ext_convert(self, value): """Default converter for the ext:// protocol.""" return self.resolve(value)
[ "def", "ext_convert", "(", "self", ",", "value", ")", ":", "return", "self", ".", "resolve", "(", "value", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/logging/config.py#L399-L401
BestSonny/SSTD
174d452189f6bf9cf4b6957719392008bd974069
python/caffe/draw.py
python
get_layer_label
(layer, rankdir)
return node_label
Define node label based on layer type. Parameters ---------- layer : ? rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. Returns ------- string : A label for the current layer
Define node label based on layer type.
[ "Define", "node", "label", "based", "on", "layer", "type", "." ]
def get_layer_label(layer, rankdir): """Define node label based on layer type. Parameters ---------- layer : ? rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. Returns ------- string : A label for the current layer """ if rankdir in ('TB', 'BT'): # If graph orientation is vertical, horizontal space is free and # vertical space is not; separate words with spaces separator = ' ' else: # If graph orientation is horizontal, vertical space is free and # horizontal space is not; separate words with newlines separator = '\\n' if layer.type == 'Convolution' or layer.type == 'Deconvolution': # Outer double quotes needed or else colon characters don't parse # properly node_label = '"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d"' %\ (layer.name, separator, layer.type, separator, layer.convolution_param.kernel_size[0] if len(layer.convolution_param.kernel_size._values) else 1, separator, layer.convolution_param.stride[0] if len(layer.convolution_param.stride._values) else 1, separator, layer.convolution_param.pad[0] if len(layer.convolution_param.pad._values) else 0) elif layer.type == 'Pooling': pooling_types_dict = get_pooling_types_dict() node_label = '"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d"' %\ (layer.name, separator, pooling_types_dict[layer.pooling_param.pool], layer.type, separator, layer.pooling_param.kernel_size, separator, layer.pooling_param.stride, separator, layer.pooling_param.pad) else: node_label = '"%s%s(%s)"' % (layer.name, separator, layer.type) return node_label
[ "def", "get_layer_label", "(", "layer", ",", "rankdir", ")", ":", "if", "rankdir", "in", "(", "'TB'", ",", "'BT'", ")", ":", "# If graph orientation is vertical, horizontal space is free and", "# vertical space is not; separate words with spaces", "separator", "=", "' '", "else", ":", "# If graph orientation is horizontal, vertical space is free and", "# horizontal space is not; separate words with newlines", "separator", "=", "'\\\\n'", "if", "layer", ".", "type", "==", "'Convolution'", "or", "layer", ".", "type", "==", "'Deconvolution'", ":", "# Outer double quotes needed or else colon characters don't parse", "# properly", "node_label", "=", "'\"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d\"'", "%", "(", "layer", ".", "name", ",", "separator", ",", "layer", ".", "type", ",", "separator", ",", "layer", ".", "convolution_param", ".", "kernel_size", "[", "0", "]", "if", "len", "(", "layer", ".", "convolution_param", ".", "kernel_size", ".", "_values", ")", "else", "1", ",", "separator", ",", "layer", ".", "convolution_param", ".", "stride", "[", "0", "]", "if", "len", "(", "layer", ".", "convolution_param", ".", "stride", ".", "_values", ")", "else", "1", ",", "separator", ",", "layer", ".", "convolution_param", ".", "pad", "[", "0", "]", "if", "len", "(", "layer", ".", "convolution_param", ".", "pad", ".", "_values", ")", "else", "0", ")", "elif", "layer", ".", "type", "==", "'Pooling'", ":", "pooling_types_dict", "=", "get_pooling_types_dict", "(", ")", "node_label", "=", "'\"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d\"'", "%", "(", "layer", ".", "name", ",", "separator", ",", "pooling_types_dict", "[", "layer", ".", "pooling_param", ".", "pool", "]", ",", "layer", ".", "type", ",", "separator", ",", "layer", ".", "pooling_param", ".", "kernel_size", ",", "separator", ",", "layer", ".", "pooling_param", ".", "stride", ",", "separator", ",", "layer", ".", "pooling_param", ".", "pad", ")", "else", ":", "node_label", "=", "'\"%s%s(%s)\"'", "%", "(", "layer", ".", "name", ",", "separator", ",", "layer", ".", "type", ")", "return", "node_label" ]
https://github.com/BestSonny/SSTD/blob/174d452189f6bf9cf4b6957719392008bd974069/python/caffe/draw.py#L62-L114
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/utils/__init__.py
python
all_estimators
(include_meta_estimators=None, include_other=None, type_filter=None, include_dont_test=None)
return sorted(set(estimators), key=itemgetter(0))
Get a list of all estimators from sklearn. This function crawls the module and gets all classes that inherit from BaseEstimator. Classes that are defined in test-modules are not included. By default meta_estimators such as GridSearchCV are also not included. Parameters ---------- include_meta_estimators : boolean, default=False Deprecated, ignored. .. deprecated:: 0.21 ``include_meta_estimators`` has been deprecated and has no effect in 0.21 and will be removed in 0.23. include_other : boolean, default=False Deprecated, ignored. .. deprecated:: 0.21 ``include_other`` has been deprecated and has not effect in 0.21 and will be removed in 0.23. type_filter : string, list of string, or None, default=None Which kind of estimators should be returned. If None, no filter is applied and all estimators are returned. Possible values are 'classifier', 'regressor', 'cluster' and 'transformer' to get estimators only of these specific types, or a list of these to get the estimators that fit at least one of the types. include_dont_test : boolean, default=False Deprecated, ignored. .. deprecated:: 0.21 ``include_dont_test`` has been deprecated and has no effect in 0.21 and will be removed in 0.23. Returns ------- estimators : list of tuples List of (name, class), where ``name`` is the class name as string and ``class`` is the actuall type of the class.
Get a list of all estimators from sklearn.
[ "Get", "a", "list", "of", "all", "estimators", "from", "sklearn", "." ]
def all_estimators(include_meta_estimators=None, include_other=None, type_filter=None, include_dont_test=None): """Get a list of all estimators from sklearn. This function crawls the module and gets all classes that inherit from BaseEstimator. Classes that are defined in test-modules are not included. By default meta_estimators such as GridSearchCV are also not included. Parameters ---------- include_meta_estimators : boolean, default=False Deprecated, ignored. .. deprecated:: 0.21 ``include_meta_estimators`` has been deprecated and has no effect in 0.21 and will be removed in 0.23. include_other : boolean, default=False Deprecated, ignored. .. deprecated:: 0.21 ``include_other`` has been deprecated and has not effect in 0.21 and will be removed in 0.23. type_filter : string, list of string, or None, default=None Which kind of estimators should be returned. If None, no filter is applied and all estimators are returned. Possible values are 'classifier', 'regressor', 'cluster' and 'transformer' to get estimators only of these specific types, or a list of these to get the estimators that fit at least one of the types. include_dont_test : boolean, default=False Deprecated, ignored. .. deprecated:: 0.21 ``include_dont_test`` has been deprecated and has no effect in 0.21 and will be removed in 0.23. Returns ------- estimators : list of tuples List of (name, class), where ``name`` is the class name as string and ``class`` is the actuall type of the class. """ # lazy import to avoid circular imports from sklearn.base from ._testing import ignore_warnings from ..base import (BaseEstimator, ClassifierMixin, RegressorMixin, TransformerMixin, ClusterMixin) def is_abstract(c): if not(hasattr(c, '__abstractmethods__')): return False if not len(c.__abstractmethods__): return False return True if include_other is not None: warnings.warn("include_other was deprecated in version 0.21," " has no effect and will be removed in 0.23", DeprecationWarning) if include_dont_test is not None: warnings.warn("include_dont_test was deprecated in version 0.21," " has no effect and will be removed in 0.23", DeprecationWarning) if include_meta_estimators is not None: warnings.warn("include_meta_estimators was deprecated in version 0.21," " has no effect and will be removed in 0.23", DeprecationWarning) all_classes = [] modules_to_ignore = {"tests", "externals", "setup", "conftest"} root = str(Path(__file__).parent.parent) # sklearn package # Ignore deprecation warnings triggered at import time and from walking # packages with ignore_warnings(category=FutureWarning): for importer, modname, ispkg in pkgutil.walk_packages( path=[root], prefix='sklearn.'): mod_parts = modname.split(".") if (any(part in modules_to_ignore for part in mod_parts) or '._' in modname): continue module = import_module(modname) classes = inspect.getmembers(module, inspect.isclass) classes = [(name, est_cls) for name, est_cls in classes if not name.startswith("_")] # TODO: Remove when FeatureHasher is implemented in PYPY # Skips FeatureHasher for PYPY if IS_PYPY and 'feature_extraction' in modname: classes = [(name, est_cls) for name, est_cls in classes if name == "FeatureHasher"] all_classes.extend(classes) all_classes = set(all_classes) estimators = [c for c in all_classes if (issubclass(c[1], BaseEstimator) and c[0] != 'BaseEstimator')] # get rid of abstract base classes estimators = [c for c in estimators if not is_abstract(c[1])] if type_filter is not None: if not isinstance(type_filter, list): type_filter = [type_filter] else: type_filter = list(type_filter) # copy filtered_estimators = [] filters = {'classifier': ClassifierMixin, 'regressor': RegressorMixin, 'transformer': TransformerMixin, 'cluster': ClusterMixin} for name, mixin in filters.items(): if name in type_filter: type_filter.remove(name) filtered_estimators.extend([est for est in estimators if issubclass(est[1], mixin)]) estimators = filtered_estimators if type_filter: raise ValueError("Parameter type_filter must be 'classifier', " "'regressor', 'transformer', 'cluster' or " "None, got" " %s." % repr(type_filter)) # drop duplicates, sort for reproducibility # itemgetter is used to ensure the sort does not extend to the 2nd item of # the tuple return sorted(set(estimators), key=itemgetter(0))
[ "def", "all_estimators", "(", "include_meta_estimators", "=", "None", ",", "include_other", "=", "None", ",", "type_filter", "=", "None", ",", "include_dont_test", "=", "None", ")", ":", "# lazy import to avoid circular imports from sklearn.base", "from", ".", "_testing", "import", "ignore_warnings", "from", ".", ".", "base", "import", "(", "BaseEstimator", ",", "ClassifierMixin", ",", "RegressorMixin", ",", "TransformerMixin", ",", "ClusterMixin", ")", "def", "is_abstract", "(", "c", ")", ":", "if", "not", "(", "hasattr", "(", "c", ",", "'__abstractmethods__'", ")", ")", ":", "return", "False", "if", "not", "len", "(", "c", ".", "__abstractmethods__", ")", ":", "return", "False", "return", "True", "if", "include_other", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"include_other was deprecated in version 0.21,\"", "\" has no effect and will be removed in 0.23\"", ",", "DeprecationWarning", ")", "if", "include_dont_test", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"include_dont_test was deprecated in version 0.21,\"", "\" has no effect and will be removed in 0.23\"", ",", "DeprecationWarning", ")", "if", "include_meta_estimators", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"include_meta_estimators was deprecated in version 0.21,\"", "\" has no effect and will be removed in 0.23\"", ",", "DeprecationWarning", ")", "all_classes", "=", "[", "]", "modules_to_ignore", "=", "{", "\"tests\"", ",", "\"externals\"", ",", "\"setup\"", ",", "\"conftest\"", "}", "root", "=", "str", "(", "Path", "(", "__file__", ")", ".", "parent", ".", "parent", ")", "# sklearn package", "# Ignore deprecation warnings triggered at import time and from walking", "# packages", "with", "ignore_warnings", "(", "category", "=", "FutureWarning", ")", ":", "for", "importer", ",", "modname", ",", "ispkg", "in", "pkgutil", ".", "walk_packages", "(", "path", "=", "[", "root", "]", ",", "prefix", "=", "'sklearn.'", ")", ":", "mod_parts", "=", "modname", ".", "split", "(", "\".\"", ")", "if", "(", "any", "(", "part", "in", "modules_to_ignore", "for", "part", "in", "mod_parts", ")", "or", "'._'", "in", "modname", ")", ":", "continue", "module", "=", "import_module", "(", "modname", ")", "classes", "=", "inspect", ".", "getmembers", "(", "module", ",", "inspect", ".", "isclass", ")", "classes", "=", "[", "(", "name", ",", "est_cls", ")", "for", "name", ",", "est_cls", "in", "classes", "if", "not", "name", ".", "startswith", "(", "\"_\"", ")", "]", "# TODO: Remove when FeatureHasher is implemented in PYPY", "# Skips FeatureHasher for PYPY", "if", "IS_PYPY", "and", "'feature_extraction'", "in", "modname", ":", "classes", "=", "[", "(", "name", ",", "est_cls", ")", "for", "name", ",", "est_cls", "in", "classes", "if", "name", "==", "\"FeatureHasher\"", "]", "all_classes", ".", "extend", "(", "classes", ")", "all_classes", "=", "set", "(", "all_classes", ")", "estimators", "=", "[", "c", "for", "c", "in", "all_classes", "if", "(", "issubclass", "(", "c", "[", "1", "]", ",", "BaseEstimator", ")", "and", "c", "[", "0", "]", "!=", "'BaseEstimator'", ")", "]", "# get rid of abstract base classes", "estimators", "=", "[", "c", "for", "c", "in", "estimators", "if", "not", "is_abstract", "(", "c", "[", "1", "]", ")", "]", "if", "type_filter", "is", "not", "None", ":", "if", "not", "isinstance", "(", "type_filter", ",", "list", ")", ":", "type_filter", "=", "[", "type_filter", "]", "else", ":", "type_filter", "=", "list", "(", "type_filter", ")", "# copy", "filtered_estimators", "=", "[", "]", "filters", "=", "{", "'classifier'", ":", "ClassifierMixin", ",", "'regressor'", ":", "RegressorMixin", ",", "'transformer'", ":", "TransformerMixin", ",", "'cluster'", ":", "ClusterMixin", "}", "for", "name", ",", "mixin", "in", "filters", ".", "items", "(", ")", ":", "if", "name", "in", "type_filter", ":", "type_filter", ".", "remove", "(", "name", ")", "filtered_estimators", ".", "extend", "(", "[", "est", "for", "est", "in", "estimators", "if", "issubclass", "(", "est", "[", "1", "]", ",", "mixin", ")", "]", ")", "estimators", "=", "filtered_estimators", "if", "type_filter", ":", "raise", "ValueError", "(", "\"Parameter type_filter must be 'classifier', \"", "\"'regressor', 'transformer', 'cluster' or \"", "\"None, got\"", "\" %s.\"", "%", "repr", "(", "type_filter", ")", ")", "# drop duplicates, sort for reproducibility", "# itemgetter is used to ensure the sort does not extend to the 2nd item of", "# the tuple", "return", "sorted", "(", "set", "(", "estimators", ")", ",", "key", "=", "itemgetter", "(", "0", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/utils/__init__.py#L1152-L1283
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/bijector.py
python
_Bijector.inverse_log_det_jacobian
(self, x, name='inverse_log_det_jacobian')
Returns the (log o det o Jacobian o inverse)(x). Mathematically, returns: log(det(dY/dX g^{-1}))(Y). Args: x: `Tensor`. The input to the "inverse" Jacobian evaluation. name: The name to give this op. Returns: `Tensor`.
Returns the (log o det o Jacobian o inverse)(x).
[ "Returns", "the", "(", "log", "o", "det", "o", "Jacobian", "o", "inverse", ")", "(", "x", ")", "." ]
def inverse_log_det_jacobian(self, x, name='inverse_log_det_jacobian'): """Returns the (log o det o Jacobian o inverse)(x). Mathematically, returns: log(det(dY/dX g^{-1}))(Y). Args: x: `Tensor`. The input to the "inverse" Jacobian evaluation. name: The name to give this op. Returns: `Tensor`. """ with ops.name_scope(self.name): with ops.op_scope([x], name): x = ops.convert_to_tensor(x) try: return self._inverse_log_det_jacobian(x) except NotImplementedError: return self._inverse_and_inverse_log_det_jacobian(x)[1]
[ "def", "inverse_log_det_jacobian", "(", "self", ",", "x", ",", "name", "=", "'inverse_log_det_jacobian'", ")", ":", "with", "ops", ".", "name_scope", "(", "self", ".", "name", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "x", "]", ",", "name", ")", ":", "x", "=", "ops", ".", "convert_to_tensor", "(", "x", ")", "try", ":", "return", "self", ".", "_inverse_log_det_jacobian", "(", "x", ")", "except", "NotImplementedError", ":", "return", "self", ".", "_inverse_and_inverse_log_det_jacobian", "(", "x", ")", "[", "1", "]" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/bijector.py#L184-L202
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/fixes/fix_metaclass.py
python
fixup_indent
(suite)
If an INDENT is followed by a thing with a prefix then nuke the prefix Otherwise we get in trouble when removing __metaclass__ at suite start
If an INDENT is followed by a thing with a prefix then nuke the prefix Otherwise we get in trouble when removing __metaclass__ at suite start
[ "If", "an", "INDENT", "is", "followed", "by", "a", "thing", "with", "a", "prefix", "then", "nuke", "the", "prefix", "Otherwise", "we", "get", "in", "trouble", "when", "removing", "__metaclass__", "at", "suite", "start" ]
def fixup_indent(suite): """ If an INDENT is followed by a thing with a prefix then nuke the prefix Otherwise we get in trouble when removing __metaclass__ at suite start """ kids = suite.children[::-1] # find the first indent while kids: node = kids.pop() if node.type == token.INDENT: break # find the first Leaf while kids: node = kids.pop() if isinstance(node, Leaf) and node.type != token.DEDENT: if node.prefix: node.prefix = '' return else: kids.extend(node.children[::-1])
[ "def", "fixup_indent", "(", "suite", ")", ":", "kids", "=", "suite", ".", "children", "[", ":", ":", "-", "1", "]", "# find the first indent", "while", "kids", ":", "node", "=", "kids", ".", "pop", "(", ")", "if", "node", ".", "type", "==", "token", ".", "INDENT", ":", "break", "# find the first Leaf", "while", "kids", ":", "node", "=", "kids", ".", "pop", "(", ")", "if", "isinstance", "(", "node", ",", "Leaf", ")", "and", "node", ".", "type", "!=", "token", ".", "DEDENT", ":", "if", "node", ".", "prefix", ":", "node", ".", "prefix", "=", "''", "return", "else", ":", "kids", ".", "extend", "(", "node", ".", "children", "[", ":", ":", "-", "1", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/fixes/fix_metaclass.py#L123-L142
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/html.py
python
HtmlPrintout.SetHtmlText
(*args, **kwargs)
return _html.HtmlPrintout_SetHtmlText(*args, **kwargs)
SetHtmlText(self, String html, String basepath=EmptyString, bool isdir=True)
SetHtmlText(self, String html, String basepath=EmptyString, bool isdir=True)
[ "SetHtmlText", "(", "self", "String", "html", "String", "basepath", "=", "EmptyString", "bool", "isdir", "=", "True", ")" ]
def SetHtmlText(*args, **kwargs): """SetHtmlText(self, String html, String basepath=EmptyString, bool isdir=True)""" return _html.HtmlPrintout_SetHtmlText(*args, **kwargs)
[ "def", "SetHtmlText", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlPrintout_SetHtmlText", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L1276-L1278
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/httplib.py
python
HTTPResponse.getheaders
(self)
return self.msg.items()
Return list of (header, value) tuples.
Return list of (header, value) tuples.
[ "Return", "list", "of", "(", "header", "value", ")", "tuples", "." ]
def getheaders(self): """Return list of (header, value) tuples.""" if self.msg is None: raise ResponseNotReady() return self.msg.items()
[ "def", "getheaders", "(", "self", ")", ":", "if", "self", ".", "msg", "is", "None", ":", "raise", "ResponseNotReady", "(", ")", "return", "self", ".", "msg", ".", "items", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/httplib.py#L673-L677
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Image.ResampleBilinear
(*args, **kwargs)
return _core_.Image_ResampleBilinear(*args, **kwargs)
ResampleBilinear(self, int width, int height) -> Image
ResampleBilinear(self, int width, int height) -> Image
[ "ResampleBilinear", "(", "self", "int", "width", "int", "height", ")", "-", ">", "Image" ]
def ResampleBilinear(*args, **kwargs): """ResampleBilinear(self, int width, int height) -> Image""" return _core_.Image_ResampleBilinear(*args, **kwargs)
[ "def", "ResampleBilinear", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Image_ResampleBilinear", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L2926-L2928
SoarGroup/Soar
a1c5e249499137a27da60533c72969eef3b8ab6b
scons/scons-time.py
python
SConsTimer.outdent
(self, s)
return '\n'.join([strip_initial_spaces(l) for l in lines]) + '\n'
Strip as many spaces from each line as are found at the beginning of the first line in the list.
Strip as many spaces from each line as are found at the beginning of the first line in the list.
[ "Strip", "as", "many", "spaces", "from", "each", "line", "as", "are", "found", "at", "the", "beginning", "of", "the", "first", "line", "in", "the", "list", "." ]
def outdent(self, s): """ Strip as many spaces from each line as are found at the beginning of the first line in the list. """ lines = s.split('\n') if lines[0] == '': lines = lines[1:] spaces = re.match(' *', lines[0]).group(0) def strip_initial_spaces(line, s=spaces): if line.startswith(spaces): line = line[len(spaces):] return line return '\n'.join([strip_initial_spaces(l) for l in lines]) + '\n'
[ "def", "outdent", "(", "self", ",", "s", ")", ":", "lines", "=", "s", ".", "split", "(", "'\\n'", ")", "if", "lines", "[", "0", "]", "==", "''", ":", "lines", "=", "lines", "[", "1", ":", "]", "spaces", "=", "re", ".", "match", "(", "' *'", ",", "lines", "[", "0", "]", ")", ".", "group", "(", "0", ")", "def", "strip_initial_spaces", "(", "line", ",", "s", "=", "spaces", ")", ":", "if", "line", ".", "startswith", "(", "spaces", ")", ":", "line", "=", "line", "[", "len", "(", "spaces", ")", ":", "]", "return", "line", "return", "'\\n'", ".", "join", "(", "[", "strip_initial_spaces", "(", "l", ")", "for", "l", "in", "lines", "]", ")", "+", "'\\n'" ]
https://github.com/SoarGroup/Soar/blob/a1c5e249499137a27da60533c72969eef3b8ab6b/scons/scons-time.py#L594-L609
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/storage_uri.py
python
FileStorageUri.names_directory
(self)
return os.path.isdir(self.object_name)
Returns True if this URI names a directory.
Returns True if this URI names a directory.
[ "Returns", "True", "if", "this", "URI", "names", "a", "directory", "." ]
def names_directory(self): """Returns True if this URI names a directory.""" if self.stream: return False return os.path.isdir(self.object_name)
[ "def", "names_directory", "(", "self", ")", ":", "if", "self", ".", "stream", ":", "return", "False", "return", "os", ".", "path", ".", "isdir", "(", "self", ".", "object_name", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/storage_uri.py#L854-L858
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/fixer_util.py
python
in_special_context
(node)
return False
Returns true if node is in an environment where all that is required of it is being iterable (ie, it doesn't matter if it returns a list or an iterator). See test_map_nochange in test_fixers.py for some examples and tests.
Returns true if node is in an environment where all that is required of it is being iterable (ie, it doesn't matter if it returns a list or an iterator). See test_map_nochange in test_fixers.py for some examples and tests.
[ "Returns", "true", "if", "node", "is", "in", "an", "environment", "where", "all", "that", "is", "required", "of", "it", "is", "being", "iterable", "(", "ie", "it", "doesn", "t", "matter", "if", "it", "returns", "a", "list", "or", "an", "iterator", ")", ".", "See", "test_map_nochange", "in", "test_fixers", ".", "py", "for", "some", "examples", "and", "tests", "." ]
def in_special_context(node): """ Returns true if node is in an environment where all that is required of it is being iterable (ie, it doesn't matter if it returns a list or an iterator). See test_map_nochange in test_fixers.py for some examples and tests. """ global p0, p1, p2, pats_built if not pats_built: p0 = patcomp.compile_pattern(p0) p1 = patcomp.compile_pattern(p1) p2 = patcomp.compile_pattern(p2) pats_built = True patterns = [p0, p1, p2] for pattern, parent in zip(patterns, attr_chain(node, "parent")): results = {} if pattern.match(parent, results) and results["node"] is node: return True return False
[ "def", "in_special_context", "(", "node", ")", ":", "global", "p0", ",", "p1", ",", "p2", ",", "pats_built", "if", "not", "pats_built", ":", "p0", "=", "patcomp", ".", "compile_pattern", "(", "p0", ")", "p1", "=", "patcomp", ".", "compile_pattern", "(", "p1", ")", "p2", "=", "patcomp", ".", "compile_pattern", "(", "p2", ")", "pats_built", "=", "True", "patterns", "=", "[", "p0", ",", "p1", ",", "p2", "]", "for", "pattern", ",", "parent", "in", "zip", "(", "patterns", ",", "attr_chain", "(", "node", ",", "\"parent\"", ")", ")", ":", "results", "=", "{", "}", "if", "pattern", ".", "match", "(", "parent", ",", "results", ")", "and", "results", "[", "\"node\"", "]", "is", "node", ":", "return", "True", "return", "False" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib2to3/fixer_util.py#L208-L225
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/framework/ops.py
python
register_tensor_conversion_function
(base_type, conversion_func, priority=100)
Registers a function for converting objects of `base_type` to `Tensor`. The conversion function must have the following signature: ```python def conversion_func(value, dtype=None, name=None, as_ref=False): # ... ``` It must return a `Tensor` with the given `dtype` if specified. If the conversion function creates a new `Tensor`, it should use the given `name` if specified. All exceptions will be propagated to the caller. The conversion function may return `NotImplemented` for some inputs. In this case, the conversion process will continue to try subsequent conversion functions. If `as_ref` is true, the function must return a `Tensor` reference, such as a `Variable`. NOTE: The conversion functions will execute in order of priority, followed by order of registration. To ensure that a conversion function `F` runs before another conversion function `G`, ensure that `F` is registered with a smaller priority than `G`. Args: base_type: The base type or tuple of base types for all objects that `conversion_func` accepts. conversion_func: A function that converts instances of `base_type` to `Tensor`. priority: Optional integer that indicates the priority for applying this conversion function. Conversion functions with smaller priority values run earlier than conversion functions with larger priority values. Defaults to 100. Raises: TypeError: If the arguments do not have the appropriate type.
Registers a function for converting objects of `base_type` to `Tensor`.
[ "Registers", "a", "function", "for", "converting", "objects", "of", "base_type", "to", "Tensor", "." ]
def register_tensor_conversion_function(base_type, conversion_func, priority=100): """Registers a function for converting objects of `base_type` to `Tensor`. The conversion function must have the following signature: ```python def conversion_func(value, dtype=None, name=None, as_ref=False): # ... ``` It must return a `Tensor` with the given `dtype` if specified. If the conversion function creates a new `Tensor`, it should use the given `name` if specified. All exceptions will be propagated to the caller. The conversion function may return `NotImplemented` for some inputs. In this case, the conversion process will continue to try subsequent conversion functions. If `as_ref` is true, the function must return a `Tensor` reference, such as a `Variable`. NOTE: The conversion functions will execute in order of priority, followed by order of registration. To ensure that a conversion function `F` runs before another conversion function `G`, ensure that `F` is registered with a smaller priority than `G`. Args: base_type: The base type or tuple of base types for all objects that `conversion_func` accepts. conversion_func: A function that converts instances of `base_type` to `Tensor`. priority: Optional integer that indicates the priority for applying this conversion function. Conversion functions with smaller priority values run earlier than conversion functions with larger priority values. Defaults to 100. Raises: TypeError: If the arguments do not have the appropriate type. """ if not (isinstance(base_type, type) or (isinstance(base_type, tuple) and all(isinstance(x, type) for x in base_type))): raise TypeError("base_type must be a type or a tuple of types.") if not callable(conversion_func): raise TypeError("conversion_func must be callable.") try: funcs_at_priority = _tensor_conversion_func_registry[priority] except KeyError: funcs_at_priority = [] _tensor_conversion_func_registry[priority] = funcs_at_priority funcs_at_priority.append((base_type, conversion_func))
[ "def", "register_tensor_conversion_function", "(", "base_type", ",", "conversion_func", ",", "priority", "=", "100", ")", ":", "if", "not", "(", "isinstance", "(", "base_type", ",", "type", ")", "or", "(", "isinstance", "(", "base_type", ",", "tuple", ")", "and", "all", "(", "isinstance", "(", "x", ",", "type", ")", "for", "x", "in", "base_type", ")", ")", ")", ":", "raise", "TypeError", "(", "\"base_type must be a type or a tuple of types.\"", ")", "if", "not", "callable", "(", "conversion_func", ")", ":", "raise", "TypeError", "(", "\"conversion_func must be callable.\"", ")", "try", ":", "funcs_at_priority", "=", "_tensor_conversion_func_registry", "[", "priority", "]", "except", "KeyError", ":", "funcs_at_priority", "=", "[", "]", "_tensor_conversion_func_registry", "[", "priority", "]", "=", "funcs_at_priority", "funcs_at_priority", ".", "append", "(", "(", "base_type", ",", "conversion_func", ")", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/ops.py#L794-L847
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/internal/actions/action_runner.py
python
ActionRunner.ScrollBouncePage
(self, left_start_ratio=0.5, top_start_ratio=0.5, direction='down', distance=100, overscroll=10, repeat_count=10, speed_in_pixels_per_second=400)
Perform scroll bounce gesture on the page. This gesture scrolls the page by the number of pixels specified in distance, in the given direction, followed by a scroll by (distance + overscroll) pixels in the opposite direction. The above gesture is repeated repeat_count times. Args: left_start_ratio: The horizontal starting coordinate of the gesture, as a ratio of the visible bounding rectangle for document.body. top_start_ratio: The vertical starting coordinate of the gesture, as a ratio of the visible bounding rectangle for document.body. direction: The direction of scroll, either 'left', 'right', 'up', 'down', 'upleft', 'upright', 'downleft', or 'downright' distance: The distance to scroll (in pixel). overscroll: The number of additional pixels to scroll back, in addition to the givendistance. repeat_count: How often we want to repeat the full gesture. speed_in_pixels_per_second: The speed of the gesture (in pixels/s).
Perform scroll bounce gesture on the page.
[ "Perform", "scroll", "bounce", "gesture", "on", "the", "page", "." ]
def ScrollBouncePage(self, left_start_ratio=0.5, top_start_ratio=0.5, direction='down', distance=100, overscroll=10, repeat_count=10, speed_in_pixels_per_second=400): """Perform scroll bounce gesture on the page. This gesture scrolls the page by the number of pixels specified in distance, in the given direction, followed by a scroll by (distance + overscroll) pixels in the opposite direction. The above gesture is repeated repeat_count times. Args: left_start_ratio: The horizontal starting coordinate of the gesture, as a ratio of the visible bounding rectangle for document.body. top_start_ratio: The vertical starting coordinate of the gesture, as a ratio of the visible bounding rectangle for document.body. direction: The direction of scroll, either 'left', 'right', 'up', 'down', 'upleft', 'upright', 'downleft', or 'downright' distance: The distance to scroll (in pixel). overscroll: The number of additional pixels to scroll back, in addition to the givendistance. repeat_count: How often we want to repeat the full gesture. speed_in_pixels_per_second: The speed of the gesture (in pixels/s). """ self._RunAction(ScrollBounceAction( left_start_ratio=left_start_ratio, top_start_ratio=top_start_ratio, direction=direction, distance=distance, overscroll=overscroll, repeat_count=repeat_count, speed_in_pixels_per_second=speed_in_pixels_per_second))
[ "def", "ScrollBouncePage", "(", "self", ",", "left_start_ratio", "=", "0.5", ",", "top_start_ratio", "=", "0.5", ",", "direction", "=", "'down'", ",", "distance", "=", "100", ",", "overscroll", "=", "10", ",", "repeat_count", "=", "10", ",", "speed_in_pixels_per_second", "=", "400", ")", ":", "self", ".", "_RunAction", "(", "ScrollBounceAction", "(", "left_start_ratio", "=", "left_start_ratio", ",", "top_start_ratio", "=", "top_start_ratio", ",", "direction", "=", "direction", ",", "distance", "=", "distance", ",", "overscroll", "=", "overscroll", ",", "repeat_count", "=", "repeat_count", ",", "speed_in_pixels_per_second", "=", "speed_in_pixels_per_second", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/internal/actions/action_runner.py#L471-L501
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
ColourRGB
(*args, **kwargs)
return val
ColourRGB(unsigned long colRGB) -> Colour Constructs a colour from a packed RGB value.
ColourRGB(unsigned long colRGB) -> Colour
[ "ColourRGB", "(", "unsigned", "long", "colRGB", ")", "-", ">", "Colour" ]
def ColourRGB(*args, **kwargs): """ ColourRGB(unsigned long colRGB) -> Colour Constructs a colour from a packed RGB value. """ val = _gdi_.new_ColourRGB(*args, **kwargs) return val
[ "def", "ColourRGB", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_gdi_", ".", "new_ColourRGB", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L313-L320
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/telnetlib.py
python
Telnet.__init__
(self, host=None, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT)
Constructor. When called without arguments, create an unconnected instance. With a hostname argument, it connects the instance; port number and timeout are optional.
Constructor.
[ "Constructor", "." ]
def __init__(self, host=None, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): """Constructor. When called without arguments, create an unconnected instance. With a hostname argument, it connects the instance; port number and timeout are optional. """ self.debuglevel = DEBUGLEVEL self.host = host self.port = port self.timeout = timeout self.sock = None self.rawq = '' self.irawq = 0 self.cookedq = '' self.eof = 0 self.iacseq = '' # Buffer for IAC sequence. self.sb = 0 # flag for SB and SE sequence. self.sbdataq = '' self.option_callback = None self._has_poll = hasattr(select, 'poll') if host is not None: self.open(host, port, timeout)
[ "def", "__init__", "(", "self", ",", "host", "=", "None", ",", "port", "=", "0", ",", "timeout", "=", "socket", ".", "_GLOBAL_DEFAULT_TIMEOUT", ")", ":", "self", ".", "debuglevel", "=", "DEBUGLEVEL", "self", ".", "host", "=", "host", "self", ".", "port", "=", "port", "self", ".", "timeout", "=", "timeout", "self", ".", "sock", "=", "None", "self", ".", "rawq", "=", "''", "self", ".", "irawq", "=", "0", "self", ".", "cookedq", "=", "''", "self", ".", "eof", "=", "0", "self", ".", "iacseq", "=", "''", "# Buffer for IAC sequence.", "self", ".", "sb", "=", "0", "# flag for SB and SE sequence.", "self", ".", "sbdataq", "=", "''", "self", ".", "option_callback", "=", "None", "self", ".", "_has_poll", "=", "hasattr", "(", "select", ",", "'poll'", ")", "if", "host", "is", "not", "None", ":", "self", ".", "open", "(", "host", ",", "port", ",", "timeout", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/telnetlib.py#L188-L211
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/nn.py
python
nce_loss
(weights, biases, inputs, labels, num_sampled, num_classes, num_true=1, sampled_values=None, remove_accidental_hits=False, partition_strategy="mod", name="nce_loss")
return _sum_rows(sampled_losses)
Computes and returns the noise-contrastive estimation training loss. See [Noise-contrastive estimation: A new estimation principle for unnormalized statistical models] (http://www.jmlr.org/proceedings/papers/v9/gutmann10a/gutmann10a.pdf). Also see our [Candidate Sampling Algorithms Reference] (../../extras/candidate_sampling.pdf) Note: In the case where `num_true` > 1, we assign to each target class the target probability 1 / `num_true` so that the target probabilities sum to 1 per-example. Note: It would be useful to allow a variable number of target classes per example. We hope to provide this functionality in a future release. For now, if you have a variable number of target classes, you can pad them out to a constant number by either repeating them or by padding with an otherwise unused class. Args: weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor` objects whose concatenation along dimension 0 has shape [num_classes, dim]. The (possibly-partitioned) class embeddings. biases: A `Tensor` of shape `[num_classes]`. The class biases. inputs: A `Tensor` of shape `[batch_size, dim]`. The forward activations of the input network. labels: A `Tensor` of type `int64` and shape `[batch_size, num_true]`. The target classes. num_sampled: An `int`. The number of classes to randomly sample per batch. num_classes: An `int`. The number of possible classes. num_true: An `int`. The number of target classes per training example. sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`, `sampled_expected_count`) returned by a `*_candidate_sampler` function. (if None, we default to `log_uniform_candidate_sampler`) remove_accidental_hits: A `bool`. Whether to remove "accidental hits" where a sampled class equals one of the target classes. If set to `True`, this is a "Sampled Logistic" loss instead of NCE, and we are learning to generate log-odds instead of log probabilities. See our [Candidate Sampling Algorithms Reference] (../../extras/candidate_sampling.pdf). Default is False. partition_strategy: A string specifying the partitioning strategy, relevant if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported. Default is `"mod"`. See `tf.nn.embedding_lookup` for more details. name: A name for the operation (optional). Returns: A `batch_size` 1-D tensor of per-example NCE losses.
Computes and returns the noise-contrastive estimation training loss.
[ "Computes", "and", "returns", "the", "noise", "-", "contrastive", "estimation", "training", "loss", "." ]
def nce_loss(weights, biases, inputs, labels, num_sampled, num_classes, num_true=1, sampled_values=None, remove_accidental_hits=False, partition_strategy="mod", name="nce_loss"): """Computes and returns the noise-contrastive estimation training loss. See [Noise-contrastive estimation: A new estimation principle for unnormalized statistical models] (http://www.jmlr.org/proceedings/papers/v9/gutmann10a/gutmann10a.pdf). Also see our [Candidate Sampling Algorithms Reference] (../../extras/candidate_sampling.pdf) Note: In the case where `num_true` > 1, we assign to each target class the target probability 1 / `num_true` so that the target probabilities sum to 1 per-example. Note: It would be useful to allow a variable number of target classes per example. We hope to provide this functionality in a future release. For now, if you have a variable number of target classes, you can pad them out to a constant number by either repeating them or by padding with an otherwise unused class. Args: weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor` objects whose concatenation along dimension 0 has shape [num_classes, dim]. The (possibly-partitioned) class embeddings. biases: A `Tensor` of shape `[num_classes]`. The class biases. inputs: A `Tensor` of shape `[batch_size, dim]`. The forward activations of the input network. labels: A `Tensor` of type `int64` and shape `[batch_size, num_true]`. The target classes. num_sampled: An `int`. The number of classes to randomly sample per batch. num_classes: An `int`. The number of possible classes. num_true: An `int`. The number of target classes per training example. sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`, `sampled_expected_count`) returned by a `*_candidate_sampler` function. (if None, we default to `log_uniform_candidate_sampler`) remove_accidental_hits: A `bool`. Whether to remove "accidental hits" where a sampled class equals one of the target classes. If set to `True`, this is a "Sampled Logistic" loss instead of NCE, and we are learning to generate log-odds instead of log probabilities. See our [Candidate Sampling Algorithms Reference] (../../extras/candidate_sampling.pdf). Default is False. partition_strategy: A string specifying the partitioning strategy, relevant if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported. Default is `"mod"`. See `tf.nn.embedding_lookup` for more details. name: A name for the operation (optional). Returns: A `batch_size` 1-D tensor of per-example NCE losses. """ logits, labels = _compute_sampled_logits( weights, biases, inputs, labels, num_sampled, num_classes, num_true=num_true, sampled_values=sampled_values, subtract_log_q=True, remove_accidental_hits=remove_accidental_hits, partition_strategy=partition_strategy, name=name) sampled_losses = sigmoid_cross_entropy_with_logits( logits, labels, name="sampled_losses") # sampled_losses is batch_size x {true_loss, sampled_losses...} # We sum out true and sampled losses. return _sum_rows(sampled_losses)
[ "def", "nce_loss", "(", "weights", ",", "biases", ",", "inputs", ",", "labels", ",", "num_sampled", ",", "num_classes", ",", "num_true", "=", "1", ",", "sampled_values", "=", "None", ",", "remove_accidental_hits", "=", "False", ",", "partition_strategy", "=", "\"mod\"", ",", "name", "=", "\"nce_loss\"", ")", ":", "logits", ",", "labels", "=", "_compute_sampled_logits", "(", "weights", ",", "biases", ",", "inputs", ",", "labels", ",", "num_sampled", ",", "num_classes", ",", "num_true", "=", "num_true", ",", "sampled_values", "=", "sampled_values", ",", "subtract_log_q", "=", "True", ",", "remove_accidental_hits", "=", "remove_accidental_hits", ",", "partition_strategy", "=", "partition_strategy", ",", "name", "=", "name", ")", "sampled_losses", "=", "sigmoid_cross_entropy_with_logits", "(", "logits", ",", "labels", ",", "name", "=", "\"sampled_losses\"", ")", "# sampled_losses is batch_size x {true_loss, sampled_losses...}", "# We sum out true and sampled losses.", "return", "_sum_rows", "(", "sampled_losses", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/nn.py#L1122-L1198
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py
python
pooling_ndhwc_max
( I=TensorDef(T1, S.N, S.OD * S.SD + S.KD * S.DD, S.OH * S.SH + S.KH * S.DH, S.OW * S.SW + S.KW * S.DW, S.C), K=TensorDef(T2, S.KD, S.KH, S.KW, index_dims=[D.kd, D.kh, D.kw]), O=TensorDef(U, S.N, S.OD, S.OH, S.OW, S.C, output=True), strides=IndexAttrDef(S.SD, S.SH, S.SW), dilations=IndexAttrDef(S.DD, S.DH, S.DW))
Performs 3D max pooling. Numeric casting is performed on the input operand, promoting it to the same data type as the accumulator/output.
Performs 3D max pooling.
[ "Performs", "3D", "max", "pooling", "." ]
def pooling_ndhwc_max( I=TensorDef(T1, S.N, S.OD * S.SD + S.KD * S.DD, S.OH * S.SH + S.KH * S.DH, S.OW * S.SW + S.KW * S.DW, S.C), K=TensorDef(T2, S.KD, S.KH, S.KW, index_dims=[D.kd, D.kh, D.kw]), O=TensorDef(U, S.N, S.OD, S.OH, S.OW, S.C, output=True), strides=IndexAttrDef(S.SD, S.SH, S.SW), dilations=IndexAttrDef(S.DD, S.DH, S.DW)): """Performs 3D max pooling. Numeric casting is performed on the input operand, promoting it to the same data type as the accumulator/output. """ implements(ConvolutionOpInterface) domain(D.n, D.od, D.oh, D.ow, D.c, D.kd, D.kh, D.kw) O[D.n, D.od, D.oh, D.ow, D.c] = ReduceFn.max[D.kd, D.kh, D.kw]( TypeFn.cast( U, I[D.n, D.od * S.SD + D.kd * S.DD, D.oh * S.SH + D.kh * S.DH, D.ow * S.SW + D.kw * S.DW, D.c]))
[ "def", "pooling_ndhwc_max", "(", "I", "=", "TensorDef", "(", "T1", ",", "S", ".", "N", ",", "S", ".", "OD", "*", "S", ".", "SD", "+", "S", ".", "KD", "*", "S", ".", "DD", ",", "S", ".", "OH", "*", "S", ".", "SH", "+", "S", ".", "KH", "*", "S", ".", "DH", ",", "S", ".", "OW", "*", "S", ".", "SW", "+", "S", ".", "KW", "*", "S", ".", "DW", ",", "S", ".", "C", ")", ",", "K", "=", "TensorDef", "(", "T2", ",", "S", ".", "KD", ",", "S", ".", "KH", ",", "S", ".", "KW", ",", "index_dims", "=", "[", "D", ".", "kd", ",", "D", ".", "kh", ",", "D", ".", "kw", "]", ")", ",", "O", "=", "TensorDef", "(", "U", ",", "S", ".", "N", ",", "S", ".", "OD", ",", "S", ".", "OH", ",", "S", ".", "OW", ",", "S", ".", "C", ",", "output", "=", "True", ")", ",", "strides", "=", "IndexAttrDef", "(", "S", ".", "SD", ",", "S", ".", "SH", ",", "S", ".", "SW", ")", ",", "dilations", "=", "IndexAttrDef", "(", "S", ".", "DD", ",", "S", ".", "DH", ",", "S", ".", "DW", ")", ")", ":", "implements", "(", "ConvolutionOpInterface", ")", "domain", "(", "D", ".", "n", ",", "D", ".", "od", ",", "D", ".", "oh", ",", "D", ".", "ow", ",", "D", ".", "c", ",", "D", ".", "kd", ",", "D", ".", "kh", ",", "D", ".", "kw", ")", "O", "[", "D", ".", "n", ",", "D", ".", "od", ",", "D", ".", "oh", ",", "D", ".", "ow", ",", "D", ".", "c", "]", "=", "ReduceFn", ".", "max", "[", "D", ".", "kd", ",", "D", ".", "kh", ",", "D", ".", "kw", "]", "(", "TypeFn", ".", "cast", "(", "U", ",", "I", "[", "D", ".", "n", ",", "D", ".", "od", "*", "S", ".", "SD", "+", "D", ".", "kd", "*", "S", ".", "DD", ",", "D", ".", "oh", "*", "S", ".", "SH", "+", "D", ".", "kh", "*", "S", ".", "DH", ",", "D", ".", "ow", "*", "S", ".", "SW", "+", "D", ".", "kw", "*", "S", ".", "DW", ",", "D", ".", "c", "]", ")", ")" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/mlir/python/mlir/dialects/linalg/opdsl/ops/core_named_ops.py#L589-L606
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/inspect.py
python
getmro
(cls)
return cls.__mro__
Return tuple of base classes (including cls) in method resolution order.
Return tuple of base classes (including cls) in method resolution order.
[ "Return", "tuple", "of", "base", "classes", "(", "including", "cls", ")", "in", "method", "resolution", "order", "." ]
def getmro(cls): "Return tuple of base classes (including cls) in method resolution order." return cls.__mro__
[ "def", "getmro", "(", "cls", ")", ":", "return", "cls", ".", "__mro__" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/inspect.py#L478-L480
facebook/mysql-5.6
65a650660ec7b4d627d1b738f397252ff4706207
arcanist/lint/cpp_linter/cpplint.py
python
_FunctionState.Check
(self, error, filename, linenum)
Report if too many lines in function body. Args: error: The function to call with any errors found. filename: The name of the current file. linenum: The number of the line to check.
Report if too many lines in function body.
[ "Report", "if", "too", "many", "lines", "in", "function", "body", "." ]
def Check(self, error, filename, linenum): """Report if too many lines in function body. Args: error: The function to call with any errors found. filename: The name of the current file. linenum: The number of the line to check. """ if Match(r'T(EST|est)', self.current_function): base_trigger = self._TEST_TRIGGER else: base_trigger = self._NORMAL_TRIGGER trigger = base_trigger * 2**_VerboseLevel() if self.lines_in_function > trigger: error_level = int(math.log(self.lines_in_function / base_trigger, 2)) # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... if error_level > 5: error_level = 5 error(filename, linenum, 'readability/fn_size', error_level, 'Small and focused functions are preferred:' ' %s has %d non-comment lines' ' (error triggered by exceeding %d lines).' % ( self.current_function, self.lines_in_function, trigger))
[ "def", "Check", "(", "self", ",", "error", ",", "filename", ",", "linenum", ")", ":", "if", "Match", "(", "r'T(EST|est)'", ",", "self", ".", "current_function", ")", ":", "base_trigger", "=", "self", ".", "_TEST_TRIGGER", "else", ":", "base_trigger", "=", "self", ".", "_NORMAL_TRIGGER", "trigger", "=", "base_trigger", "*", "2", "**", "_VerboseLevel", "(", ")", "if", "self", ".", "lines_in_function", ">", "trigger", ":", "error_level", "=", "int", "(", "math", ".", "log", "(", "self", ".", "lines_in_function", "/", "base_trigger", ",", "2", ")", ")", "# 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...", "if", "error_level", ">", "5", ":", "error_level", "=", "5", "error", "(", "filename", ",", "linenum", ",", "'readability/fn_size'", ",", "error_level", ",", "'Small and focused functions are preferred:'", "' %s has %d non-comment lines'", "' (error triggered by exceeding %d lines).'", "%", "(", "self", ".", "current_function", ",", "self", ".", "lines_in_function", ",", "trigger", ")", ")" ]
https://github.com/facebook/mysql-5.6/blob/65a650660ec7b4d627d1b738f397252ff4706207/arcanist/lint/cpp_linter/cpplint.py#L830-L853
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/coverage/coverage/parser.py
python
PythonParser._raw_parse
(self)
Parse the source to find the interesting facts about its lines. A handful of member fields are updated.
Parse the source to find the interesting facts about its lines.
[ "Parse", "the", "source", "to", "find", "the", "interesting", "facts", "about", "its", "lines", "." ]
def _raw_parse(self): """Parse the source to find the interesting facts about its lines. A handful of member fields are updated. """ # Find lines which match an exclusion pattern. if self.exclude: self.excluded = self.lines_matching(self.exclude) # Tokenize, to find excluded suites, to find docstrings, and to find # multi-line statements. indent = 0 exclude_indent = 0 excluding = False prev_toktype = token.INDENT first_line = None empty = True tokgen = generate_tokens(self.text) for toktype, ttext, (slineno, _), (elineno, _), ltext in tokgen: if self.show_tokens: # pragma: not covered print("%10s %5s %-20r %r" % ( tokenize.tok_name.get(toktype, toktype), nice_pair((slineno, elineno)), ttext, ltext )) if toktype == token.INDENT: indent += 1 elif toktype == token.DEDENT: indent -= 1 elif toktype == token.NAME and ttext == 'class': # Class definitions look like branches in the byte code, so # we need to exclude them. The simplest way is to note the # lines with the 'class' keyword. self.classdefs.add(slineno) elif toktype == token.OP and ttext == ':': if not excluding and elineno in self.excluded: # Start excluding a suite. We trigger off of the colon # token so that the #pragma comment will be recognized on # the same line as the colon. exclude_indent = indent excluding = True elif toktype == token.STRING and prev_toktype == token.INDENT: # Strings that are first on an indented line are docstrings. # (a trick from trace.py in the stdlib.) This works for # 99.9999% of cases. For the rest (!) see: # http://stackoverflow.com/questions/1769332/x/1769794#1769794 self.docstrings.update(range(slineno, elineno+1)) elif toktype == token.NEWLINE: if first_line is not None and elineno != first_line: # We're at the end of a line, and we've ended on a # different line than the first line of the statement, # so record a multi-line range. for l in range(first_line, elineno+1): self.multiline[l] = first_line first_line = None if ttext.strip() and toktype != tokenize.COMMENT: # A non-whitespace token. empty = False if first_line is None: # The token is not whitespace, and is the first in a # statement. first_line = slineno # Check whether to end an excluded suite. if excluding and indent <= exclude_indent: excluding = False if excluding: self.excluded.add(elineno) prev_toktype = toktype # Find the starts of the executable statements. if not empty: self.statement_starts.update(self.byte_parser._find_statements())
[ "def", "_raw_parse", "(", "self", ")", ":", "# Find lines which match an exclusion pattern.", "if", "self", ".", "exclude", ":", "self", ".", "excluded", "=", "self", ".", "lines_matching", "(", "self", ".", "exclude", ")", "# Tokenize, to find excluded suites, to find docstrings, and to find", "# multi-line statements.", "indent", "=", "0", "exclude_indent", "=", "0", "excluding", "=", "False", "prev_toktype", "=", "token", ".", "INDENT", "first_line", "=", "None", "empty", "=", "True", "tokgen", "=", "generate_tokens", "(", "self", ".", "text", ")", "for", "toktype", ",", "ttext", ",", "(", "slineno", ",", "_", ")", ",", "(", "elineno", ",", "_", ")", ",", "ltext", "in", "tokgen", ":", "if", "self", ".", "show_tokens", ":", "# pragma: not covered", "print", "(", "\"%10s %5s %-20r %r\"", "%", "(", "tokenize", ".", "tok_name", ".", "get", "(", "toktype", ",", "toktype", ")", ",", "nice_pair", "(", "(", "slineno", ",", "elineno", ")", ")", ",", "ttext", ",", "ltext", ")", ")", "if", "toktype", "==", "token", ".", "INDENT", ":", "indent", "+=", "1", "elif", "toktype", "==", "token", ".", "DEDENT", ":", "indent", "-=", "1", "elif", "toktype", "==", "token", ".", "NAME", "and", "ttext", "==", "'class'", ":", "# Class definitions look like branches in the byte code, so", "# we need to exclude them. The simplest way is to note the", "# lines with the 'class' keyword.", "self", ".", "classdefs", ".", "add", "(", "slineno", ")", "elif", "toktype", "==", "token", ".", "OP", "and", "ttext", "==", "':'", ":", "if", "not", "excluding", "and", "elineno", "in", "self", ".", "excluded", ":", "# Start excluding a suite. We trigger off of the colon", "# token so that the #pragma comment will be recognized on", "# the same line as the colon.", "exclude_indent", "=", "indent", "excluding", "=", "True", "elif", "toktype", "==", "token", ".", "STRING", "and", "prev_toktype", "==", "token", ".", "INDENT", ":", "# Strings that are first on an indented line are docstrings.", "# (a trick from trace.py in the stdlib.) This works for", "# 99.9999% of cases. For the rest (!) see:", "# http://stackoverflow.com/questions/1769332/x/1769794#1769794", "self", ".", "docstrings", ".", "update", "(", "range", "(", "slineno", ",", "elineno", "+", "1", ")", ")", "elif", "toktype", "==", "token", ".", "NEWLINE", ":", "if", "first_line", "is", "not", "None", "and", "elineno", "!=", "first_line", ":", "# We're at the end of a line, and we've ended on a", "# different line than the first line of the statement,", "# so record a multi-line range.", "for", "l", "in", "range", "(", "first_line", ",", "elineno", "+", "1", ")", ":", "self", ".", "multiline", "[", "l", "]", "=", "first_line", "first_line", "=", "None", "if", "ttext", ".", "strip", "(", ")", "and", "toktype", "!=", "tokenize", ".", "COMMENT", ":", "# A non-whitespace token.", "empty", "=", "False", "if", "first_line", "is", "None", ":", "# The token is not whitespace, and is the first in a", "# statement.", "first_line", "=", "slineno", "# Check whether to end an excluded suite.", "if", "excluding", "and", "indent", "<=", "exclude_indent", ":", "excluding", "=", "False", "if", "excluding", ":", "self", ".", "excluded", ".", "add", "(", "elineno", ")", "prev_toktype", "=", "toktype", "# Find the starts of the executable statements.", "if", "not", "empty", ":", "self", ".", "statement_starts", ".", "update", "(", "self", ".", "byte_parser", ".", "_find_statements", "(", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/parser.py#L91-L165
xiaolonw/caffe-video_triplet
c39ea1ad6e937ccf7deba4510b7e555165abf05f
scripts/cpp_lint.py
python
ReverseCloseExpression
(clean_lines, linenum, pos)
return (line, 0, -1)
If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum.
If input points to ) or } or ] or >, finds the position that opens it.
[ "If", "input", "points", "to", ")", "or", "}", "or", "]", "or", ">", "finds", "the", "position", "that", "opens", "it", "." ]
def ReverseCloseExpression(clean_lines, linenum, pos): """If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] endchar = line[pos] if endchar not in ')}]>': return (line, 0, -1) if endchar == ')': startchar = '(' if endchar == ']': startchar = '[' if endchar == '}': startchar = '{' if endchar == '>': startchar = '<' # Check last line (start_pos, num_open) = FindStartOfExpressionInLine( line, pos, 0, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Continue scanning backward while linenum > 0: linenum -= 1 line = clean_lines.elided[linenum] (start_pos, num_open) = FindStartOfExpressionInLine( line, len(line) - 1, num_open, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Did not find startchar before beginning of file, give up return (line, 0, -1)
[ "def", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "endchar", "=", "line", "[", "pos", "]", "if", "endchar", "not", "in", "')}]>'", ":", "return", "(", "line", ",", "0", ",", "-", "1", ")", "if", "endchar", "==", "')'", ":", "startchar", "=", "'('", "if", "endchar", "==", "']'", ":", "startchar", "=", "'['", "if", "endchar", "==", "'}'", ":", "startchar", "=", "'{'", "if", "endchar", "==", "'>'", ":", "startchar", "=", "'<'", "# Check last line", "(", "start_pos", ",", "num_open", ")", "=", "FindStartOfExpressionInLine", "(", "line", ",", "pos", ",", "0", ",", "startchar", ",", "endchar", ")", "if", "start_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "start_pos", ")", "# Continue scanning backward", "while", "linenum", ">", "0", ":", "linenum", "-=", "1", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "(", "start_pos", ",", "num_open", ")", "=", "FindStartOfExpressionInLine", "(", "line", ",", "len", "(", "line", ")", "-", "1", ",", "num_open", ",", "startchar", ",", "endchar", ")", "if", "start_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "start_pos", ")", "# Did not find startchar before beginning of file, give up", "return", "(", "line", ",", "0", ",", "-", "1", ")" ]
https://github.com/xiaolonw/caffe-video_triplet/blob/c39ea1ad6e937ccf7deba4510b7e555165abf05f/scripts/cpp_lint.py#L1327-L1369
borglab/gtsam
a5bee157efce6a0563704bce6a5d188c29817f39
wrap/gtwrap/interface_parser/namespace.py
python
Namespace.top_level
(self)
Return the top level namespace.
Return the top level namespace.
[ "Return", "the", "top", "level", "namespace", "." ]
def top_level(self) -> "Namespace": """Return the top level namespace.""" if self.name == '' or self.parent == '': return self else: return self.parent.top_level()
[ "def", "top_level", "(", "self", ")", "->", "\"Namespace\"", ":", "if", "self", ".", "name", "==", "''", "or", "self", ".", "parent", "==", "''", ":", "return", "self", "else", ":", "return", "self", ".", "parent", ".", "top_level", "(", ")" ]
https://github.com/borglab/gtsam/blob/a5bee157efce6a0563704bce6a5d188c29817f39/wrap/gtwrap/interface_parser/namespace.py#L117-L122
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PGCell.SetBitmap
(*args, **kwargs)
return _propgrid.PGCell_SetBitmap(*args, **kwargs)
SetBitmap(self, Bitmap bitmap)
SetBitmap(self, Bitmap bitmap)
[ "SetBitmap", "(", "self", "Bitmap", "bitmap", ")" ]
def SetBitmap(*args, **kwargs): """SetBitmap(self, Bitmap bitmap)""" return _propgrid.PGCell_SetBitmap(*args, **kwargs)
[ "def", "SetBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGCell_SetBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L155-L157
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/vi.py
python
TextObject.cut
(self, buffer)
return new_document, clipboard_data
Turn text object into `ClipboardData` instance.
Turn text object into `ClipboardData` instance.
[ "Turn", "text", "object", "into", "ClipboardData", "instance", "." ]
def cut(self, buffer): """ Turn text object into `ClipboardData` instance. """ from_, to = self.operator_range(buffer.document) from_ += buffer.cursor_position to += buffer.cursor_position to -= 1 # SelectionState does not include the end position, `operator_range` does. document = Document(buffer.text, to, SelectionState( original_cursor_position=from_, type=self.selection_type)) new_document, clipboard_data = document.cut_selection() return new_document, clipboard_data
[ "def", "cut", "(", "self", ",", "buffer", ")", ":", "from_", ",", "to", "=", "self", ".", "operator_range", "(", "buffer", ".", "document", ")", "from_", "+=", "buffer", ".", "cursor_position", "to", "+=", "buffer", ".", "cursor_position", "to", "-=", "1", "# SelectionState does not include the end position, `operator_range` does.", "document", "=", "Document", "(", "buffer", ".", "text", ",", "to", ",", "SelectionState", "(", "original_cursor_position", "=", "from_", ",", "type", "=", "self", ".", "selection_type", ")", ")", "new_document", ",", "clipboard_data", "=", "document", ".", "cut_selection", "(", ")", "return", "new_document", ",", "clipboard_data" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/key_binding/bindings/vi.py#L123-L137
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rospy/src/rospy/impl/tcpros_service.py
python
ServiceProxy.__call__
(self, *args, **kwds)
return self.call(*args, **kwds)
Callable-style version of the service API. This accepts either a request message instance, or you can call directly with arguments to create a new request instance. e.g.:: add_two_ints(AddTwoIntsRequest(1, 2)) add_two_ints(1, 2) add_two_ints(a=1, b=2) @param args: arguments to remote service @param kwds: message keyword arguments @raise ROSSerializationException: If unable to serialize message. This is usually a type error with one of the fields.
Callable-style version of the service API. This accepts either a request message instance, or you can call directly with arguments to create a new request instance. e.g.:: add_two_ints(AddTwoIntsRequest(1, 2)) add_two_ints(1, 2) add_two_ints(a=1, b=2)
[ "Callable", "-", "style", "version", "of", "the", "service", "API", ".", "This", "accepts", "either", "a", "request", "message", "instance", "or", "you", "can", "call", "directly", "with", "arguments", "to", "create", "a", "new", "request", "instance", ".", "e", ".", "g", ".", "::", "add_two_ints", "(", "AddTwoIntsRequest", "(", "1", "2", "))", "add_two_ints", "(", "1", "2", ")", "add_two_ints", "(", "a", "=", "1", "b", "=", "2", ")" ]
def __call__(self, *args, **kwds): """ Callable-style version of the service API. This accepts either a request message instance, or you can call directly with arguments to create a new request instance. e.g.:: add_two_ints(AddTwoIntsRequest(1, 2)) add_two_ints(1, 2) add_two_ints(a=1, b=2) @param args: arguments to remote service @param kwds: message keyword arguments @raise ROSSerializationException: If unable to serialize message. This is usually a type error with one of the fields. """ return self.call(*args, **kwds)
[ "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "return", "self", ".", "call", "(", "*", "args", ",", "*", "*", "kwds", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rospy/src/rospy/impl/tcpros_service.py#L422-L436
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/image_ops_impl.py
python
combined_non_max_suppression
(boxes, scores, max_output_size_per_class, max_total_size, iou_threshold=0.5, score_threshold=float('-inf'), pad_per_class=False, clip_boxes=True, name=None)
Greedily selects a subset of bounding boxes in descending order of score. This operation performs non_max_suppression on the inputs per batch, across all classes. Prunes away boxes that have high intersection-over-union (IOU) overlap with previously selected boxes. Bounding boxes are supplied as [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any diagonal pair of box corners and the coordinates can be provided as normalized (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm is agnostic to where the origin is in the coordinate system. Also note that this algorithm is invariant to orthogonal transformations and translations of the coordinate system; thus translating or reflections of the coordinate system result in the same boxes being selected by the algorithm. The output of this operation is the final boxes, scores and classes tensor returned after performing non_max_suppression. Args: boxes: A 4-D float `Tensor` of shape `[batch_size, num_boxes, q, 4]`. If `q` is 1 then same boxes are used for all classes otherwise, if `q` is equal to number of classes, class-specific boxes are used. scores: A 3-D float `Tensor` of shape `[batch_size, num_boxes, num_classes]` representing a single score corresponding to each box (each row of boxes). max_output_size_per_class: A scalar integer `Tensor` representing the maximum number of boxes to be selected by non max suppression per class max_total_size: A scalar representing maximum number of boxes retained over all classes. iou_threshold: A float representing the threshold for deciding whether boxes overlap too much with respect to IOU. score_threshold: A float representing the threshold for deciding when to remove boxes based on score. pad_per_class: If false, the output nmsed boxes, scores and classes are padded/clipped to `max_total_size`. If true, the output nmsed boxes, scores and classes are padded to be of length `max_size_per_class`*`num_classes`, unless it exceeds `max_total_size` in which case it is clipped to `max_total_size`. Defaults to false. clip_boxes: If true, the coordinates of output nmsed boxes will be clipped to [0, 1]. If false, output the box coordinates as it is. Defaults to true. name: A name for the operation (optional). Returns: 'nmsed_boxes': A [batch_size, max_detections, 4] float32 tensor containing the non-max suppressed boxes. 'nmsed_scores': A [batch_size, max_detections] float32 tensor containing the scores for the boxes. 'nmsed_classes': A [batch_size, max_detections] float32 tensor containing the class for boxes. 'valid_detections': A [batch_size] int32 tensor indicating the number of valid detections per batch item. Only the top valid_detections[i] entries in nms_boxes[i], nms_scores[i] and nms_class[i] are valid. The rest of the entries are zero paddings.
Greedily selects a subset of bounding boxes in descending order of score.
[ "Greedily", "selects", "a", "subset", "of", "bounding", "boxes", "in", "descending", "order", "of", "score", "." ]
def combined_non_max_suppression(boxes, scores, max_output_size_per_class, max_total_size, iou_threshold=0.5, score_threshold=float('-inf'), pad_per_class=False, clip_boxes=True, name=None): """Greedily selects a subset of bounding boxes in descending order of score. This operation performs non_max_suppression on the inputs per batch, across all classes. Prunes away boxes that have high intersection-over-union (IOU) overlap with previously selected boxes. Bounding boxes are supplied as [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any diagonal pair of box corners and the coordinates can be provided as normalized (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm is agnostic to where the origin is in the coordinate system. Also note that this algorithm is invariant to orthogonal transformations and translations of the coordinate system; thus translating or reflections of the coordinate system result in the same boxes being selected by the algorithm. The output of this operation is the final boxes, scores and classes tensor returned after performing non_max_suppression. Args: boxes: A 4-D float `Tensor` of shape `[batch_size, num_boxes, q, 4]`. If `q` is 1 then same boxes are used for all classes otherwise, if `q` is equal to number of classes, class-specific boxes are used. scores: A 3-D float `Tensor` of shape `[batch_size, num_boxes, num_classes]` representing a single score corresponding to each box (each row of boxes). max_output_size_per_class: A scalar integer `Tensor` representing the maximum number of boxes to be selected by non max suppression per class max_total_size: A scalar representing maximum number of boxes retained over all classes. iou_threshold: A float representing the threshold for deciding whether boxes overlap too much with respect to IOU. score_threshold: A float representing the threshold for deciding when to remove boxes based on score. pad_per_class: If false, the output nmsed boxes, scores and classes are padded/clipped to `max_total_size`. If true, the output nmsed boxes, scores and classes are padded to be of length `max_size_per_class`*`num_classes`, unless it exceeds `max_total_size` in which case it is clipped to `max_total_size`. Defaults to false. clip_boxes: If true, the coordinates of output nmsed boxes will be clipped to [0, 1]. If false, output the box coordinates as it is. Defaults to true. name: A name for the operation (optional). Returns: 'nmsed_boxes': A [batch_size, max_detections, 4] float32 tensor containing the non-max suppressed boxes. 'nmsed_scores': A [batch_size, max_detections] float32 tensor containing the scores for the boxes. 'nmsed_classes': A [batch_size, max_detections] float32 tensor containing the class for boxes. 'valid_detections': A [batch_size] int32 tensor indicating the number of valid detections per batch item. Only the top valid_detections[i] entries in nms_boxes[i], nms_scores[i] and nms_class[i] are valid. The rest of the entries are zero paddings. """ with ops.name_scope(name, 'combined_non_max_suppression'): iou_threshold = ops.convert_to_tensor( iou_threshold, dtype=dtypes.float32, name='iou_threshold') score_threshold = ops.convert_to_tensor( score_threshold, dtype=dtypes.float32, name='score_threshold') return gen_image_ops.combined_non_max_suppression( boxes, scores, max_output_size_per_class, max_total_size, iou_threshold, score_threshold, pad_per_class, clip_boxes)
[ "def", "combined_non_max_suppression", "(", "boxes", ",", "scores", ",", "max_output_size_per_class", ",", "max_total_size", ",", "iou_threshold", "=", "0.5", ",", "score_threshold", "=", "float", "(", "'-inf'", ")", ",", "pad_per_class", "=", "False", ",", "clip_boxes", "=", "True", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "'combined_non_max_suppression'", ")", ":", "iou_threshold", "=", "ops", ".", "convert_to_tensor", "(", "iou_threshold", ",", "dtype", "=", "dtypes", ".", "float32", ",", "name", "=", "'iou_threshold'", ")", "score_threshold", "=", "ops", ".", "convert_to_tensor", "(", "score_threshold", ",", "dtype", "=", "dtypes", ".", "float32", ",", "name", "=", "'score_threshold'", ")", "return", "gen_image_ops", ".", "combined_non_max_suppression", "(", "boxes", ",", "scores", ",", "max_output_size_per_class", ",", "max_total_size", ",", "iou_threshold", ",", "score_threshold", ",", "pad_per_class", ",", "clip_boxes", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/image_ops_impl.py#L3871-L3939
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/code.py
python
InteractiveInterpreter.__init__
(self, locals=None)
Constructor. The optional 'locals' argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key "__name__" set to "__console__" and key "__doc__" set to None.
Constructor.
[ "Constructor", "." ]
def __init__(self, locals=None): """Constructor. The optional 'locals' argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key "__name__" set to "__console__" and key "__doc__" set to None. """ if locals is None: locals = {"__name__": "__console__", "__doc__": None} self.locals = locals self.compile = CommandCompiler()
[ "def", "__init__", "(", "self", ",", "locals", "=", "None", ")", ":", "if", "locals", "is", "None", ":", "locals", "=", "{", "\"__name__\"", ":", "\"__console__\"", ",", "\"__doc__\"", ":", "None", "}", "self", ".", "locals", "=", "locals", "self", ".", "compile", "=", "CommandCompiler", "(", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/code.py#L37-L49
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/distributions/python/ops/distribution_util.py
python
get_broadcast_shape
(*tensors)
return d_shape
Get broadcast shape as a Python list of integers (preferred) or `Tensor`. Args: *tensors: One or more `Tensor` objects (already converted!). Returns: broadcast shape: Python list (if shapes determined statically), otherwise an `int32` `Tensor`.
Get broadcast shape as a Python list of integers (preferred) or `Tensor`.
[ "Get", "broadcast", "shape", "as", "a", "Python", "list", "of", "integers", "(", "preferred", ")", "or", "Tensor", "." ]
def get_broadcast_shape(*tensors): """Get broadcast shape as a Python list of integers (preferred) or `Tensor`. Args: *tensors: One or more `Tensor` objects (already converted!). Returns: broadcast shape: Python list (if shapes determined statically), otherwise an `int32` `Tensor`. """ # Try static. s_shape = tensors[0].shape for t in tensors[1:]: s_shape = array_ops.broadcast_static_shape(s_shape, t.shape) if s_shape.is_fully_defined(): return s_shape.as_list() # Fallback on dynamic. d_shape = array_ops.shape(tensors[0]) for t in tensors[1:]: d_shape = array_ops.broadcast_dynamic_shape(d_shape, array_ops.shape(t)) return d_shape
[ "def", "get_broadcast_shape", "(", "*", "tensors", ")", ":", "# Try static.", "s_shape", "=", "tensors", "[", "0", "]", ".", "shape", "for", "t", "in", "tensors", "[", "1", ":", "]", ":", "s_shape", "=", "array_ops", ".", "broadcast_static_shape", "(", "s_shape", ",", "t", ".", "shape", ")", "if", "s_shape", ".", "is_fully_defined", "(", ")", ":", "return", "s_shape", ".", "as_list", "(", ")", "# Fallback on dynamic.", "d_shape", "=", "array_ops", ".", "shape", "(", "tensors", "[", "0", "]", ")", "for", "t", "in", "tensors", "[", "1", ":", "]", ":", "d_shape", "=", "array_ops", ".", "broadcast_dynamic_shape", "(", "d_shape", ",", "array_ops", ".", "shape", "(", "t", ")", ")", "return", "d_shape" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/distributions/python/ops/distribution_util.py#L381-L402
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
samples/python/yolov3_onnx/yolov3_to_onnx.py
python
GraphBuilderONNX.build_onnx_graph
( self, layer_configs, weights_file_path, verbose=True)
return model_def
Iterate over all layer configs (parsed from the DarkNet representation of YOLOv3-608), create an ONNX graph, populate it with weights from the weights file and return the graph definition. Keyword arguments: layer_configs -- an OrderedDict object with all parsed layers' configurations weights_file_path -- location of the weights file verbose -- toggles if the graph is printed after creation (default: True)
Iterate over all layer configs (parsed from the DarkNet representation of YOLOv3-608), create an ONNX graph, populate it with weights from the weights file and return the graph definition.
[ "Iterate", "over", "all", "layer", "configs", "(", "parsed", "from", "the", "DarkNet", "representation", "of", "YOLOv3", "-", "608", ")", "create", "an", "ONNX", "graph", "populate", "it", "with", "weights", "from", "the", "weights", "file", "and", "return", "the", "graph", "definition", "." ]
def build_onnx_graph( self, layer_configs, weights_file_path, verbose=True): """Iterate over all layer configs (parsed from the DarkNet representation of YOLOv3-608), create an ONNX graph, populate it with weights from the weights file and return the graph definition. Keyword arguments: layer_configs -- an OrderedDict object with all parsed layers' configurations weights_file_path -- location of the weights file verbose -- toggles if the graph is printed after creation (default: True) """ for layer_name in layer_configs.keys(): layer_dict = layer_configs[layer_name] major_node_specs = self._make_onnx_node(layer_name, layer_dict) if major_node_specs.name is not None: self.major_node_specs.append(major_node_specs) outputs = list() for tensor_name in self.output_tensors.keys(): output_dims = [self.batch_size, ] + \ self.output_tensors[tensor_name] output_tensor = helper.make_tensor_value_info( tensor_name, TensorProto.FLOAT, output_dims) outputs.append(output_tensor) inputs = [self.input_tensor] weight_loader = WeightLoader(weights_file_path) initializer = list() # If a layer has parameters, add them to the initializer and input lists. for layer_name in self.param_dict.keys(): _, layer_type = layer_name.split('_', 1) params = self.param_dict[layer_name] if layer_type == 'convolutional': initializer_layer, inputs_layer = weight_loader.load_conv_weights( params) initializer.extend(initializer_layer) inputs.extend(inputs_layer) elif layer_type == "upsample": initializer_layer, inputs_layer = weight_loader.load_resize_scales( params) initializer.extend(initializer_layer) inputs.extend(inputs_layer) del weight_loader self.graph_def = helper.make_graph( nodes=self._nodes, name='YOLOv3-608', inputs=inputs, outputs=outputs, initializer=initializer ) if verbose: print(helper.printable_graph(self.graph_def)) model_def = helper.make_model(self.graph_def, producer_name='NVIDIA TensorRT sample') return model_def
[ "def", "build_onnx_graph", "(", "self", ",", "layer_configs", ",", "weights_file_path", ",", "verbose", "=", "True", ")", ":", "for", "layer_name", "in", "layer_configs", ".", "keys", "(", ")", ":", "layer_dict", "=", "layer_configs", "[", "layer_name", "]", "major_node_specs", "=", "self", ".", "_make_onnx_node", "(", "layer_name", ",", "layer_dict", ")", "if", "major_node_specs", ".", "name", "is", "not", "None", ":", "self", ".", "major_node_specs", ".", "append", "(", "major_node_specs", ")", "outputs", "=", "list", "(", ")", "for", "tensor_name", "in", "self", ".", "output_tensors", ".", "keys", "(", ")", ":", "output_dims", "=", "[", "self", ".", "batch_size", ",", "]", "+", "self", ".", "output_tensors", "[", "tensor_name", "]", "output_tensor", "=", "helper", ".", "make_tensor_value_info", "(", "tensor_name", ",", "TensorProto", ".", "FLOAT", ",", "output_dims", ")", "outputs", ".", "append", "(", "output_tensor", ")", "inputs", "=", "[", "self", ".", "input_tensor", "]", "weight_loader", "=", "WeightLoader", "(", "weights_file_path", ")", "initializer", "=", "list", "(", ")", "# If a layer has parameters, add them to the initializer and input lists.", "for", "layer_name", "in", "self", ".", "param_dict", ".", "keys", "(", ")", ":", "_", ",", "layer_type", "=", "layer_name", ".", "split", "(", "'_'", ",", "1", ")", "params", "=", "self", ".", "param_dict", "[", "layer_name", "]", "if", "layer_type", "==", "'convolutional'", ":", "initializer_layer", ",", "inputs_layer", "=", "weight_loader", ".", "load_conv_weights", "(", "params", ")", "initializer", ".", "extend", "(", "initializer_layer", ")", "inputs", ".", "extend", "(", "inputs_layer", ")", "elif", "layer_type", "==", "\"upsample\"", ":", "initializer_layer", ",", "inputs_layer", "=", "weight_loader", ".", "load_resize_scales", "(", "params", ")", "initializer", ".", "extend", "(", "initializer_layer", ")", "inputs", ".", "extend", "(", "inputs_layer", ")", "del", "weight_loader", "self", ".", "graph_def", "=", "helper", ".", "make_graph", "(", "nodes", "=", "self", ".", "_nodes", ",", "name", "=", "'YOLOv3-608'", ",", "inputs", "=", "inputs", ",", "outputs", "=", "outputs", ",", "initializer", "=", "initializer", ")", "if", "verbose", ":", "print", "(", "helper", ".", "printable_graph", "(", "self", ".", "graph_def", ")", ")", "model_def", "=", "helper", ".", "make_model", "(", "self", ".", "graph_def", ",", "producer_name", "=", "'NVIDIA TensorRT sample'", ")", "return", "model_def" ]
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/samples/python/yolov3_onnx/yolov3_to_onnx.py#L385-L440
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
dom/bindings/Codegen.py
python
CGIncludeGuard.__init__
(self, prefix, child)
|prefix| is the filename without the extension.
|prefix| is the filename without the extension.
[ "|prefix|", "is", "the", "filename", "without", "the", "extension", "." ]
def __init__(self, prefix, child): """|prefix| is the filename without the extension.""" define = 'mozilla_dom_%s_h' % prefix CGWrapper.__init__(self, child, declarePre='#ifndef %s\n#define %s\n\n' % (define, define), declarePost='\n#endif // %s\n' % define)
[ "def", "__init__", "(", "self", ",", "prefix", ",", "child", ")", ":", "define", "=", "'mozilla_dom_%s_h'", "%", "prefix", "CGWrapper", ".", "__init__", "(", "self", ",", "child", ",", "declarePre", "=", "'#ifndef %s\\n#define %s\\n\\n'", "%", "(", "define", ",", "define", ")", ",", "declarePost", "=", "'\\n#endif // %s\\n'", "%", "define", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/Codegen.py#L912-L917
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/paginate.py
python
TokenDecoder._decode
(self, token, encoded_keys)
return token
Find each encoded value and decode it.
Find each encoded value and decode it.
[ "Find", "each", "encoded", "value", "and", "decode", "it", "." ]
def _decode(self, token, encoded_keys): """Find each encoded value and decode it.""" for key in encoded_keys: encoded = self._path_get(token, key) decoded = base64.b64decode(encoded.encode('utf-8')) self._path_set(token, key, decoded) return token
[ "def", "_decode", "(", "self", ",", "token", ",", "encoded_keys", ")", ":", "for", "key", "in", "encoded_keys", ":", "encoded", "=", "self", ".", "_path_get", "(", "token", ",", "key", ")", "decoded", "=", "base64", ".", "b64decode", "(", "encoded", ".", "encode", "(", "'utf-8'", ")", ")", "self", ".", "_path_set", "(", "token", ",", "key", ",", "decoded", ")", "return", "token" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/paginate.py#L138-L144