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
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Import/App/automotive_design.py
python
build_axes
(axis,ref_direction,)
return [d2,normalise(cross_product(d1,d2)).vector.orientation,d1]
:param axis :type axis:direction :param ref_direction :type ref_direction:direction
:param axis :type axis:direction :param ref_direction :type ref_direction:direction
[ ":", "param", "axis", ":", "type", "axis", ":", "direction", ":", "param", "ref_direction", ":", "type", "ref_direction", ":", "direction" ]
def build_axes(axis,ref_direction,): ''' :param axis :type axis:direction :param ref_direction :type ref_direction:direction ''' d1 = NVL(normalise(axis),dummy_gri == direction([0,0,1])) d2 = first_proj_axis(d1,ref_direction) return [d2,normalise(cross_product(d1,d2)).vector.orientation,d1]
[ "def", "build_axes", "(", "axis", ",", "ref_direction", ",", ")", ":", "d1", "=", "NVL", "(", "normalise", "(", "axis", ")", ",", "dummy_gri", "==", "direction", "(", "[", "0", ",", "0", ",", "1", "]", ")", ")", "d2", "=", "first_proj_axis", "(", "d1", ",", "ref_direction", ")", "return", "[", "d2", ",", "normalise", "(", "cross_product", "(", "d1", ",", "d2", ")", ")", ".", "vector", ".", "orientation", ",", "d1", "]" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Import/App/automotive_design.py#L40743-L40752
cocos-creator/engine-native
984c4c9f5838253313b44ccd429bd8fac4ec8a6a
tools/bindings-generator/clang/cindex.py
python
CompileCommand.filename
(self)
return conf.lib.clang_CompileCommand_getFilename(self.cmd)
Get the working filename for this CompileCommand
Get the working filename for this CompileCommand
[ "Get", "the", "working", "filename", "for", "this", "CompileCommand" ]
def filename(self): """Get the working filename for this CompileCommand""" return conf.lib.clang_CompileCommand_getFilename(self.cmd)
[ "def", "filename", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_CompileCommand_getFilename", "(", "self", ".", "cmd", ")" ]
https://github.com/cocos-creator/engine-native/blob/984c4c9f5838253313b44ccd429bd8fac4ec8a6a/tools/bindings-generator/clang/cindex.py#L3184-L3186
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/tpu_values.py
python
TPUVariableMixin._dense_var_to_tensor
(self, dtype=None, name=None, as_ref=False)
Converts a variable to a tensor.
Converts a variable to a tensor.
[ "Converts", "a", "variable", "to", "a", "tensor", "." ]
def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): """Converts a variable to a tensor.""" # pylint: disable=protected-access if tpu_util.enclosing_tpu_context() is None: return super(TPUVariableMixin, self)._dense_var_to_tensor( dtype=dtype, name=name, as_ref=as_ref) # pylint: enable=protected-access elif dtype is not None and dtype != self.dtype: return math_ops.cast(self.read_value(), dtype) else: return self.handle if as_ref else self.read_value()
[ "def", "_dense_var_to_tensor", "(", "self", ",", "dtype", "=", "None", ",", "name", "=", "None", ",", "as_ref", "=", "False", ")", ":", "# pylint: disable=protected-access", "if", "tpu_util", ".", "enclosing_tpu_context", "(", ")", "is", "None", ":", "return", "super", "(", "TPUVariableMixin", ",", "self", ")", ".", "_dense_var_to_tensor", "(", "dtype", "=", "dtype", ",", "name", "=", "name", ",", "as_ref", "=", "as_ref", ")", "# pylint: enable=protected-access", "elif", "dtype", "is", "not", "None", "and", "dtype", "!=", "self", ".", "dtype", ":", "return", "math_ops", ".", "cast", "(", "self", ".", "read_value", "(", ")", ",", "dtype", ")", "else", ":", "return", "self", ".", "handle", "if", "as_ref", "else", "self", ".", "read_value", "(", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/tpu_values.py#L139-L149
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/round_ds.py
python
_round_ds_tbe
()
return
Round TBE register
Round TBE register
[ "Round", "TBE", "register" ]
def _round_ds_tbe(): """Round TBE register""" return
[ "def", "_round_ds_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/round_ds.py#L37-L39
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/mailbox.py
python
Mailbox.keys
(self)
return list(self.iterkeys())
Return a list of keys.
Return a list of keys.
[ "Return", "a", "list", "of", "keys", "." ]
def keys(self): """Return a list of keys.""" return list(self.iterkeys())
[ "def", "keys", "(", "self", ")", ":", "return", "list", "(", "self", ".", "iterkeys", "(", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mailbox.py#L100-L102
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/random_forest.py
python
TensorForestEstimator.predict
( self, x=None, input_fn=None, axis=None, batch_size=None, as_iterable=False)
Returns predictions for given features. Args: x: features. input_fn: Input function. If set, x must be None. axis: Axis on which to argmax (for classification). Last axis is used by default. batch_size: Override default batch size. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). Returns: Numpy array of predicted classes or regression values (or an iterable of predictions if as_iterable is True).
Returns predictions for given features.
[ "Returns", "predictions", "for", "given", "features", "." ]
def predict( self, x=None, input_fn=None, axis=None, batch_size=None, as_iterable=False): """Returns predictions for given features. Args: x: features. input_fn: Input function. If set, x must be None. axis: Axis on which to argmax (for classification). Last axis is used by default. batch_size: Override default batch size. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). Returns: Numpy array of predicted classes or regression values (or an iterable of predictions if as_iterable is True). """ probabilities = self.predict_proba( x=x, input_fn=input_fn, batch_size=batch_size, as_iterable=as_iterable) if self.params.regression: return probabilities else: if as_iterable: return (np.argmax(p, axis=0) for p in probabilities) else: return np.argmax(probabilities, axis=1)
[ "def", "predict", "(", "self", ",", "x", "=", "None", ",", "input_fn", "=", "None", ",", "axis", "=", "None", ",", "batch_size", "=", "None", ",", "as_iterable", "=", "False", ")", ":", "probabilities", "=", "self", ".", "predict_proba", "(", "x", "=", "x", ",", "input_fn", "=", "input_fn", ",", "batch_size", "=", "batch_size", ",", "as_iterable", "=", "as_iterable", ")", "if", "self", ".", "params", ".", "regression", ":", "return", "probabilities", "else", ":", "if", "as_iterable", ":", "return", "(", "np", ".", "argmax", "(", "p", ",", "axis", "=", "0", ")", "for", "p", "in", "probabilities", ")", "else", ":", "return", "np", ".", "argmax", "(", "probabilities", ",", "axis", "=", "1", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/random_forest.py#L125-L153
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/layers/python/layers/feature_column.py
python
embedding_column
(sparse_id_column, dimension, combiner="mean", initializer=None, ckpt_to_load_from=None, tensor_name_in_ckpt=None, max_norm=None, trainable=True)
return _EmbeddingColumn(sparse_id_column, dimension, combiner, initializer, ckpt_to_load_from, tensor_name_in_ckpt, max_norm=max_norm, trainable=trainable)
Creates an `_EmbeddingColumn` for feeding sparse data into a DNN. Args: sparse_id_column: A `_SparseColumn` which is created by for example `sparse_column_with_*` or crossed_column functions. Note that `combiner` defined in `sparse_id_column` is ignored. dimension: An integer specifying dimension of the embedding. combiner: A string specifying how to reduce if there are multiple entries in a single row. Currently "mean", "sqrtn" and "sum" are supported, with "mean" the default. "sqrtn" often achieves good accuracy, in particular with bag-of-words columns. Each of this can be thought as example level normalizations on the column: * "sum": do not normalize * "mean": do l1 normalization * "sqrtn": do l2 normalization For more information: `tf.embedding_lookup_sparse`. initializer: A variable initializer function to be used in embedding variable initialization. If not specified, defaults to `tf.truncated_normal_initializer` with mean 0.0 and standard deviation 1/sqrt(sparse_id_column.length). ckpt_to_load_from: (Optional). String representing checkpoint name/pattern to restore the column weights. Required if `tensor_name_in_ckpt` is not None. tensor_name_in_ckpt: (Optional). Name of the `Tensor` in the provided checkpoint from which to restore the column weights. Required if `ckpt_to_load_from` is not None. max_norm: (Optional). If not None, embedding values are l2-normalized to the value of max_norm. trainable: (Optional). Should the embedding be trainable. Default is True Returns: An `_EmbeddingColumn`.
Creates an `_EmbeddingColumn` for feeding sparse data into a DNN.
[ "Creates", "an", "_EmbeddingColumn", "for", "feeding", "sparse", "data", "into", "a", "DNN", "." ]
def embedding_column(sparse_id_column, dimension, combiner="mean", initializer=None, ckpt_to_load_from=None, tensor_name_in_ckpt=None, max_norm=None, trainable=True): """Creates an `_EmbeddingColumn` for feeding sparse data into a DNN. Args: sparse_id_column: A `_SparseColumn` which is created by for example `sparse_column_with_*` or crossed_column functions. Note that `combiner` defined in `sparse_id_column` is ignored. dimension: An integer specifying dimension of the embedding. combiner: A string specifying how to reduce if there are multiple entries in a single row. Currently "mean", "sqrtn" and "sum" are supported, with "mean" the default. "sqrtn" often achieves good accuracy, in particular with bag-of-words columns. Each of this can be thought as example level normalizations on the column: * "sum": do not normalize * "mean": do l1 normalization * "sqrtn": do l2 normalization For more information: `tf.embedding_lookup_sparse`. initializer: A variable initializer function to be used in embedding variable initialization. If not specified, defaults to `tf.truncated_normal_initializer` with mean 0.0 and standard deviation 1/sqrt(sparse_id_column.length). ckpt_to_load_from: (Optional). String representing checkpoint name/pattern to restore the column weights. Required if `tensor_name_in_ckpt` is not None. tensor_name_in_ckpt: (Optional). Name of the `Tensor` in the provided checkpoint from which to restore the column weights. Required if `ckpt_to_load_from` is not None. max_norm: (Optional). If not None, embedding values are l2-normalized to the value of max_norm. trainable: (Optional). Should the embedding be trainable. Default is True Returns: An `_EmbeddingColumn`. """ return _EmbeddingColumn(sparse_id_column, dimension, combiner, initializer, ckpt_to_load_from, tensor_name_in_ckpt, max_norm=max_norm, trainable=trainable)
[ "def", "embedding_column", "(", "sparse_id_column", ",", "dimension", ",", "combiner", "=", "\"mean\"", ",", "initializer", "=", "None", ",", "ckpt_to_load_from", "=", "None", ",", "tensor_name_in_ckpt", "=", "None", ",", "max_norm", "=", "None", ",", "trainable", "=", "True", ")", ":", "return", "_EmbeddingColumn", "(", "sparse_id_column", ",", "dimension", ",", "combiner", ",", "initializer", ",", "ckpt_to_load_from", ",", "tensor_name_in_ckpt", ",", "max_norm", "=", "max_norm", ",", "trainable", "=", "trainable", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/layers/python/layers/feature_column.py#L1259-L1302
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/vis/backends/qtbackend.py
python
QtGLWindow.setProgram
(self,program)
User will call this to set up the program variable
User will call this to set up the program variable
[ "User", "will", "call", "this", "to", "set", "up", "the", "program", "variable" ]
def setProgram(self,program): """User will call this to set up the program variable""" from ..glprogram import GLProgram assert isinstance(program,GLProgram) print("######### QGLWidget setProgram ###############") if hasattr(program,'name'): self.name = program.name if self.initialized: self.setWindowTitle(program.name) self.program = program program.window = weakref.proxy(self) if hasattr(self,'devicePixelRatio'): program.view.screenDeviceScale = self.devicePixelRatio() else: program.view.screenDeviceScale = 1 if self.initialized: program.initialize() program.reshapefunc(self.width,self.height) def idleCallback(): self.nextIdleEvent = 0 if self.program: self.program.idlefunc() if self.nextIdleEvent == 0: self.idleTimer.start(0) self.idleTimer.timeout.connect(idleCallback) else: self.reshape(program.view.w,program.view.h)
[ "def", "setProgram", "(", "self", ",", "program", ")", ":", "from", ".", ".", "glprogram", "import", "GLProgram", "assert", "isinstance", "(", "program", ",", "GLProgram", ")", "print", "(", "\"######### QGLWidget setProgram ###############\"", ")", "if", "hasattr", "(", "program", ",", "'name'", ")", ":", "self", ".", "name", "=", "program", ".", "name", "if", "self", ".", "initialized", ":", "self", ".", "setWindowTitle", "(", "program", ".", "name", ")", "self", ".", "program", "=", "program", "program", ".", "window", "=", "weakref", ".", "proxy", "(", "self", ")", "if", "hasattr", "(", "self", ",", "'devicePixelRatio'", ")", ":", "program", ".", "view", ".", "screenDeviceScale", "=", "self", ".", "devicePixelRatio", "(", ")", "else", ":", "program", ".", "view", ".", "screenDeviceScale", "=", "1", "if", "self", ".", "initialized", ":", "program", ".", "initialize", "(", ")", "program", ".", "reshapefunc", "(", "self", ".", "width", ",", "self", ".", "height", ")", "def", "idleCallback", "(", ")", ":", "self", ".", "nextIdleEvent", "=", "0", "if", "self", ".", "program", ":", "self", ".", "program", ".", "idlefunc", "(", ")", "if", "self", ".", "nextIdleEvent", "==", "0", ":", "self", ".", "idleTimer", ".", "start", "(", "0", ")", "self", ".", "idleTimer", ".", "timeout", ".", "connect", "(", "idleCallback", ")", "else", ":", "self", ".", "reshape", "(", "program", ".", "view", ".", "w", ",", "program", ".", "view", ".", "h", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/vis/backends/qtbackend.py#L130-L155
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/_pyio.py
python
IOBase.readlines
(self, hint=None)
return lines
Return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.
Return a list of lines from the stream.
[ "Return", "a", "list", "of", "lines", "from", "the", "stream", "." ]
def readlines(self, hint=None): """Return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint. """ if hint is None or hint <= 0: return list(self) n = 0 lines = [] for line in self: lines.append(line) n += len(line) if n >= hint: break return lines
[ "def", "readlines", "(", "self", ",", "hint", "=", "None", ")", ":", "if", "hint", "is", "None", "or", "hint", "<=", "0", ":", "return", "list", "(", "self", ")", "n", "=", "0", "lines", "=", "[", "]", "for", "line", "in", "self", ":", "lines", ".", "append", "(", "line", ")", "n", "+=", "len", "(", "line", ")", "if", "n", ">=", "hint", ":", "break", "return", "lines" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pyio.py#L577-L593
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py
python
transpose
(a, axes=None)
reorder dimensions per tuple axes
reorder dimensions per tuple axes
[ "reorder", "dimensions", "per", "tuple", "axes" ]
def transpose(a, axes=None): "reorder dimensions per tuple axes" m = getmask(a) d = filled(a) if m is nomask: return masked_array(numeric.transpose(d, axes)) else: return masked_array(numeric.transpose(d, axes), mask = numeric.transpose(m, axes))
[ "def", "transpose", "(", "a", ",", "axes", "=", "None", ")", ":", "m", "=", "getmask", "(", "a", ")", "d", "=", "filled", "(", "a", ")", "if", "m", "is", "nomask", ":", "return", "masked_array", "(", "numeric", ".", "transpose", "(", "d", ",", "axes", ")", ")", "else", ":", "return", "masked_array", "(", "numeric", ".", "transpose", "(", "d", ",", "axes", ")", ",", "mask", "=", "numeric", ".", "transpose", "(", "m", ",", "axes", ")", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/oldnumeric/ma.py#L1892-L1900
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/functional/tensor.py
python
full_like
( inp: Union[Tensor, SymbolVar], value: Union[int, float] )
return broadcast_to(x, inp.shape)
r"""Returns a tensor filled with given value with the same shape as input tensor. Args: inp: input tensor. value: target value. Return: output tensor. Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F inp = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3)) out = F.full_like(inp, 2) print(out.numpy()) Outputs: .. testoutput:: [[2 2 2] [2 2 2]]
r"""Returns a tensor filled with given value with the same shape as input tensor.
[ "r", "Returns", "a", "tensor", "filled", "with", "given", "value", "with", "the", "same", "shape", "as", "input", "tensor", "." ]
def full_like( inp: Union[Tensor, SymbolVar], value: Union[int, float] ) -> Union[Tensor, SymbolVar]: r"""Returns a tensor filled with given value with the same shape as input tensor. Args: inp: input tensor. value: target value. Return: output tensor. Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F inp = tensor(np.arange(1, 7, dtype=np.int32).reshape(2,3)) out = F.full_like(inp, 2) print(out.numpy()) Outputs: .. testoutput:: [[2 2 2] [2 2 2]] """ (x,) = Const(value, dtype=inp.dtype, device=inp.device)(inp) if inp.ndim == 0: return x return broadcast_to(x, inp.shape)
[ "def", "full_like", "(", "inp", ":", "Union", "[", "Tensor", ",", "SymbolVar", "]", ",", "value", ":", "Union", "[", "int", ",", "float", "]", ")", "->", "Union", "[", "Tensor", ",", "SymbolVar", "]", ":", "(", "x", ",", ")", "=", "Const", "(", "value", ",", "dtype", "=", "inp", ".", "dtype", ",", "device", "=", "inp", ".", "device", ")", "(", "inp", ")", "if", "inp", ".", "ndim", "==", "0", ":", "return", "x", "return", "broadcast_to", "(", "x", ",", "inp", ".", "shape", ")" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/functional/tensor.py#L288-L323
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBTarget.SetLaunchInfo
(self, *args)
return _lldb.SBTarget_SetLaunchInfo(self, *args)
SetLaunchInfo(self, SBLaunchInfo launch_info)
SetLaunchInfo(self, SBLaunchInfo launch_info)
[ "SetLaunchInfo", "(", "self", "SBLaunchInfo", "launch_info", ")" ]
def SetLaunchInfo(self, *args): """SetLaunchInfo(self, SBLaunchInfo launch_info)""" return _lldb.SBTarget_SetLaunchInfo(self, *args)
[ "def", "SetLaunchInfo", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBTarget_SetLaunchInfo", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L9322-L9324
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
GetCmnNbrs
(*args)
return _snap.GetCmnNbrs(*args)
GetCmnNbrs(PNEANet Graph, int const & NId1, int const & NId2) -> int Parameters: Graph: TPt< TNEANet > const & NId1: int const & NId2: int const & GetCmnNbrs(PNEANet Graph, int const & NId1, int const & NId2, TIntV NbrV) -> int Parameters: Graph: TPt< TNEANet > const & NId1: int const & NId2: int const & NbrV: TIntV &
GetCmnNbrs(PNEANet Graph, int const & NId1, int const & NId2) -> int
[ "GetCmnNbrs", "(", "PNEANet", "Graph", "int", "const", "&", "NId1", "int", "const", "&", "NId2", ")", "-", ">", "int" ]
def GetCmnNbrs(*args): """ GetCmnNbrs(PNEANet Graph, int const & NId1, int const & NId2) -> int Parameters: Graph: TPt< TNEANet > const & NId1: int const & NId2: int const & GetCmnNbrs(PNEANet Graph, int const & NId1, int const & NId2, TIntV NbrV) -> int Parameters: Graph: TPt< TNEANet > const & NId1: int const & NId2: int const & NbrV: TIntV & """ return _snap.GetCmnNbrs(*args)
[ "def", "GetCmnNbrs", "(", "*", "args", ")", ":", "return", "_snap", ".", "GetCmnNbrs", "(", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L25307-L25325
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/lite/python/lite.py
python
QuantizationMode._validate_full_integer_quantization_bias_type
(self)
Validates bias type for full interger quantization.
Validates bias type for full interger quantization.
[ "Validates", "bias", "type", "for", "full", "interger", "quantization", "." ]
def _validate_full_integer_quantization_bias_type(self): """Validates bias type for full interger quantization.""" bias_type = self._full_integer_quantization_bias_type if not bias_type: return if self.activations_type() == _dtypes.float32: raise ValueError( "`full_integer_quantization_bias_type` is only supported for full integer quantization." ) if self.activations_type() == _dtypes.int8 and bias_type != _dtypes.int32: raise ValueError( f"Expected bias type to be `dtypes.int32` for Int8Quant. " f"Current setting bias type: {bias_type}") if self.activations_type( ) == _dtypes.int16 and bias_type != _dtypes.int32 and bias_type != _dtypes.int64: raise ValueError( f"Expected bias type to be `dtypes.int32` or `dtypes.int64` for " f"Int16Quant. Current setting bias type: {bias_type}")
[ "def", "_validate_full_integer_quantization_bias_type", "(", "self", ")", ":", "bias_type", "=", "self", ".", "_full_integer_quantization_bias_type", "if", "not", "bias_type", ":", "return", "if", "self", ".", "activations_type", "(", ")", "==", "_dtypes", ".", "float32", ":", "raise", "ValueError", "(", "\"`full_integer_quantization_bias_type` is only supported for full integer quantization.\"", ")", "if", "self", ".", "activations_type", "(", ")", "==", "_dtypes", ".", "int8", "and", "bias_type", "!=", "_dtypes", ".", "int32", ":", "raise", "ValueError", "(", "f\"Expected bias type to be `dtypes.int32` for Int8Quant. \"", "f\"Current setting bias type: {bias_type}\"", ")", "if", "self", ".", "activations_type", "(", ")", "==", "_dtypes", ".", "int16", "and", "bias_type", "!=", "_dtypes", ".", "int32", "and", "bias_type", "!=", "_dtypes", ".", "int64", ":", "raise", "ValueError", "(", "f\"Expected bias type to be `dtypes.int32` or `dtypes.int64` for \"", "f\"Int16Quant. Current setting bias type: {bias_type}\"", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/lite/python/lite.py#L442-L462
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/base.py
python
TensorFlowEstimator.predict
(self, x, axis=1, batch_size=None)
return self._predict(x, axis=axis, batch_size=batch_size)
Predict class or regression for `x`. For a classification model, the predicted class for each sample in `x` is returned. For a regression model, the predicted value based on `x` is returned. Args: x: array-like matrix, [n_samples, n_features...] or iterator. axis: Which axis to argmax for classification. By default axis 1 (next after batch) is used. Use 2 for sequence predictions. batch_size: If test set is too big, use batch size to split it into mini batches. By default the batch_size member variable is used. Returns: y: array of shape [n_samples]. The predicted classes or predicted value.
Predict class or regression for `x`.
[ "Predict", "class", "or", "regression", "for", "x", "." ]
def predict(self, x, axis=1, batch_size=None): """Predict class or regression for `x`. For a classification model, the predicted class for each sample in `x` is returned. For a regression model, the predicted value based on `x` is returned. Args: x: array-like matrix, [n_samples, n_features...] or iterator. axis: Which axis to argmax for classification. By default axis 1 (next after batch) is used. Use 2 for sequence predictions. batch_size: If test set is too big, use batch size to split it into mini batches. By default the batch_size member variable is used. Returns: y: array of shape [n_samples]. The predicted classes or predicted value. """ return self._predict(x, axis=axis, batch_size=batch_size)
[ "def", "predict", "(", "self", ",", "x", ",", "axis", "=", "1", ",", "batch_size", "=", "None", ")", ":", "return", "self", ".", "_predict", "(", "x", ",", "axis", "=", "axis", ",", "batch_size", "=", "batch_size", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/base.py#L224-L243
fengbingchun/NN_Test
d6305825d5273e4569ccd1eda9ffa2a9c72e18d2
src/tiny-dnn/third_party/cpplint.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/fengbingchun/NN_Test/blob/d6305825d5273e4569ccd1eda9ffa2a9c72e18d2/src/tiny-dnn/third_party/cpplint.py#L1240-L1242
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/signal/signaltools.py
python
_inputs_swap_needed
(mode, shape1, shape2)
return False
If in 'valid' mode, returns whether or not the input arrays need to be swapped depending on whether `shape1` is at least as large as `shape2` in every dimension. This is important for some of the correlation and convolution implementations in this module, where the larger array input needs to come before the smaller array input when operating in this mode. Note that if the mode provided is not 'valid', False is immediately returned.
If in 'valid' mode, returns whether or not the input arrays need to be swapped depending on whether `shape1` is at least as large as `shape2` in every dimension.
[ "If", "in", "valid", "mode", "returns", "whether", "or", "not", "the", "input", "arrays", "need", "to", "be", "swapped", "depending", "on", "whether", "shape1", "is", "at", "least", "as", "large", "as", "shape2", "in", "every", "dimension", "." ]
def _inputs_swap_needed(mode, shape1, shape2): """ If in 'valid' mode, returns whether or not the input arrays need to be swapped depending on whether `shape1` is at least as large as `shape2` in every dimension. This is important for some of the correlation and convolution implementations in this module, where the larger array input needs to come before the smaller array input when operating in this mode. Note that if the mode provided is not 'valid', False is immediately returned. """ if mode == 'valid': ok1, ok2 = True, True for d1, d2 in zip(shape1, shape2): if not d1 >= d2: ok1 = False if not d2 >= d1: ok2 = False if not (ok1 or ok2): raise ValueError("For 'valid' mode, one must be at least " "as large as the other in every dimension") return not ok1 return False
[ "def", "_inputs_swap_needed", "(", "mode", ",", "shape1", ",", "shape2", ")", ":", "if", "mode", "==", "'valid'", ":", "ok1", ",", "ok2", "=", "True", ",", "True", "for", "d1", ",", "d2", "in", "zip", "(", "shape1", ",", "shape2", ")", ":", "if", "not", "d1", ">=", "d2", ":", "ok1", "=", "False", "if", "not", "d2", ">=", "d1", ":", "ok2", "=", "False", "if", "not", "(", "ok1", "or", "ok2", ")", ":", "raise", "ValueError", "(", "\"For 'valid' mode, one must be at least \"", "\"as large as the other in every dimension\"", ")", "return", "not", "ok1", "return", "False" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/signal/signaltools.py#L74-L102
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/pg_autoscaler/module.py
python
PgAutoscaler._calc_final_pg_target
( self, p: Dict[str, Any], pool_name: str, root_map: Dict[int, CrushSubtreeResourceStatus], root_id: int, capacity_ratio: float, bias: float, even_pools: Dict[str, Dict[str, Any]], bulk_pools: Dict[str, Dict[str, Any]], func_pass: 'PassT', bulk: bool, )
return final_ratio, pool_pg_target, final_pg_target
`profile` determines behaviour of the autoscaler. `first_pass` flag used to determine if this is the first pass where the caller tries to calculate/adjust pools that has used_ratio > even_ratio else this is the second pass, we calculate final_ratio by giving it 1 / pool_count of the root we are currently looking at.
`profile` determines behaviour of the autoscaler. `first_pass` flag used to determine if this is the first pass where the caller tries to calculate/adjust pools that has used_ratio > even_ratio else this is the second pass, we calculate final_ratio by giving it 1 / pool_count of the root we are currently looking at.
[ "profile", "determines", "behaviour", "of", "the", "autoscaler", ".", "first_pass", "flag", "used", "to", "determine", "if", "this", "is", "the", "first", "pass", "where", "the", "caller", "tries", "to", "calculate", "/", "adjust", "pools", "that", "has", "used_ratio", ">", "even_ratio", "else", "this", "is", "the", "second", "pass", "we", "calculate", "final_ratio", "by", "giving", "it", "1", "/", "pool_count", "of", "the", "root", "we", "are", "currently", "looking", "at", "." ]
def _calc_final_pg_target( self, p: Dict[str, Any], pool_name: str, root_map: Dict[int, CrushSubtreeResourceStatus], root_id: int, capacity_ratio: float, bias: float, even_pools: Dict[str, Dict[str, Any]], bulk_pools: Dict[str, Dict[str, Any]], func_pass: 'PassT', bulk: bool, ) -> Union[Tuple[float, int, int], Tuple[None, None, None]]: """ `profile` determines behaviour of the autoscaler. `first_pass` flag used to determine if this is the first pass where the caller tries to calculate/adjust pools that has used_ratio > even_ratio else this is the second pass, we calculate final_ratio by giving it 1 / pool_count of the root we are currently looking at. """ if func_pass == 'first': # first pass to deal with small pools (no bulk flag) # calculating final_pg_target based on capacity ratio # we also keep track of bulk_pools to be used in second pass if not bulk: final_ratio = capacity_ratio pg_left = root_map[root_id].pg_left assert pg_left is not None used_pg = final_ratio * pg_left root_map[root_id].pg_left -= int(used_pg) root_map[root_id].pool_used += 1 pool_pg_target = used_pg / p['size'] * bias else: bulk_pools[pool_name] = p return None, None, None elif func_pass == 'second': # second pass we calculate the final_pg_target # for pools that have used_ratio > even_ratio # and we keep track of even pools to be used in third pass pool_count = root_map[root_id].pool_count assert pool_count is not None even_ratio = 1 / (pool_count - root_map[root_id].pool_used) used_ratio = capacity_ratio if used_ratio > even_ratio: root_map[root_id].pool_used += 1 else: even_pools[pool_name] = p return None, None, None final_ratio = max(used_ratio, even_ratio) pg_left = root_map[root_id].pg_left assert pg_left is not None used_pg = final_ratio * pg_left root_map[root_id].pg_left -= int(used_pg) pool_pg_target = used_pg / p['size'] * bias else: # third pass we just split the pg_left to all even_pools pool_count = root_map[root_id].pool_count assert pool_count is not None final_ratio = 1 / (pool_count - root_map[root_id].pool_used) pool_pg_target = (final_ratio * root_map[root_id].pg_left) / p['size'] * bias min_pg = p.get('options', {}).get('pg_num_min', PG_NUM_MIN) max_pg = p.get('options', {}).get('pg_num_max') final_pg_target = max(min_pg, nearest_power_of_two(pool_pg_target)) if max_pg and max_pg < final_pg_target: final_pg_target = max_pg self.log.info("Pool '{0}' root_id {1} using {2} of space, bias {3}, " "pg target {4} quantized to {5} (current {6})".format( p['pool_name'], root_id, capacity_ratio, bias, pool_pg_target, final_pg_target, p['pg_num_target'] )) return final_ratio, pool_pg_target, final_pg_target
[ "def", "_calc_final_pg_target", "(", "self", ",", "p", ":", "Dict", "[", "str", ",", "Any", "]", ",", "pool_name", ":", "str", ",", "root_map", ":", "Dict", "[", "int", ",", "CrushSubtreeResourceStatus", "]", ",", "root_id", ":", "int", ",", "capacity_ratio", ":", "float", ",", "bias", ":", "float", ",", "even_pools", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ",", "bulk_pools", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ",", "func_pass", ":", "'PassT'", ",", "bulk", ":", "bool", ",", ")", "->", "Union", "[", "Tuple", "[", "float", ",", "int", ",", "int", "]", ",", "Tuple", "[", "None", ",", "None", ",", "None", "]", "]", ":", "if", "func_pass", "==", "'first'", ":", "# first pass to deal with small pools (no bulk flag)", "# calculating final_pg_target based on capacity ratio", "# we also keep track of bulk_pools to be used in second pass", "if", "not", "bulk", ":", "final_ratio", "=", "capacity_ratio", "pg_left", "=", "root_map", "[", "root_id", "]", ".", "pg_left", "assert", "pg_left", "is", "not", "None", "used_pg", "=", "final_ratio", "*", "pg_left", "root_map", "[", "root_id", "]", ".", "pg_left", "-=", "int", "(", "used_pg", ")", "root_map", "[", "root_id", "]", ".", "pool_used", "+=", "1", "pool_pg_target", "=", "used_pg", "/", "p", "[", "'size'", "]", "*", "bias", "else", ":", "bulk_pools", "[", "pool_name", "]", "=", "p", "return", "None", ",", "None", ",", "None", "elif", "func_pass", "==", "'second'", ":", "# second pass we calculate the final_pg_target", "# for pools that have used_ratio > even_ratio", "# and we keep track of even pools to be used in third pass", "pool_count", "=", "root_map", "[", "root_id", "]", ".", "pool_count", "assert", "pool_count", "is", "not", "None", "even_ratio", "=", "1", "/", "(", "pool_count", "-", "root_map", "[", "root_id", "]", ".", "pool_used", ")", "used_ratio", "=", "capacity_ratio", "if", "used_ratio", ">", "even_ratio", ":", "root_map", "[", "root_id", "]", ".", "pool_used", "+=", "1", "else", ":", "even_pools", "[", "pool_name", "]", "=", "p", "return", "None", ",", "None", ",", "None", "final_ratio", "=", "max", "(", "used_ratio", ",", "even_ratio", ")", "pg_left", "=", "root_map", "[", "root_id", "]", ".", "pg_left", "assert", "pg_left", "is", "not", "None", "used_pg", "=", "final_ratio", "*", "pg_left", "root_map", "[", "root_id", "]", ".", "pg_left", "-=", "int", "(", "used_pg", ")", "pool_pg_target", "=", "used_pg", "/", "p", "[", "'size'", "]", "*", "bias", "else", ":", "# third pass we just split the pg_left to all even_pools", "pool_count", "=", "root_map", "[", "root_id", "]", ".", "pool_count", "assert", "pool_count", "is", "not", "None", "final_ratio", "=", "1", "/", "(", "pool_count", "-", "root_map", "[", "root_id", "]", ".", "pool_used", ")", "pool_pg_target", "=", "(", "final_ratio", "*", "root_map", "[", "root_id", "]", ".", "pg_left", ")", "/", "p", "[", "'size'", "]", "*", "bias", "min_pg", "=", "p", ".", "get", "(", "'options'", ",", "{", "}", ")", ".", "get", "(", "'pg_num_min'", ",", "PG_NUM_MIN", ")", "max_pg", "=", "p", ".", "get", "(", "'options'", ",", "{", "}", ")", ".", "get", "(", "'pg_num_max'", ")", "final_pg_target", "=", "max", "(", "min_pg", ",", "nearest_power_of_two", "(", "pool_pg_target", ")", ")", "if", "max_pg", "and", "max_pg", "<", "final_pg_target", ":", "final_pg_target", "=", "max_pg", "self", ".", "log", ".", "info", "(", "\"Pool '{0}' root_id {1} using {2} of space, bias {3}, \"", "\"pg target {4} quantized to {5} (current {6})\"", ".", "format", "(", "p", "[", "'pool_name'", "]", ",", "root_id", ",", "capacity_ratio", ",", "bias", ",", "pool_pg_target", ",", "final_pg_target", ",", "p", "[", "'pg_num_target'", "]", ")", ")", "return", "final_ratio", ",", "pool_pg_target", ",", "final_pg_target" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/pg_autoscaler/module.py#L430-L511
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
kratos/python_scripts/sympy_fe_utilities.py
python
div
(DN,x)
return Matrix( [ simplify(div_x) ])
This method defines the divergence Keyword arguments: DN -- The shape function derivatives x -- The variable to compute the gradient
This method defines the divergence
[ "This", "method", "defines", "the", "divergence" ]
def div(DN,x): """ This method defines the divergence Keyword arguments: DN -- The shape function derivatives x -- The variable to compute the gradient """ if(DN.shape != x.shape): raise Exception("shapes are not compatible") div_x = 0 for i in range(0,DN.shape[0]): for k in range(0,DN.shape[1]): div_x += DN[i,k]*x[i,k] return Matrix( [ simplify(div_x) ])
[ "def", "div", "(", "DN", ",", "x", ")", ":", "if", "(", "DN", ".", "shape", "!=", "x", ".", "shape", ")", ":", "raise", "Exception", "(", "\"shapes are not compatible\"", ")", "div_x", "=", "0", "for", "i", "in", "range", "(", "0", ",", "DN", ".", "shape", "[", "0", "]", ")", ":", "for", "k", "in", "range", "(", "0", ",", "DN", ".", "shape", "[", "1", "]", ")", ":", "div_x", "+=", "DN", "[", "i", ",", "k", "]", "*", "x", "[", "i", ",", "k", "]", "return", "Matrix", "(", "[", "simplify", "(", "div_x", ")", "]", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/kratos/python_scripts/sympy_fe_utilities.py#L181-L196
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/state_ops.py
python
assign_add
(ref, value, use_locking=None, name=None)
return ref.assign_add(value)
Update `ref` by adding `value` to it. This operation outputs "ref" after the update is done. This makes it easier to chain operations that need to use the reset value. Unlike `tf.math.add`, this op does not broadcast. `ref` and `value` must have the same shape. Args: ref: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, `complex128`, `qint8`, `quint8`, `qint32`, `half`. Should be from a `Variable` node. value: A `Tensor`. Must have the same shape and dtype as `ref`. The value to be added to the variable. use_locking: An optional `bool`. Defaults to `False`. If True, the addition will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. name: A name for the operation (optional). Returns: Same as "ref". Returned as a convenience for operations that want to use the new value after the variable has been updated.
Update `ref` by adding `value` to it.
[ "Update", "ref", "by", "adding", "value", "to", "it", "." ]
def assign_add(ref, value, use_locking=None, name=None): """Update `ref` by adding `value` to it. This operation outputs "ref" after the update is done. This makes it easier to chain operations that need to use the reset value. Unlike `tf.math.add`, this op does not broadcast. `ref` and `value` must have the same shape. Args: ref: A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, `complex128`, `qint8`, `quint8`, `qint32`, `half`. Should be from a `Variable` node. value: A `Tensor`. Must have the same shape and dtype as `ref`. The value to be added to the variable. use_locking: An optional `bool`. Defaults to `False`. If True, the addition will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. name: A name for the operation (optional). Returns: Same as "ref". Returned as a convenience for operations that want to use the new value after the variable has been updated. """ if ref.dtype._is_ref_dtype: return gen_state_ops.assign_add( ref, value, use_locking=use_locking, name=name) return ref.assign_add(value)
[ "def", "assign_add", "(", "ref", ",", "value", ",", "use_locking", "=", "None", ",", "name", "=", "None", ")", ":", "if", "ref", ".", "dtype", ".", "_is_ref_dtype", ":", "return", "gen_state_ops", ".", "assign_add", "(", "ref", ",", "value", ",", "use_locking", "=", "use_locking", ",", "name", "=", "name", ")", "return", "ref", ".", "assign_add", "(", "value", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/state_ops.py#L168-L195
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/vision/transforms/functional.py
python
adjust_brightness
(img, brightness_factor)
Adjusts brightness of an Image. Args: img (PIL.Image|np.array): Image to be adjusted. brightness_factor (float): How much to adjust the brightness. Can be any non negative number. 0 gives a black image, 1 gives the original image while 2 increases the brightness by a factor of 2. Returns: PIL.Image or np.array: Brightness adjusted image. Examples: .. code-block:: python import numpy as np from PIL import Image from paddle.vision.transforms import functional as F fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') fake_img = Image.fromarray(fake_img) converted_img = F.adjust_brightness(fake_img, 0.4) print(converted_img.size)
Adjusts brightness of an Image.
[ "Adjusts", "brightness", "of", "an", "Image", "." ]
def adjust_brightness(img, brightness_factor): """Adjusts brightness of an Image. Args: img (PIL.Image|np.array): Image to be adjusted. brightness_factor (float): How much to adjust the brightness. Can be any non negative number. 0 gives a black image, 1 gives the original image while 2 increases the brightness by a factor of 2. Returns: PIL.Image or np.array: Brightness adjusted image. Examples: .. code-block:: python import numpy as np from PIL import Image from paddle.vision.transforms import functional as F fake_img = (np.random.rand(256, 300, 3) * 255.).astype('uint8') fake_img = Image.fromarray(fake_img) converted_img = F.adjust_brightness(fake_img, 0.4) print(converted_img.size) """ if not (_is_pil_image(img) or _is_numpy_image(img)): raise TypeError( 'img should be PIL Image or ndarray with dim=[2 or 3]. Got {}'. format(type(img))) if _is_pil_image(img): return F_pil.adjust_brightness(img, brightness_factor) else: return F_cv2.adjust_brightness(img, brightness_factor)
[ "def", "adjust_brightness", "(", "img", ",", "brightness_factor", ")", ":", "if", "not", "(", "_is_pil_image", "(", "img", ")", "or", "_is_numpy_image", "(", "img", ")", ")", ":", "raise", "TypeError", "(", "'img should be PIL Image or ndarray with dim=[2 or 3]. Got {}'", ".", "format", "(", "type", "(", "img", ")", ")", ")", "if", "_is_pil_image", "(", "img", ")", ":", "return", "F_pil", ".", "adjust_brightness", "(", "img", ",", "brightness_factor", ")", "else", ":", "return", "F_cv2", ".", "adjust_brightness", "(", "img", ",", "brightness_factor", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/vision/transforms/functional.py#L367-L401
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/metrics/python/ops/metric_ops.py
python
streaming_covariance
(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None)
return covariance, update_op
Computes the unbiased sample covariance between `predictions` and `labels`. The `streaming_covariance` function creates four local variables, `comoment`, `mean_prediction`, `mean_label`, and `count`, which are used to compute the sample covariance between predictions and labels across multiple batches of data. The covariance is ultimately returned as an idempotent operation that simply divides `comoment` by `count` - 1. We use `count` - 1 in order to get an unbiased estimate. The algorithm used for this online computation is described in https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance. Specifically, the formula used to combine two sample comoments is `C_AB = C_A + C_B + (E[x_A] - E[x_B]) * (E[y_A] - E[y_B]) * n_A * n_B / n_AB` The comoment for a single batch of data is simply `sum((x - E[x]) * (y - E[y]))`, optionally weighted. If `weights` is not None, then it is used to compute weighted comoments, means, and count. NOTE: these weights are treated as "frequency weights", as opposed to "reliability weights". See discussion of the difference on https://wikipedia.org/wiki/Weighted_arithmetic_mean#Weighted_sample_variance To facilitate the computation of covariance across multiple batches of data, the function creates an `update_op` operation, which updates underlying variables and returns the updated covariance. Args: predictions: A `Tensor` of arbitrary size. labels: A `Tensor` of the same size as `predictions`. weights: An optional set of weights which indicates the frequency with which an example is sampled. Must be broadcastable with `labels`. metrics_collections: An optional list of collections that the metric value variable should be added to. updates_collections: An optional list of collections that the metric update ops should be added to. name: An optional variable_scope name. Returns: covariance: A `Tensor` representing the current unbiased sample covariance, `comoment` / (`count` - 1). update_op: An operation that updates the local variables appropriately. Raises: ValueError: If labels and predictions are of different sizes or if either `metrics_collections` or `updates_collections` are not a list or tuple.
Computes the unbiased sample covariance between `predictions` and `labels`.
[ "Computes", "the", "unbiased", "sample", "covariance", "between", "predictions", "and", "labels", "." ]
def streaming_covariance(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the unbiased sample covariance between `predictions` and `labels`. The `streaming_covariance` function creates four local variables, `comoment`, `mean_prediction`, `mean_label`, and `count`, which are used to compute the sample covariance between predictions and labels across multiple batches of data. The covariance is ultimately returned as an idempotent operation that simply divides `comoment` by `count` - 1. We use `count` - 1 in order to get an unbiased estimate. The algorithm used for this online computation is described in https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance. Specifically, the formula used to combine two sample comoments is `C_AB = C_A + C_B + (E[x_A] - E[x_B]) * (E[y_A] - E[y_B]) * n_A * n_B / n_AB` The comoment for a single batch of data is simply `sum((x - E[x]) * (y - E[y]))`, optionally weighted. If `weights` is not None, then it is used to compute weighted comoments, means, and count. NOTE: these weights are treated as "frequency weights", as opposed to "reliability weights". See discussion of the difference on https://wikipedia.org/wiki/Weighted_arithmetic_mean#Weighted_sample_variance To facilitate the computation of covariance across multiple batches of data, the function creates an `update_op` operation, which updates underlying variables and returns the updated covariance. Args: predictions: A `Tensor` of arbitrary size. labels: A `Tensor` of the same size as `predictions`. weights: An optional set of weights which indicates the frequency with which an example is sampled. Must be broadcastable with `labels`. metrics_collections: An optional list of collections that the metric value variable should be added to. updates_collections: An optional list of collections that the metric update ops should be added to. name: An optional variable_scope name. Returns: covariance: A `Tensor` representing the current unbiased sample covariance, `comoment` / (`count` - 1). update_op: An operation that updates the local variables appropriately. Raises: ValueError: If labels and predictions are of different sizes or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope(name, 'covariance', [predictions, labels]): predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) count = _create_local('count', []) mean_prediction = _create_local('mean_prediction', []) mean_label = _create_local('mean_label', []) comoment = _create_local('comoment', []) # C_A in update equation if weights is None: batch_count = math_ops.to_float(array_ops.size(labels)) # n_B in eqn weighted_predictions = predictions weighted_labels = labels else: batch_count = math_ops.reduce_sum( _broadcast_weights(weights, labels)) # n_B in eqn weighted_predictions = predictions * weights weighted_labels = labels * weights update_count = state_ops.assign_add(count, batch_count) # n_AB in eqn prev_count = update_count - batch_count # n_A in update equation # We update the means by Delta=Error*BatchCount/(BatchCount+PrevCount) # batch_mean_prediction is E[x_B] in the update equation batch_mean_prediction = _safe_div( math_ops.reduce_sum(weighted_predictions), batch_count, 'batch_mean_prediction') delta_mean_prediction = _safe_div( (batch_mean_prediction - mean_prediction) * batch_count, update_count, 'delta_mean_prediction') update_mean_prediction = state_ops.assign_add(mean_prediction, delta_mean_prediction) # prev_mean_prediction is E[x_A] in the update equation prev_mean_prediction = update_mean_prediction - delta_mean_prediction # batch_mean_label is E[y_B] in the update equation batch_mean_label = _safe_div( math_ops.reduce_sum(weighted_labels), batch_count, 'batch_mean_label') delta_mean_label = _safe_div((batch_mean_label - mean_label) * batch_count, update_count, 'delta_mean_label') update_mean_label = state_ops.assign_add(mean_label, delta_mean_label) # prev_mean_label is E[y_A] in the update equation prev_mean_label = update_mean_label - delta_mean_label unweighted_batch_coresiduals = ( (predictions - batch_mean_prediction) * (labels - batch_mean_label)) # batch_comoment is C_B in the update equation if weights is None: batch_comoment = math_ops.reduce_sum(unweighted_batch_coresiduals) else: batch_comoment = math_ops.reduce_sum(unweighted_batch_coresiduals * weights) # View delta_comoment as = C_AB - C_A in the update equation above. # Since C_A is stored in a var, by how much do we need to increment that var # to make the var = C_AB? delta_comoment = (batch_comoment + (prev_mean_prediction - batch_mean_prediction) * (prev_mean_label - batch_mean_label) * (prev_count * batch_count / update_count)) update_comoment = state_ops.assign_add(comoment, delta_comoment) covariance = _safe_div(comoment, count - 1, 'covariance') with ops.control_dependencies([update_comoment]): update_op = _safe_div(comoment, count - 1, 'update_op') if metrics_collections: ops.add_to_collections(metrics_collections, covariance) if updates_collections: ops.add_to_collections(updates_collections, update_op) return covariance, update_op
[ "def", "streaming_covariance", "(", "predictions", ",", "labels", ",", "weights", "=", "None", ",", "metrics_collections", "=", "None", ",", "updates_collections", "=", "None", ",", "name", "=", "None", ")", ":", "with", "variable_scope", ".", "variable_scope", "(", "name", ",", "'covariance'", ",", "[", "predictions", ",", "labels", "]", ")", ":", "predictions", ",", "labels", "=", "tensor_util", ".", "remove_squeezable_dimensions", "(", "predictions", ",", "labels", ")", "predictions", ".", "get_shape", "(", ")", ".", "assert_is_compatible_with", "(", "labels", ".", "get_shape", "(", ")", ")", "count", "=", "_create_local", "(", "'count'", ",", "[", "]", ")", "mean_prediction", "=", "_create_local", "(", "'mean_prediction'", ",", "[", "]", ")", "mean_label", "=", "_create_local", "(", "'mean_label'", ",", "[", "]", ")", "comoment", "=", "_create_local", "(", "'comoment'", ",", "[", "]", ")", "# C_A in update equation", "if", "weights", "is", "None", ":", "batch_count", "=", "math_ops", ".", "to_float", "(", "array_ops", ".", "size", "(", "labels", ")", ")", "# n_B in eqn", "weighted_predictions", "=", "predictions", "weighted_labels", "=", "labels", "else", ":", "batch_count", "=", "math_ops", ".", "reduce_sum", "(", "_broadcast_weights", "(", "weights", ",", "labels", ")", ")", "# n_B in eqn", "weighted_predictions", "=", "predictions", "*", "weights", "weighted_labels", "=", "labels", "*", "weights", "update_count", "=", "state_ops", ".", "assign_add", "(", "count", ",", "batch_count", ")", "# n_AB in eqn", "prev_count", "=", "update_count", "-", "batch_count", "# n_A in update equation", "# We update the means by Delta=Error*BatchCount/(BatchCount+PrevCount)", "# batch_mean_prediction is E[x_B] in the update equation", "batch_mean_prediction", "=", "_safe_div", "(", "math_ops", ".", "reduce_sum", "(", "weighted_predictions", ")", ",", "batch_count", ",", "'batch_mean_prediction'", ")", "delta_mean_prediction", "=", "_safe_div", "(", "(", "batch_mean_prediction", "-", "mean_prediction", ")", "*", "batch_count", ",", "update_count", ",", "'delta_mean_prediction'", ")", "update_mean_prediction", "=", "state_ops", ".", "assign_add", "(", "mean_prediction", ",", "delta_mean_prediction", ")", "# prev_mean_prediction is E[x_A] in the update equation", "prev_mean_prediction", "=", "update_mean_prediction", "-", "delta_mean_prediction", "# batch_mean_label is E[y_B] in the update equation", "batch_mean_label", "=", "_safe_div", "(", "math_ops", ".", "reduce_sum", "(", "weighted_labels", ")", ",", "batch_count", ",", "'batch_mean_label'", ")", "delta_mean_label", "=", "_safe_div", "(", "(", "batch_mean_label", "-", "mean_label", ")", "*", "batch_count", ",", "update_count", ",", "'delta_mean_label'", ")", "update_mean_label", "=", "state_ops", ".", "assign_add", "(", "mean_label", ",", "delta_mean_label", ")", "# prev_mean_label is E[y_A] in the update equation", "prev_mean_label", "=", "update_mean_label", "-", "delta_mean_label", "unweighted_batch_coresiduals", "=", "(", "(", "predictions", "-", "batch_mean_prediction", ")", "*", "(", "labels", "-", "batch_mean_label", ")", ")", "# batch_comoment is C_B in the update equation", "if", "weights", "is", "None", ":", "batch_comoment", "=", "math_ops", ".", "reduce_sum", "(", "unweighted_batch_coresiduals", ")", "else", ":", "batch_comoment", "=", "math_ops", ".", "reduce_sum", "(", "unweighted_batch_coresiduals", "*", "weights", ")", "# View delta_comoment as = C_AB - C_A in the update equation above.", "# Since C_A is stored in a var, by how much do we need to increment that var", "# to make the var = C_AB?", "delta_comoment", "=", "(", "batch_comoment", "+", "(", "prev_mean_prediction", "-", "batch_mean_prediction", ")", "*", "(", "prev_mean_label", "-", "batch_mean_label", ")", "*", "(", "prev_count", "*", "batch_count", "/", "update_count", ")", ")", "update_comoment", "=", "state_ops", ".", "assign_add", "(", "comoment", ",", "delta_comoment", ")", "covariance", "=", "_safe_div", "(", "comoment", ",", "count", "-", "1", ",", "'covariance'", ")", "with", "ops", ".", "control_dependencies", "(", "[", "update_comoment", "]", ")", ":", "update_op", "=", "_safe_div", "(", "comoment", ",", "count", "-", "1", ",", "'update_op'", ")", "if", "metrics_collections", ":", "ops", ".", "add_to_collections", "(", "metrics_collections", ",", "covariance", ")", "if", "updates_collections", ":", "ops", ".", "add_to_collections", "(", "updates_collections", ",", "update_op", ")", "return", "covariance", ",", "update_op" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/metrics/python/ops/metric_ops.py#L2312-L2435
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/attrs/attr/_funcs.py
python
resolve_types
(cls, globalns=None, localns=None, attribs=None)
return cls
Resolve any strings and forward annotations in type annotations. This is only required if you need concrete types in `Attribute`'s *type* field. In other words, you don't need to resolve your types if you only use them for static type checking. With no arguments, names will be looked up in the module in which the class was created. If this is not what you want, e.g. if the name only exists inside a method, you may pass *globalns* or *localns* to specify other dictionaries in which to look up these names. See the docs of `typing.get_type_hints` for more details. :param type cls: Class to resolve. :param Optional[dict] globalns: Dictionary containing global variables. :param Optional[dict] localns: Dictionary containing local variables. :param Optional[list] attribs: List of attribs for the given class. This is necessary when calling from inside a ``field_transformer`` since *cls* is not an ``attrs`` class yet. :raise TypeError: If *cls* is not a class. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class and you didn't pass any attribs. :raise NameError: If types cannot be resolved because of missing variables. :returns: *cls* so you can use this function also as a class decorator. Please note that you have to apply it **after** `attr.s`. That means the decorator has to come in the line **before** `attr.s`. .. versionadded:: 20.1.0 .. versionadded:: 21.1.0 *attribs*
Resolve any strings and forward annotations in type annotations.
[ "Resolve", "any", "strings", "and", "forward", "annotations", "in", "type", "annotations", "." ]
def resolve_types(cls, globalns=None, localns=None, attribs=None): """ Resolve any strings and forward annotations in type annotations. This is only required if you need concrete types in `Attribute`'s *type* field. In other words, you don't need to resolve your types if you only use them for static type checking. With no arguments, names will be looked up in the module in which the class was created. If this is not what you want, e.g. if the name only exists inside a method, you may pass *globalns* or *localns* to specify other dictionaries in which to look up these names. See the docs of `typing.get_type_hints` for more details. :param type cls: Class to resolve. :param Optional[dict] globalns: Dictionary containing global variables. :param Optional[dict] localns: Dictionary containing local variables. :param Optional[list] attribs: List of attribs for the given class. This is necessary when calling from inside a ``field_transformer`` since *cls* is not an ``attrs`` class yet. :raise TypeError: If *cls* is not a class. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class and you didn't pass any attribs. :raise NameError: If types cannot be resolved because of missing variables. :returns: *cls* so you can use this function also as a class decorator. Please note that you have to apply it **after** `attr.s`. That means the decorator has to come in the line **before** `attr.s`. .. versionadded:: 20.1.0 .. versionadded:: 21.1.0 *attribs* """ try: # Since calling get_type_hints is expensive we cache whether we've # done it already. cls.__attrs_types_resolved__ except AttributeError: import typing hints = typing.get_type_hints(cls, globalns=globalns, localns=localns) for field in fields(cls) if attribs is None else attribs: if field.name in hints: # Since fields have been frozen we must work around it. _obj_setattr(field, "type", hints[field.name]) cls.__attrs_types_resolved__ = True # Return the class so you can use it as a decorator too. return cls
[ "def", "resolve_types", "(", "cls", ",", "globalns", "=", "None", ",", "localns", "=", "None", ",", "attribs", "=", "None", ")", ":", "try", ":", "# Since calling get_type_hints is expensive we cache whether we've", "# done it already.", "cls", ".", "__attrs_types_resolved__", "except", "AttributeError", ":", "import", "typing", "hints", "=", "typing", ".", "get_type_hints", "(", "cls", ",", "globalns", "=", "globalns", ",", "localns", "=", "localns", ")", "for", "field", "in", "fields", "(", "cls", ")", "if", "attribs", "is", "None", "else", "attribs", ":", "if", "field", ".", "name", "in", "hints", ":", "# Since fields have been frozen we must work around it.", "_obj_setattr", "(", "field", ",", "\"type\"", ",", "hints", "[", "field", ".", "name", "]", ")", "cls", ".", "__attrs_types_resolved__", "=", "True", "# Return the class so you can use it as a decorator too.", "return", "cls" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/attrs/attr/_funcs.py#L346-L395
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Action.py
python
_do_create_action
(act, kw)
return None
This is the actual "implementation" for the Action factory method, below. This handles the fact that passing lists to Action() itself has different semantics than passing lists as elements of lists. The former will create a ListAction, the latter will create a CommandAction by converting the inner list elements to strings.
This is the actual "implementation" for the Action factory method, below. This handles the fact that passing lists to Action() itself has different semantics than passing lists as elements of lists.
[ "This", "is", "the", "actual", "implementation", "for", "the", "Action", "factory", "method", "below", ".", "This", "handles", "the", "fact", "that", "passing", "lists", "to", "Action", "()", "itself", "has", "different", "semantics", "than", "passing", "lists", "as", "elements", "of", "lists", "." ]
def _do_create_action(act, kw): """This is the actual "implementation" for the Action factory method, below. This handles the fact that passing lists to Action() itself has different semantics than passing lists as elements of lists. The former will create a ListAction, the latter will create a CommandAction by converting the inner list elements to strings.""" if isinstance(act, ActionBase): return act if is_String(act): var=SCons.Util.get_environment_var(act) if var: # This looks like a string that is purely an Environment # variable reference, like "$FOO" or "${FOO}". We do # something special here...we lazily evaluate the contents # of that Environment variable, so a user could put something # like a function or a CommandGenerator in that variable # instead of a string. return LazyAction(var, kw) commands = str(act).split('\n') if len(commands) == 1: return CommandAction(commands[0], **kw) # The list of string commands may include a LazyAction, so we # reprocess them via _do_create_list_action. return _do_create_list_action(commands, kw) if is_List(act): return CommandAction(act, **kw) if callable(act): try: gen = kw['generator'] del kw['generator'] except KeyError: gen = 0 if gen: action_type = CommandGeneratorAction else: action_type = FunctionAction return action_type(act, kw) # Catch a common error case with a nice message: if isinstance(act, int) or isinstance(act, float): raise TypeError("Don't know how to create an Action from a number (%s)"%act) # Else fail silently (???) return None
[ "def", "_do_create_action", "(", "act", ",", "kw", ")", ":", "if", "isinstance", "(", "act", ",", "ActionBase", ")", ":", "return", "act", "if", "is_String", "(", "act", ")", ":", "var", "=", "SCons", ".", "Util", ".", "get_environment_var", "(", "act", ")", "if", "var", ":", "# This looks like a string that is purely an Environment", "# variable reference, like \"$FOO\" or \"${FOO}\". We do", "# something special here...we lazily evaluate the contents", "# of that Environment variable, so a user could put something", "# like a function or a CommandGenerator in that variable", "# instead of a string.", "return", "LazyAction", "(", "var", ",", "kw", ")", "commands", "=", "str", "(", "act", ")", ".", "split", "(", "'\\n'", ")", "if", "len", "(", "commands", ")", "==", "1", ":", "return", "CommandAction", "(", "commands", "[", "0", "]", ",", "*", "*", "kw", ")", "# The list of string commands may include a LazyAction, so we", "# reprocess them via _do_create_list_action.", "return", "_do_create_list_action", "(", "commands", ",", "kw", ")", "if", "is_List", "(", "act", ")", ":", "return", "CommandAction", "(", "act", ",", "*", "*", "kw", ")", "if", "callable", "(", "act", ")", ":", "try", ":", "gen", "=", "kw", "[", "'generator'", "]", "del", "kw", "[", "'generator'", "]", "except", "KeyError", ":", "gen", "=", "0", "if", "gen", ":", "action_type", "=", "CommandGeneratorAction", "else", ":", "action_type", "=", "FunctionAction", "return", "action_type", "(", "act", ",", "kw", ")", "# Catch a common error case with a nice message:", "if", "isinstance", "(", "act", ",", "int", ")", "or", "isinstance", "(", "act", ",", "float", ")", ":", "raise", "TypeError", "(", "\"Don't know how to create an Action from a number (%s)\"", "%", "act", ")", "# Else fail silently (???)", "return", "None" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Action.py#L441-L491
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/ceph_manager.py
python
CephManager.get_pgids_to_cancel_force
(self, backfill)
return pgids
Return the randomized list of PGs whose recovery/backfill priority is forced
Return the randomized list of PGs whose recovery/backfill priority is forced
[ "Return", "the", "randomized", "list", "of", "PGs", "whose", "recovery", "/", "backfill", "priority", "is", "forced" ]
def get_pgids_to_cancel_force(self, backfill): """ Return the randomized list of PGs whose recovery/backfill priority is forced """ j = self.get_pg_stats(); pgids = [] if backfill: wanted = 'forced_backfill' else: wanted = 'forced_recovery' for pg in j: status = pg['state'].split('+') if wanted in status and random.random() > 0.5: pgids.append(pg['pgid']) return pgids
[ "def", "get_pgids_to_cancel_force", "(", "self", ",", "backfill", ")", ":", "j", "=", "self", ".", "get_pg_stats", "(", ")", "pgids", "=", "[", "]", "if", "backfill", ":", "wanted", "=", "'forced_backfill'", "else", ":", "wanted", "=", "'forced_recovery'", "for", "pg", "in", "j", ":", "status", "=", "pg", "[", "'state'", "]", ".", "split", "(", "'+'", ")", "if", "wanted", "in", "status", "and", "random", ".", "random", "(", ")", ">", "0.5", ":", "pgids", ".", "append", "(", "pg", "[", "'pgid'", "]", ")", "return", "pgids" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/ceph_manager.py#L2376-L2390
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/sonnx.py
python
SingaBackend._create_scatter_elements
(cls, onnx_node, operator, opset_version=_opset_version)
return operator(None, None, axis)
get the ScatterElements from the onnx node Args: onnx_node(OnnxNode): a given onnx node operator (Operator Class): a singa operator class opset_version(int): the opset version Returns: singa operator instance
get the ScatterElements from the onnx node Args: onnx_node(OnnxNode): a given onnx node operator (Operator Class): a singa operator class opset_version(int): the opset version Returns: singa operator instance
[ "get", "the", "ScatterElements", "from", "the", "onnx", "node", "Args", ":", "onnx_node", "(", "OnnxNode", ")", ":", "a", "given", "onnx", "node", "operator", "(", "Operator", "Class", ")", ":", "a", "singa", "operator", "class", "opset_version", "(", "int", ")", ":", "the", "opset", "version", "Returns", ":", "singa", "operator", "instance" ]
def _create_scatter_elements(cls, onnx_node, operator, opset_version=_opset_version): """ get the ScatterElements from the onnx node Args: onnx_node(OnnxNode): a given onnx node operator (Operator Class): a singa operator class opset_version(int): the opset version Returns: singa operator instance """ axis = onnx_node.getattr("axis", 0) onnx_node.set_attr_inputs(onnx_node.inputs[1], 'indices') onnx_node.set_attr_inputs(onnx_node.inputs[2], 'updates') return operator(None, None, axis)
[ "def", "_create_scatter_elements", "(", "cls", ",", "onnx_node", ",", "operator", ",", "opset_version", "=", "_opset_version", ")", ":", "axis", "=", "onnx_node", ".", "getattr", "(", "\"axis\"", ",", "0", ")", "onnx_node", ".", "set_attr_inputs", "(", "onnx_node", ".", "inputs", "[", "1", "]", ",", "'indices'", ")", "onnx_node", ".", "set_attr_inputs", "(", "onnx_node", ".", "inputs", "[", "2", "]", ",", "'updates'", ")", "return", "operator", "(", "None", ",", "None", ",", "axis", ")" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/sonnx.py#L1711-L1727
runtimejs/runtime
0a6e84c30823d35a4548d6634166784260ae7b74
deps/v8/tools/stats-viewer.py
python
StatsViewer.RefreshCounters
(self)
Tear down and rebuild the controls in the main window.
Tear down and rebuild the controls in the main window.
[ "Tear", "down", "and", "rebuild", "the", "controls", "in", "the", "main", "window", "." ]
def RefreshCounters(self): """Tear down and rebuild the controls in the main window.""" counters = self.ComputeCounters() self.RebuildMainWindow(counters)
[ "def", "RefreshCounters", "(", "self", ")", ":", "counters", "=", "self", ".", "ComputeCounters", "(", ")", "self", ".", "RebuildMainWindow", "(", "counters", ")" ]
https://github.com/runtimejs/runtime/blob/0a6e84c30823d35a4548d6634166784260ae7b74/deps/v8/tools/stats-viewer.py#L172-L175
scanner-research/scanner
04a0c4b4196341995985acd729c0788aab823e1c
python/scannerpy/column.py
python
Column.load
(self, ty=None, fn=None, rows=None, workers=16)
Loads the results of a Scanner computation into Python. Kwargs: fn: Optional function to apply to the binary blobs as they are read in. Returns: Generator that yields either a numpy array for frame columns or a binary blob for non-frame columns (optionally processed by the `fn`).
Loads the results of a Scanner computation into Python.
[ "Loads", "the", "results", "of", "a", "Scanner", "computation", "into", "Python", "." ]
def load(self, ty=None, fn=None, rows=None, workers=16): """ Loads the results of a Scanner computation into Python. Kwargs: fn: Optional function to apply to the binary blobs as they are read in. Returns: Generator that yields either a numpy array for frame columns or a binary blob for non-frame columns (optionally processed by the `fn`). """ self._load_meta() # If the column is a video, then dump the requested frames to disk as # PNGs and return the decoded PNGs if (self._descriptor.type == protobufs.Video and self._video_descriptor.codec_type == protobufs.VideoDescriptor.H264): png_table_name = self._sc._png_dump_prefix.format( self._table.name(), self._name) frame = self._sc.io.Input([NamedVideoStream(self._sc, self._table.name())]) enc_input = frame if rows is not None: sampled_frame = self._sc.streams.Gather(frame, indices=[rows]) enc_input = sampled_frame img = self._sc.ops.ImageEncoder(frame=enc_input) output = [NamedStream(self._sc, png_table_name)] output_op = self._sc.io.Output(img, output) self._sc.run(output_op, PerfParams.estimate(), cache_mode=CacheMode.Overwrite, show_progress=False) return output[0].load() elif self._descriptor.type == protobufs.Video: frame_type = self._video_descriptor.frame_type if frame_type == protobufs.U8: dtype = np.uint8 elif frame_type == protobufs.F32: dtype = np.float32 elif frame_type == protobufs.F64: dtype = np.float64 def raw_frame_gen(shape0, shape1, shape2, typ): def parser(bufs): output = np.frombuffer(bufs, dtype=typ) return output.reshape((shape0, shape1, shape2)) return parser parser_fn = raw_frame_gen( self._video_descriptor.height, self._video_descriptor.width, self._video_descriptor.channels, dtype) return self._load(fn=parser_fn, rows=rows, workers=workers) else: # Use a deserialize function if provided. # If not, use a type if provided. # If not, attempt to determine the type from the column's table descriptor. # If that doesn't work, then assume no deserialization function, and return bytes. if fn is None: if ty is None: type_name = self._descriptor.type_name if type_name != "": ty = scannertypes.get_type_info_cpp(type_name) if ty is not None: fn = ty.deserialize return self._load(fn, rows=rows, workers=workers)
[ "def", "load", "(", "self", ",", "ty", "=", "None", ",", "fn", "=", "None", ",", "rows", "=", "None", ",", "workers", "=", "16", ")", ":", "self", ".", "_load_meta", "(", ")", "# If the column is a video, then dump the requested frames to disk as", "# PNGs and return the decoded PNGs", "if", "(", "self", ".", "_descriptor", ".", "type", "==", "protobufs", ".", "Video", "and", "self", ".", "_video_descriptor", ".", "codec_type", "==", "protobufs", ".", "VideoDescriptor", ".", "H264", ")", ":", "png_table_name", "=", "self", ".", "_sc", ".", "_png_dump_prefix", ".", "format", "(", "self", ".", "_table", ".", "name", "(", ")", ",", "self", ".", "_name", ")", "frame", "=", "self", ".", "_sc", ".", "io", ".", "Input", "(", "[", "NamedVideoStream", "(", "self", ".", "_sc", ",", "self", ".", "_table", ".", "name", "(", ")", ")", "]", ")", "enc_input", "=", "frame", "if", "rows", "is", "not", "None", ":", "sampled_frame", "=", "self", ".", "_sc", ".", "streams", ".", "Gather", "(", "frame", ",", "indices", "=", "[", "rows", "]", ")", "enc_input", "=", "sampled_frame", "img", "=", "self", ".", "_sc", ".", "ops", ".", "ImageEncoder", "(", "frame", "=", "enc_input", ")", "output", "=", "[", "NamedStream", "(", "self", ".", "_sc", ",", "png_table_name", ")", "]", "output_op", "=", "self", ".", "_sc", ".", "io", ".", "Output", "(", "img", ",", "output", ")", "self", ".", "_sc", ".", "run", "(", "output_op", ",", "PerfParams", ".", "estimate", "(", ")", ",", "cache_mode", "=", "CacheMode", ".", "Overwrite", ",", "show_progress", "=", "False", ")", "return", "output", "[", "0", "]", ".", "load", "(", ")", "elif", "self", ".", "_descriptor", ".", "type", "==", "protobufs", ".", "Video", ":", "frame_type", "=", "self", ".", "_video_descriptor", ".", "frame_type", "if", "frame_type", "==", "protobufs", ".", "U8", ":", "dtype", "=", "np", ".", "uint8", "elif", "frame_type", "==", "protobufs", ".", "F32", ":", "dtype", "=", "np", ".", "float32", "elif", "frame_type", "==", "protobufs", ".", "F64", ":", "dtype", "=", "np", ".", "float64", "def", "raw_frame_gen", "(", "shape0", ",", "shape1", ",", "shape2", ",", "typ", ")", ":", "def", "parser", "(", "bufs", ")", ":", "output", "=", "np", ".", "frombuffer", "(", "bufs", ",", "dtype", "=", "typ", ")", "return", "output", ".", "reshape", "(", "(", "shape0", ",", "shape1", ",", "shape2", ")", ")", "return", "parser", "parser_fn", "=", "raw_frame_gen", "(", "self", ".", "_video_descriptor", ".", "height", ",", "self", ".", "_video_descriptor", ".", "width", ",", "self", ".", "_video_descriptor", ".", "channels", ",", "dtype", ")", "return", "self", ".", "_load", "(", "fn", "=", "parser_fn", ",", "rows", "=", "rows", ",", "workers", "=", "workers", ")", "else", ":", "# Use a deserialize function if provided.", "# If not, use a type if provided.", "# If not, attempt to determine the type from the column's table descriptor.", "# If that doesn't work, then assume no deserialization function, and return bytes.", "if", "fn", "is", "None", ":", "if", "ty", "is", "None", ":", "type_name", "=", "self", ".", "_descriptor", ".", "type_name", "if", "type_name", "!=", "\"\"", ":", "ty", "=", "scannertypes", ".", "get_type_info_cpp", "(", "type_name", ")", "if", "ty", "is", "not", "None", ":", "fn", "=", "ty", ".", "deserialize", "return", "self", ".", "_load", "(", "fn", ",", "rows", "=", "rows", ",", "workers", "=", "workers", ")" ]
https://github.com/scanner-research/scanner/blob/04a0c4b4196341995985acd729c0788aab823e1c/python/scannerpy/column.py#L214-L281
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/v8/third_party/jinja2/nodes.py
python
Node.set_ctx
(self, ctx)
return self
Reset the context of a node and all child nodes. Per default the parser will all generate nodes that have a 'load' context as it's the most common one. This method is used in the parser to set assignment targets and other nodes to a store context.
Reset the context of a node and all child nodes. Per default the parser will all generate nodes that have a 'load' context as it's the most common one. This method is used in the parser to set assignment targets and other nodes to a store context.
[ "Reset", "the", "context", "of", "a", "node", "and", "all", "child", "nodes", ".", "Per", "default", "the", "parser", "will", "all", "generate", "nodes", "that", "have", "a", "load", "context", "as", "it", "s", "the", "most", "common", "one", ".", "This", "method", "is", "used", "in", "the", "parser", "to", "set", "assignment", "targets", "and", "other", "nodes", "to", "a", "store", "context", "." ]
def set_ctx(self, ctx): """Reset the context of a node and all child nodes. Per default the parser will all generate nodes that have a 'load' context as it's the most common one. This method is used in the parser to set assignment targets and other nodes to a store context. """ todo = deque([self]) while todo: node = todo.popleft() if 'ctx' in node.fields: node.ctx = ctx todo.extend(node.iter_child_nodes()) return self
[ "def", "set_ctx", "(", "self", ",", "ctx", ")", ":", "todo", "=", "deque", "(", "[", "self", "]", ")", "while", "todo", ":", "node", "=", "todo", ".", "popleft", "(", ")", "if", "'ctx'", "in", "node", ".", "fields", ":", "node", ".", "ctx", "=", "ctx", "todo", ".", "extend", "(", "node", ".", "iter_child_nodes", "(", ")", ")", "return", "self" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/nodes.py#L194-L206
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/connection.py
python
EC2Connection.confirm_product_instance
(self, product_code, instance_id, dry_run=False)
return (rs.status, rs.ownerId)
:type dry_run: bool :param dry_run: Set to True if the operation should not actually run.
:type dry_run: bool :param dry_run: Set to True if the operation should not actually run.
[ ":", "type", "dry_run", ":", "bool", ":", "param", "dry_run", ":", "Set", "to", "True", "if", "the", "operation", "should", "not", "actually", "run", "." ]
def confirm_product_instance(self, product_code, instance_id, dry_run=False): """ :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. """ params = {'ProductCode': product_code, 'InstanceId': instance_id} if dry_run: params['DryRun'] = 'true' rs = self.get_object('ConfirmProductInstance', params, ResultSet, verb='POST') return (rs.status, rs.ownerId)
[ "def", "confirm_product_instance", "(", "self", ",", "product_code", ",", "instance_id", ",", "dry_run", "=", "False", ")", ":", "params", "=", "{", "'ProductCode'", ":", "product_code", ",", "'InstanceId'", ":", "instance_id", "}", "if", "dry_run", ":", "params", "[", "'DryRun'", "]", "=", "'true'", "rs", "=", "self", ".", "get_object", "(", "'ConfirmProductInstance'", ",", "params", ",", "ResultSet", ",", "verb", "=", "'POST'", ")", "return", "(", "rs", ".", "status", ",", "rs", ".", "ownerId", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/ec2/connection.py#L1081-L1094
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/ndarray/ndarray.py
python
NDArray.copyto
(self, other)
Copies the value of this array to another array. If ``other`` is a ``NDArray`` object, then ``other.shape`` and ``self.shape`` should be the same. This function copies the value from ``self`` to ``other``. If ``other`` is a context, a new ``NDArray`` will be first created on the target context, and the value of ``self`` is copied. Parameters ---------- other : NDArray or Context The destination array or context. Returns ------- NDArray, CSRNDArray or RowSparseNDArray The copied array. If ``other`` is an ``NDArray``, then the return value and ``other`` will point to the same ``NDArray``. Examples -------- >>> x = mx.nd.ones((2,3)) >>> y = mx.nd.zeros((2,3), mx.gpu(0)) >>> z = x.copyto(y) >>> z is y True >>> y.asnumpy() array([[ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) >>> y.copyto(mx.gpu(0)) <NDArray 2x3 @gpu(0)>
Copies the value of this array to another array.
[ "Copies", "the", "value", "of", "this", "array", "to", "another", "array", "." ]
def copyto(self, other): """Copies the value of this array to another array. If ``other`` is a ``NDArray`` object, then ``other.shape`` and ``self.shape`` should be the same. This function copies the value from ``self`` to ``other``. If ``other`` is a context, a new ``NDArray`` will be first created on the target context, and the value of ``self`` is copied. Parameters ---------- other : NDArray or Context The destination array or context. Returns ------- NDArray, CSRNDArray or RowSparseNDArray The copied array. If ``other`` is an ``NDArray``, then the return value and ``other`` will point to the same ``NDArray``. Examples -------- >>> x = mx.nd.ones((2,3)) >>> y = mx.nd.zeros((2,3), mx.gpu(0)) >>> z = x.copyto(y) >>> z is y True >>> y.asnumpy() array([[ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) >>> y.copyto(mx.gpu(0)) <NDArray 2x3 @gpu(0)> """ if isinstance(other, NDArray): if other.handle is self.handle: warnings.warn('You are attempting to copy an array to itself', RuntimeWarning) return False return _internal._copyto(self, out=other) elif isinstance(other, Context): hret = NDArray(_new_alloc_handle(self.shape, other, True, self.dtype)) return _internal._copyto(self, out=hret) else: raise TypeError('copyto does not support type ' + str(type(other)))
[ "def", "copyto", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "NDArray", ")", ":", "if", "other", ".", "handle", "is", "self", ".", "handle", ":", "warnings", ".", "warn", "(", "'You are attempting to copy an array to itself'", ",", "RuntimeWarning", ")", "return", "False", "return", "_internal", ".", "_copyto", "(", "self", ",", "out", "=", "other", ")", "elif", "isinstance", "(", "other", ",", "Context", ")", ":", "hret", "=", "NDArray", "(", "_new_alloc_handle", "(", "self", ".", "shape", ",", "other", ",", "True", ",", "self", ".", "dtype", ")", ")", "return", "_internal", ".", "_copyto", "(", "self", ",", "out", "=", "hret", ")", "else", ":", "raise", "TypeError", "(", "'copyto does not support type '", "+", "str", "(", "type", "(", "other", ")", ")", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/ndarray/ndarray.py#L2075-L2119
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/gtk/gizmos.py
python
TreeListCtrl.GetMainColumn
(*args, **kwargs)
return _gizmos.TreeListCtrl_GetMainColumn(*args, **kwargs)
GetMainColumn(self) -> size_t
GetMainColumn(self) -> size_t
[ "GetMainColumn", "(", "self", ")", "-", ">", "size_t" ]
def GetMainColumn(*args, **kwargs): """GetMainColumn(self) -> size_t""" return _gizmos.TreeListCtrl_GetMainColumn(*args, **kwargs)
[ "def", "GetMainColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gizmos", ".", "TreeListCtrl_GetMainColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/gtk/gizmos.py#L590-L592
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/multiprocessing/process.py
python
_ParentProcess.join
(self, timeout=None)
Wait until parent process terminates
Wait until parent process terminates
[ "Wait", "until", "parent", "process", "terminates" ]
def join(self, timeout=None): ''' Wait until parent process terminates ''' from multiprocessing.connection import wait wait([self._sentinel], timeout=timeout)
[ "def", "join", "(", "self", ",", "timeout", "=", "None", ")", ":", "from", "multiprocessing", ".", "connection", "import", "wait", "wait", "(", "[", "self", ".", "_sentinel", "]", ",", "timeout", "=", "timeout", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/multiprocessing/process.py#L378-L383
yifita/3PU
9ca4c3dfe4e3ead08c72e98a62e4cf181d5c70e0
code/mixed_data_provider.py
python
Fetcher.rotate_perturbation_point_cloud
(self, batch_data, angle_sigma=0.03, angle_clip=0.09)
return batch_data
Randomly perturb the point clouds by small rotations Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, rotated batch of point clouds
Randomly perturb the point clouds by small rotations Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, rotated batch of point clouds
[ "Randomly", "perturb", "the", "point", "clouds", "by", "small", "rotations", "Input", ":", "BxNx3", "array", "original", "batch", "of", "point", "clouds", "Return", ":", "BxNx3", "array", "rotated", "batch", "of", "point", "clouds" ]
def rotate_perturbation_point_cloud(self, batch_data, angle_sigma=0.03, angle_clip=0.09): """ Randomly perturb the point clouds by small rotations Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, rotated batch of point clouds """ batch_size, num_point, num_channels = batch_data.get_shape().as_list() angles = tf.clip_by_value(tf.random_normal((batch_size, 3))*angle_sigma, -angle_clip, angle_clip) cos_x, cos_y, cos_z = tf.split(tf.cos(angles), 3, axis=-1) # 3*[B, 1] sin_x, sin_y, sin_z = tf.split(tf.sin(angles), 3, axis=-1) # 3*[B, 1] one = tf.ones_like(cos_x, dtype=tf.float32) zero = tf.zeros_like(cos_x, dtype=tf.float32) # [B, 3, 3] Rx = tf.stack( [tf.concat([one, zero, zero], axis=1), tf.concat([zero, cos_x, sin_x], axis=1), tf.concat([zero, -sin_x, cos_x], axis=1)], axis=1) Ry = tf.stack( [tf.concat([cos_y, zero, -sin_y], axis=1), tf.concat([zero, one, zero], axis=1), tf.concat([sin_y, zero, cos_y], axis=1)], axis=1) Rz = tf.stack( [tf.concat([cos_z, sin_z, zero], axis=1), tf.concat([-sin_z, cos_z, zero], axis=1), tf.concat([zero, zero, one], axis=1)], axis=1) if is_2D: rotation_matrix = Rz else: rotation_matrix = tf.matmul(Rz, tf.matmul(Ry, Rx)) if num_channels > 3: batch_data = tf.concat( [tf.matmul(batch_data[:, :, :3], rotation_matrix), tf.matmul(batch_data[:, :, 3:], rotation_matrix), batch_data[:, :, 6:]], axis=-1) else: batch_data = tf.matmul(batch_data, rotation_matrix) return batch_data
[ "def", "rotate_perturbation_point_cloud", "(", "self", ",", "batch_data", ",", "angle_sigma", "=", "0.03", ",", "angle_clip", "=", "0.09", ")", ":", "batch_size", ",", "num_point", ",", "num_channels", "=", "batch_data", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "angles", "=", "tf", ".", "clip_by_value", "(", "tf", ".", "random_normal", "(", "(", "batch_size", ",", "3", ")", ")", "*", "angle_sigma", ",", "-", "angle_clip", ",", "angle_clip", ")", "cos_x", ",", "cos_y", ",", "cos_z", "=", "tf", ".", "split", "(", "tf", ".", "cos", "(", "angles", ")", ",", "3", ",", "axis", "=", "-", "1", ")", "# 3*[B, 1]", "sin_x", ",", "sin_y", ",", "sin_z", "=", "tf", ".", "split", "(", "tf", ".", "sin", "(", "angles", ")", ",", "3", ",", "axis", "=", "-", "1", ")", "# 3*[B, 1]", "one", "=", "tf", ".", "ones_like", "(", "cos_x", ",", "dtype", "=", "tf", ".", "float32", ")", "zero", "=", "tf", ".", "zeros_like", "(", "cos_x", ",", "dtype", "=", "tf", ".", "float32", ")", "# [B, 3, 3]", "Rx", "=", "tf", ".", "stack", "(", "[", "tf", ".", "concat", "(", "[", "one", ",", "zero", ",", "zero", "]", ",", "axis", "=", "1", ")", ",", "tf", ".", "concat", "(", "[", "zero", ",", "cos_x", ",", "sin_x", "]", ",", "axis", "=", "1", ")", ",", "tf", ".", "concat", "(", "[", "zero", ",", "-", "sin_x", ",", "cos_x", "]", ",", "axis", "=", "1", ")", "]", ",", "axis", "=", "1", ")", "Ry", "=", "tf", ".", "stack", "(", "[", "tf", ".", "concat", "(", "[", "cos_y", ",", "zero", ",", "-", "sin_y", "]", ",", "axis", "=", "1", ")", ",", "tf", ".", "concat", "(", "[", "zero", ",", "one", ",", "zero", "]", ",", "axis", "=", "1", ")", ",", "tf", ".", "concat", "(", "[", "sin_y", ",", "zero", ",", "cos_y", "]", ",", "axis", "=", "1", ")", "]", ",", "axis", "=", "1", ")", "Rz", "=", "tf", ".", "stack", "(", "[", "tf", ".", "concat", "(", "[", "cos_z", ",", "sin_z", ",", "zero", "]", ",", "axis", "=", "1", ")", ",", "tf", ".", "concat", "(", "[", "-", "sin_z", ",", "cos_z", ",", "zero", "]", ",", "axis", "=", "1", ")", ",", "tf", ".", "concat", "(", "[", "zero", ",", "zero", ",", "one", "]", ",", "axis", "=", "1", ")", "]", ",", "axis", "=", "1", ")", "if", "is_2D", ":", "rotation_matrix", "=", "Rz", "else", ":", "rotation_matrix", "=", "tf", ".", "matmul", "(", "Rz", ",", "tf", ".", "matmul", "(", "Ry", ",", "Rx", ")", ")", "if", "num_channels", ">", "3", ":", "batch_data", "=", "tf", ".", "concat", "(", "[", "tf", ".", "matmul", "(", "batch_data", "[", ":", ",", ":", ",", ":", "3", "]", ",", "rotation_matrix", ")", ",", "tf", ".", "matmul", "(", "batch_data", "[", ":", ",", ":", ",", "3", ":", "]", ",", "rotation_matrix", ")", ",", "batch_data", "[", ":", ",", ":", ",", "6", ":", "]", "]", ",", "axis", "=", "-", "1", ")", "else", ":", "batch_data", "=", "tf", ".", "matmul", "(", "batch_data", ",", "rotation_matrix", ")", "return", "batch_data" ]
https://github.com/yifita/3PU/blob/9ca4c3dfe4e3ead08c72e98a62e4cf181d5c70e0/code/mixed_data_provider.py#L253-L296
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
driver/python/pysequoiadb/domain.py
python
domain.list_collection_spaces
(self)
return result
List all collection spaces in this domain. Return values: The cursor object of collection spaces. Exceptions: pysequoiadb.error.SDBBaseError
List all collection spaces in this domain.
[ "List", "all", "collection", "spaces", "in", "this", "domain", "." ]
def list_collection_spaces(self): """List all collection spaces in this domain. Return values: The cursor object of collection spaces. Exceptions: pysequoiadb.error.SDBBaseError """ result = cursor() try: rc = sdb.domain_list_cs(self._domain, result._cursor) raise_if_error(rc, "Failed to list collection spaces of %s" % self._domain_name) except: del result raise return result
[ "def", "list_collection_spaces", "(", "self", ")", ":", "result", "=", "cursor", "(", ")", "try", ":", "rc", "=", "sdb", ".", "domain_list_cs", "(", "self", ".", "_domain", ",", "result", ".", "_cursor", ")", "raise_if_error", "(", "rc", ",", "\"Failed to list collection spaces of %s\"", "%", "self", ".", "_domain_name", ")", "except", ":", "del", "result", "raise", "return", "result" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/driver/python/pysequoiadb/domain.py#L92-L108
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/processors.py
python
HighlightMatchingBracketProcessor._get_positions_to_highlight
(self, document: Document)
Return a list of (row, col) tuples that need to be highlighted.
Return a list of (row, col) tuples that need to be highlighted.
[ "Return", "a", "list", "of", "(", "row", "col", ")", "tuples", "that", "need", "to", "be", "highlighted", "." ]
def _get_positions_to_highlight(self, document: Document) -> List[Tuple[int, int]]: """ Return a list of (row, col) tuples that need to be highlighted. """ pos: Optional[int] # Try for the character under the cursor. if document.current_char and document.current_char in self.chars: pos = document.find_matching_bracket_position( start_pos=document.cursor_position - self.max_cursor_distance, end_pos=document.cursor_position + self.max_cursor_distance, ) # Try for the character before the cursor. elif ( document.char_before_cursor and document.char_before_cursor in self._closing_braces and document.char_before_cursor in self.chars ): document = Document(document.text, document.cursor_position - 1) pos = document.find_matching_bracket_position( start_pos=document.cursor_position - self.max_cursor_distance, end_pos=document.cursor_position + self.max_cursor_distance, ) else: pos = None # Return a list of (row, col) tuples that need to be highlighted. if pos: pos += document.cursor_position # pos is relative. row, col = document.translate_index_to_position(pos) return [ (row, col), (document.cursor_position_row, document.cursor_position_col), ] else: return []
[ "def", "_get_positions_to_highlight", "(", "self", ",", "document", ":", "Document", ")", "->", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", ":", "pos", ":", "Optional", "[", "int", "]", "# Try for the character under the cursor.", "if", "document", ".", "current_char", "and", "document", ".", "current_char", "in", "self", ".", "chars", ":", "pos", "=", "document", ".", "find_matching_bracket_position", "(", "start_pos", "=", "document", ".", "cursor_position", "-", "self", ".", "max_cursor_distance", ",", "end_pos", "=", "document", ".", "cursor_position", "+", "self", ".", "max_cursor_distance", ",", ")", "# Try for the character before the cursor.", "elif", "(", "document", ".", "char_before_cursor", "and", "document", ".", "char_before_cursor", "in", "self", ".", "_closing_braces", "and", "document", ".", "char_before_cursor", "in", "self", ".", "chars", ")", ":", "document", "=", "Document", "(", "document", ".", "text", ",", "document", ".", "cursor_position", "-", "1", ")", "pos", "=", "document", ".", "find_matching_bracket_position", "(", "start_pos", "=", "document", ".", "cursor_position", "-", "self", ".", "max_cursor_distance", ",", "end_pos", "=", "document", ".", "cursor_position", "+", "self", ".", "max_cursor_distance", ",", ")", "else", ":", "pos", "=", "None", "# Return a list of (row, col) tuples that need to be highlighted.", "if", "pos", ":", "pos", "+=", "document", ".", "cursor_position", "# pos is relative.", "row", ",", "col", "=", "document", ".", "translate_index_to_position", "(", "pos", ")", "return", "[", "(", "row", ",", "col", ")", ",", "(", "document", ".", "cursor_position_row", ",", "document", ".", "cursor_position_col", ")", ",", "]", "else", ":", "return", "[", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/layout/processors.py#L361-L398
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/py/crust.py
python
Display.__init__
(self, parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.CLIP_CHILDREN | wx.SUNKEN_BORDER, static=False)
Create Display instance.
Create Display instance.
[ "Create", "Display", "instance", "." ]
def __init__(self, parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.CLIP_CHILDREN | wx.SUNKEN_BORDER, static=False): """Create Display instance.""" editwindow.EditWindow.__init__(self, parent, id, pos, size, style) # Configure various defaults and user preferences. self.SetReadOnly(True) self.SetWrapMode(False) if not static: dispatcher.connect(receiver=self.push, signal='Interpreter.push')
[ "def", "__init__", "(", "self", ",", "parent", ",", "id", "=", "-", "1", ",", "pos", "=", "wx", ".", "DefaultPosition", ",", "size", "=", "wx", ".", "DefaultSize", ",", "style", "=", "wx", ".", "CLIP_CHILDREN", "|", "wx", ".", "SUNKEN_BORDER", ",", "static", "=", "False", ")", ":", "editwindow", ".", "EditWindow", ".", "__init__", "(", "self", ",", "parent", ",", "id", ",", "pos", ",", "size", ",", "style", ")", "# Configure various defaults and user preferences.", "self", ".", "SetReadOnly", "(", "True", ")", "self", ".", "SetWrapMode", "(", "False", ")", "if", "not", "static", ":", "dispatcher", ".", "connect", "(", "receiver", "=", "self", ".", "push", ",", "signal", "=", "'Interpreter.push'", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/py/crust.py#L161-L171
wyrover/book-code
7f4883d9030d553bc6bcfa3da685e34789839900
3rdparty/protobuf/python/google/protobuf/internal/python_message.py
python
GeneratedProtocolMessageType.__new__
(cls, name, bases, dictionary)
return new_class
Custom allocation for runtime-generated class types. We override __new__ because this is apparently the only place where we can meaningfully set __slots__ on the class we're creating(?). (The interplay between metaclasses and slots is not very well-documented). Args: name: Name of the class (ignored, but required by the metaclass protocol). bases: Base classes of the class we're constructing. (Should be message.Message). We ignore this field, but it's required by the metaclass protocol dictionary: The class dictionary of the class we're constructing. dictionary[_DESCRIPTOR_KEY] must contain a Descriptor object describing this protocol message type. Returns: Newly-allocated class.
Custom allocation for runtime-generated class types.
[ "Custom", "allocation", "for", "runtime", "-", "generated", "class", "types", "." ]
def __new__(cls, name, bases, dictionary): """Custom allocation for runtime-generated class types. We override __new__ because this is apparently the only place where we can meaningfully set __slots__ on the class we're creating(?). (The interplay between metaclasses and slots is not very well-documented). Args: name: Name of the class (ignored, but required by the metaclass protocol). bases: Base classes of the class we're constructing. (Should be message.Message). We ignore this field, but it's required by the metaclass protocol dictionary: The class dictionary of the class we're constructing. dictionary[_DESCRIPTOR_KEY] must contain a Descriptor object describing this protocol message type. Returns: Newly-allocated class. """ descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY] if descriptor.full_name in well_known_types.WKTBASES: bases += (well_known_types.WKTBASES[descriptor.full_name],) _AddClassAttributesForNestedExtensions(descriptor, dictionary) _AddSlots(descriptor, dictionary) superclass = super(GeneratedProtocolMessageType, cls) new_class = superclass.__new__(cls, name, bases, dictionary) return new_class
[ "def", "__new__", "(", "cls", ",", "name", ",", "bases", ",", "dictionary", ")", ":", "descriptor", "=", "dictionary", "[", "GeneratedProtocolMessageType", ".", "_DESCRIPTOR_KEY", "]", "if", "descriptor", ".", "full_name", "in", "well_known_types", ".", "WKTBASES", ":", "bases", "+=", "(", "well_known_types", ".", "WKTBASES", "[", "descriptor", ".", "full_name", "]", ",", ")", "_AddClassAttributesForNestedExtensions", "(", "descriptor", ",", "dictionary", ")", "_AddSlots", "(", "descriptor", ",", "dictionary", ")", "superclass", "=", "super", "(", "GeneratedProtocolMessageType", ",", "cls", ")", "new_class", "=", "superclass", ".", "__new__", "(", "cls", ",", "name", ",", "bases", ",", "dictionary", ")", "return", "new_class" ]
https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/internal/python_message.py#L112-L141
FEniCS/dolfinx
3dfdf038cccdb70962865b58a63bf29c2e55ec6e
python/dolfinx/fem/assemble.py
python
assemble_matrix_nest
(a: typing.List[typing.List[FormMetaClass]], bcs: typing.List[DirichletBCMetaClass] = [], mat_types=[], diagonal: float = 1.0, coeffs=Coefficients(None, None))
return A
Assemble bilinear forms into matrix
Assemble bilinear forms into matrix
[ "Assemble", "bilinear", "forms", "into", "matrix" ]
def assemble_matrix_nest(a: typing.List[typing.List[FormMetaClass]], bcs: typing.List[DirichletBCMetaClass] = [], mat_types=[], diagonal: float = 1.0, coeffs=Coefficients(None, None)) -> PETSc.Mat: """Assemble bilinear forms into matrix""" A = _cpp.fem.petsc.create_matrix_nest(a, mat_types) assemble_matrix_nest(A, a, bcs, diagonal, coeffs) return A
[ "def", "assemble_matrix_nest", "(", "a", ":", "typing", ".", "List", "[", "typing", ".", "List", "[", "FormMetaClass", "]", "]", ",", "bcs", ":", "typing", ".", "List", "[", "DirichletBCMetaClass", "]", "=", "[", "]", ",", "mat_types", "=", "[", "]", ",", "diagonal", ":", "float", "=", "1.0", ",", "coeffs", "=", "Coefficients", "(", "None", ",", "None", ")", ")", "->", "PETSc", ".", "Mat", ":", "A", "=", "_cpp", ".", "fem", ".", "petsc", ".", "create_matrix_nest", "(", "a", ",", "mat_types", ")", "assemble_matrix_nest", "(", "A", ",", "a", ",", "bcs", ",", "diagonal", ",", "coeffs", ")", "return", "A" ]
https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/python/dolfinx/fem/assemble.py#L287-L294
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
TextEntryBase.GetSelection
(*args, **kwargs)
return _core_.TextEntryBase_GetSelection(*args, **kwargs)
GetSelection() -> (from, to) If the return values from and to are the same, there is no selection.
GetSelection() -> (from, to)
[ "GetSelection", "()", "-", ">", "(", "from", "to", ")" ]
def GetSelection(*args, **kwargs): """ GetSelection() -> (from, to) If the return values from and to are the same, there is no selection. """ return _core_.TextEntryBase_GetSelection(*args, **kwargs)
[ "def", "GetSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "TextEntryBase_GetSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L13311-L13317
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/clang/tools/scan-build-py/libscanbuild/intercept.py
python
is_preload_disabled
(platform)
Library-based interposition will fail silently if SIP is enabled, so this should be detected. You can detect whether SIP is enabled on Darwin by checking whether (1) there is a binary called 'csrutil' in the path and, if so, (2) whether the output of executing 'csrutil status' contains 'System Integrity Protection status: enabled'. Same problem on linux when SELinux is enabled. The status query program 'sestatus' and the output when it's enabled 'SELinux status: enabled'.
Library-based interposition will fail silently if SIP is enabled, so this should be detected. You can detect whether SIP is enabled on Darwin by checking whether (1) there is a binary called 'csrutil' in the path and, if so, (2) whether the output of executing 'csrutil status' contains 'System Integrity Protection status: enabled'.
[ "Library", "-", "based", "interposition", "will", "fail", "silently", "if", "SIP", "is", "enabled", "so", "this", "should", "be", "detected", ".", "You", "can", "detect", "whether", "SIP", "is", "enabled", "on", "Darwin", "by", "checking", "whether", "(", "1", ")", "there", "is", "a", "binary", "called", "csrutil", "in", "the", "path", "and", "if", "so", "(", "2", ")", "whether", "the", "output", "of", "executing", "csrutil", "status", "contains", "System", "Integrity", "Protection", "status", ":", "enabled", "." ]
def is_preload_disabled(platform): """ Library-based interposition will fail silently if SIP is enabled, so this should be detected. You can detect whether SIP is enabled on Darwin by checking whether (1) there is a binary called 'csrutil' in the path and, if so, (2) whether the output of executing 'csrutil status' contains 'System Integrity Protection status: enabled'. Same problem on linux when SELinux is enabled. The status query program 'sestatus' and the output when it's enabled 'SELinux status: enabled'. """ if platform == 'darwin': pattern = re.compile(r'System Integrity Protection status:\s+enabled') command = ['csrutil', 'status'] elif platform in {'linux', 'linux2'}: pattern = re.compile(r'SELinux status:\s+enabled') command = ['sestatus'] else: return False try: lines = subprocess.check_output(command).decode('utf-8') return any((pattern.match(line) for line in lines.splitlines())) except: return False
[ "def", "is_preload_disabled", "(", "platform", ")", ":", "if", "platform", "==", "'darwin'", ":", "pattern", "=", "re", ".", "compile", "(", "r'System Integrity Protection status:\\s+enabled'", ")", "command", "=", "[", "'csrutil'", ",", "'status'", "]", "elif", "platform", "in", "{", "'linux'", ",", "'linux2'", "}", ":", "pattern", "=", "re", ".", "compile", "(", "r'SELinux status:\\s+enabled'", ")", "command", "=", "[", "'sestatus'", "]", "else", ":", "return", "False", "try", ":", "lines", "=", "subprocess", ".", "check_output", "(", "command", ")", ".", "decode", "(", "'utf-8'", ")", "return", "any", "(", "(", "pattern", ".", "match", "(", "line", ")", "for", "line", "in", "lines", ".", "splitlines", "(", ")", ")", ")", "except", ":", "return", "False" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/tools/scan-build-py/libscanbuild/intercept.py#L234-L257
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
TransformPoser.get
(self)
return _robotsim.TransformPoser_get(self)
r""" get(TransformPoser self)
r""" get(TransformPoser self)
[ "r", "get", "(", "TransformPoser", "self", ")" ]
def get(self) -> "void": r""" get(TransformPoser self) """ return _robotsim.TransformPoser_get(self)
[ "def", "get", "(", "self", ")", "->", "\"void\"", ":", "return", "_robotsim", ".", "TransformPoser_get", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L3560-L3566
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/debug/lib/debug_data.py
python
DebugTensorDatum.tensor_name
(self)
return _get_tensor_name(self.node_name, self.output_slot)
Name of the tensor watched by the debug op. Returns: (`str`) `Tensor` name, in the form of `node_name`:`output_slot`
Name of the tensor watched by the debug op.
[ "Name", "of", "the", "tensor", "watched", "by", "the", "debug", "op", "." ]
def tensor_name(self): """Name of the tensor watched by the debug op. Returns: (`str`) `Tensor` name, in the form of `node_name`:`output_slot` """ return _get_tensor_name(self.node_name, self.output_slot)
[ "def", "tensor_name", "(", "self", ")", ":", "return", "_get_tensor_name", "(", "self", ".", "node_name", ",", "self", ".", "output_slot", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/lib/debug_data.py#L414-L421
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/locators.py
python
PyPIRPCLocator.__init__
(self, url, **kwargs)
Initialise an instance. :param url: The URL to use for XML-RPC. :param kwargs: Passed to the superclass constructor.
Initialise an instance.
[ "Initialise", "an", "instance", "." ]
def __init__(self, url, **kwargs): """ Initialise an instance. :param url: The URL to use for XML-RPC. :param kwargs: Passed to the superclass constructor. """ super(PyPIRPCLocator, self).__init__(**kwargs) self.base_url = url self.client = ServerProxy(url, timeout=3.0)
[ "def", "__init__", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "super", "(", "PyPIRPCLocator", ",", "self", ")", ".", "__init__", "(", "*", "*", "kwargs", ")", "self", ".", "base_url", "=", "url", "self", ".", "client", "=", "ServerProxy", "(", "url", ",", "timeout", "=", "3.0", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/locators.py#L377-L386
quarnster/boxeebox-xbmc
7209547d3d247a4082de956f4d9a765086d96985
tools/EventClients/Clients/PS3 Sixaxis Controller/ps3d.py
python
PS3RemoteThread.zeroconf_service_handler
(self, event, service)
return
Zeroconf event handler
Zeroconf event handler
[ "Zeroconf", "event", "handler" ]
def zeroconf_service_handler(self, event, service): """ Zeroconf event handler """ if event == zeroconf.SERVICE_FOUND: # new xbmc service detected self.services.append( service ) elif event == zeroconf.SERVICE_LOST: # xbmc service lost try: # search for the service by name, since IP+port isn't available for s in self.services: # nuke it, if found if service['name'] == s['name']: self.services.remove(s) break except: pass return
[ "def", "zeroconf_service_handler", "(", "self", ",", "event", ",", "service", ")", ":", "if", "event", "==", "zeroconf", ".", "SERVICE_FOUND", ":", "# new xbmc service detected", "self", ".", "services", ".", "append", "(", "service", ")", "elif", "event", "==", "zeroconf", ".", "SERVICE_LOST", ":", "# xbmc service lost", "try", ":", "# search for the service by name, since IP+port isn't available", "for", "s", "in", "self", ".", "services", ":", "# nuke it, if found", "if", "service", "[", "'name'", "]", "==", "s", "[", "'name'", "]", ":", "self", ".", "services", ".", "remove", "(", "s", ")", "break", "except", ":", "pass", "return" ]
https://github.com/quarnster/boxeebox-xbmc/blob/7209547d3d247a4082de956f4d9a765086d96985/tools/EventClients/Clients/PS3 Sixaxis Controller/ps3d.py#L230-L247
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/io/parquet.py
python
ParquetDatasetWriter.__init__
( self, path, partition_cols, index=None, compression=None, statistics="ROWGROUP", )
Write a parquet file or dataset incrementally Parameters ---------- path : str File path or Root Directory path. Will be used as Root Directory path while writing a partitioned dataset. partition_cols : list Column names by which to partition the dataset Columns are partitioned in the order they are given index : bool, default None If ``True``, include the dataframe’s index(es) in the file output. If ``False``, they will not be written to the file. If ``None``, index(es) other than RangeIndex will be saved as columns. compression : {'snappy', None}, default 'snappy' Name of the compression to use. Use ``None`` for no compression. statistics : {'ROWGROUP', 'PAGE', 'NONE'}, default 'ROWGROUP' Level at which column statistics should be included in file. Examples ________ Using a context >>> df1 = cudf.DataFrame({"a": [1, 1, 2, 2, 1], "b": [9, 8, 7, 6, 5]}) >>> df2 = cudf.DataFrame({"a": [1, 3, 3, 1, 3], "b": [4, 3, 2, 1, 0]}) >>> with ParquetDatasetWriter("./dataset", partition_cols=["a"]) as cw: ... cw.write_table(df1) ... cw.write_table(df2) By manually calling ``close()`` >>> cw = ParquetDatasetWriter("./dataset", partition_cols=["a"]) >>> cw.write_table(df1) >>> cw.write_table(df2) >>> cw.close() Both the methods will generate the same directory structure .. code-block:: bash dataset/ a=1 <filename>.parquet a=2 <filename>.parquet a=3 <filename>.parquet
Write a parquet file or dataset incrementally
[ "Write", "a", "parquet", "file", "or", "dataset", "incrementally" ]
def __init__( self, path, partition_cols, index=None, compression=None, statistics="ROWGROUP", ) -> None: """ Write a parquet file or dataset incrementally Parameters ---------- path : str File path or Root Directory path. Will be used as Root Directory path while writing a partitioned dataset. partition_cols : list Column names by which to partition the dataset Columns are partitioned in the order they are given index : bool, default None If ``True``, include the dataframe’s index(es) in the file output. If ``False``, they will not be written to the file. If ``None``, index(es) other than RangeIndex will be saved as columns. compression : {'snappy', None}, default 'snappy' Name of the compression to use. Use ``None`` for no compression. statistics : {'ROWGROUP', 'PAGE', 'NONE'}, default 'ROWGROUP' Level at which column statistics should be included in file. Examples ________ Using a context >>> df1 = cudf.DataFrame({"a": [1, 1, 2, 2, 1], "b": [9, 8, 7, 6, 5]}) >>> df2 = cudf.DataFrame({"a": [1, 3, 3, 1, 3], "b": [4, 3, 2, 1, 0]}) >>> with ParquetDatasetWriter("./dataset", partition_cols=["a"]) as cw: ... cw.write_table(df1) ... cw.write_table(df2) By manually calling ``close()`` >>> cw = ParquetDatasetWriter("./dataset", partition_cols=["a"]) >>> cw.write_table(df1) >>> cw.write_table(df2) >>> cw.close() Both the methods will generate the same directory structure .. code-block:: bash dataset/ a=1 <filename>.parquet a=2 <filename>.parquet a=3 <filename>.parquet """ self.path = path self.common_args = { "index": index, "compression": compression, "statistics": statistics, } self.partition_cols = partition_cols # Collection of `ParquetWriter`s, and the corresponding # partition_col values they're responsible for self._chunked_writers: List[ Tuple[libparquet.ParquetWriter, List[str], str] ] = [] # Map of partition_col values to their ParquetWriter's index # in self._chunked_writers for reverse lookup self.path_cw_map: Dict[str, int] = {} self.filename = None
[ "def", "__init__", "(", "self", ",", "path", ",", "partition_cols", ",", "index", "=", "None", ",", "compression", "=", "None", ",", "statistics", "=", "\"ROWGROUP\"", ",", ")", "->", "None", ":", "self", ".", "path", "=", "path", "self", ".", "common_args", "=", "{", "\"index\"", ":", "index", ",", "\"compression\"", ":", "compression", ",", "\"statistics\"", ":", "statistics", ",", "}", "self", ".", "partition_cols", "=", "partition_cols", "# Collection of `ParquetWriter`s, and the corresponding", "# partition_col values they're responsible for", "self", ".", "_chunked_writers", ":", "List", "[", "Tuple", "[", "libparquet", ".", "ParquetWriter", ",", "List", "[", "str", "]", ",", "str", "]", "]", "=", "[", "]", "# Map of partition_col values to their ParquetWriter's index", "# in self._chunked_writers for reverse lookup", "self", ".", "path_cw_map", ":", "Dict", "[", "str", ",", "int", "]", "=", "{", "}", "self", ".", "filename", "=", "None" ]
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/io/parquet.py#L692-L766
google/shaka-packager
e1b0c7c45431327fd3ce193514a5407d07b39b22
packager/third_party/protobuf/python/google/protobuf/text_format.py
python
Tokenizer.ConsumeIdentifier
(self)
return result
Consumes protocol message field identifier. Returns: Identifier string. Raises: ParseError: If an identifier couldn't be consumed.
Consumes protocol message field identifier.
[ "Consumes", "protocol", "message", "field", "identifier", "." ]
def ConsumeIdentifier(self): """Consumes protocol message field identifier. Returns: Identifier string. Raises: ParseError: If an identifier couldn't be consumed. """ result = self.token if not self._IDENTIFIER.match(result): raise self.ParseError('Expected identifier.') self.NextToken() return result
[ "def", "ConsumeIdentifier", "(", "self", ")", ":", "result", "=", "self", ".", "token", "if", "not", "self", ".", "_IDENTIFIER", ".", "match", "(", "result", ")", ":", "raise", "self", ".", "ParseError", "(", "'Expected identifier.'", ")", "self", ".", "NextToken", "(", ")", "return", "result" ]
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/text_format.py#L1058-L1071
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py
python
_GetOutputFilePathAndTool
(spec, msbuild)
return out_file, vc_tool, msbuild_tool
Returns the path and tool to use for this target. Figures out the path of the file this spec will create and the name of the VC tool that will create it. Arguments: spec: The target dictionary containing the properties of the target. Returns: A triple of (file path, name of the vc tool, name of the msbuild tool)
Returns the path and tool to use for this target.
[ "Returns", "the", "path", "and", "tool", "to", "use", "for", "this", "target", "." ]
def _GetOutputFilePathAndTool(spec, msbuild): """Returns the path and tool to use for this target. Figures out the path of the file this spec will create and the name of the VC tool that will create it. Arguments: spec: The target dictionary containing the properties of the target. Returns: A triple of (file path, name of the vc tool, name of the msbuild tool) """ # Select a name for the output file. out_file = "" vc_tool = "" msbuild_tool = "" output_file_map = { "executable": ("VCLinkerTool", "Link", "$(OutDir)", ".exe"), "shared_library": ("VCLinkerTool", "Link", "$(OutDir)", ".dll"), "loadable_module": ("VCLinkerTool", "Link", "$(OutDir)", ".dll"), "windows_driver": ("VCLinkerTool", "Link", "$(OutDir)", ".sys"), "static_library": ("VCLibrarianTool", "Lib", "$(OutDir)lib\\", ".lib"), } output_file_props = output_file_map.get(spec["type"]) if output_file_props and int(spec.get("msvs_auto_output_file", 1)): vc_tool, msbuild_tool, out_dir, suffix = output_file_props if spec.get("standalone_static_library", 0): out_dir = "$(OutDir)" out_dir = spec.get("product_dir", out_dir) product_extension = spec.get("product_extension") if product_extension: suffix = "." + product_extension elif msbuild: suffix = "$(TargetExt)" prefix = spec.get("product_prefix", "") product_name = spec.get("product_name", "$(ProjectName)") out_file = ntpath.join(out_dir, prefix + product_name + suffix) return out_file, vc_tool, msbuild_tool
[ "def", "_GetOutputFilePathAndTool", "(", "spec", ",", "msbuild", ")", ":", "# Select a name for the output file.", "out_file", "=", "\"\"", "vc_tool", "=", "\"\"", "msbuild_tool", "=", "\"\"", "output_file_map", "=", "{", "\"executable\"", ":", "(", "\"VCLinkerTool\"", ",", "\"Link\"", ",", "\"$(OutDir)\"", ",", "\".exe\"", ")", ",", "\"shared_library\"", ":", "(", "\"VCLinkerTool\"", ",", "\"Link\"", ",", "\"$(OutDir)\"", ",", "\".dll\"", ")", ",", "\"loadable_module\"", ":", "(", "\"VCLinkerTool\"", ",", "\"Link\"", ",", "\"$(OutDir)\"", ",", "\".dll\"", ")", ",", "\"windows_driver\"", ":", "(", "\"VCLinkerTool\"", ",", "\"Link\"", ",", "\"$(OutDir)\"", ",", "\".sys\"", ")", ",", "\"static_library\"", ":", "(", "\"VCLibrarianTool\"", ",", "\"Lib\"", ",", "\"$(OutDir)lib\\\\\"", ",", "\".lib\"", ")", ",", "}", "output_file_props", "=", "output_file_map", ".", "get", "(", "spec", "[", "\"type\"", "]", ")", "if", "output_file_props", "and", "int", "(", "spec", ".", "get", "(", "\"msvs_auto_output_file\"", ",", "1", ")", ")", ":", "vc_tool", ",", "msbuild_tool", ",", "out_dir", ",", "suffix", "=", "output_file_props", "if", "spec", ".", "get", "(", "\"standalone_static_library\"", ",", "0", ")", ":", "out_dir", "=", "\"$(OutDir)\"", "out_dir", "=", "spec", ".", "get", "(", "\"product_dir\"", ",", "out_dir", ")", "product_extension", "=", "spec", ".", "get", "(", "\"product_extension\"", ")", "if", "product_extension", ":", "suffix", "=", "\".\"", "+", "product_extension", "elif", "msbuild", ":", "suffix", "=", "\"$(TargetExt)\"", "prefix", "=", "spec", ".", "get", "(", "\"product_prefix\"", ",", "\"\"", ")", "product_name", "=", "spec", ".", "get", "(", "\"product_name\"", ",", "\"$(ProjectName)\"", ")", "out_file", "=", "ntpath", ".", "join", "(", "out_dir", ",", "prefix", "+", "product_name", "+", "suffix", ")", "return", "out_file", ",", "vc_tool", ",", "msbuild_tool" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L1316-L1352
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/framework/tensor_util.py
python
constant_value
(tensor)
return ret
Returns the constant value of the given tensor, if efficiently calculable. This function attempts to partially evaluate the given tensor, and returns its value as a numpy ndarray if this succeeds. TODO(mrry): Consider whether this function should use a registration mechanism like gradients and ShapeFunctions, so that it is easily extensible. NOTE: If `constant_value(tensor)` returns a non-`None` result, it will no longer be possible to feed a different value for `tensor`. This allows the result of this function to influence the graph that is constructed, and permits static shape optimizations. Args: tensor: The Tensor to be evaluated. Returns: A numpy ndarray containing the constant value of the given `tensor`, or None if it cannot be calculated. Raises: TypeError: if tensor is not an ops.Tensor.
Returns the constant value of the given tensor, if efficiently calculable.
[ "Returns", "the", "constant", "value", "of", "the", "given", "tensor", "if", "efficiently", "calculable", "." ]
def constant_value(tensor): """Returns the constant value of the given tensor, if efficiently calculable. This function attempts to partially evaluate the given tensor, and returns its value as a numpy ndarray if this succeeds. TODO(mrry): Consider whether this function should use a registration mechanism like gradients and ShapeFunctions, so that it is easily extensible. NOTE: If `constant_value(tensor)` returns a non-`None` result, it will no longer be possible to feed a different value for `tensor`. This allows the result of this function to influence the graph that is constructed, and permits static shape optimizations. Args: tensor: The Tensor to be evaluated. Returns: A numpy ndarray containing the constant value of the given `tensor`, or None if it cannot be calculated. Raises: TypeError: if tensor is not an ops.Tensor. """ ret = _ConstantValue(tensor) if ret is not None: # The caller may now depend on the constant value of `tensor`, so we # conservatively prevent it from being fed. tensor.graph.prevent_feeding(tensor) return ret
[ "def", "constant_value", "(", "tensor", ")", ":", "ret", "=", "_ConstantValue", "(", "tensor", ")", "if", "ret", "is", "not", "None", ":", "# The caller may now depend on the constant value of `tensor`, so we", "# conservatively prevent it from being fed.", "tensor", ".", "graph", ".", "prevent_feeding", "(", "tensor", ")", "return", "ret" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/framework/tensor_util.py#L601-L631
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/mox3/mox3/mox.py
python
MockMethod.__init__
(self, method_name, call_queue, replay_mode, method_to_mock=None, description=None, class_to_bind=None)
Construct a new mock method. Args: # method_name: the name of the method # call_queue: deque of calls, verify this call against the head, # or add this call to the queue. # replay_mode: False if we are recording, True if we are verifying # calls against the call queue. # method_to_mock: The actual method being mocked, used for # introspection. # description: optionally, a descriptive name for this method. # Typically this is equal to the descriptive name of # the method's class. # class_to_bind: optionally, a class that is used for unbound # methods (or functions in Python3) to which method # is bound, in order not to loose binding # information. If given, it will be used for # checking the type of first method parameter method_name: str call_queue: list or deque replay_mode: bool method_to_mock: a method object description: str or None class_to_bind: type or None
Construct a new mock method.
[ "Construct", "a", "new", "mock", "method", "." ]
def __init__(self, method_name, call_queue, replay_mode, method_to_mock=None, description=None, class_to_bind=None): """Construct a new mock method. Args: # method_name: the name of the method # call_queue: deque of calls, verify this call against the head, # or add this call to the queue. # replay_mode: False if we are recording, True if we are verifying # calls against the call queue. # method_to_mock: The actual method being mocked, used for # introspection. # description: optionally, a descriptive name for this method. # Typically this is equal to the descriptive name of # the method's class. # class_to_bind: optionally, a class that is used for unbound # methods (or functions in Python3) to which method # is bound, in order not to loose binding # information. If given, it will be used for # checking the type of first method parameter method_name: str call_queue: list or deque replay_mode: bool method_to_mock: a method object description: str or None class_to_bind: type or None """ self._name = method_name self.__name__ = method_name self._call_queue = call_queue if not isinstance(call_queue, collections.deque): self._call_queue = collections.deque(self._call_queue) self._replay_mode = replay_mode self._description = description self._params = None self._named_params = None self._return_value = None self._exception = None self._side_effects = None try: self._checker = MethodSignatureChecker(method_to_mock, class_to_bind=class_to_bind) except ValueError: self._checker = None
[ "def", "__init__", "(", "self", ",", "method_name", ",", "call_queue", ",", "replay_mode", ",", "method_to_mock", "=", "None", ",", "description", "=", "None", ",", "class_to_bind", "=", "None", ")", ":", "self", ".", "_name", "=", "method_name", "self", ".", "__name__", "=", "method_name", "self", ".", "_call_queue", "=", "call_queue", "if", "not", "isinstance", "(", "call_queue", ",", "collections", ".", "deque", ")", ":", "self", ".", "_call_queue", "=", "collections", ".", "deque", "(", "self", ".", "_call_queue", ")", "self", ".", "_replay_mode", "=", "replay_mode", "self", ".", "_description", "=", "description", "self", ".", "_params", "=", "None", "self", ".", "_named_params", "=", "None", "self", ".", "_return_value", "=", "None", "self", ".", "_exception", "=", "None", "self", ".", "_side_effects", "=", "None", "try", ":", "self", ".", "_checker", "=", "MethodSignatureChecker", "(", "method_to_mock", ",", "class_to_bind", "=", "class_to_bind", ")", "except", "ValueError", ":", "self", ".", "_checker", "=", "None" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mox3/mox3/mox.py#L1041-L1087
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/turtle.py
python
TurtleScreenBase._drawline
(self, lineitem, coordlist=None, fill=None, width=None, top=False)
Configure lineitem according to provided arguments: coordlist is sequence of coordinates fill is drawing color width is width of drawn line. top is a boolean value, which specifies if polyitem will be put on top of the canvas' displaylist so it will not be covered by other items.
Configure lineitem according to provided arguments: coordlist is sequence of coordinates fill is drawing color width is width of drawn line. top is a boolean value, which specifies if polyitem will be put on top of the canvas' displaylist so it will not be covered by other items.
[ "Configure", "lineitem", "according", "to", "provided", "arguments", ":", "coordlist", "is", "sequence", "of", "coordinates", "fill", "is", "drawing", "color", "width", "is", "width", "of", "drawn", "line", ".", "top", "is", "a", "boolean", "value", "which", "specifies", "if", "polyitem", "will", "be", "put", "on", "top", "of", "the", "canvas", "displaylist", "so", "it", "will", "not", "be", "covered", "by", "other", "items", "." ]
def _drawline(self, lineitem, coordlist=None, fill=None, width=None, top=False): """Configure lineitem according to provided arguments: coordlist is sequence of coordinates fill is drawing color width is width of drawn line. top is a boolean value, which specifies if polyitem will be put on top of the canvas' displaylist so it will not be covered by other items. """ if coordlist is not None: cl = [] for x, y in coordlist: cl.append(x * self.xscale) cl.append(-y * self.yscale) self.cv.coords(lineitem, *cl) if fill is not None: self.cv.itemconfigure(lineitem, fill=fill) if width is not None: self.cv.itemconfigure(lineitem, width=width) if top: self.cv.tag_raise(lineitem)
[ "def", "_drawline", "(", "self", ",", "lineitem", ",", "coordlist", "=", "None", ",", "fill", "=", "None", ",", "width", "=", "None", ",", "top", "=", "False", ")", ":", "if", "coordlist", "is", "not", "None", ":", "cl", "=", "[", "]", "for", "x", ",", "y", "in", "coordlist", ":", "cl", ".", "append", "(", "x", "*", "self", ".", "xscale", ")", "cl", ".", "append", "(", "-", "y", "*", "self", ".", "yscale", ")", "self", ".", "cv", ".", "coords", "(", "lineitem", ",", "*", "cl", ")", "if", "fill", "is", "not", "None", ":", "self", ".", "cv", ".", "itemconfigure", "(", "lineitem", ",", "fill", "=", "fill", ")", "if", "width", "is", "not", "None", ":", "self", ".", "cv", ".", "itemconfigure", "(", "lineitem", ",", "width", "=", "width", ")", "if", "top", ":", "self", ".", "cv", ".", "tag_raise", "(", "lineitem", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/turtle.py#L529-L550
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/numbers.py
python
Integral.__xor__
(self, other)
self ^ other
self ^ other
[ "self", "^", "other" ]
def __xor__(self, other): """self ^ other""" raise NotImplementedError
[ "def", "__xor__", "(", "self", ",", "other", ")", ":", "raise", "NotImplementedError" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/numbers.py#L351-L353
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/compilerop.py
python
CachingCompiler.reset_compiler_flags
(self)
Reset compiler flags to default state.
Reset compiler flags to default state.
[ "Reset", "compiler", "flags", "to", "default", "state", "." ]
def reset_compiler_flags(self): """Reset compiler flags to default state.""" # This value is copied from codeop.Compile.__init__, so if that ever # changes, it will need to be updated. self.flags = codeop.PyCF_DONT_IMPLY_DEDENT
[ "def", "reset_compiler_flags", "(", "self", ")", ":", "# This value is copied from codeop.Compile.__init__, so if that ever", "# changes, it will need to be updated.", "self", ".", "flags", "=", "codeop", ".", "PyCF_DONT_IMPLY_DEDENT" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/compilerop.py#L103-L107
mysql/mysql-workbench
2f35f9034f015cbcd22139a60e1baa2e3e8e795c
plugins/wb.admin/backend/wb_log_reader.py
python
BaseLogFileReader.has_next
(self)
return self.chunk_end < self.file_size
If there is a next chunk that can be read.
If there is a next chunk that can be read.
[ "If", "there", "is", "a", "next", "chunk", "that", "can", "be", "read", "." ]
def has_next(self): ''' If there is a next chunk that can be read. ''' return self.chunk_end < self.file_size
[ "def", "has_next", "(", "self", ")", ":", "return", "self", ".", "chunk_end", "<", "self", ".", "file_size" ]
https://github.com/mysql/mysql-workbench/blob/2f35f9034f015cbcd22139a60e1baa2e3e8e795c/plugins/wb.admin/backend/wb_log_reader.py#L410-L414
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_keras2_converter.py
python
_convert_training_info
(model, builder, output_features)
Convert the training information from the given Keras 'model' into the Core ML in 'builder'. :param model: keras.model.Sequential The source Keras model. :param builder: NeutralNetworkBuilder The target model that will gain the loss and optimizer. :param output_features: list of tuples, (str, datatype) The set of tensor names that are output from the layers in the Keras model.
Convert the training information from the given Keras 'model' into the Core ML in 'builder'.
[ "Convert", "the", "training", "information", "from", "the", "given", "Keras", "model", "into", "the", "Core", "ML", "in", "builder", "." ]
def _convert_training_info(model, builder, output_features): """ Convert the training information from the given Keras 'model' into the Core ML in 'builder'. :param model: keras.model.Sequential The source Keras model. :param builder: NeutralNetworkBuilder The target model that will gain the loss and optimizer. :param output_features: list of tuples, (str, datatype) The set of tensor names that are output from the layers in the Keras model. """ # Keras does not have a number of epochs compiled into the model, so we # invent one here for ease of use. 1 makes the most sense, as the user # can just invoke training repeatedly if they'd like to do more. builder.set_epochs(1) import keras try: if ( model.loss == keras.losses.categorical_crossentropy or model.loss == "categorical_crossentropy" ): builder.set_categorical_cross_entropy_loss( name="loss_layer", input=output_features[0][0] ) elif ( model.loss == keras.losses.mean_squared_error or model.loss == "mean_squared_error" ): builder.set_mean_squared_error_loss( name="loss_layer", input_feature=output_features[0] ) else: print( "Models loss: " + str(model.loss) + ", vs Keras loss: " + str(keras.losses.mean_squared_error) ) logging.warning( "Loss " + str(model.loss) + " is not yet " "supported by Core ML. The loss layer will " "not be carried over. To train this model, " "you will need to manually add a supported " "loss layer." ) except AttributeError: logging.warning( "Core ML conversion was asked to respect trainable " "parameters from the Keras model, but the input " "model does not include a loss layer." ) try: opt = model.optimizer except AttributeError: logging.warning( "Core ML conversion was asked to respect trainable " "parameters from the Keras model, but could not read " "the optimizer from Keras." ) return if model.optimizer: # a dict of the parameters we need. cfg = model.optimizer.get_config() if "decay" in cfg and cfg["decay"] != 0.0: logging.warning( "Keras optimizer has 'decay' set, which is " "not supported in Core ML. This parameter " "of the optimizer will be ignored. Clients " "can change the learning rate from within an " "MLUpdateTask callback to achieve the same " "effect." ) if isinstance(model.optimizer, keras.optimizers.SGD): params = SgdParams(lr=cfg["lr"], momentum=cfg["momentum"]) if "nesterov" in cfg and cfg["nesterov"] == True: logging.warning( "Keras SGD optimizer has 'nesterov' set, " "but this is not supported by Core ML. " "The parameter will be ignored." ) # Keras does not require a user to specify batch size up front, # as Core ML does. We need to choose something, let's be a bit # wide to minimize the chance of user "surprise" when running. params.set_batch(16, [1, 16, 32]) builder.set_sgd_optimizer(params) elif isinstance(model.optimizer, keras.optimizers.Adam): params = AdamParams( lr=cfg["lr"], beta1=cfg["beta_1"], beta2=cfg["beta_2"], eps=cfg["epsilon"], ) if "amsgrad" in cfg and cfg["amsgrad"] == True: logging.warning( "Keras Adam optimizer has 'amsgrad' set, " "but this is not supported by Core ML. " "The parameter will be ignored." ) # Keras does not require a user to specify batch size up front, # as Core ML does. We need to choose something, let's be a bit # wide to minimize the chance of user "surprise" when running. params.set_batch(16, [1, 16, 32]) builder.set_adam_optimizer(params) else: logging.warning( "Optimizer " + str(model.optimizer) + " is " "not yet supported by Core ML. The optimizer " "will not be carried over. To train this " "model, you will need to manually add a " "supported optimizer." ) else: logging.warning( "Core ML conversion was asked to respect " "trainable parameters from the Keras model, but " "the input model does not include an optimizer." )
[ "def", "_convert_training_info", "(", "model", ",", "builder", ",", "output_features", ")", ":", "# Keras does not have a number of epochs compiled into the model, so we", "# invent one here for ease of use. 1 makes the most sense, as the user", "# can just invoke training repeatedly if they'd like to do more.", "builder", ".", "set_epochs", "(", "1", ")", "import", "keras", "try", ":", "if", "(", "model", ".", "loss", "==", "keras", ".", "losses", ".", "categorical_crossentropy", "or", "model", ".", "loss", "==", "\"categorical_crossentropy\"", ")", ":", "builder", ".", "set_categorical_cross_entropy_loss", "(", "name", "=", "\"loss_layer\"", ",", "input", "=", "output_features", "[", "0", "]", "[", "0", "]", ")", "elif", "(", "model", ".", "loss", "==", "keras", ".", "losses", ".", "mean_squared_error", "or", "model", ".", "loss", "==", "\"mean_squared_error\"", ")", ":", "builder", ".", "set_mean_squared_error_loss", "(", "name", "=", "\"loss_layer\"", ",", "input_feature", "=", "output_features", "[", "0", "]", ")", "else", ":", "print", "(", "\"Models loss: \"", "+", "str", "(", "model", ".", "loss", ")", "+", "\", vs Keras loss: \"", "+", "str", "(", "keras", ".", "losses", ".", "mean_squared_error", ")", ")", "logging", ".", "warning", "(", "\"Loss \"", "+", "str", "(", "model", ".", "loss", ")", "+", "\" is not yet \"", "\"supported by Core ML. The loss layer will \"", "\"not be carried over. To train this model, \"", "\"you will need to manually add a supported \"", "\"loss layer.\"", ")", "except", "AttributeError", ":", "logging", ".", "warning", "(", "\"Core ML conversion was asked to respect trainable \"", "\"parameters from the Keras model, but the input \"", "\"model does not include a loss layer.\"", ")", "try", ":", "opt", "=", "model", ".", "optimizer", "except", "AttributeError", ":", "logging", ".", "warning", "(", "\"Core ML conversion was asked to respect trainable \"", "\"parameters from the Keras model, but could not read \"", "\"the optimizer from Keras.\"", ")", "return", "if", "model", ".", "optimizer", ":", "# a dict of the parameters we need.", "cfg", "=", "model", ".", "optimizer", ".", "get_config", "(", ")", "if", "\"decay\"", "in", "cfg", "and", "cfg", "[", "\"decay\"", "]", "!=", "0.0", ":", "logging", ".", "warning", "(", "\"Keras optimizer has 'decay' set, which is \"", "\"not supported in Core ML. This parameter \"", "\"of the optimizer will be ignored. Clients \"", "\"can change the learning rate from within an \"", "\"MLUpdateTask callback to achieve the same \"", "\"effect.\"", ")", "if", "isinstance", "(", "model", ".", "optimizer", ",", "keras", ".", "optimizers", ".", "SGD", ")", ":", "params", "=", "SgdParams", "(", "lr", "=", "cfg", "[", "\"lr\"", "]", ",", "momentum", "=", "cfg", "[", "\"momentum\"", "]", ")", "if", "\"nesterov\"", "in", "cfg", "and", "cfg", "[", "\"nesterov\"", "]", "==", "True", ":", "logging", ".", "warning", "(", "\"Keras SGD optimizer has 'nesterov' set, \"", "\"but this is not supported by Core ML. \"", "\"The parameter will be ignored.\"", ")", "# Keras does not require a user to specify batch size up front,", "# as Core ML does. We need to choose something, let's be a bit", "# wide to minimize the chance of user \"surprise\" when running.", "params", ".", "set_batch", "(", "16", ",", "[", "1", ",", "16", ",", "32", "]", ")", "builder", ".", "set_sgd_optimizer", "(", "params", ")", "elif", "isinstance", "(", "model", ".", "optimizer", ",", "keras", ".", "optimizers", ".", "Adam", ")", ":", "params", "=", "AdamParams", "(", "lr", "=", "cfg", "[", "\"lr\"", "]", ",", "beta1", "=", "cfg", "[", "\"beta_1\"", "]", ",", "beta2", "=", "cfg", "[", "\"beta_2\"", "]", ",", "eps", "=", "cfg", "[", "\"epsilon\"", "]", ",", ")", "if", "\"amsgrad\"", "in", "cfg", "and", "cfg", "[", "\"amsgrad\"", "]", "==", "True", ":", "logging", ".", "warning", "(", "\"Keras Adam optimizer has 'amsgrad' set, \"", "\"but this is not supported by Core ML. \"", "\"The parameter will be ignored.\"", ")", "# Keras does not require a user to specify batch size up front,", "# as Core ML does. We need to choose something, let's be a bit", "# wide to minimize the chance of user \"surprise\" when running.", "params", ".", "set_batch", "(", "16", ",", "[", "1", ",", "16", ",", "32", "]", ")", "builder", ".", "set_adam_optimizer", "(", "params", ")", "else", ":", "logging", ".", "warning", "(", "\"Optimizer \"", "+", "str", "(", "model", ".", "optimizer", ")", "+", "\" is \"", "\"not yet supported by Core ML. The optimizer \"", "\"will not be carried over. To train this \"", "\"model, you will need to manually add a \"", "\"supported optimizer.\"", ")", "else", ":", "logging", ".", "warning", "(", "\"Core ML conversion was asked to respect \"", "\"trainable parameters from the Keras model, but \"", "\"the input model does not include an optimizer.\"", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_keras2_converter.py#L193-L313
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/signal/ltisys.py
python
StateSpace.__init__
(self, *system, **kwargs)
Initialize the state space lti/dlti system.
Initialize the state space lti/dlti system.
[ "Initialize", "the", "state", "space", "lti", "/", "dlti", "system", "." ]
def __init__(self, *system, **kwargs): """Initialize the state space lti/dlti system.""" # Conversion of lti instances is handled in __new__ if isinstance(system[0], LinearTimeInvariant): return # Remove system arguments, not needed by parents anymore super(StateSpace, self).__init__(**kwargs) self._A = None self._B = None self._C = None self._D = None self.A, self.B, self.C, self.D = abcd_normalize(*system)
[ "def", "__init__", "(", "self", ",", "*", "system", ",", "*", "*", "kwargs", ")", ":", "# Conversion of lti instances is handled in __new__", "if", "isinstance", "(", "system", "[", "0", "]", ",", "LinearTimeInvariant", ")", ":", "return", "# Remove system arguments, not needed by parents anymore", "super", "(", "StateSpace", ",", "self", ")", ".", "__init__", "(", "*", "*", "kwargs", ")", "self", ".", "_A", "=", "None", "self", ".", "_B", "=", "None", "self", ".", "_C", "=", "None", "self", ".", "_D", "=", "None", "self", ".", "A", ",", "self", ".", "B", ",", "self", ".", "C", ",", "self", ".", "D", "=", "abcd_normalize", "(", "*", "system", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/signal/ltisys.py#L1319-L1333
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/python/timeseries/input_pipeline.py
python
TFExampleReader.__init__
(self, filenames, features)
Configure `tf.Example` parsing. Args: filenames: A filename or list of filenames to read the time series from. Each line must have columns corresponding to `column_names`. features: A dictionary mapping from feature keys to `tf.io.FixedLenFeature` objects. Must include `TrainEvalFeatures.TIMES` (scalar integer) and `TrainEvalFeatures.VALUES` (floating point vector) features. Raises: ValueError: If required times/values features are not present.
Configure `tf.Example` parsing.
[ "Configure", "tf", ".", "Example", "parsing", "." ]
def __init__(self, filenames, features): """Configure `tf.Example` parsing. Args: filenames: A filename or list of filenames to read the time series from. Each line must have columns corresponding to `column_names`. features: A dictionary mapping from feature keys to `tf.io.FixedLenFeature` objects. Must include `TrainEvalFeatures.TIMES` (scalar integer) and `TrainEvalFeatures.VALUES` (floating point vector) features. Raises: ValueError: If required times/values features are not present. """ if feature_keys.TrainEvalFeatures.TIMES not in features: raise ValueError("'{}' is a required column.".format( feature_keys.TrainEvalFeatures.TIMES)) if feature_keys.TrainEvalFeatures.VALUES not in features: raise ValueError("'{}' is a required column.".format( feature_keys.TrainEvalFeatures.VALUES)) self._features = features super(TFExampleReader, self).__init__(filenames=filenames)
[ "def", "__init__", "(", "self", ",", "filenames", ",", "features", ")", ":", "if", "feature_keys", ".", "TrainEvalFeatures", ".", "TIMES", "not", "in", "features", ":", "raise", "ValueError", "(", "\"'{}' is a required column.\"", ".", "format", "(", "feature_keys", ".", "TrainEvalFeatures", ".", "TIMES", ")", ")", "if", "feature_keys", ".", "TrainEvalFeatures", ".", "VALUES", "not", "in", "features", ":", "raise", "ValueError", "(", "\"'{}' is a required column.\"", ".", "format", "(", "feature_keys", ".", "TrainEvalFeatures", ".", "VALUES", ")", ")", "self", ".", "_features", "=", "features", "super", "(", "TFExampleReader", ",", "self", ")", ".", "__init__", "(", "filenames", "=", "filenames", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/timeseries/python/timeseries/input_pipeline.py#L519-L540
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
MenuEvent.GetMenu
(*args, **kwargs)
return _core_.MenuEvent_GetMenu(*args, **kwargs)
GetMenu(self) -> Menu Returns the menu which is being opened or closed. This method should only be used with the OPEN and CLOSE events.
GetMenu(self) -> Menu
[ "GetMenu", "(", "self", ")", "-", ">", "Menu" ]
def GetMenu(*args, **kwargs): """ GetMenu(self) -> Menu Returns the menu which is being opened or closed. This method should only be used with the OPEN and CLOSE events. """ return _core_.MenuEvent_GetMenu(*args, **kwargs)
[ "def", "GetMenu", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MenuEvent_GetMenu", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L6461-L6468
FEniCS/dolfinx
3dfdf038cccdb70962865b58a63bf29c2e55ec6e
python/dolfinx/fem/function.py
python
FunctionSpace.mesh
(self)
return self._cpp_object.mesh
Return the mesh on which the function space is defined.
Return the mesh on which the function space is defined.
[ "Return", "the", "mesh", "on", "which", "the", "function", "space", "is", "defined", "." ]
def mesh(self) -> _cpp.mesh.Mesh: """Return the mesh on which the function space is defined.""" return self._cpp_object.mesh
[ "def", "mesh", "(", "self", ")", "->", "_cpp", ".", "mesh", ".", "Mesh", ":", "return", "self", ".", "_cpp_object", ".", "mesh" ]
https://github.com/FEniCS/dolfinx/blob/3dfdf038cccdb70962865b58a63bf29c2e55ec6e/python/dolfinx/fem/function.py#L553-L555
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
v8_7_5/tools/stats-viewer.py
python
UiCounter.__init__
(self, var, format)
Creates a new ui counter. Args: var: the Tkinter string variable for updating the ui format: the format string used to format this counter
Creates a new ui counter.
[ "Creates", "a", "new", "ui", "counter", "." ]
def __init__(self, var, format): """Creates a new ui counter. Args: var: the Tkinter string variable for updating the ui format: the format string used to format this counter """ self.var = var self.format = format self.last_value = None
[ "def", "__init__", "(", "self", ",", "var", ",", "format", ")", ":", "self", ".", "var", "=", "var", "self", ".", "format", "=", "format", "self", ".", "last_value", "=", "None" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/v8_7_5/tools/stats-viewer.py#L274-L283
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryISISLoadAndProcess.py
python
ReflectometryISISLoadAndProcess.category
(self)
return 'Reflectometry\\ISIS;Workflow\\Reflectometry'
Return the categories of the algorithm.
Return the categories of the algorithm.
[ "Return", "the", "categories", "of", "the", "algorithm", "." ]
def category(self): """Return the categories of the algorithm.""" return 'Reflectometry\\ISIS;Workflow\\Reflectometry'
[ "def", "category", "(", "self", ")", ":", "return", "'Reflectometry\\\\ISIS;Workflow\\\\Reflectometry'" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryISISLoadAndProcess.py#L47-L49
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/configDialog.py
python
ConfigDialog.SaveAllChangedConfigs
(self)
Save configuration changes to the user config file.
Save configuration changes to the user config file.
[ "Save", "configuration", "changes", "to", "the", "user", "config", "file", "." ]
def SaveAllChangedConfigs(self): "Save configuration changes to the user config file." idleConf.userCfg['main'].Save() for configType in self.changedItems.keys(): cfgTypeHasChanges = False for section in self.changedItems[configType].keys(): if section == 'HelpFiles': #this section gets completely replaced idleConf.userCfg['main'].remove_section('HelpFiles') cfgTypeHasChanges = True for item in self.changedItems[configType][section].keys(): value = self.changedItems[configType][section][item] if self.SetUserValue(configType,section,item,value): cfgTypeHasChanges = True if cfgTypeHasChanges: idleConf.userCfg[configType].Save() for configType in ['keys', 'highlight']: # save these even if unchanged! idleConf.userCfg[configType].Save() self.ResetChangedItems()
[ "def", "SaveAllChangedConfigs", "(", "self", ")", ":", "idleConf", ".", "userCfg", "[", "'main'", "]", ".", "Save", "(", ")", "for", "configType", "in", "self", ".", "changedItems", ".", "keys", "(", ")", ":", "cfgTypeHasChanges", "=", "False", "for", "section", "in", "self", ".", "changedItems", "[", "configType", "]", ".", "keys", "(", ")", ":", "if", "section", "==", "'HelpFiles'", ":", "#this section gets completely replaced", "idleConf", ".", "userCfg", "[", "'main'", "]", ".", "remove_section", "(", "'HelpFiles'", ")", "cfgTypeHasChanges", "=", "True", "for", "item", "in", "self", ".", "changedItems", "[", "configType", "]", "[", "section", "]", ".", "keys", "(", ")", ":", "value", "=", "self", ".", "changedItems", "[", "configType", "]", "[", "section", "]", "[", "item", "]", "if", "self", ".", "SetUserValue", "(", "configType", ",", "section", ",", "item", ",", "value", ")", ":", "cfgTypeHasChanges", "=", "True", "if", "cfgTypeHasChanges", ":", "idleConf", ".", "userCfg", "[", "configType", "]", ".", "Save", "(", ")", "for", "configType", "in", "[", "'keys'", ",", "'highlight'", "]", ":", "# save these even if unchanged!", "idleConf", ".", "userCfg", "[", "configType", "]", ".", "Save", "(", ")", "self", ".", "ResetChangedItems", "(", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/idlelib/configDialog.py#L1099-L1118
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/tex.py
python
generate_common
(env)
Add internal Builders and construction variables for LaTeX to an Environment.
Add internal Builders and construction variables for LaTeX to an Environment.
[ "Add", "internal", "Builders", "and", "construction", "variables", "for", "LaTeX", "to", "an", "Environment", "." ]
def generate_common(env): """Add internal Builders and construction variables for LaTeX to an Environment.""" # Add OSX system paths so TeX tools can be found # when a list of tools is given the exists() method is not called generate_darwin(env) # A generic tex file Action, sufficient for all tex files. global TeXAction if TeXAction is None: TeXAction = SCons.Action.Action("$TEXCOM", "$TEXCOMSTR") # An Action to build a latex file. This might be needed more # than once if we are dealing with labels and bibtex. global LaTeXAction if LaTeXAction is None: LaTeXAction = SCons.Action.Action("$LATEXCOM", "$LATEXCOMSTR") # Define an action to run BibTeX on a file. global BibTeXAction if BibTeXAction is None: BibTeXAction = SCons.Action.Action("$BIBTEXCOM", "$BIBTEXCOMSTR") # Define an action to run Biber on a file. global BiberAction if BiberAction is None: BiberAction = SCons.Action.Action("$BIBERCOM", "$BIBERCOMSTR") # Define an action to run MakeIndex on a file. global MakeIndexAction if MakeIndexAction is None: MakeIndexAction = SCons.Action.Action("$MAKEINDEXCOM", "$MAKEINDEXCOMSTR") # Define an action to run MakeIndex on a file for nomenclatures. global MakeNclAction if MakeNclAction is None: MakeNclAction = SCons.Action.Action("$MAKENCLCOM", "$MAKENCLCOMSTR") # Define an action to run MakeIndex on a file for glossaries. global MakeGlossaryAction if MakeGlossaryAction is None: MakeGlossaryAction = SCons.Action.Action("$MAKEGLOSSARYCOM", "$MAKEGLOSSARYCOMSTR") # Define an action to run MakeIndex on a file for acronyms. global MakeAcronymsAction if MakeAcronymsAction is None: MakeAcronymsAction = SCons.Action.Action("$MAKEACRONYMSCOM", "$MAKEACRONYMSCOMSTR") try: environ = env['ENV'] except KeyError: environ = {} env['ENV'] = environ # Some Linux platforms have pdflatex set up in a way # that requires that the HOME environment variable be set. # Add it here if defined. v = os.environ.get('HOME') if v: environ['HOME'] = v CDCOM = 'cd ' if platform.system() == 'Windows': # allow cd command to change drives on Windows CDCOM = 'cd /D ' env['TEX'] = 'tex' env['TEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder') env['TEXCOM'] = CDCOM + '${TARGET.dir} && $TEX $TEXFLAGS ${SOURCE.file}' env['PDFTEX'] = 'pdftex' env['PDFTEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder') env['PDFTEXCOM'] = CDCOM + '${TARGET.dir} && $PDFTEX $PDFTEXFLAGS ${SOURCE.file}' env['LATEX'] = 'latex' env['LATEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder') env['LATEXCOM'] = CDCOM + '${TARGET.dir} && $LATEX $LATEXFLAGS ${SOURCE.file}' env['LATEXRETRIES'] = 4 env['PDFLATEX'] = 'pdflatex' env['PDFLATEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode -recorder') env['PDFLATEXCOM'] = CDCOM + '${TARGET.dir} && $PDFLATEX $PDFLATEXFLAGS ${SOURCE.file}' env['BIBTEX'] = 'bibtex' env['BIBTEXFLAGS'] = SCons.Util.CLVar('') env['BIBTEXCOM'] = CDCOM + '${TARGET.dir} && $BIBTEX $BIBTEXFLAGS ${SOURCE.filebase}' env['BIBER'] = 'biber' env['BIBERFLAGS'] = SCons.Util.CLVar('') env['BIBERCOM'] = CDCOM + '${TARGET.dir} && $BIBER $BIBERFLAGS ${SOURCE.filebase}' env['MAKEINDEX'] = 'makeindex' env['MAKEINDEXFLAGS'] = SCons.Util.CLVar('') env['MAKEINDEXCOM'] = CDCOM + '${TARGET.dir} && $MAKEINDEX $MAKEINDEXFLAGS ${SOURCE.file}' env['MAKEGLOSSARY'] = 'makeindex' env['MAKEGLOSSARYSTYLE'] = '${SOURCE.filebase}.ist' env['MAKEGLOSSARYFLAGS'] = SCons.Util.CLVar('-s ${MAKEGLOSSARYSTYLE} -t ${SOURCE.filebase}.glg') env['MAKEGLOSSARYCOM'] = CDCOM + '${TARGET.dir} && $MAKEGLOSSARY ${SOURCE.filebase}.glo $MAKEGLOSSARYFLAGS -o ${SOURCE.filebase}.gls' env['MAKEACRONYMS'] = 'makeindex' env['MAKEACRONYMSSTYLE'] = '${SOURCE.filebase}.ist' env['MAKEACRONYMSFLAGS'] = SCons.Util.CLVar('-s ${MAKEACRONYMSSTYLE} -t ${SOURCE.filebase}.alg') env['MAKEACRONYMSCOM'] = CDCOM + '${TARGET.dir} && $MAKEACRONYMS ${SOURCE.filebase}.acn $MAKEACRONYMSFLAGS -o ${SOURCE.filebase}.acr' env['MAKENCL'] = 'makeindex' env['MAKENCLSTYLE'] = 'nomencl.ist' env['MAKENCLFLAGS'] = '-s ${MAKENCLSTYLE} -t ${SOURCE.filebase}.nlg' env['MAKENCLCOM'] = CDCOM + '${TARGET.dir} && $MAKENCL ${SOURCE.filebase}.nlo $MAKENCLFLAGS -o ${SOURCE.filebase}.nls' env['MAKENEWGLOSSARY'] = 'makeindex' env['MAKENEWGLOSSARYCOM'] = CDCOM + '${TARGET.dir} && $MAKENEWGLOSSARY '
[ "def", "generate_common", "(", "env", ")", ":", "# Add OSX system paths so TeX tools can be found", "# when a list of tools is given the exists() method is not called", "generate_darwin", "(", "env", ")", "# A generic tex file Action, sufficient for all tex files.", "global", "TeXAction", "if", "TeXAction", "is", "None", ":", "TeXAction", "=", "SCons", ".", "Action", ".", "Action", "(", "\"$TEXCOM\"", ",", "\"$TEXCOMSTR\"", ")", "# An Action to build a latex file. This might be needed more", "# than once if we are dealing with labels and bibtex.", "global", "LaTeXAction", "if", "LaTeXAction", "is", "None", ":", "LaTeXAction", "=", "SCons", ".", "Action", ".", "Action", "(", "\"$LATEXCOM\"", ",", "\"$LATEXCOMSTR\"", ")", "# Define an action to run BibTeX on a file.", "global", "BibTeXAction", "if", "BibTeXAction", "is", "None", ":", "BibTeXAction", "=", "SCons", ".", "Action", ".", "Action", "(", "\"$BIBTEXCOM\"", ",", "\"$BIBTEXCOMSTR\"", ")", "# Define an action to run Biber on a file.", "global", "BiberAction", "if", "BiberAction", "is", "None", ":", "BiberAction", "=", "SCons", ".", "Action", ".", "Action", "(", "\"$BIBERCOM\"", ",", "\"$BIBERCOMSTR\"", ")", "# Define an action to run MakeIndex on a file.", "global", "MakeIndexAction", "if", "MakeIndexAction", "is", "None", ":", "MakeIndexAction", "=", "SCons", ".", "Action", ".", "Action", "(", "\"$MAKEINDEXCOM\"", ",", "\"$MAKEINDEXCOMSTR\"", ")", "# Define an action to run MakeIndex on a file for nomenclatures.", "global", "MakeNclAction", "if", "MakeNclAction", "is", "None", ":", "MakeNclAction", "=", "SCons", ".", "Action", ".", "Action", "(", "\"$MAKENCLCOM\"", ",", "\"$MAKENCLCOMSTR\"", ")", "# Define an action to run MakeIndex on a file for glossaries.", "global", "MakeGlossaryAction", "if", "MakeGlossaryAction", "is", "None", ":", "MakeGlossaryAction", "=", "SCons", ".", "Action", ".", "Action", "(", "\"$MAKEGLOSSARYCOM\"", ",", "\"$MAKEGLOSSARYCOMSTR\"", ")", "# Define an action to run MakeIndex on a file for acronyms.", "global", "MakeAcronymsAction", "if", "MakeAcronymsAction", "is", "None", ":", "MakeAcronymsAction", "=", "SCons", ".", "Action", ".", "Action", "(", "\"$MAKEACRONYMSCOM\"", ",", "\"$MAKEACRONYMSCOMSTR\"", ")", "try", ":", "environ", "=", "env", "[", "'ENV'", "]", "except", "KeyError", ":", "environ", "=", "{", "}", "env", "[", "'ENV'", "]", "=", "environ", "# Some Linux platforms have pdflatex set up in a way", "# that requires that the HOME environment variable be set.", "# Add it here if defined.", "v", "=", "os", ".", "environ", ".", "get", "(", "'HOME'", ")", "if", "v", ":", "environ", "[", "'HOME'", "]", "=", "v", "CDCOM", "=", "'cd '", "if", "platform", ".", "system", "(", ")", "==", "'Windows'", ":", "# allow cd command to change drives on Windows", "CDCOM", "=", "'cd /D '", "env", "[", "'TEX'", "]", "=", "'tex'", "env", "[", "'TEXFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "'-interaction=nonstopmode -recorder'", ")", "env", "[", "'TEXCOM'", "]", "=", "CDCOM", "+", "'${TARGET.dir} && $TEX $TEXFLAGS ${SOURCE.file}'", "env", "[", "'PDFTEX'", "]", "=", "'pdftex'", "env", "[", "'PDFTEXFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "'-interaction=nonstopmode -recorder'", ")", "env", "[", "'PDFTEXCOM'", "]", "=", "CDCOM", "+", "'${TARGET.dir} && $PDFTEX $PDFTEXFLAGS ${SOURCE.file}'", "env", "[", "'LATEX'", "]", "=", "'latex'", "env", "[", "'LATEXFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "'-interaction=nonstopmode -recorder'", ")", "env", "[", "'LATEXCOM'", "]", "=", "CDCOM", "+", "'${TARGET.dir} && $LATEX $LATEXFLAGS ${SOURCE.file}'", "env", "[", "'LATEXRETRIES'", "]", "=", "4", "env", "[", "'PDFLATEX'", "]", "=", "'pdflatex'", "env", "[", "'PDFLATEXFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "'-interaction=nonstopmode -recorder'", ")", "env", "[", "'PDFLATEXCOM'", "]", "=", "CDCOM", "+", "'${TARGET.dir} && $PDFLATEX $PDFLATEXFLAGS ${SOURCE.file}'", "env", "[", "'BIBTEX'", "]", "=", "'bibtex'", "env", "[", "'BIBTEXFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "''", ")", "env", "[", "'BIBTEXCOM'", "]", "=", "CDCOM", "+", "'${TARGET.dir} && $BIBTEX $BIBTEXFLAGS ${SOURCE.filebase}'", "env", "[", "'BIBER'", "]", "=", "'biber'", "env", "[", "'BIBERFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "''", ")", "env", "[", "'BIBERCOM'", "]", "=", "CDCOM", "+", "'${TARGET.dir} && $BIBER $BIBERFLAGS ${SOURCE.filebase}'", "env", "[", "'MAKEINDEX'", "]", "=", "'makeindex'", "env", "[", "'MAKEINDEXFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "''", ")", "env", "[", "'MAKEINDEXCOM'", "]", "=", "CDCOM", "+", "'${TARGET.dir} && $MAKEINDEX $MAKEINDEXFLAGS ${SOURCE.file}'", "env", "[", "'MAKEGLOSSARY'", "]", "=", "'makeindex'", "env", "[", "'MAKEGLOSSARYSTYLE'", "]", "=", "'${SOURCE.filebase}.ist'", "env", "[", "'MAKEGLOSSARYFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "'-s ${MAKEGLOSSARYSTYLE} -t ${SOURCE.filebase}.glg'", ")", "env", "[", "'MAKEGLOSSARYCOM'", "]", "=", "CDCOM", "+", "'${TARGET.dir} && $MAKEGLOSSARY ${SOURCE.filebase}.glo $MAKEGLOSSARYFLAGS -o ${SOURCE.filebase}.gls'", "env", "[", "'MAKEACRONYMS'", "]", "=", "'makeindex'", "env", "[", "'MAKEACRONYMSSTYLE'", "]", "=", "'${SOURCE.filebase}.ist'", "env", "[", "'MAKEACRONYMSFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "'-s ${MAKEACRONYMSSTYLE} -t ${SOURCE.filebase}.alg'", ")", "env", "[", "'MAKEACRONYMSCOM'", "]", "=", "CDCOM", "+", "'${TARGET.dir} && $MAKEACRONYMS ${SOURCE.filebase}.acn $MAKEACRONYMSFLAGS -o ${SOURCE.filebase}.acr'", "env", "[", "'MAKENCL'", "]", "=", "'makeindex'", "env", "[", "'MAKENCLSTYLE'", "]", "=", "'nomencl.ist'", "env", "[", "'MAKENCLFLAGS'", "]", "=", "'-s ${MAKENCLSTYLE} -t ${SOURCE.filebase}.nlg'", "env", "[", "'MAKENCLCOM'", "]", "=", "CDCOM", "+", "'${TARGET.dir} && $MAKENCL ${SOURCE.filebase}.nlo $MAKENCLFLAGS -o ${SOURCE.filebase}.nls'", "env", "[", "'MAKENEWGLOSSARY'", "]", "=", "'makeindex'", "env", "[", "'MAKENEWGLOSSARYCOM'", "]", "=", "CDCOM", "+", "'${TARGET.dir} && $MAKENEWGLOSSARY '" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/tex.py#L866-L977
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/buffer.py
python
Buffer.delete
(self, count: int = 1)
Delete specified number of characters and Return the deleted text.
Delete specified number of characters and Return the deleted text.
[ "Delete", "specified", "number", "of", "characters", "and", "Return", "the", "deleted", "text", "." ]
def delete(self, count: int = 1) -> str: """ Delete specified number of characters and Return the deleted text. """ if self.cursor_position < len(self.text): deleted = self.document.text_after_cursor[:count] self.text = ( self.text[: self.cursor_position] + self.text[self.cursor_position + len(deleted) :] ) return deleted else: return ""
[ "def", "delete", "(", "self", ",", "count", ":", "int", "=", "1", ")", "->", "str", ":", "if", "self", ".", "cursor_position", "<", "len", "(", "self", ".", "text", ")", ":", "deleted", "=", "self", ".", "document", ".", "text_after_cursor", "[", ":", "count", "]", "self", ".", "text", "=", "(", "self", ".", "text", "[", ":", "self", ".", "cursor_position", "]", "+", "self", ".", "text", "[", "self", ".", "cursor_position", "+", "len", "(", "deleted", ")", ":", "]", ")", "return", "deleted", "else", ":", "return", "\"\"" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/buffer.py#L805-L817
msracver/Deep-Image-Analogy
632b9287b42552e32dad64922967c8c9ec7fc4d3
scripts/cpp_lint.py
python
_IncludeState.CanonicalizeAlphabeticalOrder
(self, header_path)
return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
Returns a path canonicalized for alphabetical comparison. - replaces "-" with "_" so they both cmp the same. - removes '-inl' since we don't require them to be after the main header. - lowercase everything, just in case. Args: header_path: Path to be canonicalized. Returns: Canonicalized path.
Returns a path canonicalized for alphabetical comparison.
[ "Returns", "a", "path", "canonicalized", "for", "alphabetical", "comparison", "." ]
def CanonicalizeAlphabeticalOrder(self, header_path): """Returns a path canonicalized for alphabetical comparison. - replaces "-" with "_" so they both cmp the same. - removes '-inl' since we don't require them to be after the main header. - lowercase everything, just in case. Args: header_path: Path to be canonicalized. Returns: Canonicalized path. """ return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
[ "def", "CanonicalizeAlphabeticalOrder", "(", "self", ",", "header_path", ")", ":", "return", "header_path", ".", "replace", "(", "'-inl.h'", ",", "'.h'", ")", ".", "replace", "(", "'-'", ",", "'_'", ")", ".", "lower", "(", ")" ]
https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/scripts/cpp_lint.py#L597-L610
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
DisplayChangedEvent.__init__
(self, *args, **kwargs)
__init__(self) -> DisplayChangedEvent
__init__(self) -> DisplayChangedEvent
[ "__init__", "(", "self", ")", "-", ">", "DisplayChangedEvent" ]
def __init__(self, *args, **kwargs): """__init__(self) -> DisplayChangedEvent""" _core_.DisplayChangedEvent_swiginit(self,_core_.new_DisplayChangedEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_core_", ".", "DisplayChangedEvent_swiginit", "(", "self", ",", "_core_", ".", "new_DisplayChangedEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L7142-L7144
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/PublicKey/RSA.py
python
_import_keyDER
(extern_key, passphrase)
Import an RSA key (public or private half), encoded in DER form.
Import an RSA key (public or private half), encoded in DER form.
[ "Import", "an", "RSA", "key", "(", "public", "or", "private", "half", ")", "encoded", "in", "DER", "form", "." ]
def _import_keyDER(extern_key, passphrase): """Import an RSA key (public or private half), encoded in DER form.""" decodings = (_import_pkcs1_private, _import_pkcs1_public, _import_subjectPublicKeyInfo, _import_x509_cert, _import_pkcs8) for decoding in decodings: try: return decoding(extern_key, passphrase) except ValueError: pass raise ValueError("RSA key format is not supported")
[ "def", "_import_keyDER", "(", "extern_key", ",", "passphrase", ")", ":", "decodings", "=", "(", "_import_pkcs1_private", ",", "_import_pkcs1_public", ",", "_import_subjectPublicKeyInfo", ",", "_import_x509_cert", ",", "_import_pkcs8", ")", "for", "decoding", "in", "decodings", ":", "try", ":", "return", "decoding", "(", "extern_key", ",", "passphrase", ")", "except", "ValueError", ":", "pass", "raise", "ValueError", "(", "\"RSA key format is not supported\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/PublicKey/RSA.py#L667-L682
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
FontEnumerator_GetFacenames
(*args)
return _gdi_.FontEnumerator_GetFacenames(*args)
FontEnumerator_GetFacenames() -> PyObject
FontEnumerator_GetFacenames() -> PyObject
[ "FontEnumerator_GetFacenames", "()", "-", ">", "PyObject" ]
def FontEnumerator_GetFacenames(*args): """FontEnumerator_GetFacenames() -> PyObject""" return _gdi_.FontEnumerator_GetFacenames(*args)
[ "def", "FontEnumerator_GetFacenames", "(", "*", "args", ")", ":", "return", "_gdi_", ".", "FontEnumerator_GetFacenames", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L2687-L2689
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TUNGraphEdgeI.__eq__
(self, *args)
return _snap.TUNGraphEdgeI___eq__(self, *args)
__eq__(TUNGraphEdgeI self, TUNGraphEdgeI EdgeI) -> bool Parameters: EdgeI: TUNGraphEdgeI const &
__eq__(TUNGraphEdgeI self, TUNGraphEdgeI EdgeI) -> bool
[ "__eq__", "(", "TUNGraphEdgeI", "self", "TUNGraphEdgeI", "EdgeI", ")", "-", ">", "bool" ]
def __eq__(self, *args): """ __eq__(TUNGraphEdgeI self, TUNGraphEdgeI EdgeI) -> bool Parameters: EdgeI: TUNGraphEdgeI const & """ return _snap.TUNGraphEdgeI___eq__(self, *args)
[ "def", "__eq__", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TUNGraphEdgeI___eq__", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L20664-L20672
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/ps/the_one_ps.py
python
TheOnePSRuntime._ps_inference_save_persistables
(self, executor, dirname, main_program=None, mode=0, **kwargs)
This function filters out all variables with `persistable==True` from the give `main_program` and then saves these variables to the folder `dirname` or file `filename`. The `dirname` is used to specify the folder where persistable variables are going to be saved. If you would like to save variables in separate files, set `filename` None; if you would like to save all variables in a single file, use `filename` to specify the file name.
This function filters out all variables with `persistable==True` from the give `main_program` and then saves these variables to the folder `dirname` or file `filename`.
[ "This", "function", "filters", "out", "all", "variables", "with", "persistable", "==", "True", "from", "the", "give", "main_program", "and", "then", "saves", "these", "variables", "to", "the", "folder", "dirname", "or", "file", "filename", "." ]
def _ps_inference_save_persistables(self, executor, dirname, main_program=None, mode=0, **kwargs): """ This function filters out all variables with `persistable==True` from the give `main_program` and then saves these variables to the folder `dirname` or file `filename`. The `dirname` is used to specify the folder where persistable variables are going to be saved. If you would like to save variables in separate files, set `filename` None; if you would like to save all variables in a single file, use `filename` to specify the file name. """ if isinstance(executor, ParallelExecutor): raise TypeError( "in fleet.save() function, executor must be as Executor type, ParallelExecutor is not allowed" ) if not isinstance(executor, Executor): raise TypeError( "in fleet.save() function, executor must be as Executor type") if main_program is None: main_program = self.context['origin_ps_main_program'] if isinstance(main_program, CompiledProgram): raise TypeError( "in fleet.save() function, main_program must be as Program type, CompiledProgram is not allowed" ) # Todo(MrChengmo): Save optimizer status # self._save_distributed_persistables(executor, dirname, main_program, # mode) self._worker.save_all_model(dirname, mode)
[ "def", "_ps_inference_save_persistables", "(", "self", ",", "executor", ",", "dirname", ",", "main_program", "=", "None", ",", "mode", "=", "0", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "executor", ",", "ParallelExecutor", ")", ":", "raise", "TypeError", "(", "\"in fleet.save() function, executor must be as Executor type, ParallelExecutor is not allowed\"", ")", "if", "not", "isinstance", "(", "executor", ",", "Executor", ")", ":", "raise", "TypeError", "(", "\"in fleet.save() function, executor must be as Executor type\"", ")", "if", "main_program", "is", "None", ":", "main_program", "=", "self", ".", "context", "[", "'origin_ps_main_program'", "]", "if", "isinstance", "(", "main_program", ",", "CompiledProgram", ")", ":", "raise", "TypeError", "(", "\"in fleet.save() function, main_program must be as Program type, CompiledProgram is not allowed\"", ")", "# Todo(MrChengmo): Save optimizer status", "# self._save_distributed_persistables(executor, dirname, main_program,", "# mode)", "self", ".", "_worker", ".", "save_all_model", "(", "dirname", ",", "mode", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/ps/the_one_ps.py#L1146-L1183
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/http/cookies.py
python
BaseCookie.js_output
(self, attrs=None)
return _nulljoin(result)
Return a string suitable for JavaScript.
Return a string suitable for JavaScript.
[ "Return", "a", "string", "suitable", "for", "JavaScript", "." ]
def js_output(self, attrs=None): """Return a string suitable for JavaScript.""" result = [] items = sorted(self.items()) for key, value in items: result.append(value.js_output(attrs)) return _nulljoin(result)
[ "def", "js_output", "(", "self", ",", "attrs", "=", "None", ")", ":", "result", "=", "[", "]", "items", "=", "sorted", "(", "self", ".", "items", "(", ")", ")", "for", "key", ",", "value", "in", "items", ":", "result", ".", "append", "(", "value", ".", "js_output", "(", "attrs", ")", ")", "return", "_nulljoin", "(", "result", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/http/cookies.py#L514-L520
nvdla/sw
79538ba1b52b040a4a4645f630e457fa01839e90
umd/external/protobuf-2.6/python/google/protobuf/internal/containers.py
python
RepeatedScalarFieldContainer.__getslice__
(self, start, stop)
return self._values[start:stop]
Retrieves the subset of items from between the specified indices.
Retrieves the subset of items from between the specified indices.
[ "Retrieves", "the", "subset", "of", "items", "from", "between", "the", "specified", "indices", "." ]
def __getslice__(self, start, stop): """Retrieves the subset of items from between the specified indices.""" return self._values[start:stop]
[ "def", "__getslice__", "(", "self", ",", "start", ",", "stop", ")", ":", "return", "self", ".", "_values", "[", "start", ":", "stop", "]" ]
https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/google/protobuf/internal/containers.py#L154-L156
Dobiasd/frugally-deep
99d9378c6ef537a209bcb2a102e953899a6ab0e3
keras_export/convert_model.py
python
get_layer_input_shape_tensor_shape
(layer)
return keras_shape_to_fdeep_tensor_shape(layer.input_shape)
Convert layer input shape to an fdeep shape
Convert layer input shape to an fdeep shape
[ "Convert", "layer", "input", "shape", "to", "an", "fdeep", "shape" ]
def get_layer_input_shape_tensor_shape(layer): """Convert layer input shape to an fdeep shape""" return keras_shape_to_fdeep_tensor_shape(layer.input_shape)
[ "def", "get_layer_input_shape_tensor_shape", "(", "layer", ")", ":", "return", "keras_shape_to_fdeep_tensor_shape", "(", "layer", ".", "input_shape", ")" ]
https://github.com/Dobiasd/frugally-deep/blob/99d9378c6ef537a209bcb2a102e953899a6ab0e3/keras_export/convert_model.py#L79-L81
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/tools/sanitizers/sancov_formatter.py
python
merge
(options)
Implements the 'merge' action of this tool.
Implements the 'merge' action of this tool.
[ "Implements", "the", "merge", "action", "of", "this", "tool", "." ]
def merge(options): """Implements the 'merge' action of this tool.""" # Check if folder with coverage output exists. assert (os.path.exists(options.coverage_dir) and os.path.isdir(options.coverage_dir)) # Inputs for multiprocessing. List of tuples of: # Coverage dir, executable name, sancov file name. inputs = [] for f in os.listdir(options.coverage_dir): match = SANCOV_FILE_RE.match(f) if match: inputs.append((options.coverage_dir, match.group(1), f)) logging.info('Merging %d sancov files into %s', len(inputs), options.json_input) # Post-process covered lines in parallel. pool = Pool(CPUS) try: results = pool.imap_unordered(get_covered_lines, inputs) finally: pool.close() # Load existing json data file for merging the results. with open(options.json_input, 'r') as f: data = json.load(f) # Merge muliprocessing results. Mutates data. merge_covered_line_results(data, results) logging.info('Merged data from %d executables, which covers %d files.', len(data['tests']), len(data['files'])) logging.info('Writing results to %s', options.json_output) # Write merged results to file. with open(options.json_output, 'w') as f: json.dump(data, f, sort_keys=True)
[ "def", "merge", "(", "options", ")", ":", "# Check if folder with coverage output exists.", "assert", "(", "os", ".", "path", ".", "exists", "(", "options", ".", "coverage_dir", ")", "and", "os", ".", "path", ".", "isdir", "(", "options", ".", "coverage_dir", ")", ")", "# Inputs for multiprocessing. List of tuples of:", "# Coverage dir, executable name, sancov file name.", "inputs", "=", "[", "]", "for", "f", "in", "os", ".", "listdir", "(", "options", ".", "coverage_dir", ")", ":", "match", "=", "SANCOV_FILE_RE", ".", "match", "(", "f", ")", "if", "match", ":", "inputs", ".", "append", "(", "(", "options", ".", "coverage_dir", ",", "match", ".", "group", "(", "1", ")", ",", "f", ")", ")", "logging", ".", "info", "(", "'Merging %d sancov files into %s'", ",", "len", "(", "inputs", ")", ",", "options", ".", "json_input", ")", "# Post-process covered lines in parallel.", "pool", "=", "Pool", "(", "CPUS", ")", "try", ":", "results", "=", "pool", ".", "imap_unordered", "(", "get_covered_lines", ",", "inputs", ")", "finally", ":", "pool", ".", "close", "(", ")", "# Load existing json data file for merging the results.", "with", "open", "(", "options", ".", "json_input", ",", "'r'", ")", "as", "f", ":", "data", "=", "json", ".", "load", "(", "f", ")", "# Merge muliprocessing results. Mutates data.", "merge_covered_line_results", "(", "data", ",", "results", ")", "logging", ".", "info", "(", "'Merged data from %d executables, which covers %d files.'", ",", "len", "(", "data", "[", "'tests'", "]", ")", ",", "len", "(", "data", "[", "'files'", "]", ")", ")", "logging", ".", "info", "(", "'Writing results to %s'", ",", "options", ".", "json_output", ")", "# Write merged results to file.", "with", "open", "(", "options", ".", "json_output", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "data", ",", "f", ",", "sort_keys", "=", "True", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/v8/tools/sanitizers/sancov_formatter.py#L334-L372
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/variables.py
python
Variable._set_save_slice_info
(self, save_slice_info)
Sets the slice info for this `Variable`. Args: save_slice_info: A `Variable.SaveSliceInfo` object.
Sets the slice info for this `Variable`.
[ "Sets", "the", "slice", "info", "for", "this", "Variable", "." ]
def _set_save_slice_info(self, save_slice_info): """Sets the slice info for this `Variable`. Args: save_slice_info: A `Variable.SaveSliceInfo` object. """ self._save_slice_info = save_slice_info
[ "def", "_set_save_slice_info", "(", "self", ",", "save_slice_info", ")", ":", "self", ".", "_save_slice_info", "=", "save_slice_info" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/variables.py#L1035-L1041
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/ops/gradients.py
python
_hessian_vector_product
(ys, xs, v)
return gradients(elemwise_products, xs)
Multiply the Hessian of `ys` wrt `xs` by `v`. This is an efficient construction that uses a backprop-like approach to compute the product between the Hessian and another vector. The Hessian is usually too large to be explicitly computed or even represented, but this method allows us to at least multiply by it for the same big-O cost as backprop. Implicit Hessian-vector products are the main practical, scalable way of using second derivatives with neural networks. They allow us to do things like construct Krylov subspaces and approximate conjugate gradient descent. Example: if `y` = 1/2 `x`^T A `x`, then `hessian_vector_product(y, x, v)` will return an expression that evaluates to the same values as (A + A.T) `v`. Args: ys: A scalar value, or a tensor or list of tensors to be summed to yield a scalar. xs: A list of tensors that we should construct the Hessian over. v: A list of tensors, with the same shapes as xs, that we want to multiply by the Hessian. Returns: A list of tensors (or if the list would be length 1, a single tensor) containing the product between the Hessian and `v`. Raises: ValueError: `xs` and `v` have different length.
Multiply the Hessian of `ys` wrt `xs` by `v`.
[ "Multiply", "the", "Hessian", "of", "ys", "wrt", "xs", "by", "v", "." ]
def _hessian_vector_product(ys, xs, v): """Multiply the Hessian of `ys` wrt `xs` by `v`. This is an efficient construction that uses a backprop-like approach to compute the product between the Hessian and another vector. The Hessian is usually too large to be explicitly computed or even represented, but this method allows us to at least multiply by it for the same big-O cost as backprop. Implicit Hessian-vector products are the main practical, scalable way of using second derivatives with neural networks. They allow us to do things like construct Krylov subspaces and approximate conjugate gradient descent. Example: if `y` = 1/2 `x`^T A `x`, then `hessian_vector_product(y, x, v)` will return an expression that evaluates to the same values as (A + A.T) `v`. Args: ys: A scalar value, or a tensor or list of tensors to be summed to yield a scalar. xs: A list of tensors that we should construct the Hessian over. v: A list of tensors, with the same shapes as xs, that we want to multiply by the Hessian. Returns: A list of tensors (or if the list would be length 1, a single tensor) containing the product between the Hessian and `v`. Raises: ValueError: `xs` and `v` have different length. """ # Validate the input length = len(xs) if len(v) != length: raise ValueError("xs and v must have the same length.") # First backprop grads = gradients(ys, xs) assert len(grads) == length elemwise_products = [math_ops.mul(grad_elem, array_ops.stop_gradient(v_elem)) for grad_elem, v_elem in zip(grads, v) if grad_elem is not None] # Second backprop return gradients(elemwise_products, xs)
[ "def", "_hessian_vector_product", "(", "ys", ",", "xs", ",", "v", ")", ":", "# Validate the input", "length", "=", "len", "(", "xs", ")", "if", "len", "(", "v", ")", "!=", "length", ":", "raise", "ValueError", "(", "\"xs and v must have the same length.\"", ")", "# First backprop", "grads", "=", "gradients", "(", "ys", ",", "xs", ")", "assert", "len", "(", "grads", ")", "==", "length", "elemwise_products", "=", "[", "math_ops", ".", "mul", "(", "grad_elem", ",", "array_ops", ".", "stop_gradient", "(", "v_elem", ")", ")", "for", "grad_elem", ",", "v_elem", "in", "zip", "(", "grads", ",", "v", ")", "if", "grad_elem", "is", "not", "None", "]", "# Second backprop", "return", "gradients", "(", "elemwise_products", ",", "xs", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/gradients.py#L729-L777
nnrg/opennero
43e12a1bcba6e228639db3886fec1dc47ddc24cb
mods/Roomba/RTNEATAgent.py
python
RTNEATAgent.initialize
(self, init_info)
return True
Initialize an agent brain with sensor information
Initialize an agent brain with sensor information
[ "Initialize", "an", "agent", "brain", "with", "sensor", "information" ]
def initialize(self, init_info): """ Initialize an agent brain with sensor information """ self.actions = init_info.actions # constraints for actions self.sensors = init_info.sensors # constraints for sensors return True
[ "def", "initialize", "(", "self", ",", "init_info", ")", ":", "self", ".", "actions", "=", "init_info", ".", "actions", "# constraints for actions", "self", ".", "sensors", "=", "init_info", ".", "sensors", "# constraints for sensors", "return", "True" ]
https://github.com/nnrg/opennero/blob/43e12a1bcba6e228639db3886fec1dc47ddc24cb/mods/Roomba/RTNEATAgent.py#L18-L24
microsoft/onnxruntime
f92e47e95b13a240e37caf7b36577983544f98fc
orttraining/orttraining/python/training/ortmodule/_fallback.py
python
_FallbackManager.handle_exception
(self, exception: Exception, log_level: _logger.LogLevel, override_policy: Optional[_FallbackPolicy] = None)
Process incoming `exception` based on the selected `policy` If the incoming `exception` is handled by the specified policy, `_FallbackManager` saves the exception so that ORTModule can track the pending fallback and trigger it during model execution. Otherwise, the incoming exception is immediately raised. Args: exception (`ORTModuleFallbackException`): Exception that must be handled override_policy (`_FallbackPolicy`, optional): Policy to be checked for the incoming `exception`. if None is specified, all (except _FallbackPolicy.FALLBACK_DISABLE) are implicitly checked Raises: `exception`: Original exception is raised when there is no matching policy for it
Process incoming `exception` based on the selected `policy`
[ "Process", "incoming", "exception", "based", "on", "the", "selected", "policy" ]
def handle_exception(self, exception: Exception, log_level: _logger.LogLevel, override_policy: Optional[_FallbackPolicy] = None) -> None: '''Process incoming `exception` based on the selected `policy` If the incoming `exception` is handled by the specified policy, `_FallbackManager` saves the exception so that ORTModule can track the pending fallback and trigger it during model execution. Otherwise, the incoming exception is immediately raised. Args: exception (`ORTModuleFallbackException`): Exception that must be handled override_policy (`_FallbackPolicy`, optional): Policy to be checked for the incoming `exception`. if None is specified, all (except _FallbackPolicy.FALLBACK_DISABLE) are implicitly checked Raises: `exception`: Original exception is raised when there is no matching policy for it ''' def _set_exception(policy: _FallbackPolicy, exception: Exception, log_level: _logger.LogLevel): if policy is not _FallbackPolicy.FALLBACK_DISABLE and \ self.policy.is_set(policy) and \ (policy.value in self._policy_exception_map and type(exception) in self._policy_exception_map[policy.value]): if log_level <= _logger.LogLevel.INFO: warnings.warn( f'Fallback for policy {policy.name} is pending.', UserWarning) # ORTModuleInitException exceptions do not call `fallback()` through `GraphExecutionManager`, # Instead, it fallbacks to PyTorch implicitly through `ORTModule._torch_module = TorchModulePytorch(module)` if log_level <= _logger.LogLevel.WARNING and policy == _FallbackPolicy.FALLBACK_BAD_INITIALIZATION: warnings.warn( (f'Fallback to PyTorch due to exception {type(exception)} was triggered. ' 'Report this issue with a minimal repro at https://www.github.com/microsoft/onnxruntime. ' f'See details below:\n\n{_utils.get_exception_as_string(exception)}'), UserWarning) self._exception = exception if override_policy is None: for policy in _FallbackPolicy: _set_exception(policy, exception, log_level) else: _set_exception(override_policy, exception, log_level) if self._exception is None: # No fallback, raise failure to user raise exception
[ "def", "handle_exception", "(", "self", ",", "exception", ":", "Exception", ",", "log_level", ":", "_logger", ".", "LogLevel", ",", "override_policy", ":", "Optional", "[", "_FallbackPolicy", "]", "=", "None", ")", "->", "None", ":", "def", "_set_exception", "(", "policy", ":", "_FallbackPolicy", ",", "exception", ":", "Exception", ",", "log_level", ":", "_logger", ".", "LogLevel", ")", ":", "if", "policy", "is", "not", "_FallbackPolicy", ".", "FALLBACK_DISABLE", "and", "self", ".", "policy", ".", "is_set", "(", "policy", ")", "and", "(", "policy", ".", "value", "in", "self", ".", "_policy_exception_map", "and", "type", "(", "exception", ")", "in", "self", ".", "_policy_exception_map", "[", "policy", ".", "value", "]", ")", ":", "if", "log_level", "<=", "_logger", ".", "LogLevel", ".", "INFO", ":", "warnings", ".", "warn", "(", "f'Fallback for policy {policy.name} is pending.'", ",", "UserWarning", ")", "# ORTModuleInitException exceptions do not call `fallback()` through `GraphExecutionManager`,", "# Instead, it fallbacks to PyTorch implicitly through `ORTModule._torch_module = TorchModulePytorch(module)`", "if", "log_level", "<=", "_logger", ".", "LogLevel", ".", "WARNING", "and", "policy", "==", "_FallbackPolicy", ".", "FALLBACK_BAD_INITIALIZATION", ":", "warnings", ".", "warn", "(", "(", "f'Fallback to PyTorch due to exception {type(exception)} was triggered. '", "'Report this issue with a minimal repro at https://www.github.com/microsoft/onnxruntime. '", "f'See details below:\\n\\n{_utils.get_exception_as_string(exception)}'", ")", ",", "UserWarning", ")", "self", ".", "_exception", "=", "exception", "if", "override_policy", "is", "None", ":", "for", "policy", "in", "_FallbackPolicy", ":", "_set_exception", "(", "policy", ",", "exception", ",", "log_level", ")", "else", ":", "_set_exception", "(", "override_policy", ",", "exception", ",", "log_level", ")", "if", "self", ".", "_exception", "is", "None", ":", "# No fallback, raise failure to user", "raise", "exception" ]
https://github.com/microsoft/onnxruntime/blob/f92e47e95b13a240e37caf7b36577983544f98fc/orttraining/orttraining/python/training/ortmodule/_fallback.py#L105-L151
TGAC/KAT
e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216
deps/jellyfish-2.2.0/swig/python/jellyfish.py
python
MerDNA.reverse_complement
(self)
return _jellyfish.MerDNA_reverse_complement(self)
Change the mer to its reverse complement
Change the mer to its reverse complement
[ "Change", "the", "mer", "to", "its", "reverse", "complement" ]
def reverse_complement(self): """Change the mer to its reverse complement""" return _jellyfish.MerDNA_reverse_complement(self)
[ "def", "reverse_complement", "(", "self", ")", ":", "return", "_jellyfish", ".", "MerDNA_reverse_complement", "(", "self", ")" ]
https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/jellyfish-2.2.0/swig/python/jellyfish.py#L137-L139
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/webapp2/webapp2.py
python
RequestContext.__enter__
(self)
return request, response
Enters the request context. :returns: A tuple ``(request, response)``.
Enters the request context.
[ "Enters", "the", "request", "context", "." ]
def __enter__(self): """Enters the request context. :returns: A tuple ``(request, response)``. """ # Build request and response. request = self.app.request_class(self.environ) response = self.app.response_class() # Make active app and response available through the request object. request.app = self.app request.response = response # Register global variables. self.app.set_globals(app=self.app, request=request) return request, response
[ "def", "__enter__", "(", "self", ")", ":", "# Build request and response.", "request", "=", "self", ".", "app", ".", "request_class", "(", "self", ".", "environ", ")", "response", "=", "self", ".", "app", ".", "response_class", "(", ")", "# Make active app and response available through the request object.", "request", ".", "app", "=", "self", ".", "app", "request", ".", "response", "=", "response", "# Register global variables.", "self", ".", "app", ".", "set_globals", "(", "app", "=", "self", ".", "app", ",", "request", "=", "request", ")", "return", "request", ",", "response" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/webapp2/webapp2.py#L1401-L1415
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextCtrl.LinesJoin
(*args, **kwargs)
return _stc.StyledTextCtrl_LinesJoin(*args, **kwargs)
LinesJoin(self) Join the lines in the target.
LinesJoin(self)
[ "LinesJoin", "(", "self", ")" ]
def LinesJoin(*args, **kwargs): """ LinesJoin(self) Join the lines in the target. """ return _stc.StyledTextCtrl_LinesJoin(*args, **kwargs)
[ "def", "LinesJoin", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_LinesJoin", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L4297-L4303
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ToolBarToolBase.GetLongHelp
(*args, **kwargs)
return _controls_.ToolBarToolBase_GetLongHelp(*args, **kwargs)
GetLongHelp(self) -> String
GetLongHelp(self) -> String
[ "GetLongHelp", "(", "self", ")", "-", ">", "String" ]
def GetLongHelp(*args, **kwargs): """GetLongHelp(self) -> String""" return _controls_.ToolBarToolBase_GetLongHelp(*args, **kwargs)
[ "def", "GetLongHelp", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ToolBarToolBase_GetLongHelp", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L3509-L3511
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/abins/input/casteploader.py
python
CASTEPLoader._check_acoustic_sum
(self)
Checks if acoustic sum correction has been applied during calculations. :returns: True is correction has been applied, otherwise False.
Checks if acoustic sum correction has been applied during calculations. :returns: True is correction has been applied, otherwise False.
[ "Checks", "if", "acoustic", "sum", "correction", "has", "been", "applied", "during", "calculations", ".", ":", "returns", ":", "True", "is", "correction", "has", "been", "applied", "otherwise", "False", "." ]
def _check_acoustic_sum(self): """ Checks if acoustic sum correction has been applied during calculations. :returns: True is correction has been applied, otherwise False. """ header_str_sum = r"^ +q-pt=\s+\d+ +(%(s)s) +(%(s)s) +(%(s)s) +(%(s)s) + " \ r"(%(s)s) + (%(s)s) + (%(s)s)" % {'s': self._float_regex} header_sum = re.compile(header_str_sum) with open(self._clerk.get_input_filename(), "r") as f: found = False for line in f: # iterate over the file one line at a time(memory efficient) if header_sum.match(line): return True return found
[ "def", "_check_acoustic_sum", "(", "self", ")", ":", "header_str_sum", "=", "r\"^ +q-pt=\\s+\\d+ +(%(s)s) +(%(s)s) +(%(s)s) +(%(s)s) + \"", "r\"(%(s)s) + (%(s)s) + (%(s)s)\"", "%", "{", "'s'", ":", "self", ".", "_float_regex", "}", "header_sum", "=", "re", ".", "compile", "(", "header_str_sum", ")", "with", "open", "(", "self", ".", "_clerk", ".", "get_input_filename", "(", ")", ",", "\"r\"", ")", "as", "f", ":", "found", "=", "False", "for", "line", "in", "f", ":", "# iterate over the file one line at a time(memory efficient)", "if", "header_sum", ".", "match", "(", "line", ")", ":", "return", "True", "return", "found" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/abins/input/casteploader.py#L171-L186
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py
python
NanLoss.__init__
(self, loss_tensor, every_n_steps=100, fail_on_nan_loss=True)
Initializes NanLoss monitor. Args: loss_tensor: `Tensor`, the loss tensor. every_n_steps: `int`, run check every this many steps. fail_on_nan_loss: `bool`, whether to raise exception when loss is NaN.
Initializes NanLoss monitor.
[ "Initializes", "NanLoss", "monitor", "." ]
def __init__(self, loss_tensor, every_n_steps=100, fail_on_nan_loss=True): """Initializes NanLoss monitor. Args: loss_tensor: `Tensor`, the loss tensor. every_n_steps: `int`, run check every this many steps. fail_on_nan_loss: `bool`, whether to raise exception when loss is NaN. """ super(NanLoss, self).__init__(every_n_steps=every_n_steps) self._loss_tensor = loss_tensor self._fail_on_nan_loss = fail_on_nan_loss
[ "def", "__init__", "(", "self", ",", "loss_tensor", ",", "every_n_steps", "=", "100", ",", "fail_on_nan_loss", "=", "True", ")", ":", "super", "(", "NanLoss", ",", "self", ")", ".", "__init__", "(", "every_n_steps", "=", "every_n_steps", ")", "self", ".", "_loss_tensor", "=", "loss_tensor", "self", ".", "_fail_on_nan_loss", "=", "fail_on_nan_loss" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/learn/python/learn/monitors.py#L1064-L1074
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/nanops.py
python
nanprod
(values, axis=None, skipna=True, min_count=0, mask=None)
return _maybe_null_out(result, axis, mask, min_count=min_count)
Parameters ---------- values : ndarray[dtype] axis: int, optional skipna : bool, default True min_count: int, default 0 mask : ndarray[bool], optional nan-mask if known Returns ------- result : dtype Examples -------- >>> import pandas.core.nanops as nanops >>> s = pd.Series([1, 2, 3, np.nan]) >>> nanops.nanprod(s) 6.0 Returns -------- The product of all elements on a given axis. ( NaNs are treated as 1)
Parameters ---------- values : ndarray[dtype] axis: int, optional skipna : bool, default True min_count: int, default 0 mask : ndarray[bool], optional nan-mask if known
[ "Parameters", "----------", "values", ":", "ndarray", "[", "dtype", "]", "axis", ":", "int", "optional", "skipna", ":", "bool", "default", "True", "min_count", ":", "int", "default", "0", "mask", ":", "ndarray", "[", "bool", "]", "optional", "nan", "-", "mask", "if", "known" ]
def nanprod(values, axis=None, skipna=True, min_count=0, mask=None): """ Parameters ---------- values : ndarray[dtype] axis: int, optional skipna : bool, default True min_count: int, default 0 mask : ndarray[bool], optional nan-mask if known Returns ------- result : dtype Examples -------- >>> import pandas.core.nanops as nanops >>> s = pd.Series([1, 2, 3, np.nan]) >>> nanops.nanprod(s) 6.0 Returns -------- The product of all elements on a given axis. ( NaNs are treated as 1) """ if mask is None: mask = isna(values) if skipna and not is_any_int_dtype(values): values = values.copy() values[mask] = 1 result = values.prod(axis) return _maybe_null_out(result, axis, mask, min_count=min_count)
[ "def", "nanprod", "(", "values", ",", "axis", "=", "None", ",", "skipna", "=", "True", ",", "min_count", "=", "0", ",", "mask", "=", "None", ")", ":", "if", "mask", "is", "None", ":", "mask", "=", "isna", "(", "values", ")", "if", "skipna", "and", "not", "is_any_int_dtype", "(", "values", ")", ":", "values", "=", "values", ".", "copy", "(", ")", "values", "[", "mask", "]", "=", "1", "result", "=", "values", ".", "prod", "(", "axis", ")", "return", "_maybe_null_out", "(", "result", ",", "axis", ",", "mask", ",", "min_count", "=", "min_count", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/nanops.py#L984-L1016
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Tools/scripts/patchcheck.py
python
reported_news
(file_paths)
return any(p.startswith(os.path.join('Misc', 'NEWS.d', 'next')) for p in file_paths)
Check if Misc/NEWS.d has been changed.
Check if Misc/NEWS.d has been changed.
[ "Check", "if", "Misc", "/", "NEWS", ".", "d", "has", "been", "changed", "." ]
def reported_news(file_paths): """Check if Misc/NEWS.d has been changed.""" return any(p.startswith(os.path.join('Misc', 'NEWS.d', 'next')) for p in file_paths)
[ "def", "reported_news", "(", "file_paths", ")", ":", "return", "any", "(", "p", ".", "startswith", "(", "os", ".", "path", ".", "join", "(", "'Misc'", ",", "'NEWS.d'", ",", "'next'", ")", ")", "for", "p", "in", "file_paths", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Tools/scripts/patchcheck.py#L202-L205
apache/kudu
90895ce76590f10730ad7aac3613b69d89ff5422
build-support/check_compatibility.py
python
find_client_jars
(path)
return [j for j in all_jars if ( "-javadoc" not in j and "-sources" not in j and "-test-sources" not in j and "-tests" not in j and "-unshaded" not in j and "buildSrc" not in j and "gradle-wrapper" not in j and "kudu-backup" not in j and "kudu-hive" not in j and "kudu-jepsen" not in j and "kudu-proto" not in j and "kudu-subprocess" not in j)]
Return a list of jars within 'path' to be checked for compatibility.
Return a list of jars within 'path' to be checked for compatibility.
[ "Return", "a", "list", "of", "jars", "within", "path", "to", "be", "checked", "for", "compatibility", "." ]
def find_client_jars(path): """ Return a list of jars within 'path' to be checked for compatibility. """ all_jars = set(check_output(["find", path, "-name", "*.jar"]).decode('utf-8').splitlines()) return [j for j in all_jars if ( "-javadoc" not in j and "-sources" not in j and "-test-sources" not in j and "-tests" not in j and "-unshaded" not in j and "buildSrc" not in j and "gradle-wrapper" not in j and "kudu-backup" not in j and "kudu-hive" not in j and "kudu-jepsen" not in j and "kudu-proto" not in j and "kudu-subprocess" not in j)]
[ "def", "find_client_jars", "(", "path", ")", ":", "all_jars", "=", "set", "(", "check_output", "(", "[", "\"find\"", ",", "path", ",", "\"-name\"", ",", "\"*.jar\"", "]", ")", ".", "decode", "(", "'utf-8'", ")", ".", "splitlines", "(", ")", ")", "return", "[", "j", "for", "j", "in", "all_jars", "if", "(", "\"-javadoc\"", "not", "in", "j", "and", "\"-sources\"", "not", "in", "j", "and", "\"-test-sources\"", "not", "in", "j", "and", "\"-tests\"", "not", "in", "j", "and", "\"-unshaded\"", "not", "in", "j", "and", "\"buildSrc\"", "not", "in", "j", "and", "\"gradle-wrapper\"", "not", "in", "j", "and", "\"kudu-backup\"", "not", "in", "j", "and", "\"kudu-hive\"", "not", "in", "j", "and", "\"kudu-jepsen\"", "not", "in", "j", "and", "\"kudu-proto\"", "not", "in", "j", "and", "\"kudu-subprocess\"", "not", "in", "j", ")", "]" ]
https://github.com/apache/kudu/blob/90895ce76590f10730ad7aac3613b69d89ff5422/build-support/check_compatibility.py#L121-L136
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/advancedsplash.py
python
AdvancedSplash.OnCloseWindow
(self, event)
Handles the ``wx.EVT_CLOSE`` event for :class:`AdvancedSplash`. :param `event`: a :class:`CloseEvent` to be processed. :note: This reproduces the behavior of :class:`SplashScreen`.
Handles the ``wx.EVT_CLOSE`` event for :class:`AdvancedSplash`.
[ "Handles", "the", "wx", ".", "EVT_CLOSE", "event", "for", ":", "class", ":", "AdvancedSplash", "." ]
def OnCloseWindow(self, event): """ Handles the ``wx.EVT_CLOSE`` event for :class:`AdvancedSplash`. :param `event`: a :class:`CloseEvent` to be processed. :note: This reproduces the behavior of :class:`SplashScreen`. """ if hasattr(self, "_splashtimer"): self._splashtimer.Stop() del self._splashtimer self.Destroy()
[ "def", "OnCloseWindow", "(", "self", ",", "event", ")", ":", "if", "hasattr", "(", "self", ",", "\"_splashtimer\"", ")", ":", "self", ".", "_splashtimer", ".", "Stop", "(", ")", "del", "self", ".", "_splashtimer", "self", ".", "Destroy", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/advancedsplash.py#L380-L393
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/aui.py
python
AuiNotebookEvent.SetDragSource
(*args, **kwargs)
return _aui.AuiNotebookEvent_SetDragSource(*args, **kwargs)
SetDragSource(self, AuiNotebook s)
SetDragSource(self, AuiNotebook s)
[ "SetDragSource", "(", "self", "AuiNotebook", "s", ")" ]
def SetDragSource(*args, **kwargs): """SetDragSource(self, AuiNotebook s)""" return _aui.AuiNotebookEvent_SetDragSource(*args, **kwargs)
[ "def", "SetDragSource", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiNotebookEvent_SetDragSource", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L1084-L1086
facebook/bistro
db9eff7e92f5cedcc917a440d5c88064c7980e40
build/fbcode_builder/getdeps/platform.py
python
get_available_ram
()
Returns a platform-appropriate available RAM metric in MiB.
Returns a platform-appropriate available RAM metric in MiB.
[ "Returns", "a", "platform", "-", "appropriate", "available", "RAM", "metric", "in", "MiB", "." ]
def get_available_ram() -> int: """ Returns a platform-appropriate available RAM metric in MiB. """ if sys.platform == "linux": return _get_available_ram_linux() elif sys.platform == "darwin": return _get_available_ram_macos() elif sys.platform == "win32": return _get_available_ram_windows() else: raise NotImplementedError( f"platform {sys.platform} does not have an implementation of get_available_ram" )
[ "def", "get_available_ram", "(", ")", "->", "int", ":", "if", "sys", ".", "platform", "==", "\"linux\"", ":", "return", "_get_available_ram_linux", "(", ")", "elif", "sys", ".", "platform", "==", "\"darwin\"", ":", "return", "_get_available_ram_macos", "(", ")", "elif", "sys", ".", "platform", "==", "\"win32\"", ":", "return", "_get_available_ram_windows", "(", ")", "else", ":", "raise", "NotImplementedError", "(", "f\"platform {sys.platform} does not have an implementation of get_available_ram\"", ")" ]
https://github.com/facebook/bistro/blob/db9eff7e92f5cedcc917a440d5c88064c7980e40/build/fbcode_builder/getdeps/platform.py#L133-L146
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
bindings/python/htcondor/htchirp/htchirp.py
python
HTChirp.getfile
(self, remote_file, local_file)
return bytes_recv
Retrieve an entire file efficiently from the remote machine. :param remote_file: Path to file to be sent from remote machine :param local_file: Path to file to be written to on local machine :returns: Bytes written
Retrieve an entire file efficiently from the remote machine.
[ "Retrieve", "an", "entire", "file", "efficiently", "from", "the", "remote", "machine", "." ]
def getfile(self, remote_file, local_file): """Retrieve an entire file efficiently from the remote machine. :param remote_file: Path to file to be sent from remote machine :param local_file: Path to file to be written to on local machine :returns: Bytes written """ length = int(self._simple_command("getfile {0}\n".format(quote(remote_file)))) bytes_recv = self._get_fixed_data(length, local_file) return bytes_recv
[ "def", "getfile", "(", "self", ",", "remote_file", ",", "local_file", ")", ":", "length", "=", "int", "(", "self", ".", "_simple_command", "(", "\"getfile {0}\\n\"", ".", "format", "(", "quote", "(", "remote_file", ")", ")", ")", ")", "bytes_recv", "=", "self", ".", "_get_fixed_data", "(", "length", ",", "local_file", ")", "return", "bytes_recv" ]
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/bindings/python/htcondor/htchirp/htchirp.py#L881-L893
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBCommandInterpreter.HasCustomQuitExitCode
(self)
return _lldb.SBCommandInterpreter_HasCustomQuitExitCode(self)
HasCustomQuitExitCode(SBCommandInterpreter self) -> bool
HasCustomQuitExitCode(SBCommandInterpreter self) -> bool
[ "HasCustomQuitExitCode", "(", "SBCommandInterpreter", "self", ")", "-", ">", "bool" ]
def HasCustomQuitExitCode(self): """HasCustomQuitExitCode(SBCommandInterpreter self) -> bool""" return _lldb.SBCommandInterpreter_HasCustomQuitExitCode(self)
[ "def", "HasCustomQuitExitCode", "(", "self", ")", ":", "return", "_lldb", ".", "SBCommandInterpreter_HasCustomQuitExitCode", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L2697-L2699
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/png/png.py
python
Test.testPGMin
(self)
Test that the command line tool can read PGM files.
Test that the command line tool can read PGM files.
[ "Test", "that", "the", "command", "line", "tool", "can", "read", "PGM", "files", "." ]
def testPGMin(self): """Test that the command line tool can read PGM files.""" def do(): return _main(['testPGMin']) s = BytesIO() s.write(strtobytes('P5 2 2 3\n')) s.write(strtobytes('\x00\x01\x02\x03')) s.flush() s.seek(0) o = BytesIO() testWithIO(s, o, do) r = Reader(bytes=o.getvalue()) x,y,pixels,meta = r.read() self.assertTrue(r.greyscale) self.assertEqual(r.bitdepth, 2)
[ "def", "testPGMin", "(", "self", ")", ":", "def", "do", "(", ")", ":", "return", "_main", "(", "[", "'testPGMin'", "]", ")", "s", "=", "BytesIO", "(", ")", "s", ".", "write", "(", "strtobytes", "(", "'P5 2 2 3\\n'", ")", ")", "s", ".", "write", "(", "strtobytes", "(", "'\\x00\\x01\\x02\\x03'", ")", ")", "s", ".", "flush", "(", ")", "s", ".", "seek", "(", "0", ")", "o", "=", "BytesIO", "(", ")", "testWithIO", "(", "s", ",", "o", ",", "do", ")", "r", "=", "Reader", "(", "bytes", "=", "o", ".", "getvalue", "(", ")", ")", "x", ",", "y", ",", "pixels", ",", "meta", "=", "r", ".", "read", "(", ")", "self", ".", "assertTrue", "(", "r", ".", "greyscale", ")", "self", ".", "assertEqual", "(", "r", ".", "bitdepth", ",", "2", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/png/png.py#L2649-L2663
rodeofx/OpenWalter
6116fbe3f04f1146c854afbfbdbe944feaee647e
walter/common/walterWidgets/walterBaseTreeView.py
python
BaseDelegate.drawIcon
(self, rect, painter, option, index)
Draw the item's icon.
Draw the item's icon.
[ "Draw", "the", "item", "s", "icon", "." ]
def drawIcon(self, rect, painter, option, index): """Draw the item's icon.""" painter.save() if (index.column() == 0): icon = toPyObject(index.data(ICON)) if icon: newRect = QtCore.QRect() padding = dpiScale(4) center = \ toPyObject(index.data(QtCore.Qt.SizeHintRole)).height() / 2 newRect.setRight(rect.left() - padding) newRect.setLeft(newRect.right() - self.ICON_WIDTH + dpiScale(1)) newRect.setTop(rect.top() + center - self.ICON_WIDTH / 2) newRect.setBottom(newRect.top() + self.ICON_WIDTH - dpiScale(1)) painter.drawPixmap(newRect, icon) painter.restore()
[ "def", "drawIcon", "(", "self", ",", "rect", ",", "painter", ",", "option", ",", "index", ")", ":", "painter", ".", "save", "(", ")", "if", "(", "index", ".", "column", "(", ")", "==", "0", ")", ":", "icon", "=", "toPyObject", "(", "index", ".", "data", "(", "ICON", ")", ")", "if", "icon", ":", "newRect", "=", "QtCore", ".", "QRect", "(", ")", "padding", "=", "dpiScale", "(", "4", ")", "center", "=", "toPyObject", "(", "index", ".", "data", "(", "QtCore", ".", "Qt", ".", "SizeHintRole", ")", ")", ".", "height", "(", ")", "/", "2", "newRect", ".", "setRight", "(", "rect", ".", "left", "(", ")", "-", "padding", ")", "newRect", ".", "setLeft", "(", "newRect", ".", "right", "(", ")", "-", "self", ".", "ICON_WIDTH", "+", "dpiScale", "(", "1", ")", ")", "newRect", ".", "setTop", "(", "rect", ".", "top", "(", ")", "+", "center", "-", "self", ".", "ICON_WIDTH", "/", "2", ")", "newRect", ".", "setBottom", "(", "newRect", ".", "top", "(", ")", "+", "self", ".", "ICON_WIDTH", "-", "dpiScale", "(", "1", ")", ")", "painter", ".", "drawPixmap", "(", "newRect", ",", "icon", ")", "painter", ".", "restore", "(", ")" ]
https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/common/walterWidgets/walterBaseTreeView.py#L317-L335
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/matlib.py
python
rand
(*args)
return asmatrix(np.random.rand(*args))
Return a matrix of random values with given shape. Create a matrix of the given shape and propagate it with random samples from a uniform distribution over ``[0, 1)``. Parameters ---------- \\*args : Arguments Shape of the output. If given as N integers, each integer specifies the size of one dimension. If given as a tuple, this tuple gives the complete shape. Returns ------- out : ndarray The matrix of random values with shape given by `\\*args`. See Also -------- randn, numpy.random.rand Examples -------- >>> import numpy.matlib >>> np.matlib.rand(2, 3) matrix([[ 0.68340382, 0.67926887, 0.83271405], [ 0.00793551, 0.20468222, 0.95253525]]) #random >>> np.matlib.rand((2, 3)) matrix([[ 0.84682055, 0.73626594, 0.11308016], [ 0.85429008, 0.3294825 , 0.89139555]]) #random If the first argument is a tuple, other arguments are ignored: >>> np.matlib.rand((2, 3), 4) matrix([[ 0.46898646, 0.15163588, 0.95188261], [ 0.59208621, 0.09561818, 0.00583606]]) #random
Return a matrix of random values with given shape.
[ "Return", "a", "matrix", "of", "random", "values", "with", "given", "shape", "." ]
def rand(*args): """ Return a matrix of random values with given shape. Create a matrix of the given shape and propagate it with random samples from a uniform distribution over ``[0, 1)``. Parameters ---------- \\*args : Arguments Shape of the output. If given as N integers, each integer specifies the size of one dimension. If given as a tuple, this tuple gives the complete shape. Returns ------- out : ndarray The matrix of random values with shape given by `\\*args`. See Also -------- randn, numpy.random.rand Examples -------- >>> import numpy.matlib >>> np.matlib.rand(2, 3) matrix([[ 0.68340382, 0.67926887, 0.83271405], [ 0.00793551, 0.20468222, 0.95253525]]) #random >>> np.matlib.rand((2, 3)) matrix([[ 0.84682055, 0.73626594, 0.11308016], [ 0.85429008, 0.3294825 , 0.89139555]]) #random If the first argument is a tuple, other arguments are ignored: >>> np.matlib.rand((2, 3), 4) matrix([[ 0.46898646, 0.15163588, 0.95188261], [ 0.59208621, 0.09561818, 0.00583606]]) #random """ if isinstance(args[0], tuple): args = args[0] return asmatrix(np.random.rand(*args))
[ "def", "rand", "(", "*", "args", ")", ":", "if", "isinstance", "(", "args", "[", "0", "]", ",", "tuple", ")", ":", "args", "=", "args", "[", "0", "]", "return", "asmatrix", "(", "np", ".", "random", ".", "rand", "(", "*", "args", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/matlib.py#L220-L263
zachriggle/ida-splode
a4aee3be415b318a0e051a523ebd0a8d6d5e0026
py/idasplode/query.py
python
TracesWhichModifyOrReadCurrentIdaFile
(query={})
return TracesWhichInteractWithMemory(low=addr.Min(), high=addr.Max())
Queries for all Read and Write traces, where either the memory read, or the value at the memory address read, is within the file open in IDA.
Queries for all Read and Write traces, where either the memory read, or the value at the memory address read, is within the file open in IDA.
[ "Queries", "for", "all", "Read", "and", "Write", "traces", "where", "either", "the", "memory", "read", "or", "the", "value", "at", "the", "memory", "address", "read", "is", "within", "the", "file", "open", "in", "IDA", "." ]
def TracesWhichModifyOrReadCurrentIdaFile(query={}): """ Queries for all Read and Write traces, where either the memory read, or the value at the memory address read, is within the file open in IDA. """ return TracesWhichInteractWithMemory(low=addr.Min(), high=addr.Max())
[ "def", "TracesWhichModifyOrReadCurrentIdaFile", "(", "query", "=", "{", "}", ")", ":", "return", "TracesWhichInteractWithMemory", "(", "low", "=", "addr", ".", "Min", "(", ")", ",", "high", "=", "addr", ".", "Max", "(", ")", ")" ]
https://github.com/zachriggle/ida-splode/blob/a4aee3be415b318a0e051a523ebd0a8d6d5e0026/py/idasplode/query.py#L81-L87
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/agilepy/lib_wx/objpanel.py
python
BooleanWidgetContainer.get_widgetvalue
(self)
return self.valuewidget.GetValue()
Returnes current value from valuewidget. Depends on attribute type and hence widgettype. To be overwritten.
Returnes current value from valuewidget. Depends on attribute type and hence widgettype. To be overwritten.
[ "Returnes", "current", "value", "from", "valuewidget", ".", "Depends", "on", "attribute", "type", "and", "hence", "widgettype", ".", "To", "be", "overwritten", "." ]
def get_widgetvalue(self): """ Returnes current value from valuewidget. Depends on attribute type and hence widgettype. To be overwritten. """ return self.valuewidget.GetValue()
[ "def", "get_widgetvalue", "(", "self", ")", ":", "return", "self", ".", "valuewidget", ".", "GetValue", "(", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/objpanel.py#L801-L807
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
Slider.GetLineSize
(*args, **kwargs)
return _controls_.Slider_GetLineSize(*args, **kwargs)
GetLineSize(self) -> int
GetLineSize(self) -> int
[ "GetLineSize", "(", "self", ")", "-", ">", "int" ]
def GetLineSize(*args, **kwargs): """GetLineSize(self) -> int""" return _controls_.Slider_GetLineSize(*args, **kwargs)
[ "def", "GetLineSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "Slider_GetLineSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L2879-L2881
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/zoombar.py
python
ZoomBarImage.SetSize
(self, width, height)
Sets the button size. :param `width`: the button width; :param `height`: the button height.
Sets the button size.
[ "Sets", "the", "button", "size", "." ]
def SetSize(self, width, height): """ Sets the button size. :param `width`: the button width; :param `height`: the button height. """ self._width = width self._height = height
[ "def", "SetSize", "(", "self", ",", "width", ",", "height", ")", ":", "self", ".", "_width", "=", "width", "self", ".", "_height", "=", "height" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/zoombar.py#L430-L439
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/codecs.py
python
StreamWriter.write
(self, object)
Writes the object's contents encoded to self.stream.
Writes the object's contents encoded to self.stream.
[ "Writes", "the", "object", "s", "contents", "encoded", "to", "self", ".", "stream", "." ]
def write(self, object): """ Writes the object's contents encoded to self.stream. """ data, consumed = self.encode(object, self.errors) self.stream.write(data)
[ "def", "write", "(", "self", ",", "object", ")", ":", "data", ",", "consumed", "=", "self", ".", "encode", "(", "object", ",", "self", ".", "errors", ")", "self", ".", "stream", ".", "write", "(", "data", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/codecs.py#L347-L352