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
dmtcp/dmtcp
48a23686e1ce6784829b783ced9c62a14d620507
util/cpplint.py
python
FileInfo.IsSource
(self)
return _IsSourceExtension(self.Extension()[1:])
File has a source file extension.
File has a source file extension.
[ "File", "has", "a", "source", "file", "extension", "." ]
def IsSource(self): """File has a source file extension.""" return _IsSourceExtension(self.Extension()[1:])
[ "def", "IsSource", "(", "self", ")", ":", "return", "_IsSourceExtension", "(", "self", ".", "Extension", "(", ")", "[", "1", ":", "]", ")" ]
https://github.com/dmtcp/dmtcp/blob/48a23686e1ce6784829b783ced9c62a14d620507/util/cpplint.py#L1156-L1158
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/dispatch.py
python
Dispatcher.source_warnings
(self)
return self._source_warnings
Return warnings in sourcing handlers.
Return warnings in sourcing handlers.
[ "Return", "warnings", "in", "sourcing", "handlers", "." ]
def source_warnings(self): """Return warnings in sourcing handlers.""" return self._source_warnings
[ "def", "source_warnings", "(", "self", ")", ":", "return", "self", ".", "_source_warnings" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/dispatch.py#L231-L234
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-utils/modtool/core/base.py
python
validate_name
(kind, name)
Checks that block, module etc names are alphanumeric.
Checks that block, module etc names are alphanumeric.
[ "Checks", "that", "block", "module", "etc", "names", "are", "alphanumeric", "." ]
def validate_name(kind, name): """ Checks that block, module etc names are alphanumeric. """ if not re.fullmatch('[a-zA-Z0-9_]+', name): raise ModToolException( "Invalid {} name '{}': names can only contain letters, numbers and underscores".format(kind, name))
[ "def", "validate_name", "(", "kind", ",", "name", ")", ":", "if", "not", "re", ".", "fullmatch", "(", "'[a-zA-Z0-9_]+'", ",", "name", ")", ":", "raise", "ModToolException", "(", "\"Invalid {} name '{}': names can only contain letters, numbers and underscores\"", ".", ...
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-utils/modtool/core/base.py#L47-L51
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_parser.py
python
p_moduleend
(p)
moduleend :
moduleend :
[ "moduleend", ":" ]
def p_moduleend(p): 'moduleend :' p[0] = None
[ "def", "p_moduleend", "(", "p", ")", ":", "p", "[", "0", "]", "=", "None" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L455-L457
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
IconLocation.__init__
(self, *args, **kwargs)
__init__(self, String filename=&wxPyEmptyString, int num=0) -> IconLocation
__init__(self, String filename=&wxPyEmptyString, int num=0) -> IconLocation
[ "__init__", "(", "self", "String", "filename", "=", "&wxPyEmptyString", "int", "num", "=", "0", ")", "-", ">", "IconLocation" ]
def __init__(self, *args, **kwargs): """__init__(self, String filename=&wxPyEmptyString, int num=0) -> IconLocation""" _gdi_.IconLocation_swiginit(self,_gdi_.new_IconLocation(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_gdi_", ".", "IconLocation_swiginit", "(", "self", ",", "_gdi_", ".", "new_IconLocation", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L1391-L1393
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
dev/archery/archery/utils/maven.py
python
MavenDefinition.build_arguments
(self)
return arguments
Return the arguments to maven invocation for build.
Return the arguments to maven invocation for build.
[ "Return", "the", "arguments", "to", "maven", "invocation", "for", "build", "." ]
def build_arguments(self): """" Return the arguments to maven invocation for build. """ arguments = self.build_definitions + [ "-B", "-DskipTests", "-Drat.skip=true", "-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer." "Slf4jMavenTransferListener=warn", "-T", "2C", "install" ] return arguments
[ "def", "build_arguments", "(", "self", ")", ":", "arguments", "=", "self", ".", "build_definitions", "+", "[", "\"-B\"", ",", "\"-DskipTests\"", ",", "\"-Drat.skip=true\"", ",", "\"-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.\"", "\"Slf4jMavenTransferListener=w...
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/dev/archery/archery/utils/maven.py#L64-L72
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/dummyarray.py
python
iter_strides_c_contig
(arr, shape=None)
yields the c-contiguous strides
yields the c-contiguous strides
[ "yields", "the", "c", "-", "contiguous", "strides" ]
def iter_strides_c_contig(arr, shape=None): """yields the c-contiguous strides """ shape = arr.shape if shape is None else shape itemsize = arr.itemsize def gen(): yield itemsize sum = 1 for s in reversed(shape[1:]): sum *= s yield sum * itemsize for i in reversed(list(gen())): yield i
[ "def", "iter_strides_c_contig", "(", "arr", ",", "shape", "=", "None", ")", ":", "shape", "=", "arr", ".", "shape", "if", "shape", "is", "None", "else", "shape", "itemsize", "=", "arr", ".", "itemsize", "def", "gen", "(", ")", ":", "yield", "itemsize",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/dummyarray.py#L377-L391
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
example/gluon/style_transfer/utils.py
python
CenterCrop.__call__
(self, img)
return img.crop((x1, y1, x1 + tw, y1 + th))
Args: img (PIL.Image): Image to be cropped. Returns: PIL.Image: Cropped image.
Args: img (PIL.Image): Image to be cropped. Returns: PIL.Image: Cropped image.
[ "Args", ":", "img", "(", "PIL", ".", "Image", ")", ":", "Image", "to", "be", "cropped", ".", "Returns", ":", "PIL", ".", "Image", ":", "Cropped", "image", "." ]
def __call__(self, img): """ Args: img (PIL.Image): Image to be cropped. Returns: PIL.Image: Cropped image. """ w, h = img.size th, tw = self.size x1 = int(round((w - tw) / 2.)) y1 = int(round((h - th) / 2.)) return img.crop((x1, y1, x1 + tw, y1 + th))
[ "def", "__call__", "(", "self", ",", "img", ")", ":", "w", ",", "h", "=", "img", ".", "size", "th", ",", "tw", "=", "self", ".", "size", "x1", "=", "int", "(", "round", "(", "(", "w", "-", "tw", ")", "/", "2.", ")", ")", "y1", "=", "int",...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/gluon/style_transfer/utils.py#L191-L202
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/grid.py
python
GridRangeSelectEvent.GetTopLeftCoords
(*args, **kwargs)
return _grid.GridRangeSelectEvent_GetTopLeftCoords(*args, **kwargs)
GetTopLeftCoords(self) -> GridCellCoords
GetTopLeftCoords(self) -> GridCellCoords
[ "GetTopLeftCoords", "(", "self", ")", "-", ">", "GridCellCoords" ]
def GetTopLeftCoords(*args, **kwargs): """GetTopLeftCoords(self) -> GridCellCoords""" return _grid.GridRangeSelectEvent_GetTopLeftCoords(*args, **kwargs)
[ "def", "GetTopLeftCoords", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridRangeSelectEvent_GetTopLeftCoords", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L2401-L2403
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/functional/tensor.py
python
arange
( start: Union[int, float, Tensor] = 0, stop: Optional[Union[int, float, Tensor]] = None, step: Union[int, float, Tensor] = 1, dtype="float32", device: Optional[CompNode] = None, )
return result
r"""Returns evenly spaced values within the half-open interval ``[start, stop)`` as a one-dimensional tensor. Note: This function cannot guarantee that the interval does not include the stop value in those cases where step is not an integer and floating-point rounding errors affect the length of the output tensor. Args: start: if ``stop`` is specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``. stop: the end of the interval. Default: ``None``. step: the distance between two adjacent elements ( ``out[i+1] - out[i]`` ). Must not be 0 ; may be negative, this results i an empty tensor if stop >= start . Default: 1 . Keyword args: dtype( :attr:`.Tensor.dtype` ): output tensor data type. Default: ``float32``. device( :attr:`.Tensor.device` ): device on which to place the created tensor. Default: ``None``. Returns: A one-dimensional tensor containing evenly spaced values. The length of the output tensor must be ``ceil((stop-start)/step)`` if ``stop - start`` and ``step`` have the same sign, and length 0 otherwise. Examples: >>> F.arange(5) Tensor([0. 1. 2. 3. 4.], device=xpux:0) >>> F.arange(1, 4) Tensor([1. 2. 3.], device=xpux:0)
r"""Returns evenly spaced values within the half-open interval ``[start, stop)`` as a one-dimensional tensor.
[ "r", "Returns", "evenly", "spaced", "values", "within", "the", "half", "-", "open", "interval", "[", "start", "stop", ")", "as", "a", "one", "-", "dimensional", "tensor", "." ]
def arange( start: Union[int, float, Tensor] = 0, stop: Optional[Union[int, float, Tensor]] = None, step: Union[int, float, Tensor] = 1, dtype="float32", device: Optional[CompNode] = None, ) -> Tensor: r"""Returns evenly spaced values within the half-open interval ``[start, stop)`` as a one-dimensional tensor. Note: This function cannot guarantee that the interval does not include the stop value in those cases where step is not an integer and floating-point rounding errors affect the length of the output tensor. Args: start: if ``stop`` is specified, the start of interval (inclusive); otherwise, the end of the interval (exclusive). If ``stop`` is not specified, the default starting value is ``0``. stop: the end of the interval. Default: ``None``. step: the distance between two adjacent elements ( ``out[i+1] - out[i]`` ). Must not be 0 ; may be negative, this results i an empty tensor if stop >= start . Default: 1 . Keyword args: dtype( :attr:`.Tensor.dtype` ): output tensor data type. Default: ``float32``. device( :attr:`.Tensor.device` ): device on which to place the created tensor. Default: ``None``. Returns: A one-dimensional tensor containing evenly spaced values. The length of the output tensor must be ``ceil((stop-start)/step)`` if ``stop - start`` and ``step`` have the same sign, and length 0 otherwise. Examples: >>> F.arange(5) Tensor([0. 1. 2. 3. 4.], device=xpux:0) >>> F.arange(1, 4) Tensor([1. 2. 3.], device=xpux:0) """ if stop is None: start, stop = 0, start start = Tensor(start, dtype="float32") stop = Tensor(stop, dtype="float32") step = Tensor(step, dtype="float32") num = ceil((stop - start) / step) stop = start + step * (num - 1) result = linspace(start, stop, num, device=device) if np.dtype(dtype) != np.float32: return result.astype(dtype) return result
[ "def", "arange", "(", "start", ":", "Union", "[", "int", ",", "float", ",", "Tensor", "]", "=", "0", ",", "stop", ":", "Optional", "[", "Union", "[", "int", ",", "float", ",", "Tensor", "]", "]", "=", "None", ",", "step", ":", "Union", "[", "in...
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/functional/tensor.py#L1097-L1147
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
uCSIsCatCo
(code)
return ret
Check whether the character is part of Co UCS Category
Check whether the character is part of Co UCS Category
[ "Check", "whether", "the", "character", "is", "part", "of", "Co", "UCS", "Category" ]
def uCSIsCatCo(code): """Check whether the character is part of Co UCS Category """ ret = libxml2mod.xmlUCSIsCatCo(code) return ret
[ "def", "uCSIsCatCo", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsCatCo", "(", "code", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L1473-L1476
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/indexes/multi.py
python
MultiIndex.is_monotonic_increasing
(self)
return if the index is monotonic increasing (only equal or increasing) values.
return if the index is monotonic increasing (only equal or increasing) values.
[ "return", "if", "the", "index", "is", "monotonic", "increasing", "(", "only", "equal", "or", "increasing", ")", "values", "." ]
def is_monotonic_increasing(self): """ return if the index is monotonic increasing (only equal or increasing) values. """ # reversed() because lexsort() wants the most significant key last. values = [self._get_level_values(i).values for i in reversed(range(len(self.levels)))] try: sort_order = np.lexsort(values) return Index(sort_order).is_monotonic except TypeError: # we have mixed types and np.lexsort is not happy return Index(self.values).is_monotonic
[ "def", "is_monotonic_increasing", "(", "self", ")", ":", "# reversed() because lexsort() wants the most significant key last.", "values", "=", "[", "self", ".", "_get_level_values", "(", "i", ")", ".", "values", "for", "i", "in", "reversed", "(", "range", "(", "len"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/indexes/multi.py#L1187-L1202
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
tools/filelock.py
python
BaseFileLock.release
(self, force = False)
return None
Releases the file lock. Please note, that the lock is only completly released, if the lock counter is 0. Also note, that the lock file itself is not automatically deleted. :arg bool force: If true, the lock counter is ignored and the lock is released in every case.
Releases the file lock.
[ "Releases", "the", "file", "lock", "." ]
def release(self, force = False): """ Releases the file lock. Please note, that the lock is only completly released, if the lock counter is 0. Also note, that the lock file itself is not automatically deleted. :arg bool force: If true, the lock counter is ignored and the lock is released in every case. """ with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: lock_id = id(self) lock_filename = self._lock_file logger().debug('Attempting to release lock %s on %s', lock_id, lock_filename) self._release() self._lock_counter = 0 logger().debug('Lock %s released on %s', lock_id, lock_filename) return None
[ "def", "release", "(", "self", ",", "force", "=", "False", ")", ":", "with", "self", ".", "_thread_lock", ":", "if", "self", ".", "is_locked", ":", "self", ".", "_lock_counter", "-=", "1", "if", "self", ".", "_lock_counter", "==", "0", "or", "force", ...
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/tools/filelock.py#L300-L327
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Tool/msvc.py
python
object_emitter
(target, source, env, parent_emitter)
return (target, source)
Sets up the PCH dependencies for an object file.
Sets up the PCH dependencies for an object file.
[ "Sets", "up", "the", "PCH", "dependencies", "for", "an", "object", "file", "." ]
def object_emitter(target, source, env, parent_emitter): """Sets up the PCH dependencies for an object file.""" validate_vars(env) parent_emitter(target, source, env) # Add a dependency, but only if the target (e.g. 'Source1.obj') # doesn't correspond to the pre-compiled header ('Source1.pch'). # If the basenames match, then this was most likely caused by # someone adding the source file to both the env.PCH() and the # env.Program() calls, and adding the explicit dependency would # cause a cycle on the .pch file itself. # # See issue #2505 for a discussion of what to do if it turns # out this assumption causes trouble in the wild: # https://github.com/SCons/scons/issues/2505 if 'PCH' in env: pch = env['PCH'] if str(target[0]) != SCons.Util.splitext(str(pch))[0] + '.obj': env.Depends(target, pch) return (target, source)
[ "def", "object_emitter", "(", "target", ",", "source", ",", "env", ",", "parent_emitter", ")", ":", "validate_vars", "(", "env", ")", "parent_emitter", "(", "target", ",", "source", ",", "env", ")", "# Add a dependency, but only if the target (e.g. 'Source1.obj')", ...
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Tool/msvc.py#L98-L120
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/_pydecimal.py
python
Context.is_finite
(self, a)
return a.is_finite()
Return True if the operand is finite; otherwise return False. A Decimal instance is considered finite if it is neither infinite nor a NaN. >>> ExtendedContext.is_finite(Decimal('2.50')) True >>> ExtendedContext.is_finite(Decimal('-0.3')) True >>> ExtendedContext.is_finite(Decimal('0')) True >>> ExtendedContext.is_finite(Decimal('Inf')) False >>> ExtendedContext.is_finite(Decimal('NaN')) False >>> ExtendedContext.is_finite(1) True
Return True if the operand is finite; otherwise return False.
[ "Return", "True", "if", "the", "operand", "is", "finite", ";", "otherwise", "return", "False", "." ]
def is_finite(self, a): """Return True if the operand is finite; otherwise return False. A Decimal instance is considered finite if it is neither infinite nor a NaN. >>> ExtendedContext.is_finite(Decimal('2.50')) True >>> ExtendedContext.is_finite(Decimal('-0.3')) True >>> ExtendedContext.is_finite(Decimal('0')) True >>> ExtendedContext.is_finite(Decimal('Inf')) False >>> ExtendedContext.is_finite(Decimal('NaN')) False >>> ExtendedContext.is_finite(1) True """ a = _convert_other(a, raiseit=True) return a.is_finite()
[ "def", "is_finite", "(", "self", ",", "a", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "is_finite", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pydecimal.py#L4499-L4519
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/build_py.py
python
build_py.exclude_data_files
(self, package, src_dir, files)
return list(_unique_everseen(keepers))
Filter filenames for package's data files in 'src_dir
Filter filenames for package's data files in 'src_dir
[ "Filter", "filenames", "for", "package", "s", "data", "files", "in", "src_dir" ]
def exclude_data_files(self, package, src_dir, files): """Filter filenames for package's data files in 'src_dir'""" files = list(files) patterns = self._get_platform_patterns( self.exclude_package_data, package, src_dir, ) match_groups = ( fnmatch.filter(files, pattern) for pattern in patterns ) # flatten the groups of matches into an iterable of matches matches = itertools.chain.from_iterable(match_groups) bad = set(matches) keepers = ( fn for fn in files if fn not in bad ) # ditch dupes return list(_unique_everseen(keepers))
[ "def", "exclude_data_files", "(", "self", ",", "package", ",", "src_dir", ",", "files", ")", ":", "files", "=", "list", "(", "files", ")", "patterns", "=", "self", ".", "_get_platform_patterns", "(", "self", ".", "exclude_package_data", ",", "package", ",", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/build_py.py#L202-L223
psnonis/FinBERT
c0c555d833a14e2316a3701e59c0b5156f804b4e
bert-gpu/tensorrt-inference-server/src/clients/python/__init__.py
python
InferContext.run
(self, inputs, outputs, batch_size=1, flags=0)
return self._get_results(outputs, batch_size)
Run inference using the supplied 'inputs' to calculate the outputs specified by 'outputs'. Parameters ---------- inputs : dict Dictionary from input name to the value(s) for that input. An input value is specified as a numpy array. Each input in the dictionary maps to a list of values (i.e. a list of numpy array objects), where the length of the list must equal the 'batch_size'. outputs : dict Dictionary from output name to a value indicating the ResultFormat that should be used for that output. For RAW the value should be ResultFormat.RAW. For CLASS the value should be a tuple (ResultFormat.CLASS, k), where 'k' indicates how many classification results should be returned for the output. batch_size : int The batch size of the inference. Each input must provide an appropriately sized batch of inputs. flags : int The flags to use for the inference. The bitwise-or of InferRequestHeader.Flag values. Returns ------- dict A dictionary from output name to the list of values for that output (one list element for each entry of the batch). The format of a value returned for an output depends on the output format specified in 'outputs'. For format RAW a value is a numpy array of the appropriate type and shape for the output. For format CLASS a value is the top 'k' output values returned as an array of (class index, class value, class label) tuples. Raises ------ InferenceServerException If all inputs are not specified, if the size of input data does not match expectations, if unknown output names are specified or if server fails to perform inference.
Run inference using the supplied 'inputs' to calculate the outputs specified by 'outputs'.
[ "Run", "inference", "using", "the", "supplied", "inputs", "to", "calculate", "the", "outputs", "specified", "by", "outputs", "." ]
def run(self, inputs, outputs, batch_size=1, flags=0): """Run inference using the supplied 'inputs' to calculate the outputs specified by 'outputs'. Parameters ---------- inputs : dict Dictionary from input name to the value(s) for that input. An input value is specified as a numpy array. Each input in the dictionary maps to a list of values (i.e. a list of numpy array objects), where the length of the list must equal the 'batch_size'. outputs : dict Dictionary from output name to a value indicating the ResultFormat that should be used for that output. For RAW the value should be ResultFormat.RAW. For CLASS the value should be a tuple (ResultFormat.CLASS, k), where 'k' indicates how many classification results should be returned for the output. batch_size : int The batch size of the inference. Each input must provide an appropriately sized batch of inputs. flags : int The flags to use for the inference. The bitwise-or of InferRequestHeader.Flag values. Returns ------- dict A dictionary from output name to the list of values for that output (one list element for each entry of the batch). The format of a value returned for an output depends on the output format specified in 'outputs'. For format RAW a value is a numpy array of the appropriate type and shape for the output. For format CLASS a value is the top 'k' output values returned as an array of (class index, class value, class label) tuples. Raises ------ InferenceServerException If all inputs are not specified, if the size of input data does not match expectations, if unknown output names are specified or if server fails to perform inference. """ self._last_request_id = None self._last_request_model_name = None self._last_request_model_version = None # The input values must be contiguous and the lifetime of those # contiguous copies must span until the inference completes # so grab a reference to them at this scope. contiguous_input = list() # Set run option and input values self._prepare_request(inputs, outputs, flags, batch_size, contiguous_input) # Run inference... self._last_request_id = _raise_if_error(c_void_p(_crequest_infer_ctx_run(self._ctx))) return self._get_results(outputs, batch_size)
[ "def", "run", "(", "self", ",", "inputs", ",", "outputs", ",", "batch_size", "=", "1", ",", "flags", "=", "0", ")", ":", "self", ".", "_last_request_id", "=", "None", "self", ".", "_last_request_model_name", "=", "None", "self", ".", "_last_request_model_v...
https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/tensorrt-inference-server/src/clients/python/__init__.py#L814-L878
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/bisect-builds.py
python
Bisect
(base_url, platform, official_builds, is_aura, good_rev=0, bad_rev=0, num_runs=1, command="%p %a", try_args=(), profile=None, flash_path=None, pdf_path=None, interactive=True, evaluate=AskIsGoodBuild)
return (revlist[minrev], revlist[maxrev])
Given known good and known bad revisions, run a binary search on all archived revisions to determine the last known good revision. @param platform Which build to download/run ('mac', 'win', 'linux64', etc.). @param official_builds Specify build type (Chromium or Official build). @param good_rev Number/tag of the known good revision. @param bad_rev Number/tag of the known bad revision. @param num_runs Number of times to run each build for asking good/bad. @param try_args A tuple of arguments to pass to the test application. @param profile The name of the user profile to run with. @param interactive If it is false, use command exit code for good or bad judgment of the argument build. @param evaluate A function which returns 'g' if the argument build is good, 'b' if it's bad or 'u' if unknown. Threading is used to fetch Chromium revisions in the background, speeding up the user's experience. For example, suppose the bounds of the search are good_rev=0, bad_rev=100. The first revision to be checked is 50. Depending on whether revision 50 is good or bad, the next revision to check will be either 25 or 75. So, while revision 50 is being checked, the script will download revisions 25 and 75 in the background. Once the good/bad verdict on rev 50 is known: - If rev 50 is good, the download of rev 25 is cancelled, and the next test is run on rev 75. - If rev 50 is bad, the download of rev 75 is cancelled, and the next test is run on rev 25.
Given known good and known bad revisions, run a binary search on all archived revisions to determine the last known good revision.
[ "Given", "known", "good", "and", "known", "bad", "revisions", "run", "a", "binary", "search", "on", "all", "archived", "revisions", "to", "determine", "the", "last", "known", "good", "revision", "." ]
def Bisect(base_url, platform, official_builds, is_aura, good_rev=0, bad_rev=0, num_runs=1, command="%p %a", try_args=(), profile=None, flash_path=None, pdf_path=None, interactive=True, evaluate=AskIsGoodBuild): """Given known good and known bad revisions, run a binary search on all archived revisions to determine the last known good revision. @param platform Which build to download/run ('mac', 'win', 'linux64', etc.). @param official_builds Specify build type (Chromium or Official build). @param good_rev Number/tag of the known good revision. @param bad_rev Number/tag of the known bad revision. @param num_runs Number of times to run each build for asking good/bad. @param try_args A tuple of arguments to pass to the test application. @param profile The name of the user profile to run with. @param interactive If it is false, use command exit code for good or bad judgment of the argument build. @param evaluate A function which returns 'g' if the argument build is good, 'b' if it's bad or 'u' if unknown. Threading is used to fetch Chromium revisions in the background, speeding up the user's experience. For example, suppose the bounds of the search are good_rev=0, bad_rev=100. The first revision to be checked is 50. Depending on whether revision 50 is good or bad, the next revision to check will be either 25 or 75. So, while revision 50 is being checked, the script will download revisions 25 and 75 in the background. Once the good/bad verdict on rev 50 is known: - If rev 50 is good, the download of rev 25 is cancelled, and the next test is run on rev 75. - If rev 50 is bad, the download of rev 75 is cancelled, and the next test is run on rev 25. """ if not profile: profile = 'profile' context = PathContext(base_url, platform, good_rev, bad_rev, official_builds, is_aura, flash_path, pdf_path) cwd = os.getcwd() print "Downloading list of known revisions..." _GetDownloadPath = lambda rev: os.path.join(cwd, '%s-%s' % (str(rev), context.archive_name)) if official_builds: revlist = context.GetOfficialBuildsList() else: revlist = context.GetRevList() # Get a list of revisions to bisect across. if len(revlist) < 2: # Don't have enough builds to bisect. msg = 'We don\'t have enough builds to bisect. revlist: %s' % revlist raise RuntimeError(msg) # Figure out our bookends and first pivot point; fetch the pivot revision. minrev = 0 maxrev = len(revlist) - 1 pivot = maxrev / 2 rev = revlist[pivot] zipfile = _GetDownloadPath(rev) fetch = DownloadJob(context, 'initial_fetch', rev, zipfile) fetch.Start() fetch.WaitFor() # Binary search time! while fetch and fetch.zipfile and maxrev - minrev > 1: if bad_rev < good_rev: min_str, max_str = "bad", "good" else: min_str, max_str = "good", "bad" print 'Bisecting range [%s (%s), %s (%s)].' % (revlist[minrev], min_str, \ revlist[maxrev], max_str) # Pre-fetch next two possible pivots # - down_pivot is the next revision to check if the current revision turns # out to be bad. # - up_pivot is the next revision to check if the current revision turns # out to be good. down_pivot = int((pivot - minrev) / 2) + minrev down_fetch = None if down_pivot != pivot and down_pivot != minrev: down_rev = revlist[down_pivot] down_fetch = DownloadJob(context, 'down_fetch', down_rev, _GetDownloadPath(down_rev)) down_fetch.Start() up_pivot = int((maxrev - pivot) / 2) + pivot up_fetch = None if up_pivot != pivot and up_pivot != maxrev: up_rev = revlist[up_pivot] up_fetch = DownloadJob(context, 'up_fetch', up_rev, _GetDownloadPath(up_rev)) up_fetch.Start() # Run test on the pivot revision. status = None stdout = None stderr = None try: (status, stdout, stderr) = RunRevision(context, rev, fetch.zipfile, profile, num_runs, command, try_args) except Exception, e: print >> sys.stderr, e # Call the evaluate function to see if the current revision is good or bad. # On that basis, kill one of the background downloads and complete the # other, as described in the comments above. try: if not interactive: if status: answer = 'b' print 'Bad revision: %s' % rev else: answer = 'g' print 'Good revision: %s' % rev else: answer = evaluate(rev, official_builds, status, stdout, stderr) if answer == 'g' and good_rev < bad_rev or \ answer == 'b' and bad_rev < good_rev: fetch.Stop() minrev = pivot if down_fetch: down_fetch.Stop() # Kill the download of the older revision. fetch = None if up_fetch: up_fetch.WaitFor() pivot = up_pivot fetch = up_fetch elif answer == 'b' and good_rev < bad_rev or \ answer == 'g' and bad_rev < good_rev: fetch.Stop() maxrev = pivot if up_fetch: up_fetch.Stop() # Kill the download of the newer revision. fetch = None if down_fetch: down_fetch.WaitFor() pivot = down_pivot fetch = down_fetch elif answer == 'r': pass # Retry requires no changes. elif answer == 'u': # Nuke the revision from the revlist and choose a new pivot. fetch.Stop() revlist.pop(pivot) maxrev -= 1 # Assumes maxrev >= pivot. if maxrev - minrev > 1: # Alternate between using down_pivot or up_pivot for the new pivot # point, without affecting the range. Do this instead of setting the # pivot to the midpoint of the new range because adjacent revisions # are likely affected by the same issue that caused the (u)nknown # response. if up_fetch and down_fetch: fetch = [up_fetch, down_fetch][len(revlist) % 2] elif up_fetch: fetch = up_fetch else: fetch = down_fetch fetch.WaitFor() if fetch == up_fetch: pivot = up_pivot - 1 # Subtracts 1 because revlist was resized. else: pivot = down_pivot zipfile = fetch.zipfile if down_fetch and fetch != down_fetch: down_fetch.Stop() if up_fetch and fetch != up_fetch: up_fetch.Stop() else: assert False, "Unexpected return value from evaluate(): " + answer except SystemExit: print "Cleaning up..." for f in [_GetDownloadPath(revlist[down_pivot]), _GetDownloadPath(revlist[up_pivot])]: try: os.unlink(f) except OSError: pass sys.exit(0) rev = revlist[pivot] return (revlist[minrev], revlist[maxrev])
[ "def", "Bisect", "(", "base_url", ",", "platform", ",", "official_builds", ",", "is_aura", ",", "good_rev", "=", "0", ",", "bad_rev", "=", "0", ",", "num_runs", "=", "1", ",", "command", "=", "\"%p %a\"", ",", "try_args", "=", "(", ")", ",", "profile",...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/bisect-builds.py#L461-L660
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathThreadMilling.py
python
_InternalThread.overshoots
(self, z)
return z + self.hPitch > self.zFinal
overshoots(z) ... returns true if adding another half helix goes beyond the thread bounds
overshoots(z) ... returns true if adding another half helix goes beyond the thread bounds
[ "overshoots", "(", "z", ")", "...", "returns", "true", "if", "adding", "another", "half", "helix", "goes", "beyond", "the", "thread", "bounds" ]
def overshoots(self, z): """overshoots(z) ... returns true if adding another half helix goes beyond the thread bounds""" if self.pitch < 0: return z + self.hPitch < self.zFinal return z + self.hPitch > self.zFinal
[ "def", "overshoots", "(", "self", ",", "z", ")", ":", "if", "self", ".", "pitch", "<", "0", ":", "return", "z", "+", "self", ".", "hPitch", "<", "self", ".", "zFinal", "return", "z", "+", "self", ".", "hPitch", ">", "self", ".", "zFinal" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathThreadMilling.py#L88-L92
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/beta.py
python
Beta.log_prob
(self, x, name="log_prob")
`Log(P[counts])`, computed for every batch member. Args: x: Non-negative floating point tensor whose shape can be broadcast with `self.a` and `self.b`. For fixed leading dimensions, the last dimension represents counts for the corresponding Beta distribution in `self.a` and `self.b`. `x` is only legal if 0 < x < 1. name: Name to give this Op, defaults to "log_prob". Returns: Log probabilities for each record, shape `[N1,...,Nm]`.
`Log(P[counts])`, computed for every batch member.
[ "Log", "(", "P", "[", "counts", "]", ")", "computed", "for", "every", "batch", "member", "." ]
def log_prob(self, x, name="log_prob"): """`Log(P[counts])`, computed for every batch member. Args: x: Non-negative floating point tensor whose shape can be broadcast with `self.a` and `self.b`. For fixed leading dimensions, the last dimension represents counts for the corresponding Beta distribution in `self.a` and `self.b`. `x` is only legal if 0 < x < 1. name: Name to give this Op, defaults to "log_prob". Returns: Log probabilities for each record, shape `[N1,...,Nm]`. """ a = self._a b = self._b with ops.name_scope(self.name): with ops.op_scope([a, x], name): x = self._check_x(x) unnorm_pdf = (a - 1) * math_ops.log(x) + ( b - 1) * math_ops.log(1 - x) normalization_factor = -(math_ops.lgamma(a) + math_ops.lgamma(b) - math_ops.lgamma(a + b)) log_prob = unnorm_pdf + normalization_factor return log_prob
[ "def", "log_prob", "(", "self", ",", "x", ",", "name", "=", "\"log_prob\"", ")", ":", "a", "=", "self", ".", "_a", "b", "=", "self", ".", "_b", "with", "ops", ".", "name_scope", "(", "self", ".", "name", ")", ":", "with", "ops", ".", "op_scope", ...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/beta.py#L314-L340
CaoWGG/TensorRT-YOLOv4
4d7c2edce99e8794a4cb4ea3540d51ce91158a36
onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py
python
SourceLocation.file
(self)
return self._get_instantiation()[0]
Get the file represented by this source location.
Get the file represented by this source location.
[ "Get", "the", "file", "represented", "by", "this", "source", "location", "." ]
def file(self): """Get the file represented by this source location.""" return self._get_instantiation()[0]
[ "def", "file", "(", "self", ")", ":", "return", "self", ".", "_get_instantiation", "(", ")", "[", "0", "]" ]
https://github.com/CaoWGG/TensorRT-YOLOv4/blob/4d7c2edce99e8794a4cb4ea3540d51ce91158a36/onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py#L198-L200
lmb-freiburg/ogn
974f72ef4bf840d6f6693d22d1843a79223e77ce
python/caffe/detector.py
python
Detector.detect_windows
(self, images_windows)
return detections
Do windowed detection over given images and windows. Windows are extracted then warped to the input dimensions of the net. Parameters ---------- images_windows: (image filename, window list) iterable. context_crop: size of context border to crop in pixels. Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts.
Do windowed detection over given images and windows. Windows are extracted then warped to the input dimensions of the net.
[ "Do", "windowed", "detection", "over", "given", "images", "and", "windows", ".", "Windows", "are", "extracted", "then", "warped", "to", "the", "input", "dimensions", "of", "the", "net", "." ]
def detect_windows(self, images_windows): """ Do windowed detection over given images and windows. Windows are extracted then warped to the input dimensions of the net. Parameters ---------- images_windows: (image filename, window list) iterable. context_crop: size of context border to crop in pixels. Returns ------- detections: list of {filename: image filename, window: crop coordinates, predictions: prediction vector} dicts. """ # Extract windows. window_inputs = [] for image_fname, windows in images_windows: image = caffe.io.load_image(image_fname).astype(np.float32) for window in windows: window_inputs.append(self.crop(image, window)) # Run through the net (warping windows to input dimensions). in_ = self.inputs[0] caffe_in = np.zeros((len(window_inputs), window_inputs[0].shape[2]) + self.blobs[in_].data.shape[2:], dtype=np.float32) for ix, window_in in enumerate(window_inputs): caffe_in[ix] = self.transformer.preprocess(in_, window_in) out = self.forward_all(**{in_: caffe_in}) predictions = out[self.outputs[0]] # Package predictions with images and windows. detections = [] ix = 0 for image_fname, windows in images_windows: for window in windows: detections.append({ 'window': window, 'prediction': predictions[ix], 'filename': image_fname }) ix += 1 return detections
[ "def", "detect_windows", "(", "self", ",", "images_windows", ")", ":", "# Extract windows.", "window_inputs", "=", "[", "]", "for", "image_fname", ",", "windows", "in", "images_windows", ":", "image", "=", "caffe", ".", "io", ".", "load_image", "(", "image_fna...
https://github.com/lmb-freiburg/ogn/blob/974f72ef4bf840d6f6693d22d1843a79223e77ce/python/caffe/detector.py#L56-L99
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/model_selection/_split.py
python
BaseCrossValidator.split
(self, X, y=None, groups=None)
Generate indices to split data into training and test set. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is the number of features. y : array-like, of length n_samples The target variable for supervised learning problems. groups : array-like, with shape (n_samples,), optional Group labels for the samples used while splitting the dataset into train/test set. Returns ------- train : ndarray The training set indices for that split. test : ndarray The testing set indices for that split.
Generate indices to split data into training and test set.
[ "Generate", "indices", "to", "split", "data", "into", "training", "and", "test", "set", "." ]
def split(self, X, y=None, groups=None): """Generate indices to split data into training and test set. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is the number of features. y : array-like, of length n_samples The target variable for supervised learning problems. groups : array-like, with shape (n_samples,), optional Group labels for the samples used while splitting the dataset into train/test set. Returns ------- train : ndarray The training set indices for that split. test : ndarray The testing set indices for that split. """ X, y, groups = indexable(X, y, groups) indices = np.arange(_num_samples(X)) for test_index in self._iter_test_masks(X, y, groups): train_index = indices[np.logical_not(test_index)] test_index = indices[test_index] yield train_index, test_index
[ "def", "split", "(", "self", ",", "X", ",", "y", "=", "None", ",", "groups", "=", "None", ")", ":", "X", ",", "y", ",", "groups", "=", "indexable", "(", "X", ",", "y", ",", "groups", ")", "indices", "=", "np", ".", "arange", "(", "_num_samples"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/model_selection/_split.py#L65-L94
Illumina/manta
75b5c38d4fcd2f6961197b28a41eb61856f2d976
src/python/lib/workflowUtil.py
python
isLocalSmtp
()
return True
return true if a local smtp server is available
return true if a local smtp server is available
[ "return", "true", "if", "a", "local", "smtp", "server", "is", "available" ]
def isLocalSmtp() : """ return true if a local smtp server is available """ import smtplib try : smtplib.SMTP('localhost') except : return False return True
[ "def", "isLocalSmtp", "(", ")", ":", "import", "smtplib", "try", ":", "smtplib", ".", "SMTP", "(", "'localhost'", ")", "except", ":", "return", "False", "return", "True" ]
https://github.com/Illumina/manta/blob/75b5c38d4fcd2f6961197b28a41eb61856f2d976/src/python/lib/workflowUtil.py#L392-L401
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/sliceviewer/lineplots.py
python
RectangleSelectionLinePlot.handle_key
(self, key)
Called if a keypress was accepted to export a region :param key: str identifying key :return: A string describing the result of the operation
Called if a keypress was accepted to export a region :param key: str identifying key :return: A string describing the result of the operation
[ "Called", "if", "a", "keypress", "was", "accepted", "to", "export", "a", "region", ":", "param", "key", ":", "str", "identifying", "key", ":", "return", ":", "A", "string", "describing", "the", "result", "of", "the", "operation" ]
def handle_key(self, key): """ Called if a keypress was accepted to export a region :param key: str identifying key :return: A string describing the result of the operation """ # if the image has been moved and the selection is not visible then do nothing if not self._selector.artists[0].get_visible(): return rect = self._selector.to_draw ll_x, ll_y = rect.get_xy() limits = ((ll_x, ll_x + rect.get_width()), (ll_y, ll_y + rect.get_height())) if key == 'r': self.exporter.export_roi(limits) if key in ('c', 'x', 'y'): self.exporter.export_cut(limits, cut_type=key)
[ "def", "handle_key", "(", "self", ",", "key", ")", ":", "# if the image has been moved and the selection is not visible then do nothing", "if", "not", "self", ".", "_selector", ".", "artists", "[", "0", "]", ".", "get_visible", "(", ")", ":", "return", "rect", "="...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/sliceviewer/lineplots.py#L360-L377
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/v8/tools/release/common_includes.py
python
Step.Retry
(self, cb, retry_on=None, wait_plan=None)
Retry a function. Params: cb: The function to retry. retry_on: A callback that takes the result of the function and returns True if the function should be retried. A function throwing an exception is always retried. wait_plan: A list of waiting delays between retries in seconds. The maximum number of retries is len(wait_plan).
Retry a function. Params: cb: The function to retry. retry_on: A callback that takes the result of the function and returns True if the function should be retried. A function throwing an exception is always retried. wait_plan: A list of waiting delays between retries in seconds. The maximum number of retries is len(wait_plan).
[ "Retry", "a", "function", ".", "Params", ":", "cb", ":", "The", "function", "to", "retry", ".", "retry_on", ":", "A", "callback", "that", "takes", "the", "result", "of", "the", "function", "and", "returns", "True", "if", "the", "function", "should", "be"...
def Retry(self, cb, retry_on=None, wait_plan=None): """ Retry a function. Params: cb: The function to retry. retry_on: A callback that takes the result of the function and returns True if the function should be retried. A function throwing an exception is always retried. wait_plan: A list of waiting delays between retries in seconds. The maximum number of retries is len(wait_plan). """ retry_on = retry_on or (lambda x: False) wait_plan = list(wait_plan or []) wait_plan.reverse() while True: got_exception = False try: result = cb() except NoRetryException as e: raise e except Exception as e: got_exception = e if got_exception or retry_on(result): if not wait_plan: # pragma: no cover raise Exception("Retried too often. Giving up. Reason: %s" % str(got_exception)) wait_time = wait_plan.pop() print "Waiting for %f seconds." % wait_time self._side_effect_handler.Sleep(wait_time) print "Retrying..." else: return result
[ "def", "Retry", "(", "self", ",", "cb", ",", "retry_on", "=", "None", ",", "wait_plan", "=", "None", ")", ":", "retry_on", "=", "retry_on", "or", "(", "lambda", "x", ":", "False", ")", "wait_plan", "=", "list", "(", "wait_plan", "or", "[", "]", ")"...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/tools/release/common_includes.py#L461-L491
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/buttonpanel.py
python
ButtonPanel.SetAlignment
(self, alignment)
Sets the buttons alignment. :param integer `alignment`: can be one of the following bits: ====================== ======= ========================== Alignment Flag Value Description ====================== ======= ========================== ``BP_ALIGN_RIGHT`` 1 Buttons are aligned on the right ``BP_ALIGN_LEFT`` 2 Buttons are aligned on the left ``BP_ALIGN_TOP`` 4 Buttons are aligned at the top ``BP_ALIGN_BOTTOM`` 8 Buttons are aligned at the bottom ====================== ======= ==========================
Sets the buttons alignment.
[ "Sets", "the", "buttons", "alignment", "." ]
def SetAlignment(self, alignment): """ Sets the buttons alignment. :param integer `alignment`: can be one of the following bits: ====================== ======= ========================== Alignment Flag Value Description ====================== ======= ========================== ``BP_ALIGN_RIGHT`` 1 Buttons are aligned on the right ``BP_ALIGN_LEFT`` 2 Buttons are aligned on the left ``BP_ALIGN_TOP`` 4 Buttons are aligned at the top ``BP_ALIGN_BOTTOM`` 8 Buttons are aligned at the bottom ====================== ======= ========================== """ if alignment == self._alignment: return self.Freeze() text = self.GetBarText() # Remove the text in any case self.RemoveText() # Remove the first and last spacers self._mainsizer.Remove(0, -1) self._mainsizer.Remove(len(self._mainsizer.GetChildren())-1, -1) self._alignment = alignment # Recreate the sizer accordingly to the new alignment self.ReCreateSizer(text)
[ "def", "SetAlignment", "(", "self", ",", "alignment", ")", ":", "if", "alignment", "==", "self", ".", "_alignment", ":", "return", "self", ".", "Freeze", "(", ")", "text", "=", "self", ".", "GetBarText", "(", ")", "# Remove the text in any case", "self", "...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/buttonpanel.py#L2049-L2082
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/pkg_resources/__init__.py
python
IResourceProvider.resource_isdir
(resource_name)
Is the named resource a directory? (like ``os.path.isdir()``)
Is the named resource a directory? (like ``os.path.isdir()``)
[ "Is", "the", "named", "resource", "a", "directory?", "(", "like", "os", ".", "path", ".", "isdir", "()", ")" ]
def resource_isdir(resource_name): """Is the named resource a directory? (like ``os.path.isdir()``)"""
[ "def", "resource_isdir", "(", "resource_name", ")", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/__init__.py#L536-L537
GeometryCollective/boundary-first-flattening
8250e5a0e85980ec50b5e8aa8f49dd6519f915cd
deps/nanogui/ext/pybind11/tools/clang/cindex.py
python
SourceLocation.offset
(self)
return self._get_instantiation()[3]
Get the file offset represented by this source location.
Get the file offset represented by this source location.
[ "Get", "the", "file", "offset", "represented", "by", "this", "source", "location", "." ]
def offset(self): """Get the file offset represented by this source location.""" return self._get_instantiation()[3]
[ "def", "offset", "(", "self", ")", ":", "return", "self", ".", "_get_instantiation", "(", ")", "[", "3", "]" ]
https://github.com/GeometryCollective/boundary-first-flattening/blob/8250e5a0e85980ec50b5e8aa8f49dd6519f915cd/deps/nanogui/ext/pybind11/tools/clang/cindex.py#L213-L215
facebook/ThreatExchange
31914a51820c73c8a0daffe62ccca29a6e3d359e
api-reference-examples/python/pytx/pytx/common.py
python
Common.__init__
(self, **kwargs)
Initialize the object. Set any attributes that were provided.
Initialize the object. Set any attributes that were provided.
[ "Initialize", "the", "object", ".", "Set", "any", "attributes", "that", "were", "provided", "." ]
def __init__(self, **kwargs): """ Initialize the object. Set any attributes that were provided. """ for name, value in kwargs.items(): self.__setattr__(name, value)
[ "def", "__init__", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "name", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "self", ".", "__setattr__", "(", "name", ",", "value", ")" ]
https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/api-reference-examples/python/pytx/pytx/common.py#L56-L62
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py
python
_MaskedBinaryOperation.__init__
(self, mbfunc, fillx=0, filly=0)
abfunc(fillx, filly) must be defined. abfunc(x, filly) = x for all x to enable reduce.
abfunc(fillx, filly) must be defined.
[ "abfunc", "(", "fillx", "filly", ")", "must", "be", "defined", "." ]
def __init__(self, mbfunc, fillx=0, filly=0): """ abfunc(fillx, filly) must be defined. abfunc(x, filly) = x for all x to enable reduce. """ super(_MaskedBinaryOperation, self).__init__(mbfunc) self.fillx = fillx self.filly = filly ufunc_domain[mbfunc] = None ufunc_fills[mbfunc] = (fillx, filly)
[ "def", "__init__", "(", "self", ",", "mbfunc", ",", "fillx", "=", "0", ",", "filly", "=", "0", ")", ":", "super", "(", "_MaskedBinaryOperation", ",", "self", ")", ".", "__init__", "(", "mbfunc", ")", "self", ".", "fillx", "=", "fillx", "self", ".", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/core.py#L1003-L1014
asLody/whale
6a661b27cc4cf83b7b5a3b02451597ee1ac7f264
whale/cpplint.py
python
_BlockInfo.CheckEnd
(self, filename, clean_lines, linenum, error)
Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Run checks that applies to text after the closing brace.
[ "Run", "checks", "that", "applies", "to", "text", "after", "the", "closing", "brace", "." ]
def CheckEnd(self, filename, clean_lines, linenum, error): """Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass
[ "def", "CheckEnd", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "pass" ]
https://github.com/asLody/whale/blob/6a661b27cc4cf83b7b5a3b02451597ee1ac7f264/whale/cpplint.py#L2230-L2241
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/optimizer/optimizer.py
python
Optimizer.fused_step
(self, indices, weights, grads, states)
Perform a fused optimization step using gradients and states. New operators that fuses optimizer's update should be put in this function. Parameters ---------- indices : list of int List of unique indices of the parameters into the individual learning rates and weight decays. Learning rates and weight decay may be set via `set_lr_mult()` and `set_wd_mult()`, respectively. weights : list of NDArray List of parameters to be updated. grads : list of NDArray List of gradients of the objective with respect to this parameter. states : List of any obj List of state returned by `create_state()`.
Perform a fused optimization step using gradients and states. New operators that fuses optimizer's update should be put in this function.
[ "Perform", "a", "fused", "optimization", "step", "using", "gradients", "and", "states", ".", "New", "operators", "that", "fuses", "optimizer", "s", "update", "should", "be", "put", "in", "this", "function", "." ]
def fused_step(self, indices, weights, grads, states): """Perform a fused optimization step using gradients and states. New operators that fuses optimizer's update should be put in this function. Parameters ---------- indices : list of int List of unique indices of the parameters into the individual learning rates and weight decays. Learning rates and weight decay may be set via `set_lr_mult()` and `set_wd_mult()`, respectively. weights : list of NDArray List of parameters to be updated. grads : list of NDArray List of gradients of the objective with respect to this parameter. states : List of any obj List of state returned by `create_state()`. """ raise NotImplementedError
[ "def", "fused_step", "(", "self", ",", "indices", ",", "weights", ",", "grads", ",", "states", ")", ":", "raise", "NotImplementedError" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/optimizer/optimizer.py#L276-L293
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/__init__.py
python
Logger.debug
(self, msg, *args, **kwargs)
Log 'msg % args' with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
Log 'msg % args' with severity 'DEBUG'.
[ "Log", "msg", "%", "args", "with", "severity", "DEBUG", "." ]
def debug(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.debug("Houston, we have a %s", "thorny problem", exc_info=1) """ if self.isEnabledFor(DEBUG): self._log(DEBUG, msg, args, **kwargs)
[ "def", "debug", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "isEnabledFor", "(", "DEBUG", ")", ":", "self", ".", "_log", "(", "DEBUG", ",", "msg", ",", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/logging/__init__.py#L1356-L1366
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/message.py
python
Message.IsInitialized
(self)
Checks if the message is initialized. Returns: The method returns True if the message is initialized (i.e. all of its required fields are set).
Checks if the message is initialized.
[ "Checks", "if", "the", "message", "is", "initialized", "." ]
def IsInitialized(self): """Checks if the message is initialized. Returns: The method returns True if the message is initialized (i.e. all of its required fields are set). """ raise NotImplementedError
[ "def", "IsInitialized", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/message.py#L134-L141
alexgkendall/caffe-segnet
344c113bf1832886f1cbe9f33ffe28a3beeaf412
scripts/cpp_lint.py
python
CheckCaffeDataLayerSetUp
(filename, clean_lines, linenum, error)
Except the base classes, Caffe DataLayer should define DataLayerSetUp instead of LayerSetUp. The base DataLayers define common SetUp steps, the subclasses should not override them. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Except the base classes, Caffe DataLayer should define DataLayerSetUp instead of LayerSetUp. The base DataLayers define common SetUp steps, the subclasses should not override them. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
[ "Except", "the", "base", "classes", "Caffe", "DataLayer", "should", "define", "DataLayerSetUp", "instead", "of", "LayerSetUp", ".", "The", "base", "DataLayers", "define", "common", "SetUp", "steps", "the", "subclasses", "should", "not", "override", "them", ".", ...
def CheckCaffeDataLayerSetUp(filename, clean_lines, linenum, error): """Except the base classes, Caffe DataLayer should define DataLayerSetUp instead of LayerSetUp. The base DataLayers define common SetUp steps, the subclasses should not override them. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] ix = line.find('DataLayer<Dtype>::LayerSetUp') if ix >= 0 and ( line.find('void DataLayer<Dtype>::LayerSetUp') != -1 or line.find('void ImageDataLayer<Dtype>::LayerSetUp') != -1 or line.find('void MemoryDataLayer<Dtype>::LayerSetUp') != -1 or line.find('void WindowDataLayer<Dtype>::LayerSetUp') != -1): error(filename, linenum, 'caffe/data_layer_setup', 2, 'Except the base classes, Caffe DataLayer should define' + ' DataLayerSetUp instead of LayerSetUp. The base DataLayers' + ' define common SetUp steps, the subclasses should' + ' not override them.') ix = line.find('DataLayer<Dtype>::DataLayerSetUp') if ix >= 0 and ( line.find('void Base') == -1 and line.find('void DataLayer<Dtype>::DataLayerSetUp') == -1 and line.find('void ImageDataLayer<Dtype>::DataLayerSetUp') == -1 and line.find('void MemoryDataLayer<Dtype>::DataLayerSetUp') == -1 and line.find('void WindowDataLayer<Dtype>::DataLayerSetUp') == -1): error(filename, linenum, 'caffe/data_layer_setup', 2, 'Except the base classes, Caffe DataLayer should define' + ' DataLayerSetUp instead of LayerSetUp. The base DataLayers' + ' define common SetUp steps, the subclasses should' + ' not override them.')
[ "def", "CheckCaffeDataLayerSetUp", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "ix", "=", "line", ".", "find", "(", "'DataLayer<Dtype>::LayerSetUp'", ")", "if", ...
https://github.com/alexgkendall/caffe-segnet/blob/344c113bf1832886f1cbe9f33ffe28a3beeaf412/scripts/cpp_lint.py#L1595-L1631
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
RadioButton.GetValue
(*args, **kwargs)
return _controls_.RadioButton_GetValue(*args, **kwargs)
GetValue(self) -> bool
GetValue(self) -> bool
[ "GetValue", "(", "self", ")", "-", ">", "bool" ]
def GetValue(*args, **kwargs): """GetValue(self) -> bool""" return _controls_.RadioButton_GetValue(*args, **kwargs)
[ "def", "GetValue", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "RadioButton_GetValue", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L2747-L2749
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/experimental/rpc/rpc_ops.py
python
GrpcClient._add_method
(self, method_name, output_specs, input_specs, client_handle, doc_string)
Method to add RPC methods to the client object.
Method to add RPC methods to the client object.
[ "Method", "to", "add", "RPC", "methods", "to", "the", "client", "object", "." ]
def _add_method(self, method_name, output_specs, input_specs, client_handle, doc_string): """Method to add RPC methods to the client object.""" def validate_and_get_flat_inputs(*args): if args is None: args = [] if input_specs: nest.assert_same_structure(args, input_specs) flat_inputs = nest.flatten(args) return flat_inputs def call_wrapper(*args, timeout_in_ms=0): status_or, deleter = gen_rpc_ops.rpc_call( client_handle, args=validate_and_get_flat_inputs(*args), method_name=method_name, timeout_in_ms=timeout_in_ms) return StatusOrResult(status_or, deleter, output_specs) def call_blocking_wrapper(*args, timeout_in_ms=0): status_or, deleter = gen_rpc_ops.rpc_call( client_handle, args=validate_and_get_flat_inputs(*args), method_name=method_name, timeout_in_ms=timeout_in_ms) status_or = StatusOrResult(status_or, deleter, output_specs) if status_or.is_ok(): return status_or.get_value() else: error_code, error_msg = status_or.get_error() raise errors.exception_type_from_error_code(error_code.numpy())( None, None, error_msg.numpy()) setattr(self, method_name, call_wrapper) call_wrapper.__doc__ = doc_string blocking_method_name = method_name + "_blocking" setattr(self, blocking_method_name, call_blocking_wrapper) call_blocking_wrapper.__doc__ = doc_string
[ "def", "_add_method", "(", "self", ",", "method_name", ",", "output_specs", ",", "input_specs", ",", "client_handle", ",", "doc_string", ")", ":", "def", "validate_and_get_flat_inputs", "(", "*", "args", ")", ":", "if", "args", "is", "None", ":", "args", "="...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/experimental/rpc/rpc_ops.py#L367-L406
llvm-dcpu16/llvm-dcpu16
ae6b01fecd03219677e391d4421df5d966d80dcf
bindings/python/llvm/object.py
python
Relocation.expire
(self)
Expire this instance, making future API accesses fail.
Expire this instance, making future API accesses fail.
[ "Expire", "this", "instance", "making", "future", "API", "accesses", "fail", "." ]
def expire(self): """Expire this instance, making future API accesses fail.""" self.expired = True
[ "def", "expire", "(", "self", ")", ":", "self", ".", "expired", "=", "True" ]
https://github.com/llvm-dcpu16/llvm-dcpu16/blob/ae6b01fecd03219677e391d4421df5d966d80dcf/bindings/python/llvm/object.py#L423-L425
dartsim/dart
495c82120c836005f2d136d4a50c8cc997fb879b
tools/cpplint.py
python
_FunctionState.Count
(self)
Count line in current function body.
Count line in current function body.
[ "Count", "line", "in", "current", "function", "body", "." ]
def Count(self): """Count line in current function body.""" if self.in_a_function: self.lines_in_function += 1
[ "def", "Count", "(", "self", ")", ":", "if", "self", ".", "in_a_function", ":", "self", ".", "lines_in_function", "+=", "1" ]
https://github.com/dartsim/dart/blob/495c82120c836005f2d136d4a50c8cc997fb879b/tools/cpplint.py#L808-L811
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
tools/i-pi/ipi/engine/normalmodes.py
python
NormalModes.get_kins
(self)
return kmd
Gets the MD kinetic energy for all the normal modes. Returns: A list of the kinetic energy for each NM.
Gets the MD kinetic energy for all the normal modes.
[ "Gets", "the", "MD", "kinetic", "energy", "for", "all", "the", "normal", "modes", "." ]
def get_kins(self): """Gets the MD kinetic energy for all the normal modes. Returns: A list of the kinetic energy for each NM. """ kmd = np.zeros(self.nbeads,float) sm = depstrip(self.beads.sm3[0]) pnm = depstrip(self.pnm) nmf = depstrip(self.nm_factor) # computes the MD ke in the normal modes representation, to properly account for CMD mass scaling for b in range(self.nbeads): sp = pnm[b]/sm # mass-scaled momentum of b-th NM kmd[b] = np.dot(sp,sp)*0.5/nmf[b] # include the partially adiabatic CMD mass scaling return kmd
[ "def", "get_kins", "(", "self", ")", ":", "kmd", "=", "np", ".", "zeros", "(", "self", ".", "nbeads", ",", "float", ")", "sm", "=", "depstrip", "(", "self", ".", "beads", ".", "sm3", "[", "0", "]", ")", "pnm", "=", "depstrip", "(", "self", ".",...
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/engine/normalmodes.py#L344-L361
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
modules/stochastic_tools/python/stochastic/histogram.py
python
command_line_options
()
return parser.parse_args()
Command-line options for histogram tool.
Command-line options for histogram tool.
[ "Command", "-", "line", "options", "for", "histogram", "tool", "." ]
def command_line_options(): """ Command-line options for histogram tool. """ parser = argparse.ArgumentParser(description="Command-line utility for creating histograms from VectorPostprocessor data.") parser.add_argument('filename', type=str, help="The VectorPostprocessor data file pattern to open, for sample 'foo_x_*.csv'.") parser.add_argument('-t', '--timesteps', default=[-1], nargs='+', type=int, help="List of timesteps to consider, by default only the final timestep is shown.") parser.add_argument('-v', '--vectors', default=[], nargs='+', type=str, help="List of vector names to consider, by default all vectors are shown.") parser.add_argument('--bins', default=None, type=int, help="Number of bins to consider.") parser.add_argument('--alpha', default=0.5, type=float, help="Set the bar chart opacity alpha setting.") parser.add_argument('--xlabel', default='Value', type=str, help="The X-axis label.") parser.add_argument('--ylabel', default='Probability', type=str, help="The X-axis label.") parser.add_argument('--uniform', default=None, type=float, nargs=2, help="Show a uniform distribution between a and b (e.g., --uniform 8 10).") parser.add_argument('--weibull', default=None, type=float, nargs=2, help="Show a Weibull distribution with given shape and scale parameters (e.g., --uniform 1 5).") return parser.parse_args()
[ "def", "command_line_options", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Command-line utility for creating histograms from VectorPostprocessor data.\"", ")", "parser", ".", "add_argument", "(", "'filename'", ",", "type", ...
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/modules/stochastic_tools/python/stochastic/histogram.py#L19-L33
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/extras/codelite.py
python
codelite_generator.collect_dirs
(self)
Create the folder structure in the CodeLite project view
Create the folder structure in the CodeLite project view
[ "Create", "the", "folder", "structure", "in", "the", "CodeLite", "project", "view" ]
def collect_dirs(self): """ Create the folder structure in the CodeLite project view """ seen = {} def make_parents(proj): # look at a project, try to make a parent if getattr(proj, 'parent', None): # aliases already have parents return x = proj.iter_path if x in seen: proj.parent = seen[x] return # There is not vsnode_vsdir for x. # So create a project representing the folder "x" n = proj.parent = seen[x] = self.vsnode_vsdir(self, make_uuid(x.abspath()), x.name) n.iter_path = x.parent self.all_projects.append(n) # recurse up to the project directory if x.height() > self.srcnode.height() + 1: make_parents(n) for p in self.all_projects[:]: # iterate over a copy of all projects if not getattr(p, 'tg', None): # but only projects that have a task generator continue # make a folder for each task generator p.iter_path = p.tg.path make_parents(p)
[ "def", "collect_dirs", "(", "self", ")", ":", "seen", "=", "{", "}", "def", "make_parents", "(", "proj", ")", ":", "# look at a project, try to make a parent", "if", "getattr", "(", "proj", ",", "'parent'", ",", "None", ")", ":", "# aliases already have parents"...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/extras/codelite.py#L843-L875
facebookincubator/katran
192eb988c398afc673620254097defb7035d669e
build/fbcode_builder/getdeps/copytree.py
python
prefetch_dir_if_eden
(dirpath)
After an amend/rebase, Eden may need to fetch a large number of trees from the servers. The simplistic single threaded walk performed by copytree makes this more expensive than is desirable so we help accelerate things by performing a prefetch on the source directory
After an amend/rebase, Eden may need to fetch a large number of trees from the servers. The simplistic single threaded walk performed by copytree makes this more expensive than is desirable so we help accelerate things by performing a prefetch on the source directory
[ "After", "an", "amend", "/", "rebase", "Eden", "may", "need", "to", "fetch", "a", "large", "number", "of", "trees", "from", "the", "servers", ".", "The", "simplistic", "single", "threaded", "walk", "performed", "by", "copytree", "makes", "this", "more", "e...
def prefetch_dir_if_eden(dirpath): """After an amend/rebase, Eden may need to fetch a large number of trees from the servers. The simplistic single threaded walk performed by copytree makes this more expensive than is desirable so we help accelerate things by performing a prefetch on the source directory""" global PREFETCHED_DIRS if dirpath in PREFETCHED_DIRS: return root = find_eden_root(dirpath) if root is None: return glob = f"{os.path.relpath(dirpath, root).replace(os.sep, '/')}/**" print(f"Prefetching {glob}") subprocess.call( ["edenfsctl", "prefetch", "--repo", root, "--silent", glob, "--background"] ) PREFETCHED_DIRS.add(dirpath)
[ "def", "prefetch_dir_if_eden", "(", "dirpath", ")", ":", "global", "PREFETCHED_DIRS", "if", "dirpath", "in", "PREFETCHED_DIRS", ":", "return", "root", "=", "find_eden_root", "(", "dirpath", ")", "if", "root", "is", "None", ":", "return", "glob", "=", "f\"{os.p...
https://github.com/facebookincubator/katran/blob/192eb988c398afc673620254097defb7035d669e/build/fbcode_builder/getdeps/copytree.py#L48-L65
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/fleet/data_generator/data_generator.py
python
MultiSlotDataGenerator._gen_str
(self, line)
return output + "\n"
Further processing the output of the process() function rewritten by user, outputting data that can be directly read by the MultiSlotDataFeed, and updating proto_info information. The input line will be in this format: >>> [(name, [feasign, ...]), ...] >>> or ((name, [feasign, ...]), ...) The output will be in this format: >>> [ids_num id1 id2 ...] ... The proto_info will be in this format: >>> [(name, type), ...] For example, if the input is like this: >>> [("words", [1926, 08, 17]), ("label", [1])] >>> or (("words", [1926, 08, 17]), ("label", [1])) the output will be: >>> 3 1234 2345 3456 1 1 the proto_info will be: >>> [("words", "uint64"), ("label", "uint64")] Args: line(str): the output of the process() function rewritten by user. Returns: Return a string data that can be read directly by the MultiSlotDataFeed.
Further processing the output of the process() function rewritten by user, outputting data that can be directly read by the MultiSlotDataFeed, and updating proto_info information.
[ "Further", "processing", "the", "output", "of", "the", "process", "()", "function", "rewritten", "by", "user", "outputting", "data", "that", "can", "be", "directly", "read", "by", "the", "MultiSlotDataFeed", "and", "updating", "proto_info", "information", "." ]
def _gen_str(self, line): ''' Further processing the output of the process() function rewritten by user, outputting data that can be directly read by the MultiSlotDataFeed, and updating proto_info information. The input line will be in this format: >>> [(name, [feasign, ...]), ...] >>> or ((name, [feasign, ...]), ...) The output will be in this format: >>> [ids_num id1 id2 ...] ... The proto_info will be in this format: >>> [(name, type), ...] For example, if the input is like this: >>> [("words", [1926, 08, 17]), ("label", [1])] >>> or (("words", [1926, 08, 17]), ("label", [1])) the output will be: >>> 3 1234 2345 3456 1 1 the proto_info will be: >>> [("words", "uint64"), ("label", "uint64")] Args: line(str): the output of the process() function rewritten by user. Returns: Return a string data that can be read directly by the MultiSlotDataFeed. ''' if sys.version > '3' and isinstance(line, zip): line = list(line) if not isinstance(line, list) and not isinstance(line, tuple): raise ValueError( "the output of process() must be in list or tuple type" "Example: [('words', [1926, 08, 17]), ('label', [1])]") output = "" if self._proto_info is None: self._proto_info = [] for item in line: name, elements = item if not isinstance(name, str): raise ValueError("name%s must be in str type" % type(name)) if not isinstance(elements, list): raise ValueError("elements%s must be in list type" % type(elements)) if not elements: raise ValueError( "the elements of each field can not be empty, you need padding it in process()." ) self._proto_info.append((name, "uint64")) if output: output += " " output += str(len(elements)) for elem in elements: if isinstance(elem, float): self._proto_info[-1] = (name, "float") elif not isinstance(elem, int) and not isinstance(elem, long): raise ValueError( "the type of element%s must be in int or float" % type(elem)) output += " " + str(elem) else: if len(line) != len(self._proto_info): raise ValueError( "the complete field set of two given line are inconsistent.") for index, item in enumerate(line): name, elements = item if not isinstance(name, str): raise ValueError("name%s must be in str type" % type(name)) if not isinstance(elements, list): raise ValueError("elements%s must be in list type" % type(elements)) if not elements: raise ValueError( "the elements of each field can not be empty, you need padding it in process()." ) if name != self._proto_info[index][0]: raise ValueError( "the field name of two given line are not match: require<%s>, get<%s>." % (self._proto_info[index][0], name)) if output: output += " " output += str(len(elements)) for elem in elements: if self._proto_info[index][1] != "float": if isinstance(elem, float): self._proto_info[index] = (name, "float") elif not isinstance(elem, int) and not isinstance(elem, long): raise ValueError( "the type of element%s must be in int or float" % type(elem)) output += " " + str(elem) return output + "\n"
[ "def", "_gen_str", "(", "self", ",", "line", ")", ":", "if", "sys", ".", "version", ">", "'3'", "and", "isinstance", "(", "line", ",", "zip", ")", ":", "line", "=", "list", "(", "line", ")", "if", "not", "isinstance", "(", "line", ",", "list", ")...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/fleet/data_generator/data_generator.py#L284-L379
jackaudio/jack2
21b293dbc37d42446141a08922cdec0d2550c6a0
waflib/Tools/ar.py
python
find_ar
(conf)
Configuration helper used by C/C++ tools to enable the support for static libraries
Configuration helper used by C/C++ tools to enable the support for static libraries
[ "Configuration", "helper", "used", "by", "C", "/", "C", "++", "tools", "to", "enable", "the", "support", "for", "static", "libraries" ]
def find_ar(conf): """Configuration helper used by C/C++ tools to enable the support for static libraries""" conf.load('ar')
[ "def", "find_ar", "(", "conf", ")", ":", "conf", ".", "load", "(", "'ar'", ")" ]
https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Tools/ar.py#L14-L16
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/linalg/_interpolative_backend.py
python
iddr_asvd
(A, k)
return U, V, S
Compute SVD of a real matrix to a specified rank using random sampling. :param A: Matrix. :type A: :class:`numpy.ndarray` :param k: Rank of SVD. :type k: int :return: Left singular vectors. :rtype: :class:`numpy.ndarray` :return: Right singular vectors. :rtype: :class:`numpy.ndarray` :return: Singular values. :rtype: :class:`numpy.ndarray`
Compute SVD of a real matrix to a specified rank using random sampling.
[ "Compute", "SVD", "of", "a", "real", "matrix", "to", "a", "specified", "rank", "using", "random", "sampling", "." ]
def iddr_asvd(A, k): """ Compute SVD of a real matrix to a specified rank using random sampling. :param A: Matrix. :type A: :class:`numpy.ndarray` :param k: Rank of SVD. :type k: int :return: Left singular vectors. :rtype: :class:`numpy.ndarray` :return: Right singular vectors. :rtype: :class:`numpy.ndarray` :return: Singular values. :rtype: :class:`numpy.ndarray` """ A = np.asfortranarray(A) m, n = A.shape w = np.empty((2*k + 28)*m + (6*k + 21)*n + 25*k**2 + 100, order='F') w_ = iddr_aidi(m, n, k) w[:w_.size] = w_ U, V, S, ier = _id.iddr_asvd(A, k, w) if ier != 0: raise _RETCODE_ERROR return U, V, S
[ "def", "iddr_asvd", "(", "A", ",", "k", ")", ":", "A", "=", "np", ".", "asfortranarray", "(", "A", ")", "m", ",", "n", "=", "A", ".", "shape", "w", "=", "np", ".", "empty", "(", "(", "2", "*", "k", "+", "28", ")", "*", "m", "+", "(", "6...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/linalg/_interpolative_backend.py#L761-L790
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/mturk/connection.py
python
MTurkConnection.set_rest_notification
(self, hit_type, url, event_types=None)
return self._set_notification(hit_type, 'REST', url, 'SetHITTypeNotification', event_types)
Performs a SetHITTypeNotification operation to set REST notification for a specified HIT type
Performs a SetHITTypeNotification operation to set REST notification for a specified HIT type
[ "Performs", "a", "SetHITTypeNotification", "operation", "to", "set", "REST", "notification", "for", "a", "specified", "HIT", "type" ]
def set_rest_notification(self, hit_type, url, event_types=None): """ Performs a SetHITTypeNotification operation to set REST notification for a specified HIT type """ return self._set_notification(hit_type, 'REST', url, 'SetHITTypeNotification', event_types)
[ "def", "set_rest_notification", "(", "self", ",", "hit_type", ",", "url", ",", "event_types", "=", "None", ")", ":", "return", "self", ".", "_set_notification", "(", "hit_type", ",", "'REST'", ",", "url", ",", "'SetHITTypeNotification'", ",", "event_types", ")...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/mturk/connection.py#L112-L118
GeometryCollective/boundary-first-flattening
8250e5a0e85980ec50b5e8aa8f49dd6519f915cd
deps/nanogui/docs/exhale.py
python
ExhaleRoot.parse
(self)
The first method that should be called after creating an ExhaleRoot object. The Breathe graph is parsed first, followed by the Doxygen xml documents. By the end of this method, all of the ``self.<breathe_kind>``, ``self.all_compounds``, and ``self.all_nodes`` lists as well as the ``self.node_by_refid`` dictionary will be populated. Lastly, this method sorts all of the internal lists. The order of execution is exactly 1. :func:`exhale.ExhaleRoot.discoverAllNodes` 2. :func:`exhale.ExhaleRoot.reparentAll` 3. Populate ``self.node_by_refid`` using ``self.all_nodes``. 4. :func:`exhale.ExhaleRoot.fileRefDiscovery` 5. :func:`exhale.ExhaleRoot.filePostProcess` 6. :func:`exhale.ExhaleRoot.sortInternals`
The first method that should be called after creating an ExhaleRoot object. The Breathe graph is parsed first, followed by the Doxygen xml documents. By the end of this method, all of the ``self.<breathe_kind>``, ``self.all_compounds``, and ``self.all_nodes`` lists as well as the ``self.node_by_refid`` dictionary will be populated. Lastly, this method sorts all of the internal lists. The order of execution is exactly
[ "The", "first", "method", "that", "should", "be", "called", "after", "creating", "an", "ExhaleRoot", "object", ".", "The", "Breathe", "graph", "is", "parsed", "first", "followed", "by", "the", "Doxygen", "xml", "documents", ".", "By", "the", "end", "of", "...
def parse(self): ''' The first method that should be called after creating an ExhaleRoot object. The Breathe graph is parsed first, followed by the Doxygen xml documents. By the end of this method, all of the ``self.<breathe_kind>``, ``self.all_compounds``, and ``self.all_nodes`` lists as well as the ``self.node_by_refid`` dictionary will be populated. Lastly, this method sorts all of the internal lists. The order of execution is exactly 1. :func:`exhale.ExhaleRoot.discoverAllNodes` 2. :func:`exhale.ExhaleRoot.reparentAll` 3. Populate ``self.node_by_refid`` using ``self.all_nodes``. 4. :func:`exhale.ExhaleRoot.fileRefDiscovery` 5. :func:`exhale.ExhaleRoot.filePostProcess` 6. :func:`exhale.ExhaleRoot.sortInternals` ''' # Find and reparent everything from the Breathe graph. self.discoverAllNodes() self.reparentAll() # now that we have all of the nodes, store them in a convenient manner for refid # lookup when parsing the Doxygen xml files for n in self.all_nodes: self.node_by_refid[n.refid] = n # find missing relationships using the Doxygen xml files self.fileRefDiscovery() self.filePostProcess() # sort all of the lists we just built self.sortInternals()
[ "def", "parse", "(", "self", ")", ":", "# Find and reparent everything from the Breathe graph.", "self", ".", "discoverAllNodes", "(", ")", "self", ".", "reparentAll", "(", ")", "# now that we have all of the nodes, store them in a convenient manner for refid", "# lookup when par...
https://github.com/GeometryCollective/boundary-first-flattening/blob/8250e5a0e85980ec50b5e8aa8f49dd6519f915cd/deps/nanogui/docs/exhale.py#L1435-L1465
vslavik/poedit
f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a
deps/boost/tools/build/src/build/type.py
python
is_derived
(type, base)
Returns true if 'type' is 'base' or has 'base' as its direct or indirect base.
Returns true if 'type' is 'base' or has 'base' as its direct or indirect base.
[ "Returns", "true", "if", "type", "is", "base", "or", "has", "base", "as", "its", "direct", "or", "indirect", "base", "." ]
def is_derived (type, base): """ Returns true if 'type' is 'base' or has 'base' as its direct or indirect base. """ assert isinstance(type, basestring) assert isinstance(base, basestring) # TODO: this isn't very efficient, especially for bases close to type if base in all_bases (type): return True else: return False
[ "def", "is_derived", "(", "type", ",", "base", ")", ":", "assert", "isinstance", "(", "type", ",", "basestring", ")", "assert", "isinstance", "(", "base", ",", "basestring", ")", "# TODO: this isn't very efficient, especially for bases close to type", "if", "base", ...
https://github.com/vslavik/poedit/blob/f7a9daa0a10037e090aa0a86f5ce0f24ececdf6a/deps/boost/tools/build/src/build/type.py#L202-L211
SonarOpenCommunity/sonar-cxx
6e1d456fdcd45d35bcdc61c980e34d85fe88971e
cxx-squid/dox/tools/grammar_parser/grammar_parser.py
python
GrammarParser.use
(self, search)
Search all rules using an expression and remove all other rules.
Search all rules using an expression and remove all other rules.
[ "Search", "all", "rules", "using", "an", "expression", "and", "remove", "all", "other", "rules", "." ]
def use(self, search): """ Search all rules using an expression and remove all other rules. """ rules = {} if search in self.rules: rules[search] = self.rules[search] for rulename, sequences in self.rules.items(): if self.__rule_use_expression(search, sequences): rules[rulename] = sequences self.rules = rules
[ "def", "use", "(", "self", ",", "search", ")", ":", "rules", "=", "{", "}", "if", "search", "in", "self", ".", "rules", ":", "rules", "[", "search", "]", "=", "self", ".", "rules", "[", "search", "]", "for", "rulename", ",", "sequences", "in", "s...
https://github.com/SonarOpenCommunity/sonar-cxx/blob/6e1d456fdcd45d35bcdc61c980e34d85fe88971e/cxx-squid/dox/tools/grammar_parser/grammar_parser.py#L137-L147
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/image_ops_impl.py
python
adjust_gamma
(image, gamma=1, gain=1)
Performs Gamma Correction on the input image. Also known as Power Law Transform. This function converts the input images at first to float representation, then transforms them pixelwise according to the equation `Out = gain * In**gamma`, and then converts the back to the original data type. Args: image : RGB image or images to adjust. gamma : A scalar or tensor. Non negative real number. gain : A scalar or tensor. The constant multiplier. Returns: A Tensor. A Gamma-adjusted tensor of the same shape and type as `image`. Usage Example: ```python >> import tensorflow as tf >> x = tf.random.normal(shape=(256, 256, 3)) >> tf.image.adjust_gamma(x, 0.2) ``` Raises: ValueError: If gamma is negative. Notes: For gamma greater than 1, the histogram will shift towards left and the output image will be darker than the input image. For gamma less than 1, the histogram will shift towards right and the output image will be brighter than the input image. References: [1] http://en.wikipedia.org/wiki/Gamma_correction
Performs Gamma Correction on the input image.
[ "Performs", "Gamma", "Correction", "on", "the", "input", "image", "." ]
def adjust_gamma(image, gamma=1, gain=1): """Performs Gamma Correction on the input image. Also known as Power Law Transform. This function converts the input images at first to float representation, then transforms them pixelwise according to the equation `Out = gain * In**gamma`, and then converts the back to the original data type. Args: image : RGB image or images to adjust. gamma : A scalar or tensor. Non negative real number. gain : A scalar or tensor. The constant multiplier. Returns: A Tensor. A Gamma-adjusted tensor of the same shape and type as `image`. Usage Example: ```python >> import tensorflow as tf >> x = tf.random.normal(shape=(256, 256, 3)) >> tf.image.adjust_gamma(x, 0.2) ``` Raises: ValueError: If gamma is negative. Notes: For gamma greater than 1, the histogram will shift towards left and the output image will be darker than the input image. For gamma less than 1, the histogram will shift towards right and the output image will be brighter than the input image. References: [1] http://en.wikipedia.org/wiki/Gamma_correction """ with ops.name_scope(None, 'adjust_gamma', [image, gamma, gain]) as name: image = ops.convert_to_tensor(image, name='image') # Remember original dtype to so we can convert back if needed orig_dtype = image.dtype if orig_dtype in [dtypes.float16, dtypes.float32]: flt_image = image else: flt_image = convert_image_dtype(image, dtypes.float32) assert_op = _assert(gamma >= 0, ValueError, 'Gamma should be a non-negative real number.') if assert_op: gamma = control_flow_ops.with_dependencies(assert_op, gamma) # According to the definition of gamma correction. adjusted_img = gain * flt_image**gamma return convert_image_dtype(adjusted_img, orig_dtype, saturate=True)
[ "def", "adjust_gamma", "(", "image", ",", "gamma", "=", "1", ",", "gain", "=", "1", ")", ":", "with", "ops", ".", "name_scope", "(", "None", ",", "'adjust_gamma'", ",", "[", "image", ",", "gamma", ",", "gain", "]", ")", "as", "name", ":", "image", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/image_ops_impl.py#L1675-L1725
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
pooling_2d
(handle, x, odd_padding=(0, 0, 0, 0))
return _Pooling2d(handle, odd_padding)(x)[0]
Pooling 2d operator Args: handle (object): PoolingHandle for cpu or CudnnPoolingHandle for gpu x (Tensor): input odd_padding (tuple of four int): the odd paddding is the value that cannot be handled by the tuple padding (w, h) mode so it needs to firstly handle the input, then use the normal padding method. Returns: the result Tensor
Pooling 2d operator Args: handle (object): PoolingHandle for cpu or CudnnPoolingHandle for gpu x (Tensor): input odd_padding (tuple of four int): the odd paddding is the value that cannot be handled by the tuple padding (w, h) mode so it needs to firstly handle the input, then use the normal padding method. Returns: the result Tensor
[ "Pooling", "2d", "operator", "Args", ":", "handle", "(", "object", ")", ":", "PoolingHandle", "for", "cpu", "or", "CudnnPoolingHandle", "for", "gpu", "x", "(", "Tensor", ")", ":", "input", "odd_padding", "(", "tuple", "of", "four", "int", ")", ":", "the"...
def pooling_2d(handle, x, odd_padding=(0, 0, 0, 0)): """ Pooling 2d operator Args: handle (object): PoolingHandle for cpu or CudnnPoolingHandle for gpu x (Tensor): input odd_padding (tuple of four int): the odd paddding is the value that cannot be handled by the tuple padding (w, h) mode so it needs to firstly handle the input, then use the normal padding method. Returns: the result Tensor """ return _Pooling2d(handle, odd_padding)(x)[0]
[ "def", "pooling_2d", "(", "handle", ",", "x", ",", "odd_padding", "=", "(", "0", ",", "0", ",", "0", ",", "0", ")", ")", ":", "return", "_Pooling2d", "(", "handle", ",", "odd_padding", ")", "(", "x", ")", "[", "0", "]" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L1904-L1918
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/affine/promote.py
python
Promote.is_symmetric
(self)
return self.ndim == 2 and self.shape[0] == self.shape[1]
Is the expression symmetric?
Is the expression symmetric?
[ "Is", "the", "expression", "symmetric?" ]
def is_symmetric(self) -> bool: """Is the expression symmetric? """ return self.ndim == 2 and self.shape[0] == self.shape[1]
[ "def", "is_symmetric", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "ndim", "==", "2", "and", "self", ".", "shape", "[", "0", "]", "==", "self", ".", "shape", "[", "1", "]" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/affine/promote.py#L73-L76
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/python_gflags/gflags.py
python
DEFINE_enum
(name, default, enum_values, help, flag_values=FLAGS, **args)
Registers a flag whose value can be any string from enum_values.
Registers a flag whose value can be any string from enum_values.
[ "Registers", "a", "flag", "whose", "value", "can", "be", "any", "string", "from", "enum_values", "." ]
def DEFINE_enum(name, default, enum_values, help, flag_values=FLAGS, **args): """Registers a flag whose value can be any string from enum_values.""" DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args), flag_values)
[ "def", "DEFINE_enum", "(", "name", ",", "default", ",", "enum_values", ",", "help", ",", "flag_values", "=", "FLAGS", ",", "*", "*", "args", ")", ":", "DEFINE_flag", "(", "EnumFlag", "(", "name", ",", "default", ",", "help", ",", "enum_values", ",", "*...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/python_gflags/gflags.py#L2624-L2628
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/fuchsia/boot_data.py
python
_GetAuthorizedKeysPath
()
return os.path.join(_SSH_DIR, 'fuchsia_authorized_keys')
Returns a path to the authorized keys which get copied to your Fuchsia device during paving
Returns a path to the authorized keys which get copied to your Fuchsia device during paving
[ "Returns", "a", "path", "to", "the", "authorized", "keys", "which", "get", "copied", "to", "your", "Fuchsia", "device", "during", "paving" ]
def _GetAuthorizedKeysPath(): """Returns a path to the authorized keys which get copied to your Fuchsia device during paving""" return os.path.join(_SSH_DIR, 'fuchsia_authorized_keys')
[ "def", "_GetAuthorizedKeysPath", "(", ")", ":", "return", "os", ".", "path", ".", "join", "(", "_SSH_DIR", ",", "'fuchsia_authorized_keys'", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/fuchsia/boot_data.py#L43-L47
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/image/image.py
python
scale_down
(src_size, size)
return int(w), int(h)
Scales down crop size if it's larger than image size. If width/height of the crop is larger than the width/height of the image, sets the width/height to the width/height of the image. Parameters ---------- src_size : tuple of int Size of the image in (width, height) format. size : tuple of int Size of the crop in (width, height) format. Returns ------- tuple of int A tuple containing the scaled crop size in (width, height) format. Example -------- >>> src_size = (640,480) >>> size = (720,120) >>> new_size = mx.img.scale_down(src_size, size) >>> new_size (640,106)
Scales down crop size if it's larger than image size.
[ "Scales", "down", "crop", "size", "if", "it", "s", "larger", "than", "image", "size", "." ]
def scale_down(src_size, size): """Scales down crop size if it's larger than image size. If width/height of the crop is larger than the width/height of the image, sets the width/height to the width/height of the image. Parameters ---------- src_size : tuple of int Size of the image in (width, height) format. size : tuple of int Size of the crop in (width, height) format. Returns ------- tuple of int A tuple containing the scaled crop size in (width, height) format. Example -------- >>> src_size = (640,480) >>> size = (720,120) >>> new_size = mx.img.scale_down(src_size, size) >>> new_size (640,106) """ w, h = size sw, sh = src_size if sh < h: w, h = float(w * sh) / h, sh if sw < w: w, h = sw, float(h * sw) / w return int(w), int(h)
[ "def", "scale_down", "(", "src_size", ",", "size", ")", ":", "w", ",", "h", "=", "size", "sw", ",", "sh", "=", "src_size", "if", "sh", "<", "h", ":", "w", ",", "h", "=", "float", "(", "w", "*", "sh", ")", "/", "h", ",", "sh", "if", "sw", ...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/image/image.py#L201-L233
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_SelfTest_REQUEST.toTpm
(self, buf)
TpmMarshaller method
TpmMarshaller method
[ "TpmMarshaller", "method" ]
def toTpm(self, buf): """ TpmMarshaller method """ buf.writeByte(self.fullTest)
[ "def", "toTpm", "(", "self", ",", "buf", ")", ":", "buf", ".", "writeByte", "(", "self", ".", "fullTest", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L9136-L9138
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/utils/py3compat.py
python
safe_unicode
(e)
return u'Unrecoverably corrupt evalue'
unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on.
unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on.
[ "unicode", "(", "e", ")", "with", "various", "fallbacks", ".", "Used", "for", "exceptions", "which", "may", "not", "be", "safe", "to", "call", "unicode", "()", "on", "." ]
def safe_unicode(e): """unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on. """ try: return unicode_type(e) except UnicodeError: pass try: return str_to_unicode(str(e)) except UnicodeError: pass try: return str_to_unicode(repr(e)) except UnicodeError: pass return u'Unrecoverably corrupt evalue'
[ "def", "safe_unicode", "(", "e", ")", ":", "try", ":", "return", "unicode_type", "(", "e", ")", "except", "UnicodeError", ":", "pass", "try", ":", "return", "str_to_unicode", "(", "str", "(", "e", ")", ")", "except", "UnicodeError", ":", "pass", "try", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/utils/py3compat.py#L61-L80
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/combo.py
python
ComboCtrl.ShowPopup
(*args, **kwargs)
return _combo.ComboCtrl_ShowPopup(*args, **kwargs)
ShowPopup(self) Show the popup window.
ShowPopup(self)
[ "ShowPopup", "(", "self", ")" ]
def ShowPopup(*args, **kwargs): """ ShowPopup(self) Show the popup window. """ return _combo.ComboCtrl_ShowPopup(*args, **kwargs)
[ "def", "ShowPopup", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_combo", ".", "ComboCtrl_ShowPopup", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/combo.py#L132-L138
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/learn/python/learn/estimators/estimator.py
python
BaseEstimator._get_train_ops
(self, features, labels)
Method that builds model graph and returns trainer ops. Expected to be overridden by sub-classes that require custom support. Args: features: `Tensor` or `dict` of `Tensor` objects. labels: `Tensor` or `dict` of `Tensor` objects. Returns: A `ModelFnOps` object.
Method that builds model graph and returns trainer ops.
[ "Method", "that", "builds", "model", "graph", "and", "returns", "trainer", "ops", "." ]
def _get_train_ops(self, features, labels): """Method that builds model graph and returns trainer ops. Expected to be overridden by sub-classes that require custom support. Args: features: `Tensor` or `dict` of `Tensor` objects. labels: `Tensor` or `dict` of `Tensor` objects. Returns: A `ModelFnOps` object. """ pass
[ "def", "_get_train_ops", "(", "self", ",", "features", ",", "labels", ")", ":", "pass" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/estimators/estimator.py#L701-L713
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/email/__init__.py
python
message_from_file
(fp, *args, **kws)
return Parser(*args, **kws).parse(fp)
Read a file and parse its contents into a Message object model. Optional _class and strict are passed to the Parser constructor.
Read a file and parse its contents into a Message object model.
[ "Read", "a", "file", "and", "parse", "its", "contents", "into", "a", "Message", "object", "model", "." ]
def message_from_file(fp, *args, **kws): """Read a file and parse its contents into a Message object model. Optional _class and strict are passed to the Parser constructor. """ from email.parser import Parser return Parser(*args, **kws).parse(fp)
[ "def", "message_from_file", "(", "fp", ",", "*", "args", ",", "*", "*", "kws", ")", ":", "from", "email", ".", "parser", "import", "Parser", "return", "Parser", "(", "*", "args", ",", "*", "*", "kws", ")", ".", "parse", "(", "fp", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/email/__init__.py#L48-L54
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/index.py
python
PackageIndex.upload_documentation
(self, metadata, doc_dir)
return self.send_request(request)
Upload documentation to the index. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the documentation to be uploaded. :param doc_dir: The pathname of the directory which contains the documentation. This should be the directory that contains the ``index.html`` for the documentation. :return: The HTTP response received from PyPI upon submission of the request.
[]
def upload_documentation(self, metadata, doc_dir): """ Upload documentation to the index. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the documentation to be uploaded. :param doc_dir: The pathname of the directory which contains the documentation. This should be the directory that contains the ``index.html`` for the documentation. :return: The HTTP response received from PyPI upon submission of the request. """ self.check_credentials() if not os.path.isdir(doc_dir): raise DistlibException('not a directory: %r' % doc_dir) fn = os.path.join(doc_dir, 'index.html') if not os.path.exists(fn): raise DistlibException('not found: %r' % fn) metadata.validate() name, version = metadata.name, metadata.version zip_data = zip_dir(doc_dir).getvalue() fields = [(':action', 'doc_upload'), ('name', name), ('version', version)] files = [('content', name, zip_data)] request = self.encode_request(fields, files) return self.send_request(request)
[ "def", "upload_documentation", "(", "self", ",", "metadata", ",", "doc_dir", ")", ":", "self", ".", "check_credentials", "(", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "doc_dir", ")", ":", "raise", "DistlibException", "(", "'not a directory: %r...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/distlib/index.py#L591-L643
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/volumes/fs/operations/versions/auth_metadata.py
python
AuthMetadataManager.subvol_metadata_lock
(self, group_name, subvol_name)
return self._lock(self._subvolume_metadata_path(group_name, subvol_name))
Return a ContextManager which locks the authorization metadata for a particular subvolume, and persists a flag to the metadata indicating that it is currently locked, so that we can detect dirty situations during recovery. This lock isn't just to make access to the metadata safe: it's also designed to be used over the two-step process of checking the metadata and then responding to an authorization request, to ensure that at the point we respond the metadata hasn't changed in the background. It's key to how we avoid security holes resulting from races during that problem ,
Return a ContextManager which locks the authorization metadata for a particular subvolume, and persists a flag to the metadata indicating that it is currently locked, so that we can detect dirty situations during recovery.
[ "Return", "a", "ContextManager", "which", "locks", "the", "authorization", "metadata", "for", "a", "particular", "subvolume", "and", "persists", "a", "flag", "to", "the", "metadata", "indicating", "that", "it", "is", "currently", "locked", "so", "that", "we", ...
def subvol_metadata_lock(self, group_name, subvol_name): """ Return a ContextManager which locks the authorization metadata for a particular subvolume, and persists a flag to the metadata indicating that it is currently locked, so that we can detect dirty situations during recovery. This lock isn't just to make access to the metadata safe: it's also designed to be used over the two-step process of checking the metadata and then responding to an authorization request, to ensure that at the point we respond the metadata hasn't changed in the background. It's key to how we avoid security holes resulting from races during that problem , """ return self._lock(self._subvolume_metadata_path(group_name, subvol_name))
[ "def", "subvol_metadata_lock", "(", "self", ",", "group_name", ",", "subvol_name", ")", ":", "return", "self", ".", "_lock", "(", "self", ".", "_subvolume_metadata_path", "(", "group_name", ",", "subvol_name", ")", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/volumes/fs/operations/versions/auth_metadata.py#L166-L180
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/last-day-where-you-can-still-cross.py
python
Solution.latestDayToCross
(self, row, col, cells)
return -1
:type row: int :type col: int :type cells: List[List[int]] :rtype: int
:type row: int :type col: int :type cells: List[List[int]] :rtype: int
[ ":", "type", "row", ":", "int", ":", "type", "col", ":", "int", ":", "type", "cells", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "int" ]
def latestDayToCross(self, row, col, cells): """ :type row: int :type col: int :type cells: List[List[int]] :rtype: int """ directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] def index(n, i, j): return i*n+j start, end = row*col, row*col+1 uf = UnionFind(row*col+2) lookup = [[False]*col for _ in xrange(row)] for i in reversed(xrange(len(cells))): r, c = cells[i] r, c = r-1, c-1 for dr, dc in directions: nr, nc = r+dr, c+dc if not (0 <= nr < row and 0 <= nc < col and lookup[nr][nc]): continue uf.union_set(index(col, r, c), index(col, nr, nc)) if r == 0: uf.union_set(start, index(col, r, c)) if r == row-1: uf.union_set(end, index(col, r, c)) if uf.find_set(start) == uf.find_set(end): return i lookup[r][c] = True return -1
[ "def", "latestDayToCross", "(", "self", ",", "row", ",", "col", ",", "cells", ")", ":", "directions", "=", "[", "(", "0", ",", "1", ")", ",", "(", "1", ",", "0", ")", ",", "(", "0", ",", "-", "1", ")", ",", "(", "-", "1", ",", "0", ")", ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/last-day-where-you-can-still-cross.py#L33-L62
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/mac_tool.py
python
MacTool._InstallResourceRules
(self, resource_rules)
return target_path
Installs ResourceRules.plist from user or SDK into the bundle. Args: resource_rules: string, optional, path to the ResourceRules.plist file to use, default to "${SDKROOT}/ResourceRules.plist" Returns: Path to the copy of ResourceRules.plist into the bundle.
Installs ResourceRules.plist from user or SDK into the bundle.
[ "Installs", "ResourceRules", ".", "plist", "from", "user", "or", "SDK", "into", "the", "bundle", "." ]
def _InstallResourceRules(self, resource_rules): """Installs ResourceRules.plist from user or SDK into the bundle. Args: resource_rules: string, optional, path to the ResourceRules.plist file to use, default to "${SDKROOT}/ResourceRules.plist" Returns: Path to the copy of ResourceRules.plist into the bundle. """ source_path = resource_rules target_path = os.path.join( os.environ['BUILT_PRODUCTS_DIR'], os.environ['CONTENTS_FOLDER_PATH'], 'ResourceRules.plist') if not source_path: source_path = os.path.join( os.environ['SDKROOT'], 'ResourceRules.plist') shutil.copy2(source_path, target_path) return target_path
[ "def", "_InstallResourceRules", "(", "self", ",", "resource_rules", ")", ":", "source_path", "=", "resource_rules", "target_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "environ", "[", "'BUILT_PRODUCTS_DIR'", "]", ",", "os", ".", "environ", "[...
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/mac_tool.py#L375-L394
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
samples/pySketch/pySketch.py
python
TextObjectValidator.Validate
(self, win)
Validate the contents of the given text control.
Validate the contents of the given text control.
[ "Validate", "the", "contents", "of", "the", "given", "text", "control", "." ]
def Validate(self, win): """ Validate the contents of the given text control. """ textCtrl = self.GetWindow() text = textCtrl.GetValue() if len(text) == 0: wx.MessageBox("A text object must contain some text!", "Error") return False else: return True
[ "def", "Validate", "(", "self", ",", "win", ")", ":", "textCtrl", "=", "self", ".", "GetWindow", "(", ")", "text", "=", "textCtrl", ".", "GetValue", "(", ")", "if", "len", "(", "text", ")", "==", "0", ":", "wx", ".", "MessageBox", "(", "\"A text ob...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/samples/pySketch/pySketch.py#L3426-L3436
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/feature_column/serialization.py
python
deserialize_feature_columns
(configs, custom_objects=None)
return [ deserialize_feature_column(c, custom_objects, columns_by_name) for c in configs ]
Deserializes a list of FeatureColumns configs. Returns a list of FeatureColumns given a list of config dicts acquired by `serialize_feature_columns`. Args: configs: A list of Dicts with the serialization of feature columns acquired by `serialize_feature_columns`. custom_objects: A Dict from custom_object name to the associated keras serializable objects (FeatureColumns, classes or functions). Returns: FeatureColumn objects corresponding to the input configs. Raises: ValueError if called with input that is not a list of FeatureColumns.
Deserializes a list of FeatureColumns configs.
[ "Deserializes", "a", "list", "of", "FeatureColumns", "configs", "." ]
def deserialize_feature_columns(configs, custom_objects=None): """Deserializes a list of FeatureColumns configs. Returns a list of FeatureColumns given a list of config dicts acquired by `serialize_feature_columns`. Args: configs: A list of Dicts with the serialization of feature columns acquired by `serialize_feature_columns`. custom_objects: A Dict from custom_object name to the associated keras serializable objects (FeatureColumns, classes or functions). Returns: FeatureColumn objects corresponding to the input configs. Raises: ValueError if called with input that is not a list of FeatureColumns. """ columns_by_name = {} return [ deserialize_feature_column(c, custom_objects, columns_by_name) for c in configs ]
[ "def", "deserialize_feature_columns", "(", "configs", ",", "custom_objects", "=", "None", ")", ":", "columns_by_name", "=", "{", "}", "return", "[", "deserialize_feature_column", "(", "c", ",", "custom_objects", ",", "columns_by_name", ")", "for", "c", "in", "co...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/feature_column/serialization.py#L164-L186
NREL/EnergyPlus
fadc5973b85c70e8cc923efb69c144e808a26078
third_party/ssc/jsoncpp/amalgamate.py
python
amalgamate_source
(source_top_dir=None, target_source_path=None, header_include_path=None)
Produces amalgamated source. Parameters: source_top_dir: top-directory target_source_path: output .cpp path header_include_path: generated header path relative to target_source_path.
Produces amalgamated source. Parameters: source_top_dir: top-directory target_source_path: output .cpp path header_include_path: generated header path relative to target_source_path.
[ "Produces", "amalgamated", "source", ".", "Parameters", ":", "source_top_dir", ":", "top", "-", "directory", "target_source_path", ":", "output", ".", "cpp", "path", "header_include_path", ":", "generated", "header", "path", "relative", "to", "target_source_path", "...
def amalgamate_source(source_top_dir=None, target_source_path=None, header_include_path=None): """Produces amalgamated source. Parameters: source_top_dir: top-directory target_source_path: output .cpp path header_include_path: generated header path relative to target_source_path. """ print("Amalgamating header...") header = AmalgamationFile(source_top_dir) header.add_text("/// Json-cpp amalgamated header (http://jsoncpp.sourceforge.net/).") header.add_text('/// It is intended to be used with #include "%s"' % header_include_path) header.add_file("LICENSE", wrap_in_comment=True) header.add_text("#ifndef JSON_AMALGAMATED_H_INCLUDED") header.add_text("# define JSON_AMALGAMATED_H_INCLUDED") header.add_text("/// If defined, indicates that the source file is amalgamated") header.add_text("/// to prevent private header inclusion.") header.add_text("#define JSON_IS_AMALGAMATION") header.add_file(os.path.join(INCLUDE_PATH, "version.h")) header.add_file(os.path.join(INCLUDE_PATH, "allocator.h")) header.add_file(os.path.join(INCLUDE_PATH, "config.h")) header.add_file(os.path.join(INCLUDE_PATH, "forwards.h")) header.add_file(os.path.join(INCLUDE_PATH, "json_features.h")) header.add_file(os.path.join(INCLUDE_PATH, "value.h")) header.add_file(os.path.join(INCLUDE_PATH, "reader.h")) header.add_file(os.path.join(INCLUDE_PATH, "writer.h")) header.add_file(os.path.join(INCLUDE_PATH, "assertions.h")) header.add_text("#endif //ifndef JSON_AMALGAMATED_H_INCLUDED") target_header_path = os.path.join(os.path.dirname(target_source_path), header_include_path) print("Writing amalgamated header to %r" % target_header_path) header.write_to(target_header_path) base, ext = os.path.splitext(header_include_path) forward_header_include_path = base + "-forwards" + ext print("Amalgamating forward header...") header = AmalgamationFile(source_top_dir) header.add_text("/// Json-cpp amalgamated forward header (http://jsoncpp.sourceforge.net/).") header.add_text('/// It is intended to be used with #include "%s"' % forward_header_include_path) header.add_text("/// This header provides forward declaration for all JsonCpp types.") header.add_file("LICENSE", wrap_in_comment=True) header.add_text("#ifndef JSON_FORWARD_AMALGAMATED_H_INCLUDED") header.add_text("# define JSON_FORWARD_AMALGAMATED_H_INCLUDED") header.add_text("/// If defined, indicates that the source file is amalgamated") header.add_text("/// to prevent private header inclusion.") header.add_text("#define JSON_IS_AMALGAMATION") header.add_file(os.path.join(INCLUDE_PATH, "config.h")) header.add_file(os.path.join(INCLUDE_PATH, "forwards.h")) header.add_text("#endif //ifndef JSON_FORWARD_AMALGAMATED_H_INCLUDED") target_forward_header_path = os.path.join(os.path.dirname(target_source_path), forward_header_include_path) print("Writing amalgamated forward header to %r" % target_forward_header_path) header.write_to(target_forward_header_path) print("Amalgamating source...") source = AmalgamationFile(source_top_dir) source.add_text("/// Json-cpp amalgamated source (http://jsoncpp.sourceforge.net/).") source.add_text('/// It is intended to be used with #include "%s"' % header_include_path) source.add_file("LICENSE", wrap_in_comment=True) source.add_text("") source.add_text('#include "%s"' % header_include_path) source.add_text(""" #ifndef JSON_IS_AMALGAMATION #error "Compile with -I PATH_TO_JSON_DIRECTORY" #endif """) source.add_text("") source.add_file(os.path.join(SRC_PATH, "json_tool.h")) source.add_file(os.path.join(SRC_PATH, "json_reader.cpp")) source.add_file(os.path.join(SRC_PATH, "json_valueiterator.inl")) source.add_file(os.path.join(SRC_PATH, "json_value.cpp")) source.add_file(os.path.join(SRC_PATH, "json_writer.cpp")) print("Writing amalgamated source to %r" % target_source_path) source.write_to(target_source_path)
[ "def", "amalgamate_source", "(", "source_top_dir", "=", "None", ",", "target_source_path", "=", "None", ",", "header_include_path", "=", "None", ")", ":", "print", "(", "\"Amalgamating header...\"", ")", "header", "=", "AmalgamationFile", "(", "source_top_dir", ")",...
https://github.com/NREL/EnergyPlus/blob/fadc5973b85c70e8cc923efb69c144e808a26078/third_party/ssc/jsoncpp/amalgamate.py#L55-L131
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Image_RGBtoHSV
(*args, **kwargs)
return _core_.Image_RGBtoHSV(*args, **kwargs)
Image_RGBtoHSV(Image_RGBValue rgb) -> Image_HSVValue Converts a color in RGB color space to HSV color space.
Image_RGBtoHSV(Image_RGBValue rgb) -> Image_HSVValue
[ "Image_RGBtoHSV", "(", "Image_RGBValue", "rgb", ")", "-", ">", "Image_HSVValue" ]
def Image_RGBtoHSV(*args, **kwargs): """ Image_RGBtoHSV(Image_RGBValue rgb) -> Image_HSVValue Converts a color in RGB color space to HSV color space. """ return _core_.Image_RGBtoHSV(*args, **kwargs)
[ "def", "Image_RGBtoHSV", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Image_RGBtoHSV", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L3830-L3836
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
Brush.IsHatch
(*args, **kwargs)
return _gdi_.Brush_IsHatch(*args, **kwargs)
IsHatch(self) -> bool Is the current style a hatch type?
IsHatch(self) -> bool
[ "IsHatch", "(", "self", ")", "-", ">", "bool" ]
def IsHatch(*args, **kwargs): """ IsHatch(self) -> bool Is the current style a hatch type? """ return _gdi_.Brush_IsHatch(*args, **kwargs)
[ "def", "IsHatch", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Brush_IsHatch", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L586-L592
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/learn/python/learn/datasets/synthetic.py
python
_archimedes_spiral
(theta, theta_offset=0., *args, **kwargs)
return x, y
Return Archimedes spiral Args: theta: array-like, angles from polar coordinates to be converted theta_offset: float, angle offset in radians (2*pi = 0)
Return Archimedes spiral
[ "Return", "Archimedes", "spiral" ]
def _archimedes_spiral(theta, theta_offset=0., *args, **kwargs): """Return Archimedes spiral Args: theta: array-like, angles from polar coordinates to be converted theta_offset: float, angle offset in radians (2*pi = 0) """ x, y = theta*np.cos(theta + theta_offset), theta*np.sin(theta + theta_offset) x_norm = np.max(np.abs(x)) y_norm = np.max(np.abs(y)) x, y = x / x_norm, y / y_norm return x, y
[ "def", "_archimedes_spiral", "(", "theta", ",", "theta_offset", "=", "0.", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "x", ",", "y", "=", "theta", "*", "np", ".", "cos", "(", "theta", "+", "theta_offset", ")", ",", "theta", "*", "np", "...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/datasets/synthetic.py#L158-L169
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/turtle.py
python
TNavigator.home
(self)
Move turtle to the origin - coordinates (0,0). No arguments. Move turtle to the origin - coordinates (0,0) and set its heading to its start-orientation (which depends on mode). Example (for a Turtle instance named turtle): >>> turtle.home()
Move turtle to the origin - coordinates (0,0).
[ "Move", "turtle", "to", "the", "origin", "-", "coordinates", "(", "0", "0", ")", "." ]
def home(self): """Move turtle to the origin - coordinates (0,0). No arguments. Move turtle to the origin - coordinates (0,0) and set its heading to its start-orientation (which depends on mode). Example (for a Turtle instance named turtle): >>> turtle.home() """ self.goto(0, 0) self.setheading(0)
[ "def", "home", "(", "self", ")", ":", "self", ".", "goto", "(", "0", ",", "0", ")", "self", ".", "setheading", "(", "0", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/turtle.py#L1778-L1790
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
FontEnumerator_GetEncodings
(*args)
return _gdi_.FontEnumerator_GetEncodings(*args)
FontEnumerator_GetEncodings() -> PyObject
FontEnumerator_GetEncodings() -> PyObject
[ "FontEnumerator_GetEncodings", "()", "-", ">", "PyObject" ]
def FontEnumerator_GetEncodings(*args): """FontEnumerator_GetEncodings() -> PyObject""" return _gdi_.FontEnumerator_GetEncodings(*args)
[ "def", "FontEnumerator_GetEncodings", "(", "*", "args", ")", ":", "return", "_gdi_", ".", "FontEnumerator_GetEncodings", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L2683-L2685
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/ops.py
python
Graph.graph_def_versions
(self)
return self._graph_def_versions
The GraphDef version information of this graph. For details on the meaning of each version, see [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto). Returns: A `VersionDef`.
The GraphDef version information of this graph.
[ "The", "GraphDef", "version", "information", "of", "this", "graph", "." ]
def graph_def_versions(self): # pylint: disable=line-too-long """The GraphDef version information of this graph. For details on the meaning of each version, see [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto). Returns: A `VersionDef`. """ # pylint: enable=line-too-long return self._graph_def_versions
[ "def", "graph_def_versions", "(", "self", ")", ":", "# pylint: disable=line-too-long", "# pylint: enable=line-too-long", "return", "self", ".", "_graph_def_versions" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/ops.py#L2341-L2352
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/sparse/scipy_sparse.py
python
_to_ijv
(ss, row_levels=(0, ), column_levels=(1, ), sort_labels=False)
return values, i_coord, j_coord, i_labels, j_labels
For arbitrary (MultiIndexed) SparseSeries return (v, i, j, ilabels, jlabels) where (v, (i, j)) is suitable for passing to scipy.sparse.coo constructor.
For arbitrary (MultiIndexed) SparseSeries return (v, i, j, ilabels, jlabels) where (v, (i, j)) is suitable for passing to scipy.sparse.coo constructor.
[ "For", "arbitrary", "(", "MultiIndexed", ")", "SparseSeries", "return", "(", "v", "i", "j", "ilabels", "jlabels", ")", "where", "(", "v", "(", "i", "j", "))", "is", "suitable", "for", "passing", "to", "scipy", ".", "sparse", ".", "coo", "constructor", ...
def _to_ijv(ss, row_levels=(0, ), column_levels=(1, ), sort_labels=False): """ For arbitrary (MultiIndexed) SparseSeries return (v, i, j, ilabels, jlabels) where (v, (i, j)) is suitable for passing to scipy.sparse.coo constructor. """ # index and column levels must be a partition of the index _check_is_partition([row_levels, column_levels], range(ss.index.nlevels)) # from the SparseSeries: get the labels and data for non-null entries values = ss._data.internal_values()._valid_sp_values nonnull_labels = ss.dropna() def get_indexers(levels): """ Return sparse coords and dense labels for subset levels """ # TODO: how to do this better? cleanly slice nonnull_labels given the # coord values_ilabels = [tuple(x[i] for i in levels) for x in nonnull_labels.index] if len(levels) == 1: values_ilabels = [x[0] for x in values_ilabels] # # performance issues with groupby ################################### # TODO: these two lines can rejplace the code below but # groupby is too slow (in some cases at least) # labels_to_i = ss.groupby(level=levels, sort=sort_labels).first() # labels_to_i[:] = np.arange(labels_to_i.shape[0]) def _get_label_to_i_dict(labels, sort_labels=False): """ Return OrderedDict of unique labels to number. Optionally sort by label. """ labels = Index(lmap(tuple, labels)).unique().tolist() # squish if sort_labels: labels = sorted(list(labels)) d = OrderedDict((k, i) for i, k in enumerate(labels)) return (d) def _get_index_subset_to_coord_dict(index, subset, sort_labels=False): ilabels = list(zip(*[index._get_level_values(i) for i in subset])) labels_to_i = _get_label_to_i_dict(ilabels, sort_labels=sort_labels) labels_to_i = Series(labels_to_i) if len(subset) > 1: labels_to_i.index = MultiIndex.from_tuples(labels_to_i.index) labels_to_i.index.names = [index.names[i] for i in subset] else: labels_to_i.index = Index(x[0] for x in labels_to_i.index) labels_to_i.index.name = index.names[subset[0]] labels_to_i.name = 'value' return (labels_to_i) labels_to_i = _get_index_subset_to_coord_dict(ss.index, levels, sort_labels=sort_labels) # ##################################################################### # ##################################################################### i_coord = labels_to_i[values_ilabels].tolist() i_labels = labels_to_i.index.tolist() return i_coord, i_labels i_coord, i_labels = get_indexers(row_levels) j_coord, j_labels = get_indexers(column_levels) return values, i_coord, j_coord, i_labels, j_labels
[ "def", "_to_ijv", "(", "ss", ",", "row_levels", "=", "(", "0", ",", ")", ",", "column_levels", "=", "(", "1", ",", ")", ",", "sort_labels", "=", "False", ")", ":", "# index and column levels must be a partition of the index", "_check_is_partition", "(", "[", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/sparse/scipy_sparse.py#L22-L88
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
TreeCtrl.GetPrevVisible
(*args, **kwargs)
return _controls_.TreeCtrl_GetPrevVisible(*args, **kwargs)
GetPrevVisible(self, TreeItemId item) -> TreeItemId
GetPrevVisible(self, TreeItemId item) -> TreeItemId
[ "GetPrevVisible", "(", "self", "TreeItemId", "item", ")", "-", ">", "TreeItemId" ]
def GetPrevVisible(*args, **kwargs): """GetPrevVisible(self, TreeItemId item) -> TreeItemId""" return _controls_.TreeCtrl_GetPrevVisible(*args, **kwargs)
[ "def", "GetPrevVisible", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_GetPrevVisible", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L5415-L5417
baidu/AnyQ
d94d450d2aaa5f7ed73424b10aa4539835b97527
tools/simnet/train/paddle/optimizers/paddle_optimizers.py
python
AdamOptimizer.ops
(self, loss)
Adam optimizer operation
Adam optimizer operation
[ "Adam", "optimizer", "operation" ]
def ops(self, loss): """ Adam optimizer operation """ adam = fluid.optimizer.AdamOptimizer( self.learning_rate, beta1=self.beta1, beta2=self.beta2, epsilon=self.epsilon) adam.minimize(loss)
[ "def", "ops", "(", "self", ",", "loss", ")", ":", "adam", "=", "fluid", ".", "optimizer", ".", "AdamOptimizer", "(", "self", ".", "learning_rate", ",", "beta1", "=", "self", ".", "beta1", ",", "beta2", "=", "self", ".", "beta2", ",", "epsilon", "=", ...
https://github.com/baidu/AnyQ/blob/d94d450d2aaa5f7ed73424b10aa4539835b97527/tools/simnet/train/paddle/optimizers/paddle_optimizers.py#L51-L57
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/cookies.py
python
RequestsCookieJar._find
(self, name, domain=None, path=None)
Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value
Requests uses this method internally to get cookie values.
[ "Requests", "uses", "this", "method", "internally", "to", "get", "cookie", "values", "." ]
def _find(self, name, domain=None, path=None): """Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value """ for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: return cookie.value raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
[ "def", "_find", "(", "self", ",", "name", ",", "domain", "=", "None", ",", "path", "=", "None", ")", ":", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "name", "==", "name", ":", "if", "domain", "is", "None", "or", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/cookies.py#L356-L374
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ListBox_GetClassDefaultAttributes
(*args, **kwargs)
return _controls_.ListBox_GetClassDefaultAttributes(*args, **kwargs)
ListBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this.
ListBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
[ "ListBox_GetClassDefaultAttributes", "(", "int", "variant", "=", "WINDOW_VARIANT_NORMAL", ")", "-", ">", "VisualAttributes" ]
def ListBox_GetClassDefaultAttributes(*args, **kwargs): """ ListBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.ListBox_GetClassDefaultAttributes(*args, **kwargs)
[ "def", "ListBox_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListBox_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L1284-L1299
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/ndlstm/python/lstm1d.py
python
ndlstm_base_unrolled
(inputs, noutput, scope=None, reverse=False)
Run an LSTM, either forward or backward. This is a 1D LSTM implementation using unrolling and the TensorFlow LSTM op. Args: inputs: input sequence (length, batch_size, ninput) noutput: depth of output scope: optional scope name reverse: run LSTM in reverse Returns: Output sequence (length, batch_size, noutput)
Run an LSTM, either forward or backward.
[ "Run", "an", "LSTM", "either", "forward", "or", "backward", "." ]
def ndlstm_base_unrolled(inputs, noutput, scope=None, reverse=False): """Run an LSTM, either forward or backward. This is a 1D LSTM implementation using unrolling and the TensorFlow LSTM op. Args: inputs: input sequence (length, batch_size, ninput) noutput: depth of output scope: optional scope name reverse: run LSTM in reverse Returns: Output sequence (length, batch_size, noutput) """ with variable_scope.variable_scope(scope, "SeqLstmUnrolled", [inputs]): length, batch_size, _ = _shape(inputs) lstm_cell = rnn_cell.BasicLSTMCell(noutput, state_is_tuple=False) state = array_ops.zeros([batch_size, lstm_cell.state_size]) output_u = [] inputs_u = array_ops.unstack(inputs) if reverse: inputs_u = list(reversed(inputs_u)) for i in xrange(length): if i > 0: variable_scope.get_variable_scope().reuse_variables() output, state = lstm_cell(inputs_u[i], state) output_u += [output] if reverse: output_u = list(reversed(output_u)) outputs = array_ops.stack(output_u) return outputs
[ "def", "ndlstm_base_unrolled", "(", "inputs", ",", "noutput", ",", "scope", "=", "None", ",", "reverse", "=", "False", ")", ":", "with", "variable_scope", ".", "variable_scope", "(", "scope", ",", "\"SeqLstmUnrolled\"", ",", "[", "inputs", "]", ")", ":", "...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/ndlstm/python/lstm1d.py#L37-L69
google-ar/WebARonTango
e86965d2cbc652156b480e0fcf77c716745578cd
chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py
python
Function.WriteCmdFlag
(self, f)
Writes the cmd cmd_flags constant.
Writes the cmd cmd_flags constant.
[ "Writes", "the", "cmd", "cmd_flags", "constant", "." ]
def WriteCmdFlag(self, f): """Writes the cmd cmd_flags constant.""" flags = [] # By default trace only at the highest level 3. trace_level = int(self.GetInfo('trace_level', default = 3)) if trace_level not in xrange(0, 4): raise KeyError("Unhandled trace_level: %d" % trace_level) flags.append('CMD_FLAG_SET_TRACE_LEVEL(%d)' % trace_level) if len(flags) > 0: cmd_flags = ' | '.join(flags) else: cmd_flags = 0 f.write(" static const uint8_t cmd_flags = %s;\n" % cmd_flags)
[ "def", "WriteCmdFlag", "(", "self", ",", "f", ")", ":", "flags", "=", "[", "]", "# By default trace only at the highest level 3.", "trace_level", "=", "int", "(", "self", ".", "GetInfo", "(", "'trace_level'", ",", "default", "=", "3", ")", ")", "if", "trace_...
https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L9543-L9558
ApolloAuto/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
modules/tools/routing/debug_passage_region.py
python
plot_junction
(junction)
Plot junction
Plot junction
[ "Plot", "junction" ]
def plot_junction(junction): """Plot junction""" plot_region(junction.passage_region, 'red')
[ "def", "plot_junction", "(", "junction", ")", ":", "plot_region", "(", "junction", ".", "passage_region", ",", "'red'", ")" ]
https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/routing/debug_passage_region.py#L75-L77
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/protobuf/python/google/protobuf/internal/encoder.py
python
MapEncoder
(field_descriptor)
return EncodeField
Encoder for extensions of MessageSet. Maps always have a wire format like this: message MapEntry { key_type key = 1; value_type value = 2; } repeated MapEntry map = N;
Encoder for extensions of MessageSet.
[ "Encoder", "for", "extensions", "of", "MessageSet", "." ]
def MapEncoder(field_descriptor): """Encoder for extensions of MessageSet. Maps always have a wire format like this: message MapEntry { key_type key = 1; value_type value = 2; } repeated MapEntry map = N; """ # Can't look at field_descriptor.message_type._concrete_class because it may # not have been initialized yet. message_type = field_descriptor.message_type encode_message = MessageEncoder(field_descriptor.number, False, False) def EncodeField(write, value): for key in value: entry_msg = message_type._concrete_class(key=key, value=value[key]) encode_message(write, entry_msg) return EncodeField
[ "def", "MapEncoder", "(", "field_descriptor", ")", ":", "# Can't look at field_descriptor.message_type._concrete_class because it may", "# not have been initialized yet.", "message_type", "=", "field_descriptor", ".", "message_type", "encode_message", "=", "MessageEncoder", "(", "f...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/internal/encoder.py#L803-L823
OpenLightingProject/ola
d1433a1bed73276fbe55ce18c03b1c208237decc
scripts/enforce_licence.py
python
GetDirectoryLicences
(root_dir)
return licences
Walk the directory tree and determine the licence for each directory.
Walk the directory tree and determine the licence for each directory.
[ "Walk", "the", "directory", "tree", "and", "determine", "the", "licence", "for", "each", "directory", "." ]
def GetDirectoryLicences(root_dir): """Walk the directory tree and determine the licence for each directory.""" LICENCE_FILE = 'LICENCE' licences = {} for dir_name, subdirs, files in os.walk(root_dir): # skip the root_dir since the licence file is different there if dir_name == root_dir: continue # skip ignored dirs since we don't check them anyways skip = False for ignored_dir in IGNORED_DIRECTORIES: if dir_name.rfind(ignored_dir) != -1: skip = True if skip: continue # don't descend into hidden dirs like .libs and .deps subdirs[:] = [d for d in subdirs if not d.startswith('.')] if LICENCE_FILE in files: f = open(os.path.join(dir_name, LICENCE_FILE)) lines = f.readlines() f.close() licences[dir_name] = TransformLicence(lines) print('Found LICENCE for directory %s' % dir_name) # use this licence for all subdirs licence = licences.get(dir_name) if licence is not None: for sub_dir in subdirs: licences[os.path.join(dir_name, sub_dir)] = licence return licences
[ "def", "GetDirectoryLicences", "(", "root_dir", ")", ":", "LICENCE_FILE", "=", "'LICENCE'", "licences", "=", "{", "}", "for", "dir_name", ",", "subdirs", ",", "files", "in", "os", ".", "walk", "(", "root_dir", ")", ":", "# skip the root_dir since the licence fil...
https://github.com/OpenLightingProject/ola/blob/d1433a1bed73276fbe55ce18c03b1c208237decc/scripts/enforce_licence.py#L210-L244
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/__init__.py
python
RegeneratableOptionParser.add_argument
(self, *args, **kw)
Add an option to the parser. This accepts the same arguments as ArgumentParser.add_argument, plus the following: regenerate: can be set to False to prevent this option from being included in regeneration. env_name: name of environment variable that additional values for this option come from. type: adds type='path', to tell the regenerator that the values of this option need to be made relative to options.depth
Add an option to the parser.
[ "Add", "an", "option", "to", "the", "parser", "." ]
def add_argument(self, *args, **kw): """Add an option to the parser. This accepts the same arguments as ArgumentParser.add_argument, plus the following: regenerate: can be set to False to prevent this option from being included in regeneration. env_name: name of environment variable that additional values for this option come from. type: adds type='path', to tell the regenerator that the values of this option need to be made relative to options.depth """ env_name = kw.pop("env_name", None) if "dest" in kw and kw.pop("regenerate", True): dest = kw["dest"] # The path type is needed for regenerating, for optparse we can just treat # it as a string. type = kw.get("type") if type == "path": kw["type"] = str self.__regeneratable_options[dest] = { "action": kw.get("action"), "type": type, "env_name": env_name, "opt": args[0], } argparse.ArgumentParser.add_argument(self, *args, **kw)
[ "def", "add_argument", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "env_name", "=", "kw", ".", "pop", "(", "\"env_name\"", ",", "None", ")", "if", "\"dest\"", "in", "kw", "and", "kw", ".", "pop", "(", "\"regenerate\"", ",", "True"...
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/__init__.py#L279-L308
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
SpherePoser.get
(self)
return _robotsim.SpherePoser_get(self)
r"""
r"""
[ "r" ]
def get(self) ->None: r""" """ return _robotsim.SpherePoser_get(self)
[ "def", "get", "(", "self", ")", "->", "None", ":", "return", "_robotsim", ".", "SpherePoser_get", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L3733-L3736
physercoe/starquant
c00cad64d1de2da05081b3dc320ef264c6295e08
cppsrc/fmt-5.3.0/support/docopt.py
python
parse_long
(tokens, options)
return [o]
long ::= '--' chars [ ( ' ' | '=' ) chars ] ;
long ::= '--' chars [ ( ' ' | '=' ) chars ] ;
[ "long", "::", "=", "--", "chars", "[", "(", "|", "=", ")", "chars", "]", ";" ]
def parse_long(tokens, options): """long ::= '--' chars [ ( ' ' | '=' ) chars ] ;""" long, eq, value = tokens.move().partition('=') assert long.startswith('--') value = None if eq == value == '' else value similar = [o for o in options if o.long == long] if tokens.error is DocoptExit and similar == []: # if no exact match similar = [o for o in options if o.long and o.long.startswith(long)] if len(similar) > 1: # might be simply specified ambiguously 2+ times? raise tokens.error('%s is not a unique prefix: %s?' % (long, ', '.join(o.long for o in similar))) elif len(similar) < 1: argcount = 1 if eq == '=' else 0 o = Option(None, long, argcount) options.append(o) if tokens.error is DocoptExit: o = Option(None, long, argcount, value if argcount else True) else: o = Option(similar[0].short, similar[0].long, similar[0].argcount, similar[0].value) if o.argcount == 0: if value is not None: raise tokens.error('%s must not have an argument' % o.long) else: if value is None: if tokens.current() in [None, '--']: raise tokens.error('%s requires argument' % o.long) value = tokens.move() if tokens.error is DocoptExit: o.value = value if value is not None else True return [o]
[ "def", "parse_long", "(", "tokens", ",", "options", ")", ":", "long", ",", "eq", ",", "value", "=", "tokens", ".", "move", "(", ")", ".", "partition", "(", "'='", ")", "assert", "long", ".", "startswith", "(", "'--'", ")", "value", "=", "None", "if...
https://github.com/physercoe/starquant/blob/c00cad64d1de2da05081b3dc320ef264c6295e08/cppsrc/fmt-5.3.0/support/docopt.py#L301-L331
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
registerHTTPPostCallbacks
()
By default, libxml submits HTTP output requests using the "PUT" method. Calling this method changes the HTTP output method to use the "POST" method instead.
By default, libxml submits HTTP output requests using the "PUT" method. Calling this method changes the HTTP output method to use the "POST" method instead.
[ "By", "default", "libxml", "submits", "HTTP", "output", "requests", "using", "the", "PUT", "method", ".", "Calling", "this", "method", "changes", "the", "HTTP", "output", "method", "to", "use", "the", "POST", "method", "instead", "." ]
def registerHTTPPostCallbacks(): """By default, libxml submits HTTP output requests using the "PUT" method. Calling this method changes the HTTP output method to use the "POST" method instead. """ libxml2mod.xmlRegisterHTTPPostCallbacks()
[ "def", "registerHTTPPostCallbacks", "(", ")", ":", "libxml2mod", ".", "xmlRegisterHTTPPostCallbacks", "(", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L1129-L1133
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/training/monitored_session.py
python
_HookedSession._call_hook_before_run
(self, run_context, fetch_dict, user_feed_dict, options)
return hook_feeds
Calls hooks.before_run and handles requests from hooks.
Calls hooks.before_run and handles requests from hooks.
[ "Calls", "hooks", ".", "before_run", "and", "handles", "requests", "from", "hooks", "." ]
def _call_hook_before_run(self, run_context, fetch_dict, user_feed_dict, options): """Calls hooks.before_run and handles requests from hooks.""" hook_feeds = {} for hook in self._hooks: request = hook.before_run(run_context) if request is not None: if request.fetches is not None: fetch_dict[hook] = request.fetches if request.feed_dict: self._raise_if_feeds_intersects( hook_feeds, request.feed_dict, 'Same tensor is fed by two hooks.') hook_feeds.update(request.feed_dict) if request.options: self._merge_run_options(options, request.options) if not hook_feeds: return user_feed_dict if not user_feed_dict: return hook_feeds self._raise_if_feeds_intersects( user_feed_dict, hook_feeds, 'Same tensor is fed by a SessionRunHook and user.') hook_feeds.update(user_feed_dict) return hook_feeds
[ "def", "_call_hook_before_run", "(", "self", ",", "run_context", ",", "fetch_dict", ",", "user_feed_dict", ",", "options", ")", ":", "hook_feeds", "=", "{", "}", "for", "hook", "in", "self", ".", "_hooks", ":", "request", "=", "hook", ".", "before_run", "(...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/training/monitored_session.py#L1133-L1160
apache/qpid-proton
6bcdfebb55ea3554bc29b1901422532db331a591
python/proton/_events.py
python
EventBase.handler
(self)
return None
The handler for this event type. Not implemented, always returns ``None``. :type: ``None``
The handler for this event type. Not implemented, always returns ``None``.
[ "The", "handler", "for", "this", "event", "type", ".", "Not", "implemented", "always", "returns", "None", "." ]
def handler(self): """ The handler for this event type. Not implemented, always returns ``None``. :type: ``None`` """ return None
[ "def", "handler", "(", "self", ")", ":", "return", "None" ]
https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_events.py#L144-L150
xenia-project/xenia
9b1fdac98665ac091b9660a5d0fbb259ed79e578
third_party/google-styleguide/cpplint/cpplint.py
python
FileInfo.Split
(self)
return (project,) + os.path.splitext(rest)
Splits the file into the directory, basename, and extension. For 'chrome/browser/browser.cc', Split() would return ('chrome/browser', 'browser', '.cc') Returns: A tuple of (directory, basename, extension).
Splits the file into the directory, basename, and extension.
[ "Splits", "the", "file", "into", "the", "directory", "basename", "and", "extension", "." ]
def Split(self): """Splits the file into the directory, basename, and extension. For 'chrome/browser/browser.cc', Split() would return ('chrome/browser', 'browser', '.cc') Returns: A tuple of (directory, basename, extension). """ googlename = self.RepositoryName() project, rest = os.path.split(googlename) return (project,) + os.path.splitext(rest)
[ "def", "Split", "(", "self", ")", ":", "googlename", "=", "self", ".", "RepositoryName", "(", ")", "project", ",", "rest", "=", "os", ".", "path", ".", "split", "(", "googlename", ")", "return", "(", "project", ",", ")", "+", "os", ".", "path", "."...
https://github.com/xenia-project/xenia/blob/9b1fdac98665ac091b9660a5d0fbb259ed79e578/third_party/google-styleguide/cpplint/cpplint.py#L920-L932
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/Input/InputFileEditorPlugin.py
python
InputFileEditorPlugin.onCurrentChanged
(self, index)
This is called when the tab is changed. If the block editor window is open we want to raise it to the front so it doesn't get lost.
This is called when the tab is changed. If the block editor window is open we want to raise it to the front so it doesn't get lost.
[ "This", "is", "called", "when", "the", "tab", "is", "changed", ".", "If", "the", "block", "editor", "window", "is", "open", "we", "want", "to", "raise", "it", "to", "the", "front", "so", "it", "doesn", "t", "get", "lost", "." ]
def onCurrentChanged(self, index): """ This is called when the tab is changed. If the block editor window is open we want to raise it to the front so it doesn't get lost. """ if index == self._index: if self.block_editor: self.block_editor.raise_()
[ "def", "onCurrentChanged", "(", "self", ",", "index", ")", ":", "if", "index", "==", "self", ".", "_index", ":", "if", "self", ".", "block_editor", ":", "self", ".", "block_editor", ".", "raise_", "(", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Input/InputFileEditorPlugin.py#L195-L203
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/tkMessageBox.py
python
askretrycancel
(title=None, message=None, **options)
return s == RETRY
Ask if operation should be retried; return true if the answer is yes
Ask if operation should be retried; return true if the answer is yes
[ "Ask", "if", "operation", "should", "be", "retried", ";", "return", "true", "if", "the", "answer", "is", "yes" ]
def askretrycancel(title=None, message=None, **options): "Ask if operation should be retried; return true if the answer is yes" s = _show(title, message, WARNING, RETRYCANCEL, **options) return s == RETRY
[ "def", "askretrycancel", "(", "title", "=", "None", ",", "message", "=", "None", ",", "*", "*", "options", ")", ":", "s", "=", "_show", "(", "title", ",", "message", ",", "WARNING", ",", "RETRYCANCEL", ",", "*", "*", "options", ")", "return", "s", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/tkMessageBox.py#L116-L119
thunil/tempoGAN
a9b92181e28a82c2029049791f875a6c1341d62b
tensorflow/tools/fluiddataloader.py
python
FluidDataLoader.mogrifyFilenameIndex
(self, fn, idxOffset)
return fn
Parse, determine index, and change
Parse, determine index, and change
[ "Parse", "determine", "index", "and", "change" ]
def mogrifyFilenameIndex(self, fn, idxOffset): """ Parse, determine index, and change """ match = re.search("(.*_)([\d]+)\.([\w]+)", fn) # split into groups: path/name_ , %04d , ext if match: if len(match.groups())!=3: raise FluidDataLoaderError("FluidDataLoader error: got filename %s, but could not fully split up into name,4-digit and extension " % (fn)) #print "A " + format(match.groups()) idx = int(match.group(2)) idx = max(self.filename_index_min, min(self.filename_index_max-1, idx+idxOffset) ) #print "A " + format(match.group(2)) fn = "%s%04d.%s" % (match.group(1), idx, match.group(3)) #print "fn " + fn else: raise FluidDataLoaderError("FluidDataLoader error: got filename %s, but could not split up into name,4-digit and extension " % (fn)) #exit() # density1_([\w]+).npz return fn
[ "def", "mogrifyFilenameIndex", "(", "self", ",", "fn", ",", "idxOffset", ")", ":", "match", "=", "re", ".", "search", "(", "\"(.*_)([\\d]+)\\.([\\w]+)\"", ",", "fn", ")", "# split into groups: path/name_ , %04d , ext", "if", "match", ":", "if", "len", "(", "matc...
https://github.com/thunil/tempoGAN/blob/a9b92181e28a82c2029049791f875a6c1341d62b/tensorflow/tools/fluiddataloader.py#L279-L297
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/fancy-sequence.py
python
Fancy.addAll
(self, inc)
:type inc: int :rtype: None
:type inc: int :rtype: None
[ ":", "type", "inc", ":", "int", ":", "rtype", ":", "None" ]
def addAll(self, inc): """ :type inc: int :rtype: None """ self.__ops[-1][1] = (self.__ops[-1][1]+inc) % MOD
[ "def", "addAll", "(", "self", ",", "inc", ")", ":", "self", ".", "__ops", "[", "-", "1", "]", "[", "1", "]", "=", "(", "self", ".", "__ops", "[", "-", "1", "]", "[", "1", "]", "+", "inc", ")", "%", "MOD" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/fancy-sequence.py#L20-L25
baidu/lac
3e10dbed9bfd87bea927c84a6627a167c17b5617
python/LAC/models.py
python
Model.train
(self, model_save_dir, train_data, test_data, iter_num, thread_num)
执行模型增量训练 Args: model_save_dir: 训练结束后模型保存的路径 train_data: 训练数据路径 test_data: 测试数据路径,若为None则不进行测试 iter_num: 训练数据的迭代次数 thread_num: 执行训练的线程数
执行模型增量训练 Args: model_save_dir: 训练结束后模型保存的路径 train_data: 训练数据路径 test_data: 测试数据路径,若为None则不进行测试 iter_num: 训练数据的迭代次数 thread_num: 执行训练的线程数
[ "执行模型增量训练", "Args", ":", "model_save_dir", ":", "训练结束后模型保存的路径", "train_data", ":", "训练数据路径", "test_data", ":", "测试数据路径,若为None则不进行测试", "iter_num", ":", "训练数据的迭代次数", "thread_num", ":", "执行训练的线程数" ]
def train(self, model_save_dir, train_data, test_data, iter_num, thread_num): """执行模型增量训练 Args: model_save_dir: 训练结束后模型保存的路径 train_data: 训练数据路径 test_data: 测试数据路径,若为None则不进行测试 iter_num: 训练数据的迭代次数 thread_num: 执行训练的线程数 """ self.args.model = self.mode self.args.train_data = train_data self.args.test_data = test_data self.args.epoch = iter_num self.args.cpu_num = thread_num logging.info("Start Training!") scope = fluid.core.Scope() with fluid.scope_guard(scope): test_program, fetch_list = nets.do_train(self.args, self.dataset, self.segment_tool) fluid.io.save_inference_model(os.path.join(model_save_dir, 'model'), ['words'], fetch_list, self.exe, main_program=test_program, ) # 拷贝配置文件 if os.path.exists(os.path.join(model_save_dir, 'conf')): shutil.rmtree(os.path.join(model_save_dir, 'conf')) shutil.copytree(os.path.join(self.model_path, 'conf'), os.path.join(model_save_dir, 'conf')) self.load_model(model_save_dir) logging.info("Finish Training!")
[ "def", "train", "(", "self", ",", "model_save_dir", ",", "train_data", ",", "test_data", ",", "iter_num", ",", "thread_num", ")", ":", "self", ".", "args", ".", "model", "=", "self", ".", "mode", "self", ".", "args", ".", "train_data", "=", "train_data",...
https://github.com/baidu/lac/blob/3e10dbed9bfd87bea927c84a6627a167c17b5617/python/LAC/models.py#L177-L210
evpo/EncryptPad
156904860aaba8e7e8729b44e269b2992f9fe9f4
deps/libencryptmsg/configure.py
python
lex_me_harder
(infofile, allowed_groups, allowed_maps, name_val_pairs)
return out
Generic lexer function for info.txt and src/build-data files
Generic lexer function for info.txt and src/build-data files
[ "Generic", "lexer", "function", "for", "info", ".", "txt", "and", "src", "/", "build", "-", "data", "files" ]
def lex_me_harder(infofile, allowed_groups, allowed_maps, name_val_pairs): """ Generic lexer function for info.txt and src/build-data files """ out = LexResult() # Format as a nameable Python variable def py_var(group): return group.replace(':', '_') lexer = shlex.shlex(open(infofile), infofile, posix=True) lexer.wordchars += ':.<>/,-!?+*' # handle various funky chars in info.txt groups = allowed_groups + allowed_maps for group in groups: out.__dict__[py_var(group)] = [] for (key, val) in name_val_pairs.items(): out.__dict__[key] = val def lexed_tokens(): # Convert to an iterator while True: token = lexer.get_token() if token != lexer.eof: yield token else: return for token in lexed_tokens(): match = re.match('<(.*)>', token) # Check for a grouping if match is not None: group = match.group(1) if group not in groups: raise LexerError('Unknown group "%s"' % (group), infofile, lexer.lineno) end_marker = '</' + group + '>' token = lexer.get_token() while token != end_marker: out.__dict__[py_var(group)].append(token) token = lexer.get_token() if token is None: raise LexerError('Group "%s" not terminated' % (group), infofile, lexer.lineno) elif token in name_val_pairs.keys(): if isinstance(out.__dict__[token], list): out.__dict__[token].append(lexer.get_token()) else: out.__dict__[token] = lexer.get_token() else: # No match -> error raise LexerError('Bad token "%s"' % (token), infofile, lexer.lineno) for group in allowed_maps: out.__dict__[group] = parse_lex_dict(out.__dict__[group]) return out
[ "def", "lex_me_harder", "(", "infofile", ",", "allowed_groups", ",", "allowed_maps", ",", "name_val_pairs", ")", ":", "out", "=", "LexResult", "(", ")", "# Format as a nameable Python variable", "def", "py_var", "(", "group", ")", ":", "return", "group", ".", "r...
https://github.com/evpo/EncryptPad/blob/156904860aaba8e7e8729b44e269b2992f9fe9f4/deps/libencryptmsg/configure.py#L63-L123
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
lldb/examples/python/file_extract.py
python
FileExtract.get_n_uint8
(self, n, fail_value=0)
Extract "n" uint8_t integers from the binary file at the current file position, returns a list of integers
Extract "n" uint8_t integers from the binary file at the current file position, returns a list of integers
[ "Extract", "n", "uint8_t", "integers", "from", "the", "binary", "file", "at", "the", "current", "file", "position", "returns", "a", "list", "of", "integers" ]
def get_n_uint8(self, n, fail_value=0): '''Extract "n" uint8_t integers from the binary file at the current file position, returns a list of integers''' s = self.read_size(n) if s: return struct.unpack(self.byte_order + ("%u" % n) + 'B', s) else: return (fail_value,) * n
[ "def", "get_n_uint8", "(", "self", ",", "n", ",", "fail_value", "=", "0", ")", ":", "s", "=", "self", ".", "read_size", "(", "n", ")", "if", "s", ":", "return", "struct", ".", "unpack", "(", "self", ".", "byte_order", "+", "(", "\"%u\"", "%", "n"...
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/examples/python/file_extract.py#L172-L178
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
TextBoxAttr.GetClearMode
(*args, **kwargs)
return _richtext.TextBoxAttr_GetClearMode(*args, **kwargs)
GetClearMode(self) -> int
GetClearMode(self) -> int
[ "GetClearMode", "(", "self", ")", "-", ">", "int" ]
def GetClearMode(*args, **kwargs): """GetClearMode(self) -> int""" return _richtext.TextBoxAttr_GetClearMode(*args, **kwargs)
[ "def", "GetClearMode", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "TextBoxAttr_GetClearMode", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L592-L594