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
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/dataview.py
python
DataViewEvent.SetColumn
(*args, **kwargs)
return _dataview.DataViewEvent_SetColumn(*args, **kwargs)
SetColumn(self, int col)
SetColumn(self, int col)
[ "SetColumn", "(", "self", "int", "col", ")" ]
def SetColumn(*args, **kwargs): """SetColumn(self, int col)""" return _dataview.DataViewEvent_SetColumn(*args, **kwargs)
[ "def", "SetColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewEvent_SetColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1911-L1913
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/boto3/s3/inject.py
python
object_copy
(self, CopySource, ExtraArgs=None, Callback=None, SourceClient=None, Config=None)
return self.meta.client.copy( CopySource=CopySource, Bucket=self.bucket_name, Key=self.key, ExtraArgs=ExtraArgs, Callback=Callback, SourceClient=SourceClient, Config=Config)
Copy an object from one S3 location to this object. This is a managed transfer which will perform a multipart copy in multiple threads if necessary. Usage:: import boto3 s3 = boto3.resource('s3') copy_source = { 'Bucket': 'mybucket', 'Key': 'mykey' } bucket = s3.Bucket('otherbucket') obj = bucket.Object('otherkey') obj.copy(copy_source) :type CopySource: dict :param CopySource: The name of the source bucket, key name of the source object, and optional version ID of the source object. The dictionary format is: ``{'Bucket': 'bucket', 'Key': 'key', 'VersionId': 'id'}``. Note that the ``VersionId`` key is optional and may be omitted. :type ExtraArgs: dict :param ExtraArgs: Extra arguments that may be passed to the client operation :type Callback: function :param Callback: A method which takes a number of bytes transferred to be periodically called during the copy. :type SourceClient: botocore or boto3 Client :param SourceClient: The client to be used for operation that may happen at the source object. For example, this client is used for the head_object that determines the size of the copy. If no client is provided, the current client is used as the client for the source object. :type Config: boto3.s3.transfer.TransferConfig :param Config: The transfer configuration to be used when performing the copy.
Copy an object from one S3 location to this object.
[ "Copy", "an", "object", "from", "one", "S3", "location", "to", "this", "object", "." ]
def object_copy(self, CopySource, ExtraArgs=None, Callback=None, SourceClient=None, Config=None): """Copy an object from one S3 location to this object. This is a managed transfer which will perform a multipart copy in multiple threads if necessary. Usage:: import boto3 s3 = boto3.resource('s3') copy_source = { 'Bucket': 'mybucket', 'Key': 'mykey' } bucket = s3.Bucket('otherbucket') obj = bucket.Object('otherkey') obj.copy(copy_source) :type CopySource: dict :param CopySource: The name of the source bucket, key name of the source object, and optional version ID of the source object. The dictionary format is: ``{'Bucket': 'bucket', 'Key': 'key', 'VersionId': 'id'}``. Note that the ``VersionId`` key is optional and may be omitted. :type ExtraArgs: dict :param ExtraArgs: Extra arguments that may be passed to the client operation :type Callback: function :param Callback: A method which takes a number of bytes transferred to be periodically called during the copy. :type SourceClient: botocore or boto3 Client :param SourceClient: The client to be used for operation that may happen at the source object. For example, this client is used for the head_object that determines the size of the copy. If no client is provided, the current client is used as the client for the source object. :type Config: boto3.s3.transfer.TransferConfig :param Config: The transfer configuration to be used when performing the copy. """ return self.meta.client.copy( CopySource=CopySource, Bucket=self.bucket_name, Key=self.key, ExtraArgs=ExtraArgs, Callback=Callback, SourceClient=SourceClient, Config=Config)
[ "def", "object_copy", "(", "self", ",", "CopySource", ",", "ExtraArgs", "=", "None", ",", "Callback", "=", "None", ",", "SourceClient", "=", "None", ",", "Config", "=", "None", ")", ":", "return", "self", ".", "meta", ".", "client", ".", "copy", "(", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/boto3/s3/inject.py#L434-L482
ouster-lidar/ouster_example
13ea8e8b8a4951fb630dbc9108666995c8443bf6
python/src/ouster/pcap/pcap.py
python
Pcap.ports
(self)
return (self._metadata.udp_port_lidar, self._metadata.udp_port_imu)
Specified or inferred ports associated with lidar and imu data. Values <= 0 indicate that no lidar or imu data will be read.
Specified or inferred ports associated with lidar and imu data.
[ "Specified", "or", "inferred", "ports", "associated", "with", "lidar", "and", "imu", "data", "." ]
def ports(self) -> Tuple[int, int]: """Specified or inferred ports associated with lidar and imu data. Values <= 0 indicate that no lidar or imu data will be read. """ return (self._metadata.udp_port_lidar, self._metadata.udp_port_imu)
[ "def", "ports", "(", "self", ")", "->", "Tuple", "[", "int", ",", "int", "]", ":", "return", "(", "self", ".", "_metadata", ".", "udp_port_lidar", ",", "self", ".", "_metadata", ".", "udp_port_imu", ")" ]
https://github.com/ouster-lidar/ouster_example/blob/13ea8e8b8a4951fb630dbc9108666995c8443bf6/python/src/ouster/pcap/pcap.py#L236-L241
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/v1/input_lib.py
python
_create_iterators_per_worker
(worker_datasets, input_workers, options=None)
return iterators
Create a multidevice iterator on each of the workers.
Create a multidevice iterator on each of the workers.
[ "Create", "a", "multidevice", "iterator", "on", "each", "of", "the", "workers", "." ]
def _create_iterators_per_worker(worker_datasets, input_workers, options=None): """Create a multidevice iterator on each of the workers.""" assert isinstance(input_workers, input_lib.InputWorkers) assert len(worker_datasets) == len(input_workers.worker_devices) iterators = [] for i, worker in enumerate(input_workers.worker_devices): with ops.device(worker): worker_devices = input_workers.compute_devices_for_worker(i) iterator = _SingleWorkerDatasetIterator( worker_datasets[i], # pylint: disable=protected-access worker, worker_devices, options) iterators.append(iterator) return iterators
[ "def", "_create_iterators_per_worker", "(", "worker_datasets", ",", "input_workers", ",", "options", "=", "None", ")", ":", "assert", "isinstance", "(", "input_workers", ",", "input_lib", ".", "InputWorkers", ")", "assert", "len", "(", "worker_datasets", ")", "=="...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/v1/input_lib.py#L405-L419
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/nn/functional/pooling.py
python
adaptive_max_pool1d
(x, output_size, return_mask=False, name=None)
return (squeeze(pool_out, [2]), squeeze(mask, [2])) if return_mask else squeeze(pool_out, [2])
This API implements adaptive max pooling 1d operation. See more details in :ref:`api_nn_pooling_AdaptiveMaxPool1d` . Args: x (Tensor): The input tensor of pooling operator, which is a 3-D tensor with shape [N, C, L]. The format of input tensor is NCL, where N is batch size, C is the number of channels, L is the length of the feature. The data type is float32 or float64. output_size (int): The pool kernel size. The value should be an integer. return_mask (bool): If true, the index of max pooling point will be returned along with outputs. It cannot be set in average pooling type. Default False. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of adaptive pooling result. The data type is same as input tensor. Raises: ValueError: 'output_size' should be an integer. Examples: .. code-block:: python # max adaptive pool1d # suppose input data in shape of [N, C, L], `output_size` is m or [m], # output shape is [N, C, m], adaptive pool divide L dimension # of input data into m grids averagely and performs poolings in each # grid to get output. # adaptive max pool performs calculations as follow: # # for i in range(m): # lstart = floor(i * L / m) # lend = ceil((i + 1) * L / m) # output[:, :, i] = max(input[:, :, lstart: lend]) # import paddle import paddle.nn.functional as F import numpy as np data = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32]).astype(np.float32)) pool_out = F.adaptive_max_pool1d(data, output_size=16) # pool_out shape: [1, 3, 16]) pool_out, indices = F.adaptive_max_pool1d(data, output_size=16, return_mask=True) # pool_out shape: [1, 3, 16] indices shape: [1, 3, 16]
This API implements adaptive max pooling 1d operation. See more details in :ref:`api_nn_pooling_AdaptiveMaxPool1d` .
[ "This", "API", "implements", "adaptive", "max", "pooling", "1d", "operation", ".", "See", "more", "details", "in", ":", "ref", ":", "api_nn_pooling_AdaptiveMaxPool1d", "." ]
def adaptive_max_pool1d(x, output_size, return_mask=False, name=None): """ This API implements adaptive max pooling 1d operation. See more details in :ref:`api_nn_pooling_AdaptiveMaxPool1d` . Args: x (Tensor): The input tensor of pooling operator, which is a 3-D tensor with shape [N, C, L]. The format of input tensor is NCL, where N is batch size, C is the number of channels, L is the length of the feature. The data type is float32 or float64. output_size (int): The pool kernel size. The value should be an integer. return_mask (bool): If true, the index of max pooling point will be returned along with outputs. It cannot be set in average pooling type. Default False. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of adaptive pooling result. The data type is same as input tensor. Raises: ValueError: 'output_size' should be an integer. Examples: .. code-block:: python # max adaptive pool1d # suppose input data in shape of [N, C, L], `output_size` is m or [m], # output shape is [N, C, m], adaptive pool divide L dimension # of input data into m grids averagely and performs poolings in each # grid to get output. # adaptive max pool performs calculations as follow: # # for i in range(m): # lstart = floor(i * L / m) # lend = ceil((i + 1) * L / m) # output[:, :, i] = max(input[:, :, lstart: lend]) # import paddle import paddle.nn.functional as F import numpy as np data = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32]).astype(np.float32)) pool_out = F.adaptive_max_pool1d(data, output_size=16) # pool_out shape: [1, 3, 16]) pool_out, indices = F.adaptive_max_pool1d(data, output_size=16, return_mask=True) # pool_out shape: [1, 3, 16] indices shape: [1, 3, 16] """ pool_type = 'max' if not in_dygraph_mode(): check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'adaptive_max_pool1d') check_type(output_size, 'pool_size', int, 'adaptive_max_pool1d') check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool1d') _check_input(x, 3) pool_size = [1] + utils.convert_to_list(output_size, 1, 'pool_size') x = unsqueeze(x, [2]) if in_dygraph_mode(): pool_out = _C_ops.max_pool2d_with_index( x, 'pooling_type', pool_type, 'ksize', pool_size, 'adaptive', True) return (squeeze(pool_out[0], [2]), squeeze( pool_out[1], [2])) if return_mask else squeeze(pool_out[0], [2]) l_type = 'max_pool2d_with_index' helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) mask = helper.create_variable_for_type_inference('int32') outputs = {"Out": pool_out, "Mask": mask} helper.append_op( type=l_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": pool_type, "ksize": pool_size, "adaptive": True, }) return (squeeze(pool_out, [2]), squeeze(mask, [2])) if return_mask else squeeze(pool_out, [2])
[ "def", "adaptive_max_pool1d", "(", "x", ",", "output_size", ",", "return_mask", "=", "False", ",", "name", "=", "None", ")", ":", "pool_type", "=", "'max'", "if", "not", "in_dygraph_mode", "(", ")", ":", "check_variable_and_dtype", "(", "x", ",", "'x'", ",...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/nn/functional/pooling.py#L1493-L1576
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/logging/__init__.py
python
LoggerAdapter._log
(self, level, msg, args, exc_info=None, extra=None, stack_info=False)
return self.logger._log( level, msg, args, exc_info=exc_info, extra=extra, stack_info=stack_info, )
Low-level log implementation, proxied to allow nested logger adapters.
Low-level log implementation, proxied to allow nested logger adapters.
[ "Low", "-", "level", "log", "implementation", "proxied", "to", "allow", "nested", "logger", "adapters", "." ]
def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False): """ Low-level log implementation, proxied to allow nested logger adapters. """ return self.logger._log( level, msg, args, exc_info=exc_info, extra=extra, stack_info=stack_info, )
[ "def", "_log", "(", "self", ",", "level", ",", "msg", ",", "args", ",", "exc_info", "=", "None", ",", "extra", "=", "None", ",", "stack_info", "=", "False", ")", ":", "return", "self", ".", "logger", ".", "_log", "(", "level", ",", "msg", ",", "a...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/logging/__init__.py#L1792-L1803
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/artmanager.py
python
DCSaver.__init__
(self, pdc)
Default class constructor. :param `pdc`: an instance of :class:`DC`.
Default class constructor.
[ "Default", "class", "constructor", "." ]
def __init__(self, pdc): """ Default class constructor. :param `pdc`: an instance of :class:`DC`. """ self._pdc = pdc self._pen = pdc.GetPen() self._brush = pdc.GetBrush()
[ "def", "__init__", "(", "self", ",", "pdc", ")", ":", "self", ".", "_pdc", "=", "pdc", "self", ".", "_pen", "=", "pdc", ".", "GetPen", "(", ")", "self", ".", "_brush", "=", "pdc", ".", "GetBrush", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/artmanager.py#L44-L53
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/registry.py
python
CPUTarget.target_context
(self)
The target context for CPU targets.
The target context for CPU targets.
[ "The", "target", "context", "for", "CPU", "targets", "." ]
def target_context(self): """ The target context for CPU targets. """ nested = self._nested._target_context if nested is not None: return nested else: return self._toplevel_target_context
[ "def", "target_context", "(", "self", ")", ":", "nested", "=", "self", ".", "_nested", ".", "_target_context", "if", "nested", "is", "not", "None", ":", "return", "nested", "else", ":", "return", "self", ".", "_toplevel_target_context" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/registry.py#L42-L50
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/cr/cr/actions/adb.py
python
Adb.Run
(cls, target, arguments)
Invoke a target binary on the device.
Invoke a target binary on the device.
[ "Invoke", "a", "target", "binary", "on", "the", "device", "." ]
def Run(cls, target, arguments): """Invoke a target binary on the device.""" with target: cr.Host.Execute( '{CR_ADB}', 'shell', 'am', 'start', '-a', '{CR_ACTION}', '-n', '{CR_INTENT}', '{CR_RUN_ARGUMENTS}', *arguments )
[ "def", "Run", "(", "cls", ",", "target", ",", "arguments", ")", ":", "with", "target", ":", "cr", ".", "Host", ".", "Execute", "(", "'{CR_ADB}'", ",", "'shell'", ",", "'am'", ",", "'start'", ",", "'-a'", ",", "'{CR_ACTION}'", ",", "'-n'", ",", "'{CR_...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/cr/cr/actions/adb.py#L37-L46
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/elementwise/ceil.py
python
floor.is_atom_concave
(self)
return False
Is the atom concave?
Is the atom concave?
[ "Is", "the", "atom", "concave?" ]
def is_atom_concave(self) -> bool: """Is the atom concave? """ return False
[ "def", "is_atom_concave", "(", "self", ")", "->", "bool", ":", "return", "False" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/elementwise/ceil.py#L129-L132
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/aui.py
python
AuiDockInfo.IsHorizontal
(*args, **kwargs)
return _aui.AuiDockInfo_IsHorizontal(*args, **kwargs)
IsHorizontal(self) -> bool
IsHorizontal(self) -> bool
[ "IsHorizontal", "(", "self", ")", "-", ">", "bool" ]
def IsHorizontal(*args, **kwargs): """IsHorizontal(self) -> bool""" return _aui.AuiDockInfo_IsHorizontal(*args, **kwargs)
[ "def", "IsHorizontal", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiDockInfo_IsHorizontal", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/aui.py#L885-L887
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/training/checkpoint_utils.py
python
_set_variable_or_list_initializer
(variable_or_list, ckpt_file, tensor_name)
Overrides initialization op of given variable or list of variables. Calls `_set_checkpoint_initializer` for each variable in the given list of variables. Args: variable_or_list: `tf.Variable` object or a list of `tf.Variable` objects. ckpt_file: string, full path of the checkpoint. tensor_name: Name of the tensor to load from the checkpoint. Raises: ValueError: if all objects in `variable_or_list` are not partitions of the same large variable.
Overrides initialization op of given variable or list of variables.
[ "Overrides", "initialization", "op", "of", "given", "variable", "or", "list", "of", "variables", "." ]
def _set_variable_or_list_initializer(variable_or_list, ckpt_file, tensor_name): """Overrides initialization op of given variable or list of variables. Calls `_set_checkpoint_initializer` for each variable in the given list of variables. Args: variable_or_list: `tf.Variable` object or a list of `tf.Variable` objects. ckpt_file: string, full path of the checkpoint. tensor_name: Name of the tensor to load from the checkpoint. Raises: ValueError: if all objects in `variable_or_list` are not partitions of the same large variable. """ if isinstance(variable_or_list, (list, tuple)): # A set of slices. slice_name = None for v in variable_or_list: slice_info = v._save_slice_info # pylint:disable=protected-access if slice_name is None: slice_name = slice_info.full_name elif slice_name != slice_info.full_name: raise ValueError("Slices must all be from the same tensor: %s != %s" % (slice_name, slice_info.full_name)) _set_checkpoint_initializer(v, ckpt_file, tensor_name, slice_info.spec) else: _set_checkpoint_initializer(variable_or_list, ckpt_file, tensor_name, "")
[ "def", "_set_variable_or_list_initializer", "(", "variable_or_list", ",", "ckpt_file", ",", "tensor_name", ")", ":", "if", "isinstance", "(", "variable_or_list", ",", "(", "list", ",", "tuple", ")", ")", ":", "# A set of slices.", "slice_name", "=", "None", "for",...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/checkpoint_utils.py#L492-L520
devsisters/libquic
8954789a056d8e7d5fcb6452fd1572ca57eb5c4e
src/third_party/protobuf/python/mox.py
python
MockObject.__setitem__
(self, key, value)
return self._CreateMockMethod('__setitem__')(key, value)
Provide custom logic for mocking classes that support item assignment. Args: key: Key to set the value for. value: Value to set. Returns: Expected return value in replay mode. A MockMethod object for the __setitem__ method that has already been called if not in replay mode. Raises: TypeError if the underlying class does not support item assignment. UnexpectedMethodCallError if the object does not expect the call to __setitem__.
Provide custom logic for mocking classes that support item assignment.
[ "Provide", "custom", "logic", "for", "mocking", "classes", "that", "support", "item", "assignment", "." ]
def __setitem__(self, key, value): """Provide custom logic for mocking classes that support item assignment. Args: key: Key to set the value for. value: Value to set. Returns: Expected return value in replay mode. A MockMethod object for the __setitem__ method that has already been called if not in replay mode. Raises: TypeError if the underlying class does not support item assignment. UnexpectedMethodCallError if the object does not expect the call to __setitem__. """ setitem = self._class_to_mock.__dict__.get('__setitem__', None) # Verify the class supports item assignment. if setitem is None: raise TypeError('object does not support item assignment') # If we are in replay mode then simply call the mock __setitem__ method. if self._replay_mode: return MockMethod('__setitem__', self._expected_calls_queue, self._replay_mode)(key, value) # Otherwise, create a mock method __setitem__. return self._CreateMockMethod('__setitem__')(key, value)
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ")", ":", "setitem", "=", "self", ".", "_class_to_mock", ".", "__dict__", ".", "get", "(", "'__setitem__'", ",", "None", ")", "# Verify the class supports item assignment.", "if", "setitem", "is", "N...
https://github.com/devsisters/libquic/blob/8954789a056d8e7d5fcb6452fd1572ca57eb5c4e/src/third_party/protobuf/python/mox.py#L427-L457
9miao/CrossApp
1f5375e061bf69841eb19728598f5ae3f508d620
tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
Type.is_pod
(self)
return conf.lib.clang_isPODType(self)
Determine whether this Type represents plain old data (POD).
Determine whether this Type represents plain old data (POD).
[ "Determine", "whether", "this", "Type", "represents", "plain", "old", "data", "(", "POD", ")", "." ]
def is_pod(self): """Determine whether this Type represents plain old data (POD).""" return conf.lib.clang_isPODType(self)
[ "def", "is_pod", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_isPODType", "(", "self", ")" ]
https://github.com/9miao/CrossApp/blob/1f5375e061bf69841eb19728598f5ae3f508d620/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L1594-L1596
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
deprecated/algorithms/sfm/OpenSfM/opensfm/transformations.py
python
Arcball.setaxes
(self, *axes)
Set axes to constrain rotations.
Set axes to constrain rotations.
[ "Set", "axes", "to", "constrain", "rotations", "." ]
def setaxes(self, *axes): """Set axes to constrain rotations.""" if axes is None: self._axes = None else: self._axes = [unit_vector(axis) for axis in axes]
[ "def", "setaxes", "(", "self", ",", "*", "axes", ")", ":", "if", "axes", "is", "None", ":", "self", ".", "_axes", "=", "None", "else", ":", "self", ".", "_axes", "=", "[", "unit_vector", "(", "axis", ")", "for", "axis", "in", "axes", "]" ]
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/OpenSfM/opensfm/transformations.py#L1562-L1567
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextCtrl.PopStyleSheet
(*args, **kwargs)
return _richtext.RichTextCtrl_PopStyleSheet(*args, **kwargs)
PopStyleSheet(self) -> wxRichTextStyleSheet Pop style sheet from top of stack
PopStyleSheet(self) -> wxRichTextStyleSheet
[ "PopStyleSheet", "(", "self", ")", "-", ">", "wxRichTextStyleSheet" ]
def PopStyleSheet(*args, **kwargs): """ PopStyleSheet(self) -> wxRichTextStyleSheet Pop style sheet from top of stack """ return _richtext.RichTextCtrl_PopStyleSheet(*args, **kwargs)
[ "def", "PopStyleSheet", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_PopStyleSheet", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L4019-L4025
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBTypeCategory.GetFilterAtIndex
(self, arg2)
return _lldb.SBTypeCategory_GetFilterAtIndex(self, arg2)
GetFilterAtIndex(SBTypeCategory self, uint32_t arg2) -> SBTypeFilter
GetFilterAtIndex(SBTypeCategory self, uint32_t arg2) -> SBTypeFilter
[ "GetFilterAtIndex", "(", "SBTypeCategory", "self", "uint32_t", "arg2", ")", "-", ">", "SBTypeFilter" ]
def GetFilterAtIndex(self, arg2): """GetFilterAtIndex(SBTypeCategory self, uint32_t arg2) -> SBTypeFilter""" return _lldb.SBTypeCategory_GetFilterAtIndex(self, arg2)
[ "def", "GetFilterAtIndex", "(", "self", ",", "arg2", ")", ":", "return", "_lldb", ".", "SBTypeCategory_GetFilterAtIndex", "(", "self", ",", "arg2", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L13147-L13149
JavierIH/zowi
830c1284154b8167c9131deb9c45189fd9e67b54
code/python-client/Oscillator.py
python
Oscillator.T
(self)
return self._T
Attribute: Return the current period
Attribute: Return the current period
[ "Attribute", ":", "Return", "the", "current", "period" ]
def T(self): """Attribute: Return the current period""" return self._T
[ "def", "T", "(", "self", ")", ":", "return", "self", ".", "_T" ]
https://github.com/JavierIH/zowi/blob/830c1284154b8167c9131deb9c45189fd9e67b54/code/python-client/Oscillator.py#L149-L151
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pytz/pytz/tzinfo.py
python
memorized_datetime
(seconds)
Create only one instance of each distinct datetime
Create only one instance of each distinct datetime
[ "Create", "only", "one", "instance", "of", "each", "distinct", "datetime" ]
def memorized_datetime(seconds): '''Create only one instance of each distinct datetime''' try: return _datetime_cache[seconds] except KeyError: # NB. We can't just do datetime.utcfromtimestamp(seconds) as this # fails with negative values under Windows (Bug #90096) dt = _epoch + timedelta(seconds=seconds) _datetime_cache[seconds] = dt return dt
[ "def", "memorized_datetime", "(", "seconds", ")", ":", "try", ":", "return", "_datetime_cache", "[", "seconds", "]", "except", "KeyError", ":", "# NB. We can't just do datetime.utcfromtimestamp(seconds) as this", "# fails with negative values under Windows (Bug #90096)", "dt", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pytz/pytz/tzinfo.py#L31-L40
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/cognito/identity/layer1.py
python
CognitoIdentityConnection.list_identities
(self, identity_pool_id, max_results, next_token=None)
return self.make_request(action='ListIdentities', body=json.dumps(params))
Lists the identities in a pool. :type identity_pool_id: string :param identity_pool_id: An identity pool ID in the format REGION:GUID. :type max_results: integer :param max_results: The maximum number of identities to return. :type next_token: string :param next_token: A pagination token.
Lists the identities in a pool.
[ "Lists", "the", "identities", "in", "a", "pool", "." ]
def list_identities(self, identity_pool_id, max_results, next_token=None): """ Lists the identities in a pool. :type identity_pool_id: string :param identity_pool_id: An identity pool ID in the format REGION:GUID. :type max_results: integer :param max_results: The maximum number of identities to return. :type next_token: string :param next_token: A pagination token. """ params = { 'IdentityPoolId': identity_pool_id, 'MaxResults': max_results, } if next_token is not None: params['NextToken'] = next_token return self.make_request(action='ListIdentities', body=json.dumps(params))
[ "def", "list_identities", "(", "self", ",", "identity_pool_id", ",", "max_results", ",", "next_token", "=", "None", ")", ":", "params", "=", "{", "'IdentityPoolId'", ":", "identity_pool_id", ",", "'MaxResults'", ":", "max_results", ",", "}", "if", "next_token", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/cognito/identity/layer1.py#L284-L305
facebookresearch/ELF
1f790173095cd910976d9f651b80beb872ec5d12
rlpytorch/model_interface.py
python
ModelInterface.clone
(self, gpu=None)
return mi
Clone the state for the model interface, including ``models`` and ``optimizers`` Args: gpu(int): gpu id to be put the model on Returns: cloned `ModelInterface`.
Clone the state for the model interface, including ``models`` and ``optimizers``
[ "Clone", "the", "state", "for", "the", "model", "interface", "including", "models", "and", "optimizers" ]
def clone(self, gpu=None): ''' Clone the state for the model interface, including ``models`` and ``optimizers`` Args: gpu(int): gpu id to be put the model on Returns: cloned `ModelInterface`. ''' mi = ModelInterface() for key, model in self.models.items(): mi.models[key] = model.clone(gpu=gpu) if key in self.optimizers: # Same parameters. mi.optimizers[key] = torch.optim.Adam(mi.models[key].parameters()) new_optim = mi.optimizers[key] old_optim = self.optimizers[key] new_optim_params = new_optim.param_groups[0] old_optim_params = old_optim.param_groups[0] # Copy the parameters. for k in new_optim_params.keys(): if k != "params": new_optim_params[k] = old_optim_params[k] # Copy the state ''' new_optim.state = { } for k, v in old_optim.state.items(): if isinstance(v, (int, float, str)): new_optim.state[k] = v else: new_optim.state[k] = v.clone() if gpu is not None: new_optim.state[k] = new_optim.state[k].cuda(gpu) ''' return mi
[ "def", "clone", "(", "self", ",", "gpu", "=", "None", ")", ":", "mi", "=", "ModelInterface", "(", ")", "for", "key", ",", "model", "in", "self", ".", "models", ".", "items", "(", ")", ":", "mi", ".", "models", "[", "key", "]", "=", "model", "."...
https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/rlpytorch/model_interface.py#L39-L74
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/binhex.py
python
hexbin
(inp, out)
(infilename, outfilename) - Decode binhexed file
(infilename, outfilename) - Decode binhexed file
[ "(", "infilename", "outfilename", ")", "-", "Decode", "binhexed", "file" ]
def hexbin(inp, out): """(infilename, outfilename) - Decode binhexed file""" ifp = HexBin(inp) finfo = ifp.FInfo if not out: out = ifp.FName if os.name == 'mac': ofss = FSSpec(out) out = ofss.as_pathname() ofp = open(out, 'wb') # XXXX Do translation on non-mac systems while 1: d = ifp.read(128000) if not d: break ofp.write(d) ofp.close() ifp.close_data() d = ifp.read_rsrc(128000) if d: ofp = openrsrc(out, 'wb') ofp.write(d) while 1: d = ifp.read_rsrc(128000) if not d: break ofp.write(d) ofp.close() if os.name == 'mac': nfinfo = ofss.GetFInfo() nfinfo.Creator = finfo.Creator nfinfo.Type = finfo.Type nfinfo.Flags = finfo.Flags ofss.SetFInfo(nfinfo) ifp.close()
[ "def", "hexbin", "(", "inp", ",", "out", ")", ":", "ifp", "=", "HexBin", "(", "inp", ")", "finfo", "=", "ifp", ".", "FInfo", "if", "not", "out", ":", "out", "=", "ifp", ".", "FName", "if", "os", ".", "name", "==", "'mac'", ":", "ofss", "=", "...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/binhex.py#L474-L510
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/ops/data_flow_ops.py
python
QueueBase.enqueue
(self, vals, name=None)
Enqueues one element to this queue. If the queue is full when this operation executes, it will block until the element has been enqueued. At runtime, this operation may raise an error if the queue is [closed](#QueueBase.close) before or during its execution. If the queue is closed before this operation runs, `tf.errors.CancelledError` will be raised. If this operation is blocked, and either (i) the queue is closed by a close operation with `cancel_pending_enqueues=True`, or (ii) the session is [closed](../../api_docs/python/client.md#Session.close), `tf.errors.CancelledError` will be raised. Args: vals: A tensor, a list or tuple of tensors, or a dictionary containing the values to enqueue. name: A name for the operation (optional). Returns: The operation that enqueues a new tuple of tensors to the queue.
Enqueues one element to this queue.
[ "Enqueues", "one", "element", "to", "this", "queue", "." ]
def enqueue(self, vals, name=None): """Enqueues one element to this queue. If the queue is full when this operation executes, it will block until the element has been enqueued. At runtime, this operation may raise an error if the queue is [closed](#QueueBase.close) before or during its execution. If the queue is closed before this operation runs, `tf.errors.CancelledError` will be raised. If this operation is blocked, and either (i) the queue is closed by a close operation with `cancel_pending_enqueues=True`, or (ii) the session is [closed](../../api_docs/python/client.md#Session.close), `tf.errors.CancelledError` will be raised. Args: vals: A tensor, a list or tuple of tensors, or a dictionary containing the values to enqueue. name: A name for the operation (optional). Returns: The operation that enqueues a new tuple of tensors to the queue. """ with ops.name_scope(name, "%s_enqueue" % self._name, self._scope_vals(vals)) as scope: vals = self._check_enqueue_dtypes(vals) # NOTE(mrry): Not using a shape function because we need access to # the `QueueBase` object. for val, shape in zip(vals, self._shapes): val.get_shape().assert_is_compatible_with(shape) return gen_data_flow_ops._queue_enqueue(self._queue_ref, vals, name=scope)
[ "def", "enqueue", "(", "self", ",", "vals", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"%s_enqueue\"", "%", "self", ".", "_name", ",", "self", ".", "_scope_vals", "(", "vals", ")", ")", "as", "scope", ...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/data_flow_ops.py#L298-L330
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/gradientbutton.py
python
GradientButton.__init__
(self, parent, id=wx.ID_ANY, bitmap=None, label="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.NO_BORDER, validator=wx.DefaultValidator, name="gradientbutton")
Default class constructor. :param `parent`: the :class:`GradientButton` parent; :param `id`: window identifier. A value of -1 indicates a default value; :param `bitmap`: the button bitmap (if any); :param `label`: the button text label; :param `pos`: the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform; :param `size`: the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform; :param `style`: the button style (unused); :param `validator`: the validator associated to the button; :param `name`: the button name.
Default class constructor.
[ "Default", "class", "constructor", "." ]
def __init__(self, parent, id=wx.ID_ANY, bitmap=None, label="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.NO_BORDER, validator=wx.DefaultValidator, name="gradientbutton"): """ Default class constructor. :param `parent`: the :class:`GradientButton` parent; :param `id`: window identifier. A value of -1 indicates a default value; :param `bitmap`: the button bitmap (if any); :param `label`: the button text label; :param `pos`: the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform; :param `size`: the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform; :param `style`: the button style (unused); :param `validator`: the validator associated to the button; :param `name`: the button name. """ wx.PyControl.__init__(self, parent, id, pos, size, style, validator, name) self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_ERASE_BACKGROUND, lambda event: None) self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp) self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave) self.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter) self.Bind(wx.EVT_SET_FOCUS, self.OnGainFocus) self.Bind(wx.EVT_KILL_FOCUS, self.OnLoseFocus) self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) self.Bind(wx.EVT_KEY_UP, self.OnKeyUp) self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDown) self._mouseAction = None self._bitmap = bitmap self._hasFocus = False self.SetLabel(label) self.InheritAttributes() self.SetInitialSize(size) self.SetBaseColours()
[ "def", "__init__", "(", "self", ",", "parent", ",", "id", "=", "wx", ".", "ID_ANY", ",", "bitmap", "=", "None", ",", "label", "=", "\"\"", ",", "pos", "=", "wx", ".", "DefaultPosition", ",", "size", "=", "wx", ".", "DefaultSize", ",", "style", "=",...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/gradientbutton.py#L161-L204
cztomczak/cefpython
5679f28cec18a57a56e298da2927aac8d8f83ad6
tools/automate-git.py
python
read_config_file
(path)
return eval(read_file(path), {'__builtins__': None}, None)
Read a configuration file.
Read a configuration file.
[ "Read", "a", "configuration", "file", "." ]
def read_config_file(path): """ Read a configuration file. """ # Parse the contents. return eval(read_file(path), {'__builtins__': None}, None)
[ "def", "read_config_file", "(", "path", ")", ":", "# Parse the contents.", "return", "eval", "(", "read_file", "(", "path", ")", ",", "{", "'__builtins__'", ":", "None", "}", ",", "None", ")" ]
https://github.com/cztomczak/cefpython/blob/5679f28cec18a57a56e298da2927aac8d8f83ad6/tools/automate-git.py#L345-L348
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/locators.py
python
get_all_distribution_names
(url=None)
return client.list_packages()
Return all distribution names known by an index. :param url: The URL of the index. :return: A list of all known distribution names.
Return all distribution names known by an index. :param url: The URL of the index. :return: A list of all known distribution names.
[ "Return", "all", "distribution", "names", "known", "by", "an", "index", ".", ":", "param", "url", ":", "The", "URL", "of", "the", "index", ".", ":", "return", ":", "A", "list", "of", "all", "known", "distribution", "names", "." ]
def get_all_distribution_names(url=None): """ Return all distribution names known by an index. :param url: The URL of the index. :return: A list of all known distribution names. """ if url is None: url = DEFAULT_INDEX client = ServerProxy(url, timeout=3.0) return client.list_packages()
[ "def", "get_all_distribution_names", "(", "url", "=", "None", ")", ":", "if", "url", "is", "None", ":", "url", "=", "DEFAULT_INDEX", "client", "=", "ServerProxy", "(", "url", ",", "timeout", "=", "3.0", ")", "return", "client", ".", "list_packages", "(", ...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/locators.py#L38-L47
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tracemalloc.py
python
Snapshot.load
(filename)
Load a snapshot from a file.
Load a snapshot from a file.
[ "Load", "a", "snapshot", "from", "a", "file", "." ]
def load(filename): """ Load a snapshot from a file. """ with open(filename, "rb") as fp: return pickle.load(fp)
[ "def", "load", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "fp", ":", "return", "pickle", ".", "load", "(", "fp", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tracemalloc.py#L408-L413
RoboJackets/robocup-software
bce13ce53ddb2ecb9696266d980722c34617dc15
rj_gameplay/stp/rc.py
python
Robot.has_ball_sense
(self)
return self.__has_ball_sense
:return: True if this robot has functioning ball sensors
:return: True if this robot has functioning ball sensors
[ ":", "return", ":", "True", "if", "this", "robot", "has", "functioning", "ball", "sensors" ]
def has_ball_sense(self) -> bool: """ :return: True if this robot has functioning ball sensors """ if not self.is_ours: warnings.warn( "Attempting to retrieve ball sense status from an opposing robot", RuntimeWarning, ) return self.__has_ball_sense
[ "def", "has_ball_sense", "(", "self", ")", "->", "bool", ":", "if", "not", "self", ".", "is_ours", ":", "warnings", ".", "warn", "(", "\"Attempting to retrieve ball sense status from an opposing robot\"", ",", "RuntimeWarning", ",", ")", "return", "self", ".", "__...
https://github.com/RoboJackets/robocup-software/blob/bce13ce53ddb2ecb9696266d980722c34617dc15/rj_gameplay/stp/rc.py#L140-L150
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/ContactStructuralMechanicsApplication/python_scripts/custom_sympy_fe_utilities.py
python
StrainToVoigt
(M)
return sympy_fe_utilities.StrainToVoigt(M)
This method transform the strains matrix to Voigt notation Keyword arguments: M -- The strain matrix
This method transform the strains matrix to Voigt notation
[ "This", "method", "transform", "the", "strains", "matrix", "to", "Voigt", "notation" ]
def StrainToVoigt(M): """ This method transform the strains matrix to Voigt notation Keyword arguments: M -- The strain matrix """ return sympy_fe_utilities.StrainToVoigt(M)
[ "def", "StrainToVoigt", "(", "M", ")", ":", "return", "sympy_fe_utilities", ".", "StrainToVoigt", "(", "M", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ContactStructuralMechanicsApplication/python_scripts/custom_sympy_fe_utilities.py#L97-L103
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythplugins/mytharchive/mythburn/scripts/mythburn.py
python
runMythtranscode
(chanid, starttime, destination, usecutlist, localfile)
return True
Use mythtranscode to cut commercials and/or clean up an mpeg2 file
Use mythtranscode to cut commercials and/or clean up an mpeg2 file
[ "Use", "mythtranscode", "to", "cut", "commercials", "and", "/", "or", "clean", "up", "an", "mpeg2", "file" ]
def runMythtranscode(chanid, starttime, destination, usecutlist, localfile): """Use mythtranscode to cut commercials and/or clean up an mpeg2 file""" try: rec = next(DB.searchRecorded(chanid=chanid, starttime=starttime)) cutlist = rec.markup.getcutlist() except StopIteration: cutlist = [] cutlist_s = "" if usecutlist and len(cutlist): cutlist_s = "'" for cut in cutlist: cutlist_s += ' %d-%d ' % cut cutlist_s += "'" write("Using cutlist: %s" % cutlist_s) if (localfile != ""): if usecutlist == True: command = "mythtranscode --mpeg2 --honorcutlist %s --infile %s --outfile %s" % (cutlist_s, quoteCmdArg(localfile), quoteCmdArg(destination)) else: command = "mythtranscode --mpeg2 --infile %s --outfile %s" % (quoteCmdArg(localfile), quoteCmdArg(destination)) else: if usecutlist == True: command = "mythtranscode --mpeg2 --honorcutlist --chanid %s --starttime %s --outfile %s" % (chanid, starttime, quoteCmdArg(destination)) else: command = "mythtranscode --mpeg2 --chanid %s --starttime %s --outfile %s" % (chanid, starttime, quoteCmdArg(destination)) result = runCommand(command) if (result != 0): write("Failed while running mythtranscode to cut commercials and/or clean up an mpeg2 file.\n" "Result: %d, Command was %s" % (result, command)) return False; return True
[ "def", "runMythtranscode", "(", "chanid", ",", "starttime", ",", "destination", ",", "usecutlist", ",", "localfile", ")", ":", "try", ":", "rec", "=", "next", "(", "DB", ".", "searchRecorded", "(", "chanid", "=", "chanid", ",", "starttime", "=", "starttime...
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythplugins/mytharchive/mythburn/scripts/mythburn.py#L1765-L1800
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
catboost/python-package/catboost/eval/_fold_models_handler.py
python
FoldModelsHandler.__init__
(self, metrics, cases, thread_count, eval_step, remove_models)
Args: :param remove_models: Set true if you want models to be removed after applying them.
Args: :param remove_models: Set true if you want models to be removed after applying them.
[ "Args", ":", ":", "param", "remove_models", ":", "Set", "true", "if", "you", "want", "models", "to", "be", "removed", "after", "applying", "them", "." ]
def __init__(self, metrics, cases, thread_count, eval_step, remove_models): """ Args: :param remove_models: Set true if you want models to be removed after applying them. """ self._cases = cases self._metrics = metrics self._case_results = dict() for case in self._cases: self._case_results[case] = dict() self._thread_count = thread_count self._eval_step = eval_step self._flag_remove_models = remove_models self._metric_descriptions = None
[ "def", "__init__", "(", "self", ",", "metrics", ",", "cases", ",", "thread_count", ",", "eval_step", ",", "remove_models", ")", ":", "self", ".", "_cases", "=", "cases", "self", ".", "_metrics", "=", "metrics", "self", ".", "_case_results", "=", "dict", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/catboost/python-package/catboost/eval/_fold_models_handler.py#L30-L46
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/framework/docs.py
python
Library.__init__
(self, title, module, module_to_name, members, documented, exclude_symbols=(), prefix=None)
Creates a new Library. Args: title: A human-readable title for the library. module: Module to pull high level docstring from (for table of contents, list of Ops to document, etc.). module_to_name: Dictionary mapping modules to short names. members: Dictionary mapping member name to (fullname, member). documented: Set of documented names to update. exclude_symbols: A list of specific symbols to exclude. prefix: A string to include at the beginning of the page.
Creates a new Library.
[ "Creates", "a", "new", "Library", "." ]
def __init__(self, title, module, module_to_name, members, documented, exclude_symbols=(), prefix=None): """Creates a new Library. Args: title: A human-readable title for the library. module: Module to pull high level docstring from (for table of contents, list of Ops to document, etc.). module_to_name: Dictionary mapping modules to short names. members: Dictionary mapping member name to (fullname, member). documented: Set of documented names to update. exclude_symbols: A list of specific symbols to exclude. prefix: A string to include at the beginning of the page. """ self._title = title self._module = module self._module_to_name = module_to_name self._members = dict(members) # Copy since we mutate it below self._exclude_symbols = frozenset(exclude_symbols) documented.update(exclude_symbols) self._documented = documented self._mentioned = set() self._prefix = prefix or ""
[ "def", "__init__", "(", "self", ",", "title", ",", "module", ",", "module_to_name", ",", "members", ",", "documented", ",", "exclude_symbols", "=", "(", ")", ",", "prefix", "=", "None", ")", ":", "self", ".", "_title", "=", "title", "self", ".", "_modu...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/docs.py#L179-L207
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/base/TabbedPreferences.py
python
TabbedPreferences.load
(self)
Load preferences from disk.
Load preferences from disk.
[ "Load", "preferences", "from", "disk", "." ]
def load(self): """ Load preferences from disk. """ settings = QtCore.QSettings() for w in self._widgets: w.load(settings)
[ "def", "load", "(", "self", ")", ":", "settings", "=", "QtCore", ".", "QSettings", "(", ")", "for", "w", "in", "self", ".", "_widgets", ":", "w", ".", "load", "(", "settings", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/base/TabbedPreferences.py#L45-L51
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/tokenize.py
python
untokenize
(iterable)
return ut.untokenize(iterable)
Transform tokens back into Python source code. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the resulting output is poor. Round-trip invariant for full input: Untokenized source will match input source exactly Round-trip invariant for limited intput: # Output text will tokenize the back to the input t1 = [tok[:2] for tok in generate_tokens(f.readline)] newcode = untokenize(t1) readline = iter(newcode.splitlines(1)).next t2 = [tok[:2] for tok in generate_tokens(readline)] assert t1 == t2
Transform tokens back into Python source code.
[ "Transform", "tokens", "back", "into", "Python", "source", "code", "." ]
def untokenize(iterable): """Transform tokens back into Python source code. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the resulting output is poor. Round-trip invariant for full input: Untokenized source will match input source exactly Round-trip invariant for limited intput: # Output text will tokenize the back to the input t1 = [tok[:2] for tok in generate_tokens(f.readline)] newcode = untokenize(t1) readline = iter(newcode.splitlines(1)).next t2 = [tok[:2] for tok in generate_tokens(readline)] assert t1 == t2 """ ut = Untokenizer() return ut.untokenize(iterable)
[ "def", "untokenize", "(", "iterable", ")", ":", "ut", "=", "Untokenizer", "(", ")", "return", "ut", ".", "untokenize", "(", "iterable", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/tokenize.py#L243-L262
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/datamodel/packer.py
python
DataPacker.load
(self, builder, ptr)
return self._do_load(builder, ptr)
Load the packed values and return a (type, value) tuples.
Load the packed values and return a (type, value) tuples.
[ "Load", "the", "packed", "values", "and", "return", "a", "(", "type", "value", ")", "tuples", "." ]
def load(self, builder, ptr): """ Load the packed values and return a (type, value) tuples. """ return self._do_load(builder, ptr)
[ "def", "load", "(", "self", ",", "builder", ",", "ptr", ")", ":", "return", "self", ".", "_do_load", "(", "builder", ",", "ptr", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/datamodel/packer.py#L48-L52
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/cgi.py
python
parse_multipart
(fp, pdict)
return partdict
Parse multipart input. Arguments: fp : input file pdict: dictionary containing other parameters of content-type header Returns a dictionary just like parse_qs(): keys are the field names, each value is a list of values for that field. This is easy to use but not much good if you are expecting megabytes to be uploaded -- in that case, use the FieldStorage class instead which is much more flexible. Note that content-type is the raw, unparsed contents of the content-type header. XXX This does not parse nested multipart parts -- use FieldStorage for that. XXX This should really be subsumed by FieldStorage altogether -- no point in having two implementations of the same parsing algorithm. Also, FieldStorage protects itself better against certain DoS attacks by limiting the size of the data read in one chunk. The API here does not support that kind of protection. This also affects parse() since it can call parse_multipart().
Parse multipart input.
[ "Parse", "multipart", "input", "." ]
def parse_multipart(fp, pdict): """Parse multipart input. Arguments: fp : input file pdict: dictionary containing other parameters of content-type header Returns a dictionary just like parse_qs(): keys are the field names, each value is a list of values for that field. This is easy to use but not much good if you are expecting megabytes to be uploaded -- in that case, use the FieldStorage class instead which is much more flexible. Note that content-type is the raw, unparsed contents of the content-type header. XXX This does not parse nested multipart parts -- use FieldStorage for that. XXX This should really be subsumed by FieldStorage altogether -- no point in having two implementations of the same parsing algorithm. Also, FieldStorage protects itself better against certain DoS attacks by limiting the size of the data read in one chunk. The API here does not support that kind of protection. This also affects parse() since it can call parse_multipart(). """ boundary = "" if 'boundary' in pdict: boundary = pdict['boundary'] if not valid_boundary(boundary): raise ValueError, ('Invalid boundary in multipart form: %r' % (boundary,)) nextpart = "--" + boundary lastpart = "--" + boundary + "--" partdict = {} terminator = "" while terminator != lastpart: bytes = -1 data = None if terminator: # At start of next part. Read headers first. headers = mimetools.Message(fp) clength = headers.getheader('content-length') if clength: try: bytes = int(clength) except ValueError: pass if bytes > 0: if maxlen and bytes > maxlen: raise ValueError, 'Maximum content length exceeded' data = fp.read(bytes) else: data = "" # Read lines until end of part. lines = [] while 1: line = fp.readline() if not line: terminator = lastpart # End outer loop break if line[:2] == "--": terminator = line.strip() if terminator in (nextpart, lastpart): break lines.append(line) # Done with part. if data is None: continue if bytes < 0: if lines: # Strip final line terminator line = lines[-1] if line[-2:] == "\r\n": line = line[:-2] elif line[-1:] == "\n": line = line[:-1] lines[-1] = line data = "".join(lines) line = headers['content-disposition'] if not line: continue key, params = parse_header(line) if key != 'form-data': continue if 'name' in params: name = params['name'] else: continue if name in partdict: partdict[name].append(data) else: partdict[name] = [data] return partdict
[ "def", "parse_multipart", "(", "fp", ",", "pdict", ")", ":", "boundary", "=", "\"\"", "if", "'boundary'", "in", "pdict", ":", "boundary", "=", "pdict", "[", "'boundary'", "]", "if", "not", "valid_boundary", "(", "boundary", ")", ":", "raise", "ValueError",...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/cgi.py#L194-L289
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/deps/v8/PRESUBMIT.py
python
_CheckNoexceptAnnotations
(input_api, output_api)
return []
Checks that all user-defined constructors and assignment operators are marked V8_NOEXCEPT. This is required for standard containers to pick the right constructors. Our macros (like MOVE_ONLY_WITH_DEFAULT_CONSTRUCTORS) add this automatically. Omitting it at some places can result in weird compiler errors if this is mixed with other classes that have the annotation. TODO(clemensb): This check should eventually be enabled for all files via tools/presubmit.py (https://crbug.com/v8/8616).
Checks that all user-defined constructors and assignment operators are marked V8_NOEXCEPT.
[ "Checks", "that", "all", "user", "-", "defined", "constructors", "and", "assignment", "operators", "are", "marked", "V8_NOEXCEPT", "." ]
def _CheckNoexceptAnnotations(input_api, output_api): """ Checks that all user-defined constructors and assignment operators are marked V8_NOEXCEPT. This is required for standard containers to pick the right constructors. Our macros (like MOVE_ONLY_WITH_DEFAULT_CONSTRUCTORS) add this automatically. Omitting it at some places can result in weird compiler errors if this is mixed with other classes that have the annotation. TODO(clemensb): This check should eventually be enabled for all files via tools/presubmit.py (https://crbug.com/v8/8616). """ def FilterFile(affected_file): return input_api.FilterSourceFile( affected_file, white_list=(r'src/.*', r'test/.*')) # matches any class name. class_name = r'\b([A-Z][A-Za-z0-9_:]*)(?:::\1)?' # initial class name is potentially followed by this to declare an assignment # operator. potential_assignment = r'(?:&\s+(?:\1::)?operator=)?\s*' # matches an argument list that contains only a reference to a class named # like the first capture group, potentially const. single_class_ref_arg = r'\(\s*(?:const\s+)?\1(?:::\1)?&&?[^,;)]*\)' # matches anything but a sequence of whitespaces followed by either # V8_NOEXCEPT or "= delete". not_followed_by_noexcept = r'(?!\s+(?:V8_NOEXCEPT|=\s+delete)\b)' full_pattern = r'^.*?' + class_name + potential_assignment + \ single_class_ref_arg + not_followed_by_noexcept + '.*?$' regexp = input_api.re.compile(full_pattern, re.MULTILINE) errors = [] for f in input_api.AffectedFiles(file_filter=FilterFile, include_deletes=False): with open(f.LocalPath()) as fh: for match in re.finditer(regexp, fh.read()): errors.append('in {}: {}'.format(f.LocalPath(), match.group().strip())) if errors: return [output_api.PresubmitPromptOrNotify( 'Copy constructors, move constructors, copy assignment operators and ' 'move assignment operators should be marked V8_NOEXCEPT.\n' 'Please report false positives on https://crbug.com/v8/8616.', errors)] return []
[ "def", "_CheckNoexceptAnnotations", "(", "input_api", ",", "output_api", ")", ":", "def", "FilterFile", "(", "affected_file", ")", ":", "return", "input_api", ".", "FilterSourceFile", "(", "affected_file", ",", "white_list", "=", "(", "r'src/.*'", ",", "r'test/.*'...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/deps/v8/PRESUBMIT.py#L456-L505
LLNL/lbann
26083e6c86050302ce33148aea70f62e61cacb92
python/lbann/launcher/openmpi.py
python
OpenMPIBatchScript.__init__
(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, launcher='mpiexec', launcher_args=[], interpreter='/bin/bash')
Construct OpenMPI script manager. Args: script_file (str): Script file. work_dir (str, optional): Working directory (default: current working directory). nodes (int, optional): Number of compute nodes (default: 1). procs_per_node (int, optional): Parallel processes per compute node (default: 1). launcher (str, optional): Parallel command launcher (default: mpiexec). launcher_args (`Iterable` of `str`, optional): Command-line arguments to mpiexec. interpreter (str, optional): Script interpreter (default: /bin/bash).
Construct OpenMPI script manager.
[ "Construct", "OpenMPI", "script", "manager", "." ]
def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, launcher='mpiexec', launcher_args=[], interpreter='/bin/bash'): """Construct OpenMPI script manager. Args: script_file (str): Script file. work_dir (str, optional): Working directory (default: current working directory). nodes (int, optional): Number of compute nodes (default: 1). procs_per_node (int, optional): Parallel processes per compute node (default: 1). launcher (str, optional): Parallel command launcher (default: mpiexec). launcher_args (`Iterable` of `str`, optional): Command-line arguments to mpiexec. interpreter (str, optional): Script interpreter (default: /bin/bash). """ super().__init__(script_file=script_file, work_dir=work_dir, interpreter=interpreter) self.nodes = nodes self.procs_per_node = procs_per_node self.launcher = launcher self.launcher_args = launcher_args
[ "def", "__init__", "(", "self", ",", "script_file", "=", "None", ",", "work_dir", "=", "os", ".", "getcwd", "(", ")", ",", "nodes", "=", "1", ",", "procs_per_node", "=", "1", ",", "launcher", "=", "'mpiexec'", ",", "launcher_args", "=", "[", "]", ","...
https://github.com/LLNL/lbann/blob/26083e6c86050302ce33148aea70f62e61cacb92/python/lbann/launcher/openmpi.py#L11-L43
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/inspector_protocol/jinja2/runtime.py
python
make_logging_undefined
(logger=None, base=None)
return LoggingUndefined
Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`.
Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created.
[ "Given", "a", "logger", "object", "this", "returns", "a", "new", "undefined", "class", "that", "will", "log", "certain", "failures", ".", "It", "will", "log", "iterations", "and", "printing", ".", "If", "no", "logger", "is", "given", "a", "default", "logge...
def make_logging_undefined(logger=None, base=None): """Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`. """ if logger is None: import logging logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler(sys.stderr)) if base is None: base = Undefined def _log_message(undef): if undef._undefined_hint is None: if undef._undefined_obj is missing: hint = '%s is undefined' % undef._undefined_name elif not isinstance(undef._undefined_name, string_types): hint = '%s has no element %s' % ( object_type_repr(undef._undefined_obj), undef._undefined_name) else: hint = '%s has no attribute %s' % ( object_type_repr(undef._undefined_obj), undef._undefined_name) else: hint = undef._undefined_hint logger.warning('Template variable warning: %s', hint) class LoggingUndefined(base): def _fail_with_undefined_error(self, *args, **kwargs): try: return base._fail_with_undefined_error(self, *args, **kwargs) except self._undefined_exception as e: logger.error('Template variable error: %s', str(e)) raise e def __str__(self): rv = base.__str__(self) _log_message(self) return rv def __iter__(self): rv = base.__iter__(self) _log_message(self) return rv if PY2: def __nonzero__(self): rv = base.__nonzero__(self) _log_message(self) return rv def __unicode__(self): rv = base.__unicode__(self) _log_message(self) return rv else: def __bool__(self): rv = base.__bool__(self) _log_message(self) return rv return LoggingUndefined
[ "def", "make_logging_undefined", "(", "logger", "=", "None", ",", "base", "=", "None", ")", ":", "if", "logger", "is", "None", ":", "import", "logging", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "addHandler", "(", "...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/inspector_protocol/jinja2/runtime.py#L677-L755
ArduPilot/ardupilot
6e684b3496122b8158ac412b609d00004b7ac306
Tools/scripts/gen_stable.py
python
make_all_stable
(basedir)
make stable directory for all vehicles
make stable directory for all vehicles
[ "make", "stable", "directory", "for", "all", "vehicles" ]
def make_all_stable(basedir): '''make stable directory for all vehicles''' for v in VEHICLES: make_stable(basedir, v)
[ "def", "make_all_stable", "(", "basedir", ")", ":", "for", "v", "in", "VEHICLES", ":", "make_stable", "(", "basedir", ",", "v", ")" ]
https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/Tools/scripts/gen_stable.py#L38-L41
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
python/setup.py
python
strtobool
(val)
Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else.
Convert a string representation of truth to true (1) or false (0).
[ "Convert", "a", "string", "representation", "of", "truth", "to", "true", "(", "1", ")", "or", "false", "(", "0", ")", "." ]
def strtobool(val): """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ # Copied from distutils val = val.lower() if val in ('y', 'yes', 't', 'true', 'on', '1'): return 1 elif val in ('n', 'no', 'f', 'false', 'off', '0'): return 0 else: raise ValueError("invalid truth value %r" % (val,))
[ "def", "strtobool", "(", "val", ")", ":", "# Copied from distutils", "val", "=", "val", ".", "lower", "(", ")", "if", "val", "in", "(", "'y'", ",", "'yes'", ",", "'t'", ",", "'true'", ",", "'on'", ",", "'1'", ")", ":", "return", "1", "elif", "val",...
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/python/setup.py#L63-L77
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pgen2/grammar.py
python
Grammar.loads
(self, pkl)
Load the grammar tables from a pickle bytes object.
Load the grammar tables from a pickle bytes object.
[ "Load", "the", "grammar", "tables", "from", "a", "pickle", "bytes", "object", "." ]
def loads(self, pkl): """Load the grammar tables from a pickle bytes object.""" self.__dict__.update(pickle.loads(pkl))
[ "def", "loads", "(", "self", ",", "pkl", ")", ":", "self", ".", "__dict__", ".", "update", "(", "pickle", ".", "loads", "(", "pkl", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/lib2to3/pgen2/grammar.py#L111-L113
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/build_py.py
python
build_py.__getattr__
(self, attr)
return orig.build_py.__getattr__(self, attr)
lazily compute data files
lazily compute data files
[ "lazily", "compute", "data", "files" ]
def __getattr__(self, attr): "lazily compute data files" if attr == 'data_files': self.data_files = self._get_data_files() return self.data_files return orig.build_py.__getattr__(self, attr)
[ "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "if", "attr", "==", "'data_files'", ":", "self", ".", "data_files", "=", "self", ".", "_get_data_files", "(", ")", "return", "self", ".", "data_files", "return", "orig", ".", "build_py", ".", "__g...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/setuptools/command/build_py.py#L63-L68
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
TextAttr.HasParagraphSpacingBefore
(*args, **kwargs)
return _controls_.TextAttr_HasParagraphSpacingBefore(*args, **kwargs)
HasParagraphSpacingBefore(self) -> bool
HasParagraphSpacingBefore(self) -> bool
[ "HasParagraphSpacingBefore", "(", "self", ")", "-", ">", "bool" ]
def HasParagraphSpacingBefore(*args, **kwargs): """HasParagraphSpacingBefore(self) -> bool""" return _controls_.TextAttr_HasParagraphSpacingBefore(*args, **kwargs)
[ "def", "HasParagraphSpacingBefore", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TextAttr_HasParagraphSpacingBefore", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L1832-L1834
OAID/Caffe-HRT
aae71e498ab842c6f92bcc23fc668423615a4d65
scripts/cpp_lint.py
python
CheckForFunctionLengths
(filename, clean_lines, linenum, function_state, error)
Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found.
Reports for long function bodies.
[ "Reports", "for", "long", "function", "bodies", "." ]
def CheckForFunctionLengths(filename, clean_lines, linenum, function_state, error): """Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found. """ lines = clean_lines.lines line = lines[linenum] raw = clean_lines.raw_lines raw_line = raw[linenum] joined_line = '' starting_func = False regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... match_result = Match(regexp, line) if match_result: # If the name is all caps and underscores, figure it's a macro and # ignore it, unless it's TEST or TEST_F. function_name = match_result.group(1).split()[-1] if function_name == 'TEST' or function_name == 'TEST_F' or ( not Match(r'[A-Z_]+$', function_name)): starting_func = True if starting_func: body_found = False for start_linenum in xrange(linenum, clean_lines.NumLines()): start_line = lines[start_linenum] joined_line += ' ' + start_line.lstrip() if Search(r'(;|})', start_line): # Declarations and trivial functions body_found = True break # ... ignore elif Search(r'{', start_line): body_found = True function = Search(r'((\w|:)*)\(', line).group(1) if Match(r'TEST', function): # Handle TEST... macros parameter_regexp = Search(r'(\(.*\))', joined_line) if parameter_regexp: # Ignore bad syntax function += parameter_regexp.group(1) else: function += '()' function_state.Begin(function) break if not body_found: # No body for the function (or evidence of a non-function) was found. error(filename, linenum, 'readability/fn_size', 5, 'Lint failed to find start of function body.') elif Match(r'^\}\s*$', line): # function end function_state.Check(error, filename, linenum) function_state.End() elif not Match(r'^\s*$', line): function_state.Count()
[ "def", "CheckForFunctionLengths", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "function_state", ",", "error", ")", ":", "lines", "=", "clean_lines", ".", "lines", "line", "=", "lines", "[", "linenum", "]", "raw", "=", "clean_lines", ".", "raw_l...
https://github.com/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/scripts/cpp_lint.py#L2384-L2451
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/core/shape_base.py
python
atleast_1d
(*arys)
Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved. Parameters ---------- arys1, arys2, ... : array_like One or more input arrays. Returns ------- ret : ndarray An array, or list of arrays, each with ``a.ndim >= 1``. Copies are made only if necessary. See Also -------- atleast_2d, atleast_3d Examples -------- >>> np.atleast_1d(1.0) array([ 1.]) >>> x = np.arange(9.0).reshape(3,3) >>> np.atleast_1d(x) array([[ 0., 1., 2.], [ 3., 4., 5.], [ 6., 7., 8.]]) >>> np.atleast_1d(x) is x True >>> np.atleast_1d(1, [3, 4]) [array([1]), array([3, 4])]
Convert inputs to arrays with at least one dimension.
[ "Convert", "inputs", "to", "arrays", "with", "at", "least", "one", "dimension", "." ]
def atleast_1d(*arys): """ Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved. Parameters ---------- arys1, arys2, ... : array_like One or more input arrays. Returns ------- ret : ndarray An array, or list of arrays, each with ``a.ndim >= 1``. Copies are made only if necessary. See Also -------- atleast_2d, atleast_3d Examples -------- >>> np.atleast_1d(1.0) array([ 1.]) >>> x = np.arange(9.0).reshape(3,3) >>> np.atleast_1d(x) array([[ 0., 1., 2.], [ 3., 4., 5.], [ 6., 7., 8.]]) >>> np.atleast_1d(x) is x True >>> np.atleast_1d(1, [3, 4]) [array([1]), array([3, 4])] """ res = [] for ary in arys: ary = asanyarray(ary) if ary.ndim == 0: result = ary.reshape(1) else: result = ary res.append(result) if len(res) == 1: return res[0] else: return res
[ "def", "atleast_1d", "(", "*", "arys", ")", ":", "res", "=", "[", "]", "for", "ary", "in", "arys", ":", "ary", "=", "asanyarray", "(", "ary", ")", "if", "ary", ".", "ndim", "==", "0", ":", "result", "=", "ary", ".", "reshape", "(", "1", ")", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/core/shape_base.py#L26-L76
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/plotconfigdialog/curvestabwidget/__init__.py
python
remove_curve_from_ax
(curve)
Remove a Line2D or ErrobarContainer from its Axes :param curve: A Line2D or ErrorbarContainer object
Remove a Line2D or ErrobarContainer from its Axes :param curve: A Line2D or ErrorbarContainer object
[ "Remove", "a", "Line2D", "or", "ErrobarContainer", "from", "its", "Axes", ":", "param", "curve", ":", "A", "Line2D", "or", "ErrorbarContainer", "object" ]
def remove_curve_from_ax(curve): """ Remove a Line2D or ErrobarContainer from its Axes :param curve: A Line2D or ErrorbarContainer object """ ax = get_ax_from_curve(curve) if isinstance(ax, MantidAxes): ax.remove_artists_if(lambda art: art == curve) else: curve.remove() if isinstance(curve, ErrorbarContainer): ax.containers.remove(curve)
[ "def", "remove_curve_from_ax", "(", "curve", ")", ":", "ax", "=", "get_ax_from_curve", "(", "curve", ")", "if", "isinstance", "(", "ax", ",", "MantidAxes", ")", ":", "ax", ".", "remove_artists_if", "(", "lambda", "art", ":", "art", "==", "curve", ")", "e...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/plotconfigdialog/curvestabwidget/__init__.py#L61-L72
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/ogr.py
python
DataSource.GetRefCount
(self, *args)
return _ogr.DataSource_GetRefCount(self, *args)
r""" GetRefCount(DataSource self) -> int int OGR_DS_GetRefCount(OGRDataSourceH hDataSource)
r""" GetRefCount(DataSource self) -> int int OGR_DS_GetRefCount(OGRDataSourceH hDataSource)
[ "r", "GetRefCount", "(", "DataSource", "self", ")", "-", ">", "int", "int", "OGR_DS_GetRefCount", "(", "OGRDataSourceH", "hDataSource", ")" ]
def GetRefCount(self, *args): r""" GetRefCount(DataSource self) -> int int OGR_DS_GetRefCount(OGRDataSourceH hDataSource) """ return _ogr.DataSource_GetRefCount(self, *args)
[ "def", "GetRefCount", "(", "self", ",", "*", "args", ")", ":", "return", "_ogr", ".", "DataSource_GetRefCount", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/ogr.py#L570-L576
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetBundlePlugInsFolderPath
(self)
return os.path.join(self.GetBundleContentsFolderPath(), 'PlugIns')
Returns the qualified path to the bundle's plugins folder. E.g, Chromium.app/Contents/PlugIns. Only valid for bundles.
Returns the qualified path to the bundle's plugins folder. E.g, Chromium.app/Contents/PlugIns. Only valid for bundles.
[ "Returns", "the", "qualified", "path", "to", "the", "bundle", "s", "plugins", "folder", ".", "E", ".", "g", "Chromium", ".", "app", "/", "Contents", "/", "PlugIns", ".", "Only", "valid", "for", "bundles", "." ]
def GetBundlePlugInsFolderPath(self): """Returns the qualified path to the bundle's plugins folder. E.g, Chromium.app/Contents/PlugIns. Only valid for bundles.""" assert self._IsBundle() return os.path.join(self.GetBundleContentsFolderPath(), 'PlugIns')
[ "def", "GetBundlePlugInsFolderPath", "(", "self", ")", ":", "assert", "self", ".", "_IsBundle", "(", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "GetBundleContentsFolderPath", "(", ")", ",", "'PlugIns'", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/tools/gyp/pylib/gyp/xcode_emulation.py#L353-L357
google/sling
f408a148a06bc2d62e853a292a8ba7266c642839
python/task/workflow.py
python
Workflow.pipe
(self, command, format=None, name=None)
return output
Run command and pipe output to channel.
Run command and pipe output to channel.
[ "Run", "command", "and", "pipe", "output", "to", "channel", "." ]
def pipe(self, command, format=None, name=None): """Run command and pipe output to channel.""" reader = self.task("pipe-reader", name, params={"command": command}) if type(format) == str: format = Format(format) if format is None: format = Format("pipe/text") output = self.channel(reader, format=format.as_message()) return output
[ "def", "pipe", "(", "self", ",", "command", ",", "format", "=", "None", ",", "name", "=", "None", ")", ":", "reader", "=", "self", ".", "task", "(", "\"pipe-reader\"", ",", "name", ",", "params", "=", "{", "\"command\"", ":", "command", "}", ")", "...
https://github.com/google/sling/blob/f408a148a06bc2d62e853a292a8ba7266c642839/python/task/workflow.py#L544-L550
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pkg_resources/__init__.py
python
safe_version
(version)
Convert an arbitrary string to a standard version string
Convert an arbitrary string to a standard version string
[ "Convert", "an", "arbitrary", "string", "to", "a", "standard", "version", "string" ]
def safe_version(version): """ Convert an arbitrary string to a standard version string """ try: # normalize the version return str(packaging.version.Version(version)) except packaging.version.InvalidVersion: version = version.replace(' ', '.') return re.sub('[^A-Za-z0-9.]+', '-', version)
[ "def", "safe_version", "(", "version", ")", ":", "try", ":", "# normalize the version", "return", "str", "(", "packaging", ".", "version", ".", "Version", "(", "version", ")", ")", "except", "packaging", ".", "version", ".", "InvalidVersion", ":", "version", ...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pkg_resources/__init__.py#L1325-L1334
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/http/cookiejar.py
python
CookieJar._normalized_cookie_tuples
(self, attrs_set)
return cookie_tuples
Return list of tuples containing normalised cookie information. attrs_set is the list of lists of key,value pairs extracted from the Set-Cookie or Set-Cookie2 headers. Tuples are name, value, standard, rest, where name and value are the cookie name and value, standard is a dictionary containing the standard cookie-attributes (discard, secure, version, expires or max-age, domain, path and port) and rest is a dictionary containing the rest of the cookie-attributes.
Return list of tuples containing normalised cookie information.
[ "Return", "list", "of", "tuples", "containing", "normalised", "cookie", "information", "." ]
def _normalized_cookie_tuples(self, attrs_set): """Return list of tuples containing normalised cookie information. attrs_set is the list of lists of key,value pairs extracted from the Set-Cookie or Set-Cookie2 headers. Tuples are name, value, standard, rest, where name and value are the cookie name and value, standard is a dictionary containing the standard cookie-attributes (discard, secure, version, expires or max-age, domain, path and port) and rest is a dictionary containing the rest of the cookie-attributes. """ cookie_tuples = [] boolean_attrs = "discard", "secure" value_attrs = ("version", "expires", "max-age", "domain", "path", "port", "comment", "commenturl") for cookie_attrs in attrs_set: name, value = cookie_attrs[0] # Build dictionary of standard cookie-attributes (standard) and # dictionary of other cookie-attributes (rest). # Note: expiry time is normalised to seconds since epoch. V0 # cookies should have the Expires cookie-attribute, and V1 cookies # should have Max-Age, but since V1 includes RFC 2109 cookies (and # since V0 cookies may be a mish-mash of Netscape and RFC 2109), we # accept either (but prefer Max-Age). max_age_set = False bad_cookie = False standard = {} rest = {} for k, v in cookie_attrs[1:]: lc = k.lower() # don't lose case distinction for unknown fields if lc in value_attrs or lc in boolean_attrs: k = lc if k in boolean_attrs and v is None: # boolean cookie-attribute is present, but has no value # (like "discard", rather than "port=80") v = True if k in standard: # only first value is significant continue if k == "domain": if v is None: _debug(" missing value for domain attribute") bad_cookie = True break # RFC 2965 section 3.3.3 v = v.lower() if k == "expires": if max_age_set: # Prefer max-age to expires (like Mozilla) continue if v is None: _debug(" missing or invalid value for expires " "attribute: treating as session cookie") continue if k == "max-age": max_age_set = True try: v = int(v) except ValueError: _debug(" missing or invalid (non-numeric) value for " "max-age attribute") bad_cookie = True break # convert RFC 2965 Max-Age to seconds since epoch # XXX Strictly you're supposed to follow RFC 2616 # age-calculation rules. Remember that zero Max-Age # is a request to discard (old and new) cookie, though. k = "expires" v = self._now + v if (k in value_attrs) or (k in boolean_attrs): if (v is None and k not in ("port", "comment", "commenturl")): _debug(" missing value for %s attribute" % k) bad_cookie = True break standard[k] = v else: rest[k] = v if bad_cookie: continue cookie_tuples.append((name, value, standard, rest)) return cookie_tuples
[ "def", "_normalized_cookie_tuples", "(", "self", ",", "attrs_set", ")", ":", "cookie_tuples", "=", "[", "]", "boolean_attrs", "=", "\"discard\"", ",", "\"secure\"", "value_attrs", "=", "(", "\"version\"", ",", "\"expires\"", ",", "\"max-age\"", ",", "\"domain\"", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/http/cookiejar.py#L1383-L1478
PyMesh/PyMesh
384ba882b7558ba6e8653ed263c419226c22bddf
python/pymesh/material.py
python
Material.create_orthotropic
(cls, density, young, poisson, shear)
return Material(PyMesh.Material.create_orthotropic( density, young, poisson, shear))
Create an orthotropic material. Args: desnity: Material density. young: Array of Young's modulus, [young_x, young_y, young_z] poisson: Array of Poisson's ratio, [poisson_yz, poisson_zy, poisson_zx, poisson_xz, poisson_xy, poisson_yx] shear: Array of Shear modulus, [shear_yz, shear_zx, shear_xy]
Create an orthotropic material.
[ "Create", "an", "orthotropic", "material", "." ]
def create_orthotropic(cls, density, young, poisson, shear): """ Create an orthotropic material. Args: desnity: Material density. young: Array of Young's modulus, [young_x, young_y, young_z] poisson: Array of Poisson's ratio, [poisson_yz, poisson_zy, poisson_zx, poisson_xz, poisson_xy, poisson_yx] shear: Array of Shear modulus, [shear_yz, shear_zx, shear_xy] """ return Material(PyMesh.Material.create_orthotropic( density, young, poisson, shear))
[ "def", "create_orthotropic", "(", "cls", ",", "density", ",", "young", ",", "poisson", ",", "shear", ")", ":", "return", "Material", "(", "PyMesh", ".", "Material", ".", "create_orthotropic", "(", "density", ",", "young", ",", "poisson", ",", "shear", ")",...
https://github.com/PyMesh/PyMesh/blob/384ba882b7558ba6e8653ed263c419226c22bddf/python/pymesh/material.py#L21-L33
BestSonny/SSTD
174d452189f6bf9cf4b6957719392008bd974069
python/caffe/coord_map.py
python
crop_params
(fn)
return (axis, offset)
Extract the crop layer parameters with defaults.
Extract the crop layer parameters with defaults.
[ "Extract", "the", "crop", "layer", "parameters", "with", "defaults", "." ]
def crop_params(fn): """ Extract the crop layer parameters with defaults. """ params = fn.params.get('crop_param', fn.params) axis = params.get('axis', 2) # default to spatial crop for N, C, H, W offset = np.array(params.get('offset', 0), ndmin=1) return (axis, offset)
[ "def", "crop_params", "(", "fn", ")", ":", "params", "=", "fn", ".", "params", ".", "get", "(", "'crop_param'", ",", "fn", ".", "params", ")", "axis", "=", "params", ".", "get", "(", "'axis'", ",", "2", ")", "# default to spatial crop for N, C, H, W", "o...
https://github.com/BestSonny/SSTD/blob/174d452189f6bf9cf4b6957719392008bd974069/python/caffe/coord_map.py#L40-L47
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Source/ThirdParty/FreeType2/FreeType2-2.6/Src/tools/docmaker/docmaker.py
python
main
( argv )
Main program loop.
Main program loop.
[ "Main", "program", "loop", "." ]
def main( argv ): """Main program loop.""" global output_dir try: opts, args = getopt.getopt( sys.argv[1:], "ht:o:p:", ["help", "title=", "output=", "prefix="] ) except getopt.GetoptError: usage() sys.exit( 2 ) if args == []: usage() sys.exit( 1 ) # process options project_title = "Project" project_prefix = None output_dir = None for opt in opts: if opt[0] in ( "-h", "--help" ): usage() sys.exit( 0 ) if opt[0] in ( "-t", "--title" ): project_title = opt[1] if opt[0] in ( "-o", "--output" ): utils.output_dir = opt[1] if opt[0] in ( "-p", "--prefix" ): project_prefix = opt[1] check_output() # create context and processor source_processor = SourceProcessor() content_processor = ContentProcessor() # retrieve the list of files to process file_list = make_file_list( args ) for filename in file_list: source_processor.parse_file( filename ) content_processor.parse_sources( source_processor ) # process sections content_processor.finish() formatter = HtmlFormatter( content_processor, project_title, project_prefix ) formatter.toc_dump() formatter.index_dump() formatter.section_dump_all()
[ "def", "main", "(", "argv", ")", ":", "global", "output_dir", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "\"ht:o:p:\"", ",", "[", "\"help\"", ",", "\"title=\"", ",", "\"output=\"",...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Source/ThirdParty/FreeType2/FreeType2-2.6/Src/tools/docmaker/docmaker.py#L51-L108
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py
python
Context.remainder_near
(self, a, b)
return a.remainder_near(b, context=self)
Returns to be "a - b * n", where n is the integer nearest the exact value of "x / b" (if two integers are equally near then the even one is chosen). If the result is equal to 0 then its sign will be the sign of a. This operation will fail under the same conditions as integer division (that is, if integer division on the same two operands would fail, the remainder cannot be calculated). >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) Decimal('-0.9') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) Decimal('-2') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) Decimal('1') >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) Decimal('-1') >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) Decimal('0.2') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) Decimal('0.1') >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) Decimal('-0.3') >>> ExtendedContext.remainder_near(3, 11) Decimal('3') >>> ExtendedContext.remainder_near(Decimal(3), 11) Decimal('3') >>> ExtendedContext.remainder_near(3, Decimal(11)) Decimal('3')
Returns to be "a - b * n", where n is the integer nearest the exact value of "x / b" (if two integers are equally near then the even one is chosen). If the result is equal to 0 then its sign will be the sign of a.
[ "Returns", "to", "be", "a", "-", "b", "*", "n", "where", "n", "is", "the", "integer", "nearest", "the", "exact", "value", "of", "x", "/", "b", "(", "if", "two", "integers", "are", "equally", "near", "then", "the", "even", "one", "is", "chosen", ")"...
def remainder_near(self, a, b): """Returns to be "a - b * n", where n is the integer nearest the exact value of "x / b" (if two integers are equally near then the even one is chosen). If the result is equal to 0 then its sign will be the sign of a. This operation will fail under the same conditions as integer division (that is, if integer division on the same two operands would fail, the remainder cannot be calculated). >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) Decimal('-0.9') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) Decimal('-2') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) Decimal('1') >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) Decimal('-1') >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) Decimal('0.2') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) Decimal('0.1') >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) Decimal('-0.3') >>> ExtendedContext.remainder_near(3, 11) Decimal('3') >>> ExtendedContext.remainder_near(Decimal(3), 11) Decimal('3') >>> ExtendedContext.remainder_near(3, Decimal(11)) Decimal('3') """ a = _convert_other(a, raiseit=True) return a.remainder_near(b, context=self)
[ "def", "remainder_near", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "remainder_near", "(", "b", ",", "context", "=", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py#L5325-L5357
yshshrm/Data-Structures-And-Algorithms-Hacktoberfest18
ce2807facfb817d1303d2ac9f1b2d90955e29a18
python/algorithms/Timsort.py
python
binary_search
(the_array, item, start, end)
Binary search that the insertion sort uses for the insertion of a new value in a sorted array
Binary search that the insertion sort uses for the insertion of a new value in a sorted array
[ "Binary", "search", "that", "the", "insertion", "sort", "uses", "for", "the", "insertion", "of", "a", "new", "value", "in", "a", "sorted", "array" ]
def binary_search(the_array, item, start, end): """ Binary search that the insertion sort uses for the insertion of a new value in a sorted array """ if start == end: if the_array[start] > item: return start else: return start + 1 if start > end: return start mid = round((start + end) / 2) if the_array[mid] < item: return binary_search(the_array, item, mid + 1, end) elif the_array[mid] > item: return binary_search(the_array, item, start, mid - 1) else: return mid
[ "def", "binary_search", "(", "the_array", ",", "item", ",", "start", ",", "end", ")", ":", "if", "start", "==", "end", ":", "if", "the_array", "[", "start", "]", ">", "item", ":", "return", "start", "else", ":", "return", "start", "+", "1", "if", "...
https://github.com/yshshrm/Data-Structures-And-Algorithms-Hacktoberfest18/blob/ce2807facfb817d1303d2ac9f1b2d90955e29a18/python/algorithms/Timsort.py#L1-L23
raspberrypi/tools
13474ee775d0c5ec8a7da4fb0a9fa84187abfc87
arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/share/gdb/python/gdb/command/explore.py
python
Explorer.explore_expr
(expr, value, is_child)
Main function to explore an expression value. Arguments: expr: The expression string that is being explored. value: The gdb.Value value of the expression. is_child: Boolean value to indicate if the expression is a child. An expression is a child if it is derived from the main expression entered by the user. For example, if the user entered an expression which evaluates to a struct, then when exploring the fields of the struct, is_child is set to True internally. Returns: No return value.
Main function to explore an expression value.
[ "Main", "function", "to", "explore", "an", "expression", "value", "." ]
def explore_expr(expr, value, is_child): """Main function to explore an expression value. Arguments: expr: The expression string that is being explored. value: The gdb.Value value of the expression. is_child: Boolean value to indicate if the expression is a child. An expression is a child if it is derived from the main expression entered by the user. For example, if the user entered an expression which evaluates to a struct, then when exploring the fields of the struct, is_child is set to True internally. Returns: No return value. """ type_code = value.type.code if type_code in Explorer.type_code_to_explorer_map: explorer_class = Explorer.type_code_to_explorer_map[type_code] while explorer_class.explore_expr(expr, value, is_child): pass else: print ("Explorer for type '%s' not yet available.\n" % str(value.type))
[ "def", "explore_expr", "(", "expr", ",", "value", ",", "is_child", ")", ":", "type_code", "=", "value", ".", "type", ".", "code", "if", "type_code", "in", "Explorer", ".", "type_code_to_explorer_map", ":", "explorer_class", "=", "Explorer", ".", "type_code_to_...
https://github.com/raspberrypi/tools/blob/13474ee775d0c5ec8a7da4fb0a9fa84187abfc87/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/share/gdb/python/gdb/command/explore.py#L66-L89
gwaldron/osgearth
4c521857d59a69743e4a9cedba00afe570f984e8
src/third_party/tinygltf/deps/cpplint.py
python
ProcessFileData
(filename, file_extension, lines, error, extra_check_functions=[])
Performs lint checks and reports any errors to the given error function. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. lines: An array of strings, each representing a line of the file, with the last element being empty if the file is terminated with a newline. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error
Performs lint checks and reports any errors to the given error function.
[ "Performs", "lint", "checks", "and", "reports", "any", "errors", "to", "the", "given", "error", "function", "." ]
def ProcessFileData(filename, file_extension, lines, error, extra_check_functions=[]): """Performs lint checks and reports any errors to the given error function. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. lines: An array of strings, each representing a line of the file, with the last element being empty if the file is terminated with a newline. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ lines = (['// marker so line numbers and indices both start at 1'] + lines + ['// marker so line numbers end in a known way']) include_state = _IncludeState() function_state = _FunctionState() nesting_state = NestingState() ResetNolintSuppressions() CheckForCopyright(filename, lines, error) RemoveMultiLineComments(filename, lines, error) clean_lines = CleansedLines(lines) if file_extension == 'h': CheckForHeaderGuard(filename, clean_lines, error) for line in xrange(clean_lines.NumLines()): ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions) FlagCxx11Features(filename, clean_lines, line, error) nesting_state.CheckCompletedBlocks(filename, error) CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) # Check that the .cc file has included its header if it exists. if file_extension == 'cc': CheckHeaderFileIncluded(filename, include_state, error) # We check here rather than inside ProcessLine so that we see raw # lines rather than "cleaned" lines. CheckForBadCharacters(filename, lines, error) CheckForNewlineAtEOF(filename, lines, error)
[ "def", "ProcessFileData", "(", "filename", ",", "file_extension", ",", "lines", ",", "error", ",", "extra_check_functions", "=", "[", "]", ")", ":", "lines", "=", "(", "[", "'// marker so line numbers and indices both start at 1'", "]", "+", "lines", "+", "[", "...
https://github.com/gwaldron/osgearth/blob/4c521857d59a69743e4a9cedba00afe570f984e8/src/third_party/tinygltf/deps/cpplint.py#L5997-L6046
potassco/clingo
e0c91d8f95cc28de1c480a871f9c97c30de83d40
libpyclingo/clingo/propagator.py
python
PropagateControl.propagate
(self)
return _c_call('bool', _lib.clingo_propagate_control_propagate, self._rep)
Propagate literals implied by added clauses. Returns ------- This method returns false if the current propagation must be stopped.
Propagate literals implied by added clauses.
[ "Propagate", "literals", "implied", "by", "added", "clauses", "." ]
def propagate(self) -> bool: ''' Propagate literals implied by added clauses. Returns ------- This method returns false if the current propagation must be stopped. ''' return _c_call('bool', _lib.clingo_propagate_control_propagate, self._rep)
[ "def", "propagate", "(", "self", ")", "->", "bool", ":", "return", "_c_call", "(", "'bool'", ",", "_lib", ".", "clingo_propagate_control_propagate", ",", "self", ".", "_rep", ")" ]
https://github.com/potassco/clingo/blob/e0c91d8f95cc28de1c480a871f9c97c30de83d40/libpyclingo/clingo/propagator.py#L614-L622
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/core/glc_assembler.py
python
GlcAssembler.Status
(message)
Outputs a status message.
Outputs a status message.
[ "Outputs", "a", "status", "message", "." ]
def Status(message): """Outputs a status message.""" print "\n%s" % message
[ "def", "Status", "(", "message", ")", ":", "print", "\"\\n%s\"", "%", "message" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/cutter/cgi-bin/core/glc_assembler.py#L131-L133
ZintrulCre/LeetCode_Archiver
de23e16ead29336b5ee7aa1898a392a5d6463d27
LeetCode/python3/55.py
python
Solution.canJump
(self, nums)
return True
:type nums: List[int] :rtype: bool
:type nums: List[int] :rtype: bool
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "rtype", ":", "bool" ]
def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ pos = 0 for i in range(len(nums)-1): pos = max(pos, i + nums[i]) if pos <= i: return False return True
[ "def", "canJump", "(", "self", ",", "nums", ")", ":", "pos", "=", "0", "for", "i", "in", "range", "(", "len", "(", "nums", ")", "-", "1", ")", ":", "pos", "=", "max", "(", "pos", ",", "i", "+", "nums", "[", "i", "]", ")", "if", "pos", "<=...
https://github.com/ZintrulCre/LeetCode_Archiver/blob/de23e16ead29336b5ee7aa1898a392a5d6463d27/LeetCode/python3/55.py#L2-L12
eldar/deepcut-cnn
928bf2f224fce132f6e4404b4c95fb017297a5e0
scripts/cpp_lint.py
python
Search
(pattern, s)
return _regexp_compile_cache[pattern].search(s)
Searches the string for the pattern, caching the compiled regexp.
Searches the string for the pattern, caching the compiled regexp.
[ "Searches", "the", "string", "for", "the", "pattern", "caching", "the", "compiled", "regexp", "." ]
def Search(pattern, s): """Searches the string for the pattern, caching the compiled regexp.""" if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].search(s)
[ "def", "Search", "(", "pattern", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pat...
https://github.com/eldar/deepcut-cnn/blob/928bf2f224fce132f6e4404b4c95fb017297a5e0/scripts/cpp_lint.py#L543-L547
apache/thrift
0b29261a4f3c6882ef3b09aae47914f0012b0472
lib/py/setup.py
python
read_file
(path)
Return the contents of a file Arguments: - path: path to the file Returns: - contents of the file
Return the contents of a file
[ "Return", "the", "contents", "of", "a", "file" ]
def read_file(path): """ Return the contents of a file Arguments: - path: path to the file Returns: - contents of the file """ with open(path, "r") as desc_file: return desc_file.read().rstrip()
[ "def", "read_file", "(", "path", ")", ":", "with", "open", "(", "path", ",", "\"r\"", ")", "as", "desc_file", ":", "return", "desc_file", ".", "read", "(", ")", ".", "rstrip", "(", ")" ]
https://github.com/apache/thrift/blob/0b29261a4f3c6882ef3b09aae47914f0012b0472/lib/py/setup.py#L65-L76
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextCtrl.GetStyleSheet
(*args, **kwargs)
return _richtext.RichTextCtrl_GetStyleSheet(*args, **kwargs)
GetStyleSheet(self) -> wxRichTextStyleSheet
GetStyleSheet(self) -> wxRichTextStyleSheet
[ "GetStyleSheet", "(", "self", ")", "-", ">", "wxRichTextStyleSheet" ]
def GetStyleSheet(*args, **kwargs): """GetStyleSheet(self) -> wxRichTextStyleSheet""" return _richtext.RichTextCtrl_GetStyleSheet(*args, **kwargs)
[ "def", "GetStyleSheet", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_GetStyleSheet", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L4003-L4005
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/polynomial/polynomial.py
python
polyadd
(c1, c2)
return pu.trimseq(ret)
Add one polynomial to another. Returns the sum of two polynomials `c1` + `c2`. The arguments are sequences of coefficients from lowest order term to highest, i.e., [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``. Parameters ---------- c1, c2 : array_like 1-D arrays of polynomial coefficients ordered from low to high. Returns ------- out : ndarray The coefficient array representing their sum. See Also -------- polysub, polymulx, polymul, polydiv, polypow Examples -------- >>> from numpy.polynomial import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> sum = P.polyadd(c1,c2); sum array([ 4., 4., 4.]) >>> P.polyval(2, sum) # 4 + 4(2) + 4(2**2) 28.0
Add one polynomial to another.
[ "Add", "one", "polynomial", "to", "another", "." ]
def polyadd(c1, c2): """ Add one polynomial to another. Returns the sum of two polynomials `c1` + `c2`. The arguments are sequences of coefficients from lowest order term to highest, i.e., [1,2,3] represents the polynomial ``1 + 2*x + 3*x**2``. Parameters ---------- c1, c2 : array_like 1-D arrays of polynomial coefficients ordered from low to high. Returns ------- out : ndarray The coefficient array representing their sum. See Also -------- polysub, polymulx, polymul, polydiv, polypow Examples -------- >>> from numpy.polynomial import polynomial as P >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> sum = P.polyadd(c1,c2); sum array([ 4., 4., 4.]) >>> P.polyval(2, sum) # 4 + 4(2) + 4(2**2) 28.0 """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if len(c1) > len(c2): c1[:c2.size] += c2 ret = c1 else: c2[:c1.size] += c1 ret = c2 return pu.trimseq(ret)
[ "def", "polyadd", "(", "c1", ",", "c2", ")", ":", "# c1, c2 are trimmed copies", "[", "c1", ",", "c2", "]", "=", "pu", ".", "as_series", "(", "[", "c1", ",", "c2", "]", ")", "if", "len", "(", "c1", ")", ">", "len", "(", "c2", ")", ":", "c1", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/polynomial/polynomial.py#L208-L249
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/pot/openvino/tools/pot/graph/builder.py
python
build_graph_for_node
(model, input_name, input_shape, node, remove_bias=False, remove_fake_quantize=False)
return graph
Build the Graph (input - node - output). The Convolution, FullyConnected node types are supported. :param model: source model :param input_name: name of the input node in the generated graph :param input_shape: shape of the input node in the generated graph :param node: node for which graph (input - node - output) will be generated :param remove_bias: remove bias in the generated graph :param remove_fake_quantize: remove fake quantize nodes in the generated graph :return: generated graph.
Build the Graph (input - node - output). The Convolution, FullyConnected node types are supported. :param model: source model :param input_name: name of the input node in the generated graph :param input_shape: shape of the input node in the generated graph :param node: node for which graph (input - node - output) will be generated :param remove_bias: remove bias in the generated graph :param remove_fake_quantize: remove fake quantize nodes in the generated graph :return: generated graph.
[ "Build", "the", "Graph", "(", "input", "-", "node", "-", "output", ")", ".", "The", "Convolution", "FullyConnected", "node", "types", "are", "supported", ".", ":", "param", "model", ":", "source", "model", ":", "param", "input_name", ":", "name", "of", "...
def build_graph_for_node(model, input_name, input_shape, node, remove_bias=False, remove_fake_quantize=False): """ Build the Graph (input - node - output). The Convolution, FullyConnected node types are supported. :param model: source model :param input_name: name of the input node in the generated graph :param input_shape: shape of the input node in the generated graph :param node: node for which graph (input - node - output) will be generated :param remove_bias: remove bias in the generated graph :param remove_fake_quantize: remove fake quantize nodes in the generated graph :return: generated graph. """ input_data_type = get_node_data_type(node, 0) nodes, edges = [], [] nodes.append((input_name, 'Parameter', {'name': input_name, 'shape': input_shape, 'type': 'Parameter', 'data_type': input_data_type})) node_attrs = deepcopy(node.attrs()) if node.has_valid('output') and node.has_valid('get_output_feature_dim'): node_attrs['get_output_feature_dim'] = None nodes.append((node.name, node.type, node_attrs)) edges.append((input_name, node.name, {'out': 0, 'in': 0})) parent_nodes = get_node_inputs(node) if parent_nodes[1].type == 'FakeQuantize' and not remove_fake_quantize: fq = parent_nodes[1] fq_name = make_copy_fake_quantize(nodes, edges, fq) edges.append((fq_name, node.name, {'out': 0, 'in': 1})) else: weights = parent_nodes[1] nodes.append((weights.name, weights.type, {'value': weights.value.copy()})) edges.append((weights.name, node.name, {'out': 0, 'in': 1})) if not remove_bias: if parent_nodes[2].type == 'FakeQuantize' and not remove_fake_quantize: fq = parent_nodes[1] fq_name = make_copy_fake_quantize(nodes, edges, fq) edges.append((fq_name, node.name, {'out': 0, 'in': 2})) else: weights = parent_nodes[2] nodes.append((weights.name, weights.type, {'value': weights.value.copy()})) edges.append((weights.name, node.name, {'out': 0, 'in': 2})) result_name = '{}/out'.format(node.name) nodes.append((result_name, 'Result', {})) edges.append((node.name, result_name, {'out': 0, 'in': 0})) graph = build_graph(*make_copy_graph_attrs(model, input_name, input_shape), nodes, edges) graph.ir_v10 = True # Add the neccessary attribute to the new graph src_node = get_node_by_name(graph, node.name) weights_node = get_node_input(src_node, 1) weights_node = get_node_input(weights_node, 0) \ if weights_node.type == 'FakeQuantize' else weights_node weights_out_dtype = weights_node.out_port(0).get_data_type() src_out_dtype = src_node.out_port(0).get_data_type() if weights_out_dtype != src_out_dtype: weights_node.out_node(0)['Insert_Convert_operation_after'] = True return graph
[ "def", "build_graph_for_node", "(", "model", ",", "input_name", ",", "input_shape", ",", "node", ",", "remove_bias", "=", "False", ",", "remove_fake_quantize", "=", "False", ")", ":", "input_data_type", "=", "get_node_data_type", "(", "node", ",", "0", ")", "n...
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/pot/openvino/tools/pot/graph/builder.py#L97-L155
raspberrypi/tools
13474ee775d0c5ec8a7da4fb0a9fa84187abfc87
arm-bcm2708/arm-rpi-4.9.3-linux-gnueabihf/share/gdb/python/gdb/command/explore.py
python
Explorer.return_to_parent_value
()
A utility function which prints that the current exploration session is returning to the parent value. Useful when exploring values.
A utility function which prints that the current exploration session is returning to the parent value. Useful when exploring values.
[ "A", "utility", "function", "which", "prints", "that", "the", "current", "exploration", "session", "is", "returning", "to", "the", "parent", "value", ".", "Useful", "when", "exploring", "values", "." ]
def return_to_parent_value(): """A utility function which prints that the current exploration session is returning to the parent value. Useful when exploring values. """ print ("\nReturning to parent value...\n")
[ "def", "return_to_parent_value", "(", ")", ":", "print", "(", "\"\\nReturning to parent value...\\n\"", ")" ]
https://github.com/raspberrypi/tools/blob/13474ee775d0c5ec8a7da4fb0a9fa84187abfc87/arm-bcm2708/arm-rpi-4.9.3-linux-gnueabihf/share/gdb/python/gdb/command/explore.py#L159-L163
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/subarrays-with-k-different-integers.py
python
Solution2.subarraysWithKDistinct
(self, A, K)
return result
:type A: List[int] :type K: int :rtype: int
:type A: List[int] :type K: int :rtype: int
[ ":", "type", "A", ":", "List", "[", "int", "]", ":", "type", "K", ":", "int", ":", "rtype", ":", "int" ]
def subarraysWithKDistinct(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ window1, window2 = Window(), Window() result, left1, left2 = 0, 0, 0 for i in A: window1.add(i) while window1.size() > K: window1.remove(A[left1]) left1 += 1 window2.add(i) while window2.size() >= K: window2.remove(A[left2]) left2 += 1 result += left2-left1 return result
[ "def", "subarraysWithKDistinct", "(", "self", ",", "A", ",", "K", ")", ":", "window1", ",", "window2", "=", "Window", "(", ")", ",", "Window", "(", ")", "result", ",", "left1", ",", "left2", "=", "0", ",", "0", ",", "0", "for", "i", "in", "A", ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/subarrays-with-k-different-integers.py#L49-L67
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
PhysicsTools/PythonAnalysis/python/rootplot/utilities.py
python
Hist.__add__
(self, b)
return c
Return the sum of self and b: x.__add__(y) <==> x + y
Return the sum of self and b: x.__add__(y) <==> x + y
[ "Return", "the", "sum", "of", "self", "and", "b", ":", "x", ".", "__add__", "(", "y", ")", "<", "==", ">", "x", "+", "y" ]
def __add__(self, b): """Return the sum of self and b: x.__add__(y) <==> x + y""" c = copy.copy(self) for i in range(len(self)): c.y[i] += b.y[i] c.yerr[0][i] += b.yerr[0][i] c.yerr[1][i] += b.yerr[1][i] c.overflow += b.overflow c.underflow += b.underflow return c
[ "def", "__add__", "(", "self", ",", "b", ")", ":", "c", "=", "copy", ".", "copy", "(", "self", ")", "for", "i", "in", "range", "(", "len", "(", "self", ")", ")", ":", "c", ".", "y", "[", "i", "]", "+=", "b", ".", "y", "[", "i", "]", "c"...
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/PythonAnalysis/python/rootplot/utilities.py#L164-L173
papyrussolution/OpenPapyrus
bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91
Src/OSF/protobuf-3.19.1/python/google/protobuf/descriptor.py
python
Descriptor.EnumValueName
(self, enum, value)
return self.enum_types_by_name[enum].values_by_number[value].name
Returns the string name of an enum value. This is just a small helper method to simplify a common operation. Args: enum: string name of the Enum. value: int, value of the enum. Returns: string name of the enum value. Raises: KeyError if either the Enum doesn't exist or the value is not a valid value for the enum.
Returns the string name of an enum value.
[ "Returns", "the", "string", "name", "of", "an", "enum", "value", "." ]
def EnumValueName(self, enum, value): """Returns the string name of an enum value. This is just a small helper method to simplify a common operation. Args: enum: string name of the Enum. value: int, value of the enum. Returns: string name of the enum value. Raises: KeyError if either the Enum doesn't exist or the value is not a valid value for the enum. """ return self.enum_types_by_name[enum].values_by_number[value].name
[ "def", "EnumValueName", "(", "self", ",", "enum", ",", "value", ")", ":", "return", "self", ".", "enum_types_by_name", "[", "enum", "]", ".", "values_by_number", "[", "value", "]", ".", "name" ]
https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/descriptor.py#L381-L397
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros/rosmake/src/rosmake/parallel_build.py
python
BuildQueue.is_completed
(self)
return len(self.built)+ len(self.failed) == self._total_pkgs
Return if the build queue has been completed
Return if the build queue has been completed
[ "Return", "if", "the", "build", "queue", "has", "been", "completed" ]
def is_completed(self): """Return if the build queue has been completed """ return len(self.built)+ len(self.failed) == self._total_pkgs
[ "def", "is_completed", "(", "self", ")", ":", "return", "len", "(", "self", ".", "built", ")", "+", "len", "(", "self", ".", "failed", ")", "==", "self", ".", "_total_pkgs" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros/rosmake/src/rosmake/parallel_build.py#L213-L215
google/ml-metadata
b60196492d2ea2bcd8e4ddff0f3757e5fd710e4d
ml_metadata/errors.py
python
AbortedError.__init__
(self, message)
Creates an `AbortedError`.
Creates an `AbortedError`.
[ "Creates", "an", "AbortedError", "." ]
def __init__(self, message): """Creates an `AbortedError`.""" super(AbortedError, self).__init__(message, ABORTED)
[ "def", "__init__", "(", "self", ",", "message", ")", ":", "super", "(", "AbortedError", ",", "self", ")", ".", "__init__", "(", "message", ",", "ABORTED", ")" ]
https://github.com/google/ml-metadata/blob/b60196492d2ea2bcd8e4ddff0f3757e5fd710e4d/ml_metadata/errors.py#L130-L132
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py
python
screen.lf
(self)
This moves the cursor down with scrolling.
This moves the cursor down with scrolling.
[ "This", "moves", "the", "cursor", "down", "with", "scrolling", "." ]
def lf (self): '''This moves the cursor down with scrolling. ''' old_r = self.cur_r self.cursor_down() if old_r == self.cur_r: self.scroll_up () self.erase_line()
[ "def", "lf", "(", "self", ")", ":", "old_r", "=", "self", ".", "cur_r", "self", ".", "cursor_down", "(", ")", "if", "old_r", "==", "self", ".", "cur_r", ":", "self", ".", "scroll_up", "(", ")", "self", ".", "erase_line", "(", ")" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/lldb/third_party/Python/module/pexpect-4.6/pexpect/screen.py#L176-L184
freeorion/freeorion
c266a40eccd3a99a17de8fe57c36ef6ba3771665
default/python/AI/AIstate.py
python
AIstate.__refresh
(self)
Turn start AIstate cleanup/refresh.
Turn start AIstate cleanup/refresh.
[ "Turn", "start", "AIstate", "cleanup", "/", "refresh", "." ]
def __refresh(self): """Turn start AIstate cleanup/refresh.""" fleetsLostBySystem.clear() invasionTargets[:] = []
[ "def", "__refresh", "(", "self", ")", ":", "fleetsLostBySystem", ".", "clear", "(", ")", "invasionTargets", "[", ":", "]", "=", "[", "]" ]
https://github.com/freeorion/freeorion/blob/c266a40eccd3a99a17de8fe57c36ef6ba3771665/default/python/AI/AIstate.py#L230-L233
devpack/android-python27
d42dd67565e104cf7b0b50eb473f615db3e69901
python-build-with-qt/PyQt-x11-gpl-4.8/pyuic/uic/icon_cache.py
python
_IconSet._file_name
(fname, base_dir)
return fname
Convert a relative filename if we have a base directory.
Convert a relative filename if we have a base directory.
[ "Convert", "a", "relative", "filename", "if", "we", "have", "a", "base", "directory", "." ]
def _file_name(fname, base_dir): """ Convert a relative filename if we have a base directory. """ fname = fname.replace("\\", "\\\\") if base_dir != '' and fname[0] != ':' and not os.path.isabs(fname): fname = os.path.join(base_dir, fname) return fname
[ "def", "_file_name", "(", "fname", ",", "base_dir", ")", ":", "fname", "=", "fname", ".", "replace", "(", "\"\\\\\"", ",", "\"\\\\\\\\\"", ")", "if", "base_dir", "!=", "''", "and", "fname", "[", "0", "]", "!=", "':'", "and", "not", "os", ".", "path",...
https://github.com/devpack/android-python27/blob/d42dd67565e104cf7b0b50eb473f615db3e69901/python-build-with-qt/PyQt-x11-gpl-4.8/pyuic/uic/icon_cache.py#L79-L87
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DirectILLIntegrateVanadium.py
python
DirectILLIntegrateVanadium.__init__
(self)
Initialize an instance of the algorithm.
Initialize an instance of the algorithm.
[ "Initialize", "an", "instance", "of", "the", "algorithm", "." ]
def __init__(self): """Initialize an instance of the algorithm.""" DataProcessorAlgorithm.__init__(self)
[ "def", "__init__", "(", "self", ")", ":", "DataProcessorAlgorithm", ".", "__init__", "(", "self", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DirectILLIntegrateVanadium.py#L20-L22
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/libmintscoordentry.py
python
CoordEntry.set_basisset
(self, name, role='BASIS')
Set the basis for this atom * @param type Keyword from input file, basis, ri_basis, etc. * @param name Value from input file
Set the basis for this atom * @param type Keyword from input file, basis, ri_basis, etc. * @param name Value from input file
[ "Set", "the", "basis", "for", "this", "atom", "*", "@param", "type", "Keyword", "from", "input", "file", "basis", "ri_basis", "etc", ".", "*", "@param", "name", "Value", "from", "input", "file" ]
def set_basisset(self, name, role='BASIS'): """Set the basis for this atom * @param type Keyword from input file, basis, ri_basis, etc. * @param name Value from input file """ self.PYbasissets[role] = name
[ "def", "set_basisset", "(", "self", ",", "name", ",", "role", "=", "'BASIS'", ")", ":", "self", ".", "PYbasissets", "[", "role", "]", "=", "name" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintscoordentry.py#L318-L324
indutny/candor
48e7260618f5091c80a3416828e2808cad3ea22e
tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetExecutablePath
(self)
Returns the directory name of the bundle represented by this target. E.g. Chromium.app/Contents/MacOS/Chromium.
Returns the directory name of the bundle represented by this target. E.g. Chromium.app/Contents/MacOS/Chromium.
[ "Returns", "the", "directory", "name", "of", "the", "bundle", "represented", "by", "this", "target", ".", "E", ".", "g", ".", "Chromium", ".", "app", "/", "Contents", "/", "MacOS", "/", "Chromium", "." ]
def GetExecutablePath(self): """Returns the directory name of the bundle represented by this target. E.g. Chromium.app/Contents/MacOS/Chromium.""" if self._IsBundle(): return self._GetBundleBinaryPath() else: return self._GetStandaloneBinaryPath()
[ "def", "GetExecutablePath", "(", "self", ")", ":", "if", "self", ".", "_IsBundle", "(", ")", ":", "return", "self", ".", "_GetBundleBinaryPath", "(", ")", "else", ":", "return", "self", ".", "_GetStandaloneBinaryPath", "(", ")" ]
https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/xcode_emulation.py#L214-L220
xbmc/xbmc
091211a754589fc40a2a1f239b0ce9f4ee138268
tools/EventClients/lib/python/xbmcclient.py
python
PacketMOUSE.__init__
(self, x, y)
Arguments: x -- horizontal position ranging from 0 to 65535 y -- vertical position ranging from 0 to 65535 The range will be mapped to the screen width and height in XBMC
Arguments: x -- horizontal position ranging from 0 to 65535 y -- vertical position ranging from 0 to 65535
[ "Arguments", ":", "x", "--", "horizontal", "position", "ranging", "from", "0", "to", "65535", "y", "--", "vertical", "position", "ranging", "from", "0", "to", "65535" ]
def __init__(self, x, y): """ Arguments: x -- horizontal position ranging from 0 to 65535 y -- vertical position ranging from 0 to 65535 The range will be mapped to the screen width and height in XBMC """ Packet.__init__(self) self.packettype = PT_MOUSE self.flags = MS_ABSOLUTE self.append_payload( chr (self.flags) ) self.append_payload( format_uint16(x) ) self.append_payload( format_uint16(y) )
[ "def", "__init__", "(", "self", ",", "x", ",", "y", ")", ":", "Packet", ".", "__init__", "(", "self", ")", "self", ".", "packettype", "=", "PT_MOUSE", "self", ".", "flags", "=", "MS_ABSOLUTE", "self", ".", "append_payload", "(", "chr", "(", "self", "...
https://github.com/xbmc/xbmc/blob/091211a754589fc40a2a1f239b0ce9f4ee138268/tools/EventClients/lib/python/xbmcclient.py#L392-L405
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
interpreter/llvm/src/tools/clang/tools/scan-build-py/libscanbuild/shell.py
python
decode
(string)
return [unescape(arg) for arg in shlex.split(string)]
Takes a command string and returns as a list.
Takes a command string and returns as a list.
[ "Takes", "a", "command", "string", "and", "returns", "as", "a", "list", "." ]
def decode(string): """ Takes a command string and returns as a list. """ def unescape(arg): """ Gets rid of the escaping characters. """ if len(arg) >= 2 and arg[0] == arg[-1] and arg[0] == '"': arg = arg[1:-1] return re.sub(r'\\(["\\])', r'\1', arg) return re.sub(r'\\([\\ $%&\(\)\[\]\{\}\*|<>@?!])', r'\1', arg) return [unescape(arg) for arg in shlex.split(string)]
[ "def", "decode", "(", "string", ")", ":", "def", "unescape", "(", "arg", ")", ":", "\"\"\" Gets rid of the escaping characters. \"\"\"", "if", "len", "(", "arg", ")", ">=", "2", "and", "arg", "[", "0", "]", "==", "arg", "[", "-", "1", "]", "and", "arg"...
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/interpreter/llvm/src/tools/clang/tools/scan-build-py/libscanbuild/shell.py#L54-L65
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py
python
PtyProcess.setwinsize
(self, rows, cols)
return _setwinsize(self.fd, rows, cols)
Set the terminal window size of the child tty. This will cause a SIGWINCH signal to be sent to the child. This does not change the physical window size. It changes the size reported to TTY-aware applications like vi or curses -- applications that respond to the SIGWINCH signal.
Set the terminal window size of the child tty.
[ "Set", "the", "terminal", "window", "size", "of", "the", "child", "tty", "." ]
def setwinsize(self, rows, cols): """Set the terminal window size of the child tty. This will cause a SIGWINCH signal to be sent to the child. This does not change the physical window size. It changes the size reported to TTY-aware applications like vi or curses -- applications that respond to the SIGWINCH signal. """ return _setwinsize(self.fd, rows, cols)
[ "def", "setwinsize", "(", "self", ",", "rows", ",", "cols", ")", ":", "return", "_setwinsize", "(", "self", ".", "fd", ",", "rows", ",", "cols", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/third_party/Python/module/ptyprocess-0.6.0/ptyprocess/ptyprocess.py#L782-L790
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Tool/javac.py
python
Java
(env, target, source, *args, **kw)
return result
A pseudo-Builder wrapper around the separate JavaClass{File,Dir} Builders.
A pseudo-Builder wrapper around the separate JavaClass{File,Dir} Builders.
[ "A", "pseudo", "-", "Builder", "wrapper", "around", "the", "separate", "JavaClass", "{", "File", "Dir", "}", "Builders", "." ]
def Java(env, target, source, *args, **kw): """ A pseudo-Builder wrapper around the separate JavaClass{File,Dir} Builders. """ if not SCons.Util.is_List(target): target = [target] if not SCons.Util.is_List(source): source = [source] # Pad the target list with repetitions of the last element in the # list so we have a target for every source element. target = target + ([target[-1]] * (len(source) - len(target))) java_suffix = env.subst('$JAVASUFFIX') result = [] for t, s in zip(target, source): if isinstance(s, SCons.Node.FS.Base): if isinstance(s, SCons.Node.FS.File): b = env.JavaClassFile else: b = env.JavaClassDir else: if os.path.isfile(s): b = env.JavaClassFile elif os.path.isdir(s): b = env.JavaClassDir elif s[-len(java_suffix):] == java_suffix: b = env.JavaClassFile else: b = env.JavaClassDir result.extend(b(t, s, *args, **kw)) return result
[ "def", "Java", "(", "env", ",", "target", ",", "source", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "not", "SCons", ".", "Util", ".", "is_List", "(", "target", ")", ":", "target", "=", "[", "target", "]", "if", "not", "SCons", ".", ...
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/javac.py#L164-L198
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/lib/io/tf_record.py
python
TFRecordWriter.__enter__
(self)
return self
Enter a `with` block.
Enter a `with` block.
[ "Enter", "a", "with", "block", "." ]
def __enter__(self): """Enter a `with` block.""" return self
[ "def", "__enter__", "(", "self", ")", ":", "return", "self" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/lib/io/tf_record.py#L98-L100
IntelligentSoftwareSystems/Galois
07514b288f708082430304f3d8b934fb3e2a821f
scripts/experimental/abelian_log_parser_multipleRuns2.py
python
match_timers
(fileName, benchmark, forHost, numRuns, numThreads, time_unit, total_hosts, partition, run_identifier)
return mean_time,rep_factor,mean_do_all,total_sync_bytes,sum_broadcast_bytes,sum_reduce_bytes,num_iter,total_work_item,hg_init_time,total_time,max_do_all,mean_sync_time,max_sync,mean_broadcast_time,max_broadcast_time,mean_reduce_time,max_reduce_time,max_comm_setup_time,max_graph_init_time
##################### BROADCAST SEND ############################## #Finding mean,max,sd BROADCAST time over all hosts max_broadcast_send = 0 sum_broadcast_send = 0 for i in range(0,int(num_iter)): broadcast_send_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sBROADCAST_SEND_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') broadcast_send_all_hosts = re.findall(broadcast_send_regex, log_data) num_arr = numpy.array(map(int,broadcast_send_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_broadcast_send_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_broadcast_send += max_broadcast_send_itr sum_broadcast_send += numpy.sum(num_arr, axis=0) mean_broadcast_send_time = float(sum_broadcast_send)/float(total_hosts) print "NEW broadcast_send_TIME ", mean_broadcast_send_time ##################### BROADCAST EXTRACT ############################## #Finding mean,max,sd BROADCAST time over all hosts max_broadcast_extract = 0 sum_broadcast_extract = 0 for i in range(0,int(num_iter)): broadcast_extract_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sBROADCAST_EXTRACT_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') broadcast_extract_all_hosts = re.findall(broadcast_extract_regex, log_data) num_arr = numpy.array(map(int,broadcast_extract_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_broadcast_extract_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_broadcast_extract += max_broadcast_extract_itr sum_broadcast_extract += numpy.sum(num_arr, axis=0) mean_broadcast_extract_time = float(sum_broadcast_extract)/float(total_hosts) print "NEW broadcast_extract_TIME ", mean_broadcast_extract_time ##################### BROADCAST recv ############################## #Finding mean,max,sd BROADCAST time over all hosts max_broadcast_recv = 0 sum_broadcast_recv = 0 for i in range(0,int(num_iter)): broadcast_recv_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sBROADCAST_RECV_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') broadcast_recv_all_hosts = re.findall(broadcast_recv_regex, log_data) num_arr = numpy.array(map(int,broadcast_recv_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_broadcast_recv_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_broadcast_recv += max_broadcast_recv_itr sum_broadcast_recv += numpy.sum(num_arr, axis=0) mean_broadcast_recv_time = float(sum_broadcast_recv)/float(total_hosts) print "NEW broadcast_recv_TIME ", mean_broadcast_recv_time ##################### BROADCAST SET ############################## #Finding mean,max,sd BROADCAST time over all hosts max_broadcast_set = 0 sum_broadcast_set = 0 for i in range(0,int(num_iter)): broadcast_set_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sBROADCAST_SET_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') broadcast_set_all_hosts = re.findall(broadcast_set_regex, log_data) num_arr = numpy.array(map(int,broadcast_set_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_broadcast_set_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_broadcast_set += max_broadcast_set_itr sum_broadcast_set += numpy.sum(num_arr, axis=0) print "max_do_all " , max_broadcast_set print "sum_do_all " , sum_broadcast_set mean_broadcast_set_time = float(sum_broadcast_set)/float(total_hosts) print "NEW broadcast_set_TIME ", mean_broadcast_set_time
##################### BROADCAST SEND ############################## #Finding mean,max,sd BROADCAST time over all hosts max_broadcast_send = 0 sum_broadcast_send = 0 for i in range(0,int(num_iter)): broadcast_send_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sBROADCAST_SEND_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') broadcast_send_all_hosts = re.findall(broadcast_send_regex, log_data) num_arr = numpy.array(map(int,broadcast_send_all_hosts))
[ "#####################", "BROADCAST", "SEND", "##############################", "#Finding", "mean", "max", "sd", "BROADCAST", "time", "over", "all", "hosts", "max_broadcast_send", "=", "0", "sum_broadcast_send", "=", "0", "for", "i", "in", "range", "(", "0", "int", ...
def match_timers(fileName, benchmark, forHost, numRuns, numThreads, time_unit, total_hosts, partition, run_identifier): mean_time = 0.0; recvNum_total = 0 recvBytes_total = 0 sendNum_total = 0 sendBytes_total = 0 sync_pull_avg_time_total = 0.0; extract_avg_time_total = 0.0; set_avg_time_total = 0.0; sync_push_avg_time_total = 0.0; graph_init_time = 0 hg_init_time = 0 total_time = 0 if(benchmark == "cc"): benchmark = "ConnectedComp" if(benchmark == "pagerank"): benchmark = "PageRank" if (time_unit == 'seconds'): divisor = 1000 else: divisor = 1 log_data = open(fileName).read() timer_regex = re.compile(re.escape(run_identifier) + r',\(NULL\),0\s,\sTIMER_0,\d*,0,(\d*)') timers = re.findall(timer_regex, log_data) #print timers time = [] total_mean_time=0.0 print timers for i in range(int(total_hosts)): time.append(0) for timer in timers: total_mean_time += float(timer) #print "TIMER : ", timer print "TOTAL MEAN TIME " , total_mean_time total_mean_time = total_mean_time/int(total_hosts) total_mean_time /= divisor mean_time = total_mean_time = round(total_mean_time, 3) print "Total Mean time: ", total_mean_time rep_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sREPLICATION_FACTOR_0_0,(\d*),\d*,(.*)') rep_search = rep_regex.search(log_data) rep_factor = 0; if rep_search is not None: rep_factor = rep_search.group(2) rep_factor = round(float(rep_factor), 3) print ("Replication factor : ", rep_factor) num_iter_regex = re.compile((run_identifier) +r',\(NULL\),0\s,\sNUM_ITERATIONS_0' + r',\d*,\d*,(\d*)') num_iter_search = num_iter_regex.search(log_data) if num_iter_regex is not None: if num_iter_search is None: num_iter = -1 else: num_iter = num_iter_search.group(1) print "NUM_ITER : ", num_iter #Finding mean,max,sd compute time over all hosts max_do_all = 0 sum_do_all = 0 sum_std_do_all = 0; for i in range(0,int(num_iter)): do_all_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\s.*DO_ALL_IMPL_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') do_all_all_hosts = re.findall(do_all_regex, log_data) num_arr = numpy.array(map(int,do_all_all_hosts)) if len(num_arr) != 0: sum_std_do_all += numpy.std(num_arr, axis=0) #print (" COMPUTE NUM_ARR", num_arr) max_compute = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_do_all += max_compute sum_do_all += numpy.sum(num_arr, axis=0) print "max_do_all " , max_do_all print "sum_do_all " , sum_do_all mean_do_all = float(sum_do_all)/float(total_hosts) mean_std_do_all = float(sum_std_do_all)/float(num_iter) print "XXXXXXXXXXXXXXXXx STD DO ALL : " , mean_std_do_all print "mean_do_all", mean_do_all ##################### SYNC ############################## ############## SYNC = BROADCAST + REDUCE ################ #Finding mean,max,sd sync time over all hosts max_sync = 0 sum_sync = 0 for i in range(0,int(num_iter)): sync_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sSYNC_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') sync_all_hosts = re.findall(sync_regex, log_data) num_arr = numpy.array(map(int,sync_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_sync_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_sync += max_sync_itr sum_sync += numpy.sum(num_arr, axis=0) mean_sync_time = float(sum_sync)/float(total_hosts) print "NEW SYNC_TIME ", mean_sync_time ##################### BROADCAST ############################## #### BROADCAST = BROADCAST_SEND + BROADCAST_EXTRACT + BROADCAST_RECV + BROADCAST_SET #Finding mean,max,sd BROADCAST time over all hosts max_broadcast_time = 0 sum_broadcast = 0 for i in range(0,int(num_iter)): broadcast_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sBROADCAST_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') broadcast_all_hosts = re.findall(broadcast_regex, log_data) num_arr = numpy.array(map(int,broadcast_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_broadcast_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_broadcast_time += max_broadcast_itr sum_broadcast += numpy.sum(num_arr, axis=0) mean_broadcast_time = float(sum_broadcast)/float(total_hosts) print "NEW BROADCAST_TIME ", mean_broadcast_time max_broadcast_set = 0 max_broadcast_recv = 0 max_broadcast_extract = 0 max_broadcast_send = 0 mean_broadcast_set_time = 0 mean_broadcast_recv_time = 0 mean_broadcast_extract_time = 0 mean_broadcast_send_time = 0 ''' ##################### BROADCAST SEND ############################## #Finding mean,max,sd BROADCAST time over all hosts max_broadcast_send = 0 sum_broadcast_send = 0 for i in range(0,int(num_iter)): broadcast_send_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sBROADCAST_SEND_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') broadcast_send_all_hosts = re.findall(broadcast_send_regex, log_data) num_arr = numpy.array(map(int,broadcast_send_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_broadcast_send_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_broadcast_send += max_broadcast_send_itr sum_broadcast_send += numpy.sum(num_arr, axis=0) mean_broadcast_send_time = float(sum_broadcast_send)/float(total_hosts) print "NEW broadcast_send_TIME ", mean_broadcast_send_time ##################### BROADCAST EXTRACT ############################## #Finding mean,max,sd BROADCAST time over all hosts max_broadcast_extract = 0 sum_broadcast_extract = 0 for i in range(0,int(num_iter)): broadcast_extract_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sBROADCAST_EXTRACT_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') broadcast_extract_all_hosts = re.findall(broadcast_extract_regex, log_data) num_arr = numpy.array(map(int,broadcast_extract_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_broadcast_extract_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_broadcast_extract += max_broadcast_extract_itr sum_broadcast_extract += numpy.sum(num_arr, axis=0) mean_broadcast_extract_time = float(sum_broadcast_extract)/float(total_hosts) print "NEW broadcast_extract_TIME ", mean_broadcast_extract_time ##################### BROADCAST recv ############################## #Finding mean,max,sd BROADCAST time over all hosts max_broadcast_recv = 0 sum_broadcast_recv = 0 for i in range(0,int(num_iter)): broadcast_recv_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sBROADCAST_RECV_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') broadcast_recv_all_hosts = re.findall(broadcast_recv_regex, log_data) num_arr = numpy.array(map(int,broadcast_recv_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_broadcast_recv_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_broadcast_recv += max_broadcast_recv_itr sum_broadcast_recv += numpy.sum(num_arr, axis=0) mean_broadcast_recv_time = float(sum_broadcast_recv)/float(total_hosts) print "NEW broadcast_recv_TIME ", mean_broadcast_recv_time ##################### BROADCAST SET ############################## #Finding mean,max,sd BROADCAST time over all hosts max_broadcast_set = 0 sum_broadcast_set = 0 for i in range(0,int(num_iter)): broadcast_set_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sBROADCAST_SET_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') broadcast_set_all_hosts = re.findall(broadcast_set_regex, log_data) num_arr = numpy.array(map(int,broadcast_set_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_broadcast_set_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_broadcast_set += max_broadcast_set_itr sum_broadcast_set += numpy.sum(num_arr, axis=0) print "max_do_all " , max_broadcast_set print "sum_do_all " , sum_broadcast_set mean_broadcast_set_time = float(sum_broadcast_set)/float(total_hosts) print "NEW broadcast_set_TIME ", mean_broadcast_set_time ''' ##################### REDUCE ############################## #Finding mean,max,sd REDUCE time over all hosts max_reduce_time = 0 sum_reduce = 0 for i in range(0,int(num_iter)): reduce_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sREDUCE_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') reduce_all_hosts = re.findall(reduce_regex, log_data) num_arr = numpy.array(map(int,reduce_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_reduce_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_reduce_time += max_reduce_itr sum_reduce += numpy.sum(num_arr, axis=0) mean_reduce_time = float(sum_reduce)/float(total_hosts) print "NEW REDUCE_TIME ", mean_reduce_time max_reduce_set = 0 max_reduce_recv = 0 max_reduce_extract = 0 max_reduce_send = 0 mean_reduce_set_time = 0 mean_reduce_recv_time = 0 mean_reduce_extract_time = 0 mean_reduce_send_time = 0 ''' ##################### REDUCE SEND ############################## #Finding mean,max,sd reduce time over all hosts max_reduce_send = 0 sum_reduce_send = 0 for i in range(0,int(num_iter)): reduce_send_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sREDUCE_SEND_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') reduce_send_all_hosts = re.findall(reduce_send_regex, log_data) num_arr = numpy.array(map(int,reduce_send_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_reduce_send_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_reduce_send += max_reduce_send_itr sum_reduce_send += numpy.sum(num_arr, axis=0) mean_reduce_send_time = float(sum_reduce_send)/float(total_hosts) print "NEW reduce_send_TIME ", mean_reduce_send_time ##################### REDUCE EXTRACT ############################## #Finding mean,max,sd reduce time over all hosts max_reduce_extract = 0 sum_reduce_extract = 0 for i in range(0,int(num_iter)): reduce_extract_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sREDUCE_EXTRACT_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') reduce_extract_all_hosts = re.findall(reduce_extract_regex, log_data) num_arr = numpy.array(map(int,reduce_extract_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_reduce_extract_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_reduce_extract += max_reduce_extract_itr sum_reduce_extract += numpy.sum(num_arr, axis=0) mean_reduce_extract_time = float(sum_reduce_extract)/float(total_hosts) print "NEW reduce_extract_TIME ", mean_reduce_extract_time ##################### REDUCE recv ############################## #Finding mean,max,sd reduce time over all hosts max_reduce_recv = 0 sum_reduce_recv = 0 for i in range(0,int(num_iter)): reduce_recv_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sREDUCE_RECV_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') reduce_recv_all_hosts = re.findall(reduce_recv_regex, log_data) num_arr = numpy.array(map(int,reduce_recv_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_reduce_recv_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_reduce_recv += max_reduce_recv_itr sum_reduce_recv += numpy.sum(num_arr, axis=0) mean_reduce_recv_time = float(sum_reduce_recv)/float(total_hosts) print "NEW reduce_recv_TIME ", mean_reduce_recv_time ##################### REDUCE SET ############################## #Finding mean,max,sd reduce time over all hosts max_reduce_set = 0 sum_reduce_set = 0 for i in range(0,int(num_iter)): reduce_set_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sREDUCE_SET_(?i)' + re.escape(benchmark) + r'_0_'+ re.escape(str(i)) + r',.*' + r',\d*,(\d*)') reduce_set_all_hosts = re.findall(reduce_set_regex, log_data) num_arr = numpy.array(map(int,reduce_set_all_hosts)) if len(num_arr) != 0: #print (" SYNC NUM_ARR", num_arr) max_reduce_set_itr = numpy.max(num_arr, axis=0) #print ("MAX : ", max_compute) max_reduce_set += max_reduce_set_itr sum_reduce_set += numpy.sum(num_arr, axis=0) mean_reduce_set_time = float(sum_reduce_set)/float(total_hosts) print "NEW reduce_set_TIME ", mean_reduce_set_time ''' # ######################## BROADCAST SENT BYTES ################################ #Finding total communication volume in bytes #2cc54509-cb49-43f9-b1a5-be8f4a4eaf1f,(NULL),0 , BROADCAST_SEND_BYTES_BFS_0_1,0,0,41851160 sum_broadcast_bytes = 0 max_broadcast_bytes = 0 min_broadcast_bytes = 0 broadcast_bytes_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sBROADCAST_SEND_BYTES_(?i)' + re.escape(benchmark) + r'_0_' +r'\d*' +r',.*' + r',\d*,(\d*)') broadcast_bytes_all_hosts = re.findall(broadcast_bytes_regex, log_data) num_arr = numpy.array(map(int,broadcast_bytes_all_hosts)) if(num_arr.size > 0): sum_broadcast_bytes += numpy.sum(num_arr, axis=0) max_broadcast_bytes += numpy.max(num_arr, axis=0) min_broadcast_bytes += numpy.min(num_arr, axis=0) print "BROADCAST SEND BYTES : ", sum_broadcast_bytes # ######################## REDUCE SENT BYTES ################################ #Finding total communication volume in bytes #2cc54509-cb49-43f9-b1a5-be8f4a4eaf1f,(NULL),0 , BROADCAST_SEND_BYTES_BFS_0_1,0,0,41851160 sum_reduce_bytes = 0 max_reduce_bytes = 0 min_reduce_bytes = 0 reduce_bytes_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sREDUCE_SEND_BYTES_(?i)' + re.escape(benchmark) + r'_0_' +r'\d*' +r',.*' + r',\d*,(\d*)') reduce_bytes_all_hosts = re.findall(reduce_bytes_regex, log_data) num_arr = numpy.array(map(int,reduce_bytes_all_hosts)) if(num_arr.size > 0): sum_reduce_bytes += numpy.sum(num_arr, axis=0) max_reduce_bytes += numpy.max(num_arr, axis=0) min_reduce_bytes += numpy.min(num_arr, axis=0) print "REDUCE SEND BYTES : ", sum_reduce_bytes total_sync_bytes = sum_reduce_bytes + sum_broadcast_bytes #75ae6860-be9f-4498-9315-1478c78551f6,(NULL),0 , NUM_WORK_ITEMS_0_0,0,0,262144 #Total work items, averaged across hosts work_items_regex = re.compile((run_identifier) + r',\(NULL\),0\s,\sNUM_WORK_ITEMS_0_\d*,\d*,\d*,(\d*)') work_items = re.findall(work_items_regex, log_data) print work_items num_arr = numpy.array(map(int,work_items)) total_work_item = numpy.sum(num_arr, axis=0) print total_work_item timer_graph_init_regex = re.compile((run_identifier) +r',\(NULL\),0\s,\sTIMER_GRAPH_INIT' + r',\d*,\d*,(\d*)') timer_graph_init_all_hosts = re.findall(timer_graph_init_regex, log_data) num_arr = numpy.array(map(int,timer_graph_init_all_hosts)) if(num_arr.size > 0): #avg_graph_init_time = float(numpy.sum(num_arr, axis=0))/float(total_hosts) max_graph_init_time = numpy.max(num_arr, axis=0) #avg_graph_init_time = round((avg_graph_init_time / divisor),3) print "max_graph_init time : ", max_graph_init_time ## Get Graph_init, HG_init, total #81a5b117-8054-46af-9a23-1f28e5ed1bba,(NULL),0 , TIMER_GRAPH_INIT,0,0,306 #timer_graph_init_regex = re.compile((run_identifier) +r',\(NULL\),0\s,\sTIMER_GRAPH_INIT,\d*,\d*,(\d*)') timer_hg_init_regex = re.compile((run_identifier) +r',\(NULL\),0\s,\sTIMER_HG_INIT' + r',\d*,\d*,(\d*)') timer_hg_init_all_hosts = re.findall(timer_hg_init_regex, log_data) num_arr = numpy.array(map(int,timer_hg_init_all_hosts)) #avg_hg_init_time = float(numpy.sum(num_arr, axis=0))/float(total_hosts) if(num_arr.size > 0): max_hg_init_time = numpy.max(num_arr, axis=0) #avg_hg_init_time = round((avg_hg_init_time / divisor),3) hg_init_time = max_hg_init_time timer_comm_setup_regex = re.compile((run_identifier) +r',\(NULL\),0\s,\sCOMMUNICATION_SETUP_TIME' + r',\d*,\d*,(\d*)') timer_comm_setup_all_hosts = re.findall(timer_comm_setup_regex, log_data) max_comm_setup_time = 0 num_arr = numpy.array(map(int,timer_comm_setup_all_hosts)) if(num_arr.size > 0): #avg_comm_setup_time = float(numpy.sum(num_arr, axis=0))/float(total_hosts) max_comm_setup_time = numpy.max(num_arr, axis=0) #max_comm_setup_time = round((avg_comm_setup_time / divisor),3) print "max_comm_setup time : ", max_comm_setup_time timer_total_regex = re.compile((run_identifier) +r',\(NULL\),0\s,\sTIMER_TOTAL' + r',\d*,\d*,(\d*)') #timer_graph_init = timer_graph_init_regex.search(log_data) #timer_hg_init = timer_hg_init_regex.search(log_data) timer_total = timer_total_regex.search(log_data) if timer_total is not None: total_time = float(timer_total.group(1)) total_time /= divisor total_time = round(total_time, 3) #return mean_time,rep_factor,mean_do_all,total_sync_bytes,sum_broadcast_bytes,sum_reduce_bytes,num_iter,total_work_item,hg_init_time,total_time,max_do_all,mean_sync_time,mean_broadcast_time,mean_broadcast_send_time,mean_broadcast_extract_time,mean_broadcast_recv_time,mean_broadcast_set_time,mean_reduce_time,mean_reduce_send_time,mean_reduce_extract_time,mean_reduce_recv_time,mean_reduce_set_time,max_comm_setup_time,max_graph_init_time return mean_time,rep_factor,mean_do_all,total_sync_bytes,sum_broadcast_bytes,sum_reduce_bytes,num_iter,total_work_item,hg_init_time,total_time,max_do_all,mean_sync_time,max_sync,mean_broadcast_time,max_broadcast_time,mean_reduce_time,max_reduce_time,max_comm_setup_time,max_graph_init_time
[ "def", "match_timers", "(", "fileName", ",", "benchmark", ",", "forHost", ",", "numRuns", ",", "numThreads", ",", "time_unit", ",", "total_hosts", ",", "partition", ",", "run_identifier", ")", ":", "mean_time", "=", "0.0", "recvNum_total", "=", "0", "recvBytes...
https://github.com/IntelligentSoftwareSystems/Galois/blob/07514b288f708082430304f3d8b934fb3e2a821f/scripts/experimental/abelian_log_parser_multipleRuns2.py#L18-L469
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PGMultiButton.GetButtonId
(*args, **kwargs)
return _propgrid.PGMultiButton_GetButtonId(*args, **kwargs)
GetButtonId(self, int i) -> int
GetButtonId(self, int i) -> int
[ "GetButtonId", "(", "self", "int", "i", ")", "-", ">", "int" ]
def GetButtonId(*args, **kwargs): """GetButtonId(self, int i) -> int""" return _propgrid.PGMultiButton_GetButtonId(*args, **kwargs)
[ "def", "GetButtonId", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGMultiButton_GetButtonId", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L2830-L2832
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/optim/thor.py
python
ThorAscend._get_fc_matrix
(self, weight_shape)
for Ascend, get fc matrix_a and matrix_g
for Ascend, get fc matrix_a and matrix_g
[ "for", "Ascend", "get", "fc", "matrix_a", "and", "matrix_g" ]
def _get_fc_matrix(self, weight_shape): """for Ascend, get fc matrix_a and matrix_g""" out_channels = weight_shape[0] in_channels = weight_shape[1] if self.conv_layer_count > 0: if out_channels == 1001: fc_matrix_a = Parameter(Tensor(np.zeros([128, 128, 16, 16]).astype(np.float16)), name='matrix_a_inv_' + str(self.thor_layer_count), requires_grad=False) fc_matrix_g = Parameter(Tensor(np.zeros([63, 63, 16, 16]).astype(np.float16)), name="matrix_g_inv_" + str(self.thor_layer_count), requires_grad=False) else: fc_matrix_a = Parameter(Tensor(np.eye(in_channels).astype(np.float16)), name='matrix_a_inv_' + str(self.thor_layer_count), requires_grad=False) fc_matrix_g = Parameter(Tensor(np.eye(out_channels).astype(np.float16)), name="matrix_g_inv_" + str(self.thor_layer_count), requires_grad=False) self.matrix_a = self.matrix_a + (fc_matrix_a,) self.matrix_g = self.matrix_g + (fc_matrix_g,)
[ "def", "_get_fc_matrix", "(", "self", ",", "weight_shape", ")", ":", "out_channels", "=", "weight_shape", "[", "0", "]", "in_channels", "=", "weight_shape", "[", "1", "]", "if", "self", ".", "conv_layer_count", ">", "0", ":", "if", "out_channels", "==", "1...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/optim/thor.py#L809-L829
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/computation/ops.py
python
Op.__unicode__
(self)
return pprint_thing(' {0} '.format(self.op).join(parened))
Print a generic n-ary operator and its operands using infix notation
Print a generic n-ary operator and its operands using infix notation
[ "Print", "a", "generic", "n", "-", "ary", "operator", "and", "its", "operands", "using", "infix", "notation" ]
def __unicode__(self): """Print a generic n-ary operator and its operands using infix notation""" # recurse over the operands parened = ('({0})'.format(pprint_thing(opr)) for opr in self.operands) return pprint_thing(' {0} '.format(self.op).join(parened))
[ "def", "__unicode__", "(", "self", ")", ":", "# recurse over the operands", "parened", "=", "(", "'({0})'", ".", "format", "(", "pprint_thing", "(", "opr", ")", ")", "for", "opr", "in", "self", ".", "operands", ")", "return", "pprint_thing", "(", "' {0} '", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/computation/ops.py#L197-L203
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
TopLevelWindow.IsFullScreen
(*args, **kwargs)
return _windows_.TopLevelWindow_IsFullScreen(*args, **kwargs)
IsFullScreen(self) -> bool
IsFullScreen(self) -> bool
[ "IsFullScreen", "(", "self", ")", "-", ">", "bool" ]
def IsFullScreen(*args, **kwargs): """IsFullScreen(self) -> bool""" return _windows_.TopLevelWindow_IsFullScreen(*args, **kwargs)
[ "def", "IsFullScreen", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "TopLevelWindow_IsFullScreen", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L449-L451
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/math_grad.py
python
_LogGrad
(op, grad)
Returns grad * (1/x).
Returns grad * (1/x).
[ "Returns", "grad", "*", "(", "1", "/", "x", ")", "." ]
def _LogGrad(op, grad): """Returns grad * (1/x).""" x = op.inputs[0] with ops.control_dependencies([grad.op]): return grad * math_ops.inv(x)
[ "def", "_LogGrad", "(", "op", ",", "grad", ")", ":", "x", "=", "op", ".", "inputs", "[", "0", "]", "with", "ops", ".", "control_dependencies", "(", "[", "grad", ".", "op", "]", ")", ":", "return", "grad", "*", "math_ops", ".", "inv", "(", "x", ...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/math_grad.py#L295-L299
whai362/PSENet
4d95395658662f2223805c36dcd573d9e190ce26
models/backbone/resnet.py
python
resnet101
(pretrained=False, **kwargs)
return model
Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on Places
Constructs a ResNet-101 model.
[ "Constructs", "a", "ResNet", "-", "101", "model", "." ]
def resnet101(pretrained=False, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on Places """ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: model.load_state_dict(load_url(model_urls['resnet101']), strict=False) return model
[ "def", "resnet101", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet", "(", "Bottleneck", ",", "[", "3", ",", "4", ",", "23", ",", "3", "]", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "model", ...
https://github.com/whai362/PSENet/blob/4d95395658662f2223805c36dcd573d9e190ce26/models/backbone/resnet.py#L214-L223
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/virtualenv/files/virtualenv_support/site.py
python
execsitecustomize
()
Run custom site specific code, if available.
Run custom site specific code, if available.
[ "Run", "custom", "site", "specific", "code", "if", "available", "." ]
def execsitecustomize(): """Run custom site specific code, if available.""" try: import sitecustomize except ImportError: pass
[ "def", "execsitecustomize", "(", ")", ":", "try", ":", "import", "sitecustomize", "except", "ImportError", ":", "pass" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/virtualenv/files/virtualenv_support/site.py#L536-L541
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
DELnHandler.WriteGetDataSizeCode
(self, func, file)
Overrriden from TypeHandler.
Overrriden from TypeHandler.
[ "Overrriden", "from", "TypeHandler", "." ]
def WriteGetDataSizeCode(self, func, file): """Overrriden from TypeHandler.""" code = """ uint32 data_size; if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) { return error::kOutOfBounds; } """ file.Write(code)
[ "def", "WriteGetDataSizeCode", "(", "self", ",", "func", ",", "file", ")", ":", "code", "=", "\"\"\" uint32 data_size;\n if (!SafeMultiplyUint32(n, sizeof(GLuint), &data_size)) {\n return error::kOutOfBounds;\n }\n\"\"\"", "file", ".", "Write", "(", "code", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/gpu/command_buffer/build_gles2_cmd_buffer.py#L3098-L3105
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/distributions/util.py
python
pad
(x, axis, front=False, back=False, value=0, count=1, name=None)
Pads `value` to the front and/or back of a `Tensor` dim, `count` times. Args: x: `Tensor` input. axis: Scalar `int`-like `Tensor` representing the single dimension to pad. (Negative indexing is supported.) front: Python `bool`; if `True` the beginning of the `axis` dimension is padded with `value`, `count` times. If `False` no front padding is made. back: Python `bool`; if `True` the end of the `axis` dimension is padded with `value`, `count` times. If `False` no end padding is made. value: Scalar `int`-like `Tensor` representing the actual value added to the front and/or back of the `axis` dimension of `x`. count: Scalar `int`-like `Tensor` representing number of elements added to the front and/or back of the `axis` dimension of `x`. E.g., if `front = back = True` then `2 * count` elements are added. name: Python `str` name prefixed to Ops created by this function. Returns: pad: The padded version of input `x`. Raises: ValueError: if both `front` and `back` are `False`. TypeError: if `count` is not `int`-like.
Pads `value` to the front and/or back of a `Tensor` dim, `count` times.
[ "Pads", "value", "to", "the", "front", "and", "/", "or", "back", "of", "a", "Tensor", "dim", "count", "times", "." ]
def pad(x, axis, front=False, back=False, value=0, count=1, name=None): """Pads `value` to the front and/or back of a `Tensor` dim, `count` times. Args: x: `Tensor` input. axis: Scalar `int`-like `Tensor` representing the single dimension to pad. (Negative indexing is supported.) front: Python `bool`; if `True` the beginning of the `axis` dimension is padded with `value`, `count` times. If `False` no front padding is made. back: Python `bool`; if `True` the end of the `axis` dimension is padded with `value`, `count` times. If `False` no end padding is made. value: Scalar `int`-like `Tensor` representing the actual value added to the front and/or back of the `axis` dimension of `x`. count: Scalar `int`-like `Tensor` representing number of elements added to the front and/or back of the `axis` dimension of `x`. E.g., if `front = back = True` then `2 * count` elements are added. name: Python `str` name prefixed to Ops created by this function. Returns: pad: The padded version of input `x`. Raises: ValueError: if both `front` and `back` are `False`. TypeError: if `count` is not `int`-like. """ with ops.name_scope(name, "pad", [x, value, count]): x = ops.convert_to_tensor(x, name="x") value = ops.convert_to_tensor(value, dtype=x.dtype, name="value") count = ops.convert_to_tensor(count, name="count") if not count.dtype.is_integer: raise TypeError("`count.dtype` (`{}`) must be `int`-like.".format( count.dtype.name)) if not front and not back: raise ValueError("At least one of `front`, `back` must be `True`.") ndims = ( x.shape.ndims if x.shape.ndims is not None else array_ops.rank( x, name="ndims")) axis = ops.convert_to_tensor(axis, name="axis") axis_ = tensor_util.constant_value(axis) if axis_ is not None: axis = axis_ if axis < 0: axis = ndims + axis count_ = tensor_util.constant_value(count) if axis_ >= 0 or x.shape.ndims is not None: head = x.shape[:axis] middle = tensor_shape.TensorShape(None if count_ is None else ( tensor_shape.dimension_at_index(x.shape, axis) + count_ * (front + back))) tail = x.shape[axis + 1:] final_shape = head.concatenate(middle.concatenate(tail)) else: final_shape = None else: axis = array_ops.where_v2(axis < 0, ndims + axis, axis) final_shape = None x = array_ops.pad( x, paddings=array_ops.one_hot( indices=array_ops.stack( [axis if front else -1, axis if back else -1]), depth=ndims, axis=0, on_value=count, dtype=dtypes.int32), constant_values=value) if final_shape is not None: x.set_shape(final_shape) return x
[ "def", "pad", "(", "x", ",", "axis", ",", "front", "=", "False", ",", "back", "=", "False", ",", "value", "=", "0", ",", "count", "=", "1", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"pad\"", ",", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/distributions/util.py#L1282-L1350
CaoWGG/TensorRT-CenterNet
f949252e37b51e60f873808f46d3683f15735e79
onnx-tensorrt/third_party/onnx/onnx/helper.py
python
strip_doc_string
(proto)
Empties `doc_string` field on any nested protobuf messages
Empties `doc_string` field on any nested protobuf messages
[ "Empties", "doc_string", "field", "on", "any", "nested", "protobuf", "messages" ]
def strip_doc_string(proto): # type: (google.protobuf.message.Message) -> None """ Empties `doc_string` field on any nested protobuf messages """ assert isinstance(proto, google.protobuf.message.Message) for descriptor in proto.DESCRIPTOR.fields: if descriptor.name == 'doc_string': proto.ClearField(descriptor.name) elif descriptor.type == descriptor.TYPE_MESSAGE: if descriptor.label == descriptor.LABEL_REPEATED: for x in getattr(proto, descriptor.name): strip_doc_string(x) elif proto.HasField(descriptor.name): strip_doc_string(getattr(proto, descriptor.name))
[ "def", "strip_doc_string", "(", "proto", ")", ":", "# type: (google.protobuf.message.Message) -> None", "assert", "isinstance", "(", "proto", ",", "google", ".", "protobuf", ".", "message", ".", "Message", ")", "for", "descriptor", "in", "proto", ".", "DESCRIPTOR", ...
https://github.com/CaoWGG/TensorRT-CenterNet/blob/f949252e37b51e60f873808f46d3683f15735e79/onnx-tensorrt/third_party/onnx/onnx/helper.py#L538-L551
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/arch/arm/ArmSystem.py
python
ArmRelease.has
(self, new_ext: ArmExtension)
Is the system implementing the provided extension (ArmExtension) ?
Is the system implementing the provided extension (ArmExtension) ?
[ "Is", "the", "system", "implementing", "the", "provided", "extension", "(", "ArmExtension", ")", "?" ]
def has(self, new_ext: ArmExtension) -> bool: """ Is the system implementing the provided extension (ArmExtension) ? """ if (new_ext.value not in [ ext.value for ext in self.extensions ]): return False else: return True
[ "def", "has", "(", "self", ",", "new_ext", ":", "ArmExtension", ")", "->", "bool", ":", "if", "(", "new_ext", ".", "value", "not", "in", "[", "ext", ".", "value", "for", "ext", "in", "self", ".", "extensions", "]", ")", ":", "return", "False", "els...
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/arch/arm/ArmSystem.py#L94-L102
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb/layer1.py
python
Layer1.describe_table
(self, table_name)
return self.make_request('DescribeTable', json_input)
Returns information about the table including current state of the table, primary key schema and when the table was created. :type table_name: str :param table_name: The name of the table to describe.
Returns information about the table including current state of the table, primary key schema and when the table was created.
[ "Returns", "information", "about", "the", "table", "including", "current", "state", "of", "the", "table", "primary", "key", "schema", "and", "when", "the", "table", "was", "created", "." ]
def describe_table(self, table_name): """ Returns information about the table including current state of the table, primary key schema and when the table was created. :type table_name: str :param table_name: The name of the table to describe. """ data = {'TableName': table_name} json_input = json.dumps(data) return self.make_request('DescribeTable', json_input)
[ "def", "describe_table", "(", "self", ",", "table_name", ")", ":", "data", "=", "{", "'TableName'", ":", "table_name", "}", "json_input", "=", "json", ".", "dumps", "(", "data", ")", "return", "self", ".", "make_request", "(", "'DescribeTable'", ",", "json...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/dynamodb/layer1.py#L208-L219
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/crywaflib/msvs.py
python
msvs_generator.collect_targets
(self)
Process the list of task generators
Process the list of task generators
[ "Process", "the", "list", "of", "task", "generators" ]
def collect_targets(self): """ Process the list of task generators """ for g in self.groups: for tg in g: if not isinstance(tg, TaskGen.task_gen): continue # only include projects which are valid for any spec which we have if self.options.specs_to_include_in_project_generation != '': bSkipModule = True allowed_specs = self.options.specs_to_include_in_project_generation.replace(' ', '').split(',') for spec_name in allowed_specs: if tg.target in self.spec_modules(spec_name): bSkipModule = False break if bSkipModule: continue if not hasattr(tg, 'msvs_includes'): tg.msvs_includes = tg.to_list(getattr(tg, 'includes', [])) + tg.to_list(getattr(tg, 'export_includes', [])) tg.post() p = self.vsnode_target(self, tg) p.collect_source() # delegate this processing p.collect_properties() self.all_projects.append(p) if p.is_android_launcher_project(): p_android_package = self.vsnode_android_package_target(self, tg) p_android_package.collect_source() # delegate this processing p_android_package.collect_properties() self.all_projects.append(p_android_package)
[ "def", "collect_targets", "(", "self", ")", ":", "for", "g", "in", "self", ".", "groups", ":", "for", "tg", "in", "g", ":", "if", "not", "isinstance", "(", "tg", ",", "TaskGen", ".", "task_gen", ")", ":", "continue", "# only include projects which are vali...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/crywaflib/msvs.py#L1793-L1830
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/model/DrillExportModel.py
python
DrillExportModel._logSuccessExport
(self, wsName)
Log all the successful exports. Args: wsName (str): name of the concerned workspace
Log all the successful exports.
[ "Log", "all", "the", "successful", "exports", "." ]
def _logSuccessExport(self, wsName): """ Log all the successful exports. Args: wsName (str): name of the concerned workspace """ if wsName not in self._successExports: return filenames = ", ".join(self._successExports[wsName]) logger.notice("Successful export of workspace {} to {}" .format(wsName, filenames)) del self._successExports[wsName]
[ "def", "_logSuccessExport", "(", "self", ",", "wsName", ")", ":", "if", "wsName", "not", "in", "self", ".", "_successExports", ":", "return", "filenames", "=", "\", \"", ".", "join", "(", "self", ".", "_successExports", "[", "wsName", "]", ")", "logger", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/drill/model/DrillExportModel.py#L203-L215
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/indexes/base.py
python
Index.putmask
(self, mask, value)
Return a new Index of the values set with the mask. See Also -------- numpy.ndarray.putmask
Return a new Index of the values set with the mask.
[ "Return", "a", "new", "Index", "of", "the", "values", "set", "with", "the", "mask", "." ]
def putmask(self, mask, value): """ Return a new Index of the values set with the mask. See Also -------- numpy.ndarray.putmask """ values = self.values.copy() try: np.putmask(values, mask, self._convert_for_op(value)) return self._shallow_copy(values) except (ValueError, TypeError) as err: if is_object_dtype(self): raise err # coerces to object return self.astype(object).putmask(mask, value)
[ "def", "putmask", "(", "self", ",", "mask", ",", "value", ")", ":", "values", "=", "self", ".", "values", ".", "copy", "(", ")", "try", ":", "np", ".", "putmask", "(", "values", ",", "mask", ",", "self", ".", "_convert_for_op", "(", "value", ")", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/indexes/base.py#L4032-L4049