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
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/sandbox.py
python
ExceptionSaver.resume
(self)
restore and re-raise any exception
restore and re-raise any exception
[ "restore", "and", "re", "-", "raise", "any", "exception" ]
def resume(self): "restore and re-raise any exception" if '_saved' not in vars(self): return type, exc = map(pickle.loads, self._saved) six.reraise(type, exc, self._tb)
[ "def", "resume", "(", "self", ")", ":", "if", "'_saved'", "not", "in", "vars", "(", "self", ")", ":", "return", "type", ",", "exc", "=", "map", "(", "pickle", ".", "loads", ",", "self", ".", "_saved", ")", "six", ".", "reraise", "(", "type", ",",...
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/sandbox.py#L134-L141
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py
python
Index.drop_duplicates
(self, keep="first")
return super().drop_duplicates(keep=keep)
Return Index with duplicate values removed. Parameters ---------- keep : {'first', 'last', ``False``}, default 'first' - 'first' : Drop duplicates except for the first occurrence. - 'last' : Drop duplicates except for the last occurrence. - ``False`` : Drop all duplicates. Returns ------- deduplicated : Index See Also -------- Series.drop_duplicates : Equivalent method on Series. DataFrame.drop_duplicates : Equivalent method on DataFrame. Index.duplicated : Related method on Index, indicating duplicate Index values. Examples -------- Generate an pandas.Index with duplicate values. >>> idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo']) The `keep` parameter controls which duplicate values are removed. The value 'first' keeps the first occurrence for each set of duplicated entries. The default value of keep is 'first'. >>> idx.drop_duplicates(keep='first') Index(['lama', 'cow', 'beetle', 'hippo'], dtype='object') The value 'last' keeps the last occurrence for each set of duplicated entries. >>> idx.drop_duplicates(keep='last') Index(['cow', 'beetle', 'lama', 'hippo'], dtype='object') The value ``False`` discards all sets of duplicated entries. >>> idx.drop_duplicates(keep=False) Index(['cow', 'beetle', 'hippo'], dtype='object')
Return Index with duplicate values removed.
[ "Return", "Index", "with", "duplicate", "values", "removed", "." ]
def drop_duplicates(self, keep="first"): """ Return Index with duplicate values removed. Parameters ---------- keep : {'first', 'last', ``False``}, default 'first' - 'first' : Drop duplicates except for the first occurrence. - 'last' : Drop duplicates except for the last occurrence. - ``False`` : Drop all duplicates. Returns ------- deduplicated : Index See Also -------- Series.drop_duplicates : Equivalent method on Series. DataFrame.drop_duplicates : Equivalent method on DataFrame. Index.duplicated : Related method on Index, indicating duplicate Index values. Examples -------- Generate an pandas.Index with duplicate values. >>> idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo']) The `keep` parameter controls which duplicate values are removed. The value 'first' keeps the first occurrence for each set of duplicated entries. The default value of keep is 'first'. >>> idx.drop_duplicates(keep='first') Index(['lama', 'cow', 'beetle', 'hippo'], dtype='object') The value 'last' keeps the last occurrence for each set of duplicated entries. >>> idx.drop_duplicates(keep='last') Index(['cow', 'beetle', 'lama', 'hippo'], dtype='object') The value ``False`` discards all sets of duplicated entries. >>> idx.drop_duplicates(keep=False) Index(['cow', 'beetle', 'hippo'], dtype='object') """ return super().drop_duplicates(keep=keep)
[ "def", "drop_duplicates", "(", "self", ",", "keep", "=", "\"first\"", ")", ":", "return", "super", "(", ")", ".", "drop_duplicates", "(", "keep", "=", "keep", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py#L1977-L2023
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/random.py
python
WichmannHill.setstate
(self, state)
Restore internal state from object returned by getstate().
Restore internal state from object returned by getstate().
[ "Restore", "internal", "state", "from", "object", "returned", "by", "getstate", "()", "." ]
def setstate(self, state): """Restore internal state from object returned by getstate().""" version = state[0] if version == 1: version, self._seed, self.gauss_next = state else: raise ValueError("state with version %s passed to " "Random.setstate() of version %s" % (version, self.VERSION))
[ "def", "setstate", "(", "self", ",", "state", ")", ":", "version", "=", "state", "[", "0", "]", "if", "version", "==", "1", ":", "version", ",", "self", ".", "_seed", ",", "self", ".", "gauss_next", "=", "state", "else", ":", "raise", "ValueError", ...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/random.py#L713-L721
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/stats/kde.py
python
gaussian_kde.integrate_box
(self, low_bounds, high_bounds, maxpts=None)
return value
Computes the integral of a pdf over a rectangular interval. Parameters ---------- low_bounds : array_like A 1-D array containing the lower bounds of integration. high_bounds : array_like A 1-D array containing the upper bounds of integration. maxpts : int, optional The maximum number of points to use for integration. Returns ------- value : scalar The result of the integral.
Computes the integral of a pdf over a rectangular interval.
[ "Computes", "the", "integral", "of", "a", "pdf", "over", "a", "rectangular", "interval", "." ]
def integrate_box(self, low_bounds, high_bounds, maxpts=None): """Computes the integral of a pdf over a rectangular interval. Parameters ---------- low_bounds : array_like A 1-D array containing the lower bounds of integration. high_bounds : array_like A 1-D array containing the upper bounds of integration. maxpts : int, optional The maximum number of points to use for integration. Returns ------- value : scalar The result of the integral. """ from . import mvn if maxpts is not None: extra_kwds = {'maxpts': maxpts} else: extra_kwds = {} value, inform = mvn.mvnun(low_bounds, high_bounds, self.dataset, self.covariance, **extra_kwds) if inform: msg = ('An integral in mvn.mvnun requires more points than %s' % (self.d * 1000)) warnings.warn(msg) return value
[ "def", "integrate_box", "(", "self", ",", "low_bounds", ",", "high_bounds", ",", "maxpts", "=", "None", ")", ":", "from", ".", "import", "mvn", "if", "maxpts", "is", "not", "None", ":", "extra_kwds", "=", "{", "'maxpts'", ":", "maxpts", "}", "else", ":...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/kde.py#L313-L345
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/framework/pr_tools/trilinosprhelpers/TrilinosPRConfigurationBase.py
python
TrilinosPRConfigurationBase.arg_pr_genconfig_job_name
(self)
return self.args.genconfig_build_name
The Jenkins job name that is executing this Pull Request test. Default is to use the value in args.pullrequest_build_name.
The Jenkins job name that is executing this Pull Request test. Default is to use the value in args.pullrequest_build_name.
[ "The", "Jenkins", "job", "name", "that", "is", "executing", "this", "Pull", "Request", "test", ".", "Default", "is", "to", "use", "the", "value", "in", "args", ".", "pullrequest_build_name", "." ]
def arg_pr_genconfig_job_name(self): """ The Jenkins job name that is executing this Pull Request test. Default is to use the value in args.pullrequest_build_name. """ return self.args.genconfig_build_name
[ "def", "arg_pr_genconfig_job_name", "(", "self", ")", ":", "return", "self", ".", "args", ".", "genconfig_build_name" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/framework/pr_tools/trilinosprhelpers/TrilinosPRConfigurationBase.py#L264-L269
fredakilla/GPlayEngine
ae6b45f4c68f696fcd171ce6996a5a4e80aee09e
thirdparty/freetype/src/tools/docmaker/content.py
python
ContentProcessor.__init__
( self )
Initialize a block content processor.
Initialize a block content processor.
[ "Initialize", "a", "block", "content", "processor", "." ]
def __init__( self ): """Initialize a block content processor.""" self.reset() self.sections = {} # dictionary of documentation sections self.section = None # current documentation section self.chapters = [] # list of chapters self.headers = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "reset", "(", ")", "self", ".", "sections", "=", "{", "}", "# dictionary of documentation sections", "self", ".", "section", "=", "None", "# current documentation section", "self", ".", "chapters", "=", "[...
https://github.com/fredakilla/GPlayEngine/blob/ae6b45f4c68f696fcd171ce6996a5a4e80aee09e/thirdparty/freetype/src/tools/docmaker/content.py#L403-L412
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/plot.py
python
PlotGraphics.getSymExtent
(self, printerScale)
return symExt
Get max width and height of lines and markers symbols for legend
Get max width and height of lines and markers symbols for legend
[ "Get", "max", "width", "and", "height", "of", "lines", "and", "markers", "symbols", "for", "legend" ]
def getSymExtent(self, printerScale): """Get max width and height of lines and markers symbols for legend""" self.objects[0]._pointSize = self._pointSize symExt = self.objects[0].getSymExtent(printerScale) for o in self.objects[1:]: o._pointSize = self._pointSize oSymExt = o.getSymExtent(printerScale) symExt = np.maximum(symExt, oSymExt) return symExt
[ "def", "getSymExtent", "(", "self", ",", "printerScale", ")", ":", "self", ".", "objects", "[", "0", "]", ".", "_pointSize", "=", "self", ".", "_pointSize", "symExt", "=", "self", ".", "objects", "[", "0", "]", ".", "getSymExtent", "(", "printerScale", ...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/plot.py#L516-L524
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
buildsystem/codecompliance/legal.py
python
find_issues
(check_files, paths, git_change_years=False)
Tests all source files for the required legal headers.
Tests all source files for the required legal headers.
[ "Tests", "all", "source", "files", "for", "the", "required", "legal", "headers", "." ]
def find_issues(check_files, paths, git_change_years=False): """ Tests all source files for the required legal headers. """ third_party_files = set() yield from test_headers( check_files, paths, git_change_years, third_party_files) # test whether all third-party files are listed in copying.md listed_files = set() for line in readfile('copying.md').split('\n'): match = re.match("^ - `([^`]+)`.*$", line) if not match: continue filename = match.group(1) listed_files.add(filename) # file listed, but has no 3rd-party header? for filename in sorted(listed_files - third_party_files): if has_ext(filename, EXTENSIONS_REQUIRING_LEGAL_HEADERS): yield ( "third-party file listing issue", ("{}\n\tlisted in copying.md, but has no " "third-party license header.").format(filename), None ) # file has 3rd-party header, but is not listed? for filename in sorted(third_party_files - listed_files): yield ( "third-party file listing issue", ("{}\n\thas a third-party license header, but isn't " "listed in copying.md").format(filename), None )
[ "def", "find_issues", "(", "check_files", ",", "paths", ",", "git_change_years", "=", "False", ")", ":", "third_party_files", "=", "set", "(", ")", "yield", "from", "test_headers", "(", "check_files", ",", "paths", ",", "git_change_years", ",", "third_party_file...
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/buildsystem/codecompliance/legal.py#L193-L230
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/extensions.py
python
ExtensionManager.unload_extension
(self, module_str)
Unload an IPython extension by its module name. This function looks up the extension's name in ``sys.modules`` and simply calls ``mod.unload_ipython_extension(self)``. Returns the string "no unload function" if the extension doesn't define a function to unload itself, "not loaded" if the extension isn't loaded, otherwise None.
Unload an IPython extension by its module name.
[ "Unload", "an", "IPython", "extension", "by", "its", "module", "name", "." ]
def unload_extension(self, module_str): """Unload an IPython extension by its module name. This function looks up the extension's name in ``sys.modules`` and simply calls ``mod.unload_ipython_extension(self)``. Returns the string "no unload function" if the extension doesn't define a function to unload itself, "not loaded" if the extension isn't loaded, otherwise None. """ if module_str not in self.loaded: return "not loaded" if module_str in sys.modules: mod = sys.modules[module_str] if self._call_unload_ipython_extension(mod): self.loaded.discard(module_str) else: return "no unload function"
[ "def", "unload_extension", "(", "self", ",", "module_str", ")", ":", "if", "module_str", "not", "in", "self", ".", "loaded", ":", "return", "\"not loaded\"", "if", "module_str", "in", "sys", ".", "modules", ":", "mod", "=", "sys", ".", "modules", "[", "m...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/extensions.py#L92-L110
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/docbook/__init__.py
python
_detect
(env)
Detect all the command line tools that we might need for creating the requested output formats.
Detect all the command line tools that we might need for creating the requested output formats.
[ "Detect", "all", "the", "command", "line", "tools", "that", "we", "might", "need", "for", "creating", "the", "requested", "output", "formats", "." ]
def _detect(env): """ Detect all the command line tools that we might need for creating the requested output formats. """ global prefer_xsltproc if env.get('DOCBOOK_PREFER_XSLTPROC',''): prefer_xsltproc = True if ((not has_libxml2 and not has_lxml) or (prefer_xsltproc)): # Try to find the XSLT processors __detect_cl_tool(env, 'DOCBOOK_XSLTPROC', xsltproc_com, xsltproc_com_priority) __detect_cl_tool(env, 'DOCBOOK_XMLLINT', xmllint_com) __detect_cl_tool(env, 'DOCBOOK_FOP', fop_com, ['fop','xep','jw'])
[ "def", "_detect", "(", "env", ")", ":", "global", "prefer_xsltproc", "if", "env", ".", "get", "(", "'DOCBOOK_PREFER_XSLTPROC'", ",", "''", ")", ":", "prefer_xsltproc", "=", "True", "if", "(", "(", "not", "has_libxml2", "and", "not", "has_lxml", ")", "or", ...
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/Tool/docbook/__init__.py#L198-L213
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/composite/multitype_ops/add_impl.py
python
_TupleAdd.__init__
(self, name)
Initialize _TupleAdd.
Initialize _TupleAdd.
[ "Initialize", "_TupleAdd", "." ]
def __init__(self, name): """Initialize _TupleAdd.""" base.TupleAdd_.__init__(self, name)
[ "def", "__init__", "(", "self", ",", "name", ")", ":", "base", ".", "TupleAdd_", ".", "__init__", "(", "self", ",", "name", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/add_impl.py#L46-L48
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
PyPreviewFrame.__init__
(self, *args, **kwargs)
__init__(self, PrintPreview preview, Frame parent, String title, Point pos=DefaultPosition, Size size=DefaultSize, long style=DEFAULT_FRAME_STYLE, String name=FrameNameStr) -> PyPreviewFrame
__init__(self, PrintPreview preview, Frame parent, String title, Point pos=DefaultPosition, Size size=DefaultSize, long style=DEFAULT_FRAME_STYLE, String name=FrameNameStr) -> PyPreviewFrame
[ "__init__", "(", "self", "PrintPreview", "preview", "Frame", "parent", "String", "title", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "DEFAULT_FRAME_STYLE", "String", "name", "=", "FrameNameStr", ")", "-", ">...
def __init__(self, *args, **kwargs): """ __init__(self, PrintPreview preview, Frame parent, String title, Point pos=DefaultPosition, Size size=DefaultSize, long style=DEFAULT_FRAME_STYLE, String name=FrameNameStr) -> PyPreviewFrame """ _windows_.PyPreviewFrame_swiginit(self,_windows_.new_PyPreviewFrame(*args, **kwargs)) self._setOORInfo(self);PyPreviewFrame._setCallbackInfo(self, self, PyPreviewFrame)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_windows_", ".", "PyPreviewFrame_swiginit", "(", "self", ",", "_windows_", ".", "new_PyPreviewFrame", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", "."...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L5727-L5734
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/utils/misc.py
python
strtobool
(val)
Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else.
Convert a string representation of truth to true (1) or false (0).
[ "Convert", "a", "string", "representation", "of", "truth", "to", "true", "(", "1", ")", "or", "false", "(", "0", ")", "." ]
def strtobool(val): # type: (str) -> int """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ val = val.lower() if val in ('y', 'yes', 't', 'true', 'on', '1'): return 1 elif val in ('n', 'no', 'f', 'false', 'off', '0'): return 0 else: raise ValueError("invalid truth value %r" % (val,))
[ "def", "strtobool", "(", "val", ")", ":", "# type: (str) -> int", "val", "=", "val", ".", "lower", "(", ")", "if", "val", "in", "(", "'y'", ",", "'yes'", ",", "'t'", ",", "'true'", ",", "'on'", ",", "'1'", ")", ":", "return", "1", "elif", "val", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/utils/misc.py#L247-L261
msftguy/ssh-rd
a5f3a79daeac5844edebf01916c9613563f1c390
_3rd/boost_1_48_0/tools/build/v2/build/feature.py
python
free_features
()
return __free_features
Returns all free features.
Returns all free features.
[ "Returns", "all", "free", "features", "." ]
def free_features (): """ Returns all free features. """ return __free_features
[ "def", "free_features", "(", ")", ":", "return", "__free_features" ]
https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/build/feature.py#L571-L574
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/tensor.py
python
Tensor.device
(self)
return super().device
r"""Returns a string represents the device a :class:`~.Tensor` storaged on.
r"""Returns a string represents the device a :class:`~.Tensor` storaged on.
[ "r", "Returns", "a", "string", "represents", "the", "device", "a", ":", "class", ":", "~", ".", "Tensor", "storaged", "on", "." ]
def device(self) -> CompNode: r"""Returns a string represents the device a :class:`~.Tensor` storaged on.""" return super().device
[ "def", "device", "(", "self", ")", "->", "CompNode", ":", "return", "super", "(", ")", ".", "device" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/tensor.py#L121-L123
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/framework/meta_graph.py
python
_read_file
(filename)
return graph_def
Reads a file containing `GraphDef` and returns the protocol buffer. Args: filename: `graph_def` filename including the path. Returns: A `GraphDef` protocol buffer. Raises: IOError: If the file doesn't exist, or cannot be successfully parsed.
Reads a file containing `GraphDef` and returns the protocol buffer.
[ "Reads", "a", "file", "containing", "GraphDef", "and", "returns", "the", "protocol", "buffer", "." ]
def _read_file(filename): """Reads a file containing `GraphDef` and returns the protocol buffer. Args: filename: `graph_def` filename including the path. Returns: A `GraphDef` protocol buffer. Raises: IOError: If the file doesn't exist, or cannot be successfully parsed. """ graph_def = graph_pb2.GraphDef() if not file_io.file_exists(filename): raise IOError(f"File {filename} does not exist.") # First try to read it as a binary file. with file_io.FileIO(filename, "rb") as f: file_content = f.read() try: graph_def.ParseFromString(file_content) return graph_def except Exception: # pylint: disable=broad-except pass # Next try to read it as a text file. try: text_format.Merge(file_content, graph_def) except text_format.ParseError as e: raise IOError(f"Cannot parse file {filename}: {str(e)}.") return graph_def
[ "def", "_read_file", "(", "filename", ")", ":", "graph_def", "=", "graph_pb2", ".", "GraphDef", "(", ")", "if", "not", "file_io", ".", "file_exists", "(", "filename", ")", ":", "raise", "IOError", "(", "f\"File {filename} does not exist.\"", ")", "# First try to...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/framework/meta_graph.py#L102-L132
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
NavigationKeyEvent.IsFromTab
(*args, **kwargs)
return _core_.NavigationKeyEvent_IsFromTab(*args, **kwargs)
IsFromTab(self) -> bool Returns ``True`` if the navigation event is originated from the Tab key.
IsFromTab(self) -> bool
[ "IsFromTab", "(", "self", ")", "-", ">", "bool" ]
def IsFromTab(*args, **kwargs): """ IsFromTab(self) -> bool Returns ``True`` if the navigation event is originated from the Tab key. """ return _core_.NavigationKeyEvent_IsFromTab(*args, **kwargs)
[ "def", "IsFromTab", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "NavigationKeyEvent_IsFromTab", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L7266-L7273
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/ipaddress.py
python
_BaseV4._is_valid_netmask
(self, netmask)
return 0 <= netmask <= self._max_prefixlen
Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask.
Verify that the netmask is valid.
[ "Verify", "that", "the", "netmask", "is", "valid", "." ]
def _is_valid_netmask(self, netmask): """Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask. """ mask = netmask.split('.') if len(mask) == 4: try: for x in mask: if int(x) not in self._valid_mask_octets: return False except ValueError: # Found something that isn't an integer or isn't valid return False for idx, y in enumerate(mask): if idx > 0 and y > mask[idx - 1]: return False return True try: netmask = int(netmask) except ValueError: return False return 0 <= netmask <= self._max_prefixlen
[ "def", "_is_valid_netmask", "(", "self", ",", "netmask", ")", ":", "mask", "=", "netmask", ".", "split", "(", "'.'", ")", "if", "len", "(", "mask", ")", "==", "4", ":", "try", ":", "for", "x", "in", "mask", ":", "if", "int", "(", "x", ")", "not...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/ipaddress.py#L1179-L1208
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/importJSON.py
python
export
(exportList, filename)
exports the given objects to a .json file
exports the given objects to a .json file
[ "exports", "the", "given", "objects", "to", "a", ".", "json", "file" ]
def export(exportList, filename): "exports the given objects to a .json file" # Convert objects data = { 'version': '0.0.1', 'description': 'Mesh data exported from FreeCAD', 'objects': [getObjectData(obj) for obj in exportList] } # Write file if six.PY2: outfile = pythonopen(filename, "wb") else: outfile = pythonopen(filename, "w") json.dump(data, outfile, separators = (',', ':')) outfile.close() # Success FreeCAD.Console.PrintMessage( translate("Arch", "Successfully written") + ' ' + filename + "\n")
[ "def", "export", "(", "exportList", ",", "filename", ")", ":", "# Convert objects", "data", "=", "{", "'version'", ":", "'0.0.1'", ",", "'description'", ":", "'Mesh data exported from FreeCAD'", ",", "'objects'", ":", "[", "getObjectData", "(", "obj", ")", "for"...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/importJSON.py#L41-L61
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py
python
_GetXcodeEnv
(xcode_settings, built_products_dir, srcroot, configuration, additional_settings=None)
return additional_settings
Return the environment variables that Xcode would set. See http://developer.apple.com/library/mac/#documentation/DeveloperTools/Reference/XcodeBuildSettingRef/1-Build_Setting_Reference/build_setting_ref.html#//apple_ref/doc/uid/TP40003931-CH3-SW153 for a full list. Args: xcode_settings: An XcodeSettings object. If this is None, this function returns an empty dict. built_products_dir: Absolute path to the built products dir. srcroot: Absolute path to the source root. configuration: The build configuration name. additional_settings: An optional dict with more values to add to the result.
Return the environment variables that Xcode would set. See http://developer.apple.com/library/mac/#documentation/DeveloperTools/Reference/XcodeBuildSettingRef/1-Build_Setting_Reference/build_setting_ref.html#//apple_ref/doc/uid/TP40003931-CH3-SW153 for a full list.
[ "Return", "the", "environment", "variables", "that", "Xcode", "would", "set", ".", "See", "http", ":", "//", "developer", ".", "apple", ".", "com", "/", "library", "/", "mac", "/", "#documentation", "/", "DeveloperTools", "/", "Reference", "/", "XcodeBuildSe...
def _GetXcodeEnv(xcode_settings, built_products_dir, srcroot, configuration, additional_settings=None): """Return the environment variables that Xcode would set. See http://developer.apple.com/library/mac/#documentation/DeveloperTools/Reference/XcodeBuildSettingRef/1-Build_Setting_Reference/build_setting_ref.html#//apple_ref/doc/uid/TP40003931-CH3-SW153 for a full list. Args: xcode_settings: An XcodeSettings object. If this is None, this function returns an empty dict. built_products_dir: Absolute path to the built products dir. srcroot: Absolute path to the source root. configuration: The build configuration name. additional_settings: An optional dict with more values to add to the result. """ if not xcode_settings: return {} # This function is considered a friend of XcodeSettings, so let it reach into # its implementation details. spec = xcode_settings.spec # These are filled in on a as-needed basis. env = { 'BUILT_PRODUCTS_DIR' : built_products_dir, 'CONFIGURATION' : configuration, 'PRODUCT_NAME' : xcode_settings.GetProductName(), # See /Developer/Platforms/MacOSX.platform/Developer/Library/Xcode/Specifications/MacOSX\ Product\ Types.xcspec for FULL_PRODUCT_NAME 'SRCROOT' : srcroot, 'SOURCE_ROOT': '${SRCROOT}', # This is not true for static libraries, but currently the env is only # written for bundles: 'TARGET_BUILD_DIR' : built_products_dir, 'TEMP_DIR' : '${TMPDIR}', } if xcode_settings.GetPerTargetSetting('SDKROOT'): env['SDKROOT'] = xcode_settings._SdkPath() else: env['SDKROOT'] = '' if spec['type'] in ( 'executable', 'static_library', 'shared_library', 'loadable_module'): env['EXECUTABLE_NAME'] = xcode_settings.GetExecutableName() env['EXECUTABLE_PATH'] = xcode_settings.GetExecutablePath() env['FULL_PRODUCT_NAME'] = xcode_settings.GetFullProductName() mach_o_type = xcode_settings.GetMachOType() if mach_o_type: env['MACH_O_TYPE'] = mach_o_type env['PRODUCT_TYPE'] = xcode_settings.GetProductType() if xcode_settings._IsBundle(): env['CONTENTS_FOLDER_PATH'] = \ xcode_settings.GetBundleContentsFolderPath() env['UNLOCALIZED_RESOURCES_FOLDER_PATH'] = \ xcode_settings.GetBundleResourceFolder() env['INFOPLIST_PATH'] = xcode_settings.GetBundlePlistPath() env['WRAPPER_NAME'] = xcode_settings.GetWrapperName() install_name = xcode_settings.GetInstallName() if install_name: env['LD_DYLIB_INSTALL_NAME'] = install_name install_name_base = xcode_settings.GetInstallNameBase() if install_name_base: env['DYLIB_INSTALL_NAME_BASE'] = install_name_base if not additional_settings: additional_settings = {} else: # Flatten lists to strings. for k in additional_settings: if not isinstance(additional_settings[k], str): additional_settings[k] = ' '.join(additional_settings[k]) additional_settings.update(env) for k in additional_settings: additional_settings[k] = _NormalizeEnvVarReferences(additional_settings[k]) return additional_settings
[ "def", "_GetXcodeEnv", "(", "xcode_settings", ",", "built_products_dir", ",", "srcroot", ",", "configuration", ",", "additional_settings", "=", "None", ")", ":", "if", "not", "xcode_settings", ":", "return", "{", "}", "# This function is considered a friend of XcodeSett...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py#L908-L983
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/python_gflags/gflags.py
python
FlagValues.AddValidator
(self, validator)
Register new flags validator to be checked. Args: validator: gflags_validators.Validator Raises: AttributeError: if validators work with a non-existing flag.
Register new flags validator to be checked.
[ "Register", "new", "flags", "validator", "to", "be", "checked", "." ]
def AddValidator(self, validator): """Register new flags validator to be checked. Args: validator: gflags_validators.Validator Raises: AttributeError: if validators work with a non-existing flag. """ for flag_name in validator.GetFlagsNames(): flag = self.FlagDict()[flag_name] flag.validators.append(validator)
[ "def", "AddValidator", "(", "self", ",", "validator", ")", ":", "for", "flag_name", "in", "validator", ".", "GetFlagsNames", "(", ")", ":", "flag", "=", "self", ".", "FlagDict", "(", ")", "[", "flag_name", "]", "flag", ".", "validators", ".", "append", ...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/python_gflags/gflags.py#L1748-L1758
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/nntplib.py
python
NNTP.set_debuglevel
(self, level)
Set the debugging level. Argument 'level' means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LF
Set the debugging level. Argument 'level' means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LF
[ "Set", "the", "debugging", "level", ".", "Argument", "level", "means", ":", "0", ":", "no", "debugging", "output", "(", "default", ")", "1", ":", "print", "commands", "and", "responses", "but", "not", "body", "text", "etc", ".", "2", ":", "also", "prin...
def set_debuglevel(self, level): """Set the debugging level. Argument 'level' means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LF""" self.debugging = level
[ "def", "set_debuglevel", "(", "self", ",", "level", ")", ":", "self", ".", "debugging", "=", "level" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/nntplib.py#L187-L193
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/sliceviewer/peaksviewer/view.py
python
PeaksViewerView.__init__
(self, painter: MplPainter, sliceinfo_provider: 'SliceViewer', parent=None)
:param painter: An object responsible for draw the peaks representations :param sliceinfo_provider: An object responsible for providing access to current slice information :param parent: An optional parent widget
:param painter: An object responsible for draw the peaks representations :param sliceinfo_provider: An object responsible for providing access to current slice information :param parent: An optional parent widget
[ ":", "param", "painter", ":", "An", "object", "responsible", "for", "draw", "the", "peaks", "representations", ":", "param", "sliceinfo_provider", ":", "An", "object", "responsible", "for", "providing", "access", "to", "current", "slice", "information", ":", "pa...
def __init__(self, painter: MplPainter, sliceinfo_provider: 'SliceViewer', parent=None): """ :param painter: An object responsible for draw the peaks representations :param sliceinfo_provider: An object responsible for providing access to current slice information :param parent: An optional parent widget """ super().__init__(parent) self._painter: MplPainter = painter self._sliceinfo_provider: 'SliceViewer' = sliceinfo_provider self._group_box: Optional[QGroupBox] = None self._presenter: Optional['PeaksViewerPresenter'] = None # handle to its presenter self._table_view: Optional[_PeaksWorkspaceTableView] = None self._setup_ui()
[ "def", "__init__", "(", "self", ",", "painter", ":", "MplPainter", ",", "sliceinfo_provider", ":", "'SliceViewer'", ",", "parent", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", "parent", ")", "self", ".", "_painter", ":", "MplPainter", ...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/sliceviewer/peaksviewer/view.py#L78-L93
Qihoo360/mongosync
55b647e81c072ebe91daaa3b9dc1a953c3c22e19
dep/mongo-cxx-driver/site_scons/buildscripts/cpplint.py
python
_CppLintState.SetOutputFormat
(self, output_format)
Sets the output format for errors.
Sets the output format for errors.
[ "Sets", "the", "output", "format", "for", "errors", "." ]
def SetOutputFormat(self, output_format): """Sets the output format for errors.""" self.output_format = output_format
[ "def", "SetOutputFormat", "(", "self", ",", "output_format", ")", ":", "self", ".", "output_format", "=", "output_format" ]
https://github.com/Qihoo360/mongosync/blob/55b647e81c072ebe91daaa3b9dc1a953c3c22e19/dep/mongo-cxx-driver/site_scons/buildscripts/cpplint.py#L507-L509
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py
python
Session.post
(self, url, data=None, json=None, **kwargs)
return self.request('POST', url, data=data, json=json, **kwargs)
r"""Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a POST request. Returns :class:`Response` object.
[ "r", "Sends", "a", "POST", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
def post(self, url, data=None, json=None, **kwargs): r"""Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('POST', url, data=data, json=json, **kwargs)
[ "def", "post", "(", "self", ",", "url", ",", "data", "=", "None", ",", "json", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "request", "(", "'POST'", ",", "url", ",", "data", "=", "data", ",", "json", "=", "json", ",",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py#L567-L578
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/poolmanager.py
python
PoolManager.urlopen
(self, method, url, redirect=True, **kw)
return self.urlopen(method, redirect_location, **kw)
Same as :meth:`urllib3.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
Same as :meth:`urllib3.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``.
[ "Same", "as", ":", "meth", ":", "urllib3", ".", "HTTPConnectionPool", ".", "urlopen", "with", "custom", "cross", "-", "host", "redirect", "logic", "and", "only", "sends", "the", "request", "-", "uri", "portion", "of", "the", "url", "." ]
def urlopen(self, method, url, redirect=True, **kw): """ Same as :meth:`urllib3.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it. """ u = parse_url(url) self._validate_proxy_scheme_url_selection(u.scheme) conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme) kw["assert_same_host"] = False kw["redirect"] = False if "headers" not in kw: kw["headers"] = self.headers.copy() if self._proxy_requires_url_absolute_form(u): response = conn.urlopen(method, url, **kw) else: response = conn.urlopen(method, u.request_uri, **kw) redirect_location = redirect and response.get_redirect_location() if not redirect_location: return response # Support relative URLs for redirecting. redirect_location = urljoin(url, redirect_location) # RFC 7231, Section 6.4.4 if response.status == 303: method = "GET" retries = kw.get("retries") if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect) # Strip headers marked as unsafe to forward to the redirected location. # Check remove_headers_on_redirect to avoid a potential network call within # conn.is_same_host() which may use socket.gethostbyname() in the future. if retries.remove_headers_on_redirect and not conn.is_same_host( redirect_location ): headers = list(six.iterkeys(kw["headers"])) for header in headers: if header.lower() in retries.remove_headers_on_redirect: kw["headers"].pop(header, None) try: retries = retries.increment(method, url, response=response, _pool=conn) except MaxRetryError: if retries.raise_on_redirect: response.drain_conn() raise return response kw["retries"] = retries kw["redirect"] = redirect log.info("Redirecting %s -> %s", url, redirect_location) response.drain_conn() return self.urlopen(method, redirect_location, **kw)
[ "def", "urlopen", "(", "self", ",", "method", ",", "url", ",", "redirect", "=", "True", ",", "*", "*", "kw", ")", ":", "u", "=", "parse_url", "(", "url", ")", "self", ".", "_validate_proxy_scheme_url_selection", "(", "u", ".", "scheme", ")", "conn", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/poolmanager.py#L352-L417
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pyio.py
python
FileIO.closefd
(self)
return self._closefd
True if the file descriptor will be closed by close().
True if the file descriptor will be closed by close().
[ "True", "if", "the", "file", "descriptor", "will", "be", "closed", "by", "close", "()", "." ]
def closefd(self): """True if the file descriptor will be closed by close().""" return self._closefd
[ "def", "closefd", "(", "self", ")", ":", "return", "self", ".", "_closefd" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pyio.py#L1744-L1746
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftviewproviders/view_draft_annotation.py
python
ViewProviderDraftAnnotation.onChanged
(self, vobj, prop)
Execute when a view property is changed.
Execute when a view property is changed.
[ "Execute", "when", "a", "view", "property", "is", "changed", "." ]
def onChanged(self, vobj, prop): """Execute when a view property is changed.""" properties = vobj.PropertiesList meta = vobj.Object.Document.Meta if prop == "AnnotationStyle" and "AnnotationStyle" in properties: if not vobj.AnnotationStyle or vobj.AnnotationStyle == " ": # unset style _msg(16 * "-") _msg("Unset style") for visprop in utils.ANNOTATION_STYLE.keys(): if visprop in properties: # make property writable vobj.setPropertyStatus(visprop, '-ReadOnly') else: # set style styles = {} for key, value in meta.items(): if key.startswith("Draft_Style_"): styles[key[12:]] = json.loads(value) if vobj.AnnotationStyle in styles: _msg(16 * "-") _msg("Style: {}".format(vobj.AnnotationStyle)) style = styles[vobj.AnnotationStyle] for visprop in style.keys(): if visprop in properties: try: getattr(vobj, visprop).setValue(style[visprop]) _msg("setValue: " "'{}', '{}'".format(visprop, style[visprop])) except AttributeError: setattr(vobj, visprop, style[visprop]) _msg("setattr: " "'{}', '{}'".format(visprop, style[visprop])) # make property read-only vobj.setPropertyStatus(visprop, 'ReadOnly')
[ "def", "onChanged", "(", "self", ",", "vobj", ",", "prop", ")", ":", "properties", "=", "vobj", ".", "PropertiesList", "meta", "=", "vobj", ".", "Object", ".", "Document", ".", "Meta", "if", "prop", "==", "\"AnnotationStyle\"", "and", "\"AnnotationStyle\"", ...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftviewproviders/view_draft_annotation.py#L152-L190
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/debug/cli/analyzer_cli.py
python
DebugAnalyzer._render_node_traceback
(self, node_name)
return debugger_cli_common.rich_text_lines_from_rich_line_list(lines)
Render traceback of a node's creation in Python, if available. Args: node_name: (str) name of the node. Returns: A RichTextLines object containing the stack trace of the node's construction.
Render traceback of a node's creation in Python, if available.
[ "Render", "traceback", "of", "a", "node", "s", "creation", "in", "Python", "if", "available", "." ]
def _render_node_traceback(self, node_name): """Render traceback of a node's creation in Python, if available. Args: node_name: (str) name of the node. Returns: A RichTextLines object containing the stack trace of the node's construction. """ lines = [RL(""), RL(""), RL("Traceback of node construction:", "bold")] try: node_stack = self._debug_dump.node_traceback(node_name) for depth, (file_path, line, function_name, text) in enumerate( node_stack): lines.append("%d: %s" % (depth, file_path)) attribute = debugger_cli_common.MenuItem( "", "ps %s -b %d" % (file_path, line)) if text else None line_number_line = RL(" ") line_number_line += RL("Line: %d" % line, attribute) lines.append(line_number_line) lines.append(" Function: %s" % function_name) lines.append(" Text: " + (("\"%s\"" % text) if text else "None")) lines.append("") except KeyError: lines.append("(Node unavailable in the loaded Python graph)") except LookupError: lines.append("(Unavailable because no Python graph has been loaded)") return debugger_cli_common.rich_text_lines_from_rich_line_list(lines)
[ "def", "_render_node_traceback", "(", "self", ",", "node_name", ")", ":", "lines", "=", "[", "RL", "(", "\"\"", ")", ",", "RL", "(", "\"\"", ")", ",", "RL", "(", "\"Traceback of node construction:\"", ",", "\"bold\"", ")", "]", "try", ":", "node_stack", ...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/cli/analyzer_cli.py#L722-L755
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
BoxSizer.__init__
(self, *args, **kwargs)
__init__(self, int orient=HORIZONTAL) -> BoxSizer Constructor for a wx.BoxSizer. *orient* may be one of ``wx.VERTICAL`` or ``wx.HORIZONTAL`` for creating either a column sizer or a row sizer.
__init__(self, int orient=HORIZONTAL) -> BoxSizer
[ "__init__", "(", "self", "int", "orient", "=", "HORIZONTAL", ")", "-", ">", "BoxSizer" ]
def __init__(self, *args, **kwargs): """ __init__(self, int orient=HORIZONTAL) -> BoxSizer Constructor for a wx.BoxSizer. *orient* may be one of ``wx.VERTICAL`` or ``wx.HORIZONTAL`` for creating either a column sizer or a row sizer. """ _core_.BoxSizer_swiginit(self,_core_.new_BoxSizer(*args, **kwargs)) self._setOORInfo(self)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_core_", ".", "BoxSizer_swiginit", "(", "self", ",", "_core_", ".", "new_BoxSizer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOORInfo",...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L15078-L15087
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
api/ctpx/ctptd.py
python
CtpTd.onRspOrderAction
(self, InputOrderActionField, RspInfoField, requestId, final)
报单操作请求响应
报单操作请求响应
[ "报单操作请求响应" ]
def onRspOrderAction(self, InputOrderActionField, RspInfoField, requestId, final): """报单操作请求响应""" # print u"onRspOrderAction --- sessionId: {0}, frontID: {1}, orderRef: {2}".format(InputOrderActionField.sessionID, # InputOrderActionField.frontID, InputOrderActionField.orderRef) # print(u"onRspOrderAction --- errorCode:{0}, errorMsg:{1}.".format( # RspInfoField.errorID, RspInfoField.errorMsg.decode('gbk'))) for listener in self._barEventListeners: listener.onRspOrderInsert(InputOrderActionField, RspInfoField)
[ "def", "onRspOrderAction", "(", "self", ",", "InputOrderActionField", ",", "RspInfoField", ",", "requestId", ",", "final", ")", ":", "# print u\"onRspOrderAction --- sessionId: {0}, frontID: {1}, orderRef: {2}\".format(InputOrderActionField.sessionID,", "# InputOrderActionField...
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/api/ctpx/ctptd.py#L116-L123
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/framework.py
python
name_scope
(prefix=None)
:api_attr: Static Graph Generate hierarchical name prefix for the operators in Static Graph. Note: This should only used for debugging and visualization purpose. Don't use it for serious analysis such as graph/program transformations. Don't use it in dygraph, since it will cause memory leak. Args: prefix(str, optional): prefix. Default is none. Examples: .. code-block:: python import paddle paddle.enable_static() with paddle.static.name_scope("s1"): a = paddle.static.data(name='data', shape=[None, 1], dtype='int32') b = a + 1 with paddle.static.name_scope("s2"): c = b * 1 with paddle.static.name_scope("s3"): d = c / 1 with paddle.static.name_scope("s1"): f = paddle.tensor.pow(d, 2.0) with paddle.static.name_scope("s4"): g = f - 1 # Op are created in the default main program. for op in paddle.static.default_main_program().block(0).ops: # elementwise_add is created in /s1/ if op.type == 'elementwise_add': assert op.desc.attr("op_namescope") == '/s1/' # elementwise_mul is created in '/s1/s2' elif op.type == 'elementwise_mul': assert op.desc.attr("op_namescope") == '/s1/s2/' # elementwise_div is created in '/s1/s3' elif op.type == 'elementwise_div': assert op.desc.attr("op_namescope") == '/s1/s3/' # elementwise_sum is created in '/s4' elif op.type == 'elementwise_sub': assert op.desc.attr("op_namescope") == '/s4/' # pow is created in /s1_1/ elif op.type == 'pow': assert op.desc.attr("op_namescope") == '/s1_1/'
:api_attr: Static Graph
[ ":", "api_attr", ":", "Static", "Graph" ]
def name_scope(prefix=None): """ :api_attr: Static Graph Generate hierarchical name prefix for the operators in Static Graph. Note: This should only used for debugging and visualization purpose. Don't use it for serious analysis such as graph/program transformations. Don't use it in dygraph, since it will cause memory leak. Args: prefix(str, optional): prefix. Default is none. Examples: .. code-block:: python import paddle paddle.enable_static() with paddle.static.name_scope("s1"): a = paddle.static.data(name='data', shape=[None, 1], dtype='int32') b = a + 1 with paddle.static.name_scope("s2"): c = b * 1 with paddle.static.name_scope("s3"): d = c / 1 with paddle.static.name_scope("s1"): f = paddle.tensor.pow(d, 2.0) with paddle.static.name_scope("s4"): g = f - 1 # Op are created in the default main program. for op in paddle.static.default_main_program().block(0).ops: # elementwise_add is created in /s1/ if op.type == 'elementwise_add': assert op.desc.attr("op_namescope") == '/s1/' # elementwise_mul is created in '/s1/s2' elif op.type == 'elementwise_mul': assert op.desc.attr("op_namescope") == '/s1/s2/' # elementwise_div is created in '/s1/s3' elif op.type == 'elementwise_div': assert op.desc.attr("op_namescope") == '/s1/s3/' # elementwise_sum is created in '/s4' elif op.type == 'elementwise_sub': assert op.desc.attr("op_namescope") == '/s4/' # pow is created in /s1_1/ elif op.type == 'pow': assert op.desc.attr("op_namescope") == '/s1_1/' """ # TODO(panyx0718): Only [0-9a-z]. # in dygraph we don't need namescope since it will cause mem leak if in_dygraph_mode(): yield else: assert prefix, "namescope prefix can not be empty." global _name_scope _name_scope = _name_scope.child(prefix) try: yield finally: _name_scope = _name_scope.parent()
[ "def", "name_scope", "(", "prefix", "=", "None", ")", ":", "# TODO(panyx0718): Only [0-9a-z].", "# in dygraph we don't need namescope since it will cause mem leak", "if", "in_dygraph_mode", "(", ")", ":", "yield", "else", ":", "assert", "prefix", ",", "\"namescope prefix ca...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/framework.py#L883-L943
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/torch.py
python
_init_torch_module
()
List and add all the torch backed ndarray functions to current module.
List and add all the torch backed ndarray functions to current module.
[ "List", "and", "add", "all", "the", "torch", "backed", "ndarray", "functions", "to", "current", "module", "." ]
def _init_torch_module(): """List and add all the torch backed ndarray functions to current module.""" plist = ctypes.POINTER(FunctionHandle)() size = ctypes.c_uint() check_call(_LIB.MXListFunctions(ctypes.byref(size), ctypes.byref(plist))) module_obj = sys.modules[__name__] for i in range(size.value): hdl = FunctionHandle(plist[i]) function = _make_torch_function(hdl) # if function name starts with underscore, register as static method of NDArray if function is not None: setattr(module_obj, function.__name__, function)
[ "def", "_init_torch_module", "(", ")", ":", "plist", "=", "ctypes", ".", "POINTER", "(", "FunctionHandle", ")", "(", ")", "size", "=", "ctypes", ".", "c_uint", "(", ")", "check_call", "(", "_LIB", ".", "MXListFunctions", "(", "ctypes", ".", "byref", "(",...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/torch.py#L167-L180
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/jinja2/environment.py
python
Environment.call_filter
(self, name, value, args=None, kwargs=None, context=None, eval_ctx=None)
return func(*args, **(kwargs or {}))
Invokes a filter on a value the same way the compiler does it. .. versionadded:: 2.7
Invokes a filter on a value the same way the compiler does it.
[ "Invokes", "a", "filter", "on", "a", "value", "the", "same", "way", "the", "compiler", "does", "it", "." ]
def call_filter(self, name, value, args=None, kwargs=None, context=None, eval_ctx=None): """Invokes a filter on a value the same way the compiler does it. .. versionadded:: 2.7 """ func = self.filters.get(name) if func is None: raise TemplateRuntimeError('no filter named %r' % name) args = [value] + list(args or ()) if getattr(func, 'contextfilter', False): if context is None: raise TemplateRuntimeError('Attempted to invoke context ' 'filter without context') args.insert(0, context) elif getattr(func, 'evalcontextfilter', False): if eval_ctx is None: if context is not None: eval_ctx = context.eval_ctx else: eval_ctx = EvalContext(self) args.insert(0, eval_ctx) elif getattr(func, 'environmentfilter', False): args.insert(0, self) return func(*args, **(kwargs or {}))
[ "def", "call_filter", "(", "self", ",", "name", ",", "value", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "context", "=", "None", ",", "eval_ctx", "=", "None", ")", ":", "func", "=", "self", ".", "filters", ".", "get", "(", "name", ...
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/environment.py#L405-L429
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
graph/library/graph.py
python
Graph.add_vertex
(self, node)
Adds new vertex to graph. If vertex is already present in graph, no action will take place. :param node: new node to be added to graph
Adds new vertex to graph. If vertex is already present in graph, no action will take place. :param node: new node to be added to graph
[ "Adds", "new", "vertex", "to", "graph", ".", "If", "vertex", "is", "already", "present", "in", "graph", "no", "action", "will", "take", "place", ".", ":", "param", "node", ":", "new", "node", "to", "be", "added", "to", "graph" ]
def add_vertex(self, node): """ Adds new vertex to graph. If vertex is already present in graph, no action will take place. :param node: new node to be added to graph """ if node not in self._graph_dict: self._graph_dict[node] = []
[ "def", "add_vertex", "(", "self", ",", "node", ")", ":", "if", "node", "not", "in", "self", ".", "_graph_dict", ":", "self", ".", "_graph_dict", "[", "node", "]", "=", "[", "]" ]
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/graph/library/graph.py#L21-L27
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/v8/third_party/jinja2/runtime.py
python
Context.get
(self, key, default=None)
Returns an item from the template context, if it doesn't exist `default` is returned.
Returns an item from the template context, if it doesn't exist `default` is returned.
[ "Returns", "an", "item", "from", "the", "template", "context", "if", "it", "doesn", "t", "exist", "default", "is", "returned", "." ]
def get(self, key, default=None): """Returns an item from the template context, if it doesn't exist `default` is returned. """ try: return self[key] except KeyError: return default
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "try", ":", "return", "self", "[", "key", "]", "except", "KeyError", ":", "return", "default" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/runtime.py#L187-L194
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/cmd.py
python
Cmd.do_help
(self, arg)
List available commands with "help" or detailed help with "help cmd".
List available commands with "help" or detailed help with "help cmd".
[ "List", "available", "commands", "with", "help", "or", "detailed", "help", "with", "help", "cmd", "." ]
def do_help(self, arg): 'List available commands with "help" or detailed help with "help cmd".' if arg: # XXX check arg syntax try: func = getattr(self, 'help_' + arg) except AttributeError: try: doc=getattr(self, 'do_' + arg).__doc__ if doc: self.stdout.write("%s\n"%str(doc)) return except AttributeError: pass self.stdout.write("%s\n"%str(self.nohelp % (arg,))) return func() else: names = self.get_names() cmds_doc = [] cmds_undoc = [] help = {} for name in names: if name[:5] == 'help_': help[name[5:]]=1 names.sort() # There can be duplicates if routines overridden prevname = '' for name in names: if name[:3] == 'do_': if name == prevname: continue prevname = name cmd=name[3:] if cmd in help: cmds_doc.append(cmd) del help[cmd] elif getattr(self, name).__doc__: cmds_doc.append(cmd) else: cmds_undoc.append(cmd) self.stdout.write("%s\n"%str(self.doc_leader)) self.print_topics(self.doc_header, cmds_doc, 15,80) self.print_topics(self.misc_header, list(help.keys()),15,80) self.print_topics(self.undoc_header, cmds_undoc, 15,80)
[ "def", "do_help", "(", "self", ",", "arg", ")", ":", "if", "arg", ":", "# XXX check arg syntax", "try", ":", "func", "=", "getattr", "(", "self", ",", "'help_'", "+", "arg", ")", "except", "AttributeError", ":", "try", ":", "doc", "=", "getattr", "(", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/cmd.py#L292-L336
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/v8/third_party/jinja2/parser.py
python
Parser.parse_statement
(self)
Parse a single statement.
Parse a single statement.
[ "Parse", "a", "single", "statement", "." ]
def parse_statement(self): """Parse a single statement.""" token = self.stream.current if token.type != 'name': self.fail('tag name expected', token.lineno) self._tag_stack.append(token.value) pop_tag = True try: if token.value in _statement_keywords: return getattr(self, 'parse_' + self.stream.current.value)() if token.value == 'call': return self.parse_call_block() if token.value == 'filter': return self.parse_filter_block() ext = self.extensions.get(token.value) if ext is not None: return ext(self) # did not work out, remove the token we pushed by accident # from the stack so that the unknown tag fail function can # produce a proper error message. self._tag_stack.pop() pop_tag = False self.fail_unknown_tag(token.value, token.lineno) finally: if pop_tag: self._tag_stack.pop()
[ "def", "parse_statement", "(", "self", ")", ":", "token", "=", "self", ".", "stream", ".", "current", "if", "token", ".", "type", "!=", "'name'", ":", "self", ".", "fail", "(", "'tag name expected'", ",", "token", ".", "lineno", ")", "self", ".", "_tag...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/v8/third_party/jinja2/parser.py#L112-L138
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/ir.py
python
FunctionIR.infer_constant
(self, name)
return self._consts.infer_constant(name)
Try to infer the constant value of a given variable.
Try to infer the constant value of a given variable.
[ "Try", "to", "infer", "the", "constant", "value", "of", "a", "given", "variable", "." ]
def infer_constant(self, name): """ Try to infer the constant value of a given variable. """ if isinstance(name, Var): name = name.name return self._consts.infer_constant(name)
[ "def", "infer_constant", "(", "self", ",", "name", ")", ":", "if", "isinstance", "(", "name", ",", "Var", ")", ":", "name", "=", "name", ".", "name", "return", "self", ".", "_consts", ".", "infer_constant", "(", "name", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/ir.py#L1394-L1400
zhaoweicai/mscnn
534bcac5710a579d60827f192035f7eef6d8c585
scripts/cpp_lint.py
python
_Filters
()
return _cpplint_state.filters
Returns the module's list of output filters, as a list.
Returns the module's list of output filters, as a list.
[ "Returns", "the", "module", "s", "list", "of", "output", "filters", "as", "a", "list", "." ]
def _Filters(): """Returns the module's list of output filters, as a list.""" return _cpplint_state.filters
[ "def", "_Filters", "(", ")", ":", "return", "_cpplint_state", ".", "filters" ]
https://github.com/zhaoweicai/mscnn/blob/534bcac5710a579d60827f192035f7eef6d8c585/scripts/cpp_lint.py#L792-L794
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/configobj/validate.py
python
is_float
(value, min=None, max=None)
return value
A check that tests that a given value is a float (an integer will be accepted), and optionally - that it is between bounds. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. This can accept negative values. >>> vtor.check('float', '2') 2.0 From now on we multiply the value to avoid comparing decimals >>> vtor.check('float', '-6.8') * 10 -68.0 >>> vtor.check('float', '12.2') * 10 122.0 >>> vtor.check('float', 8.4) * 10 84.0 >>> vtor.check('float', 'a') Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. >>> vtor.check('float(10.1)', '10.2') * 10 102.0 >>> vtor.check('float(max=20.2)', '15.1') * 10 151.0 >>> vtor.check('float(10.0)', '9.0') Traceback (most recent call last): VdtValueTooSmallError: the value "9.0" is too small. >>> vtor.check('float(max=20.0)', '35.0') Traceback (most recent call last): VdtValueTooBigError: the value "35.0" is too big.
A check that tests that a given value is a float (an integer will be accepted), and optionally - that it is between bounds. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. This can accept negative values. >>> vtor.check('float', '2') 2.0 From now on we multiply the value to avoid comparing decimals >>> vtor.check('float', '-6.8') * 10 -68.0 >>> vtor.check('float', '12.2') * 10 122.0 >>> vtor.check('float', 8.4) * 10 84.0 >>> vtor.check('float', 'a') Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. >>> vtor.check('float(10.1)', '10.2') * 10 102.0 >>> vtor.check('float(max=20.2)', '15.1') * 10 151.0 >>> vtor.check('float(10.0)', '9.0') Traceback (most recent call last): VdtValueTooSmallError: the value "9.0" is too small. >>> vtor.check('float(max=20.0)', '35.0') Traceback (most recent call last): VdtValueTooBigError: the value "35.0" is too big.
[ "A", "check", "that", "tests", "that", "a", "given", "value", "is", "a", "float", "(", "an", "integer", "will", "be", "accepted", ")", "and", "optionally", "-", "that", "it", "is", "between", "bounds", ".", "If", "the", "value", "is", "a", "string", ...
def is_float(value, min=None, max=None): """ A check that tests that a given value is a float (an integer will be accepted), and optionally - that it is between bounds. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. This can accept negative values. >>> vtor.check('float', '2') 2.0 From now on we multiply the value to avoid comparing decimals >>> vtor.check('float', '-6.8') * 10 -68.0 >>> vtor.check('float', '12.2') * 10 122.0 >>> vtor.check('float', 8.4) * 10 84.0 >>> vtor.check('float', 'a') Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. >>> vtor.check('float(10.1)', '10.2') * 10 102.0 >>> vtor.check('float(max=20.2)', '15.1') * 10 151.0 >>> vtor.check('float(10.0)', '9.0') Traceback (most recent call last): VdtValueTooSmallError: the value "9.0" is too small. >>> vtor.check('float(max=20.0)', '35.0') Traceback (most recent call last): VdtValueTooBigError: the value "35.0" is too big. """ (min_val, max_val) = _is_num_param( ('min', 'max'), (min, max), to_float=True) if not isinstance(value, (int, long, float, basestring)): raise VdtTypeError(value) if not isinstance(value, float): # if it's a string - does it represent a float ? try: value = float(value) except ValueError: raise VdtTypeError(value) if (min_val is not None) and (value < min_val): raise VdtValueTooSmallError(value) if (max_val is not None) and (value > max_val): raise VdtValueTooBigError(value) return value
[ "def", "is_float", "(", "value", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "(", "min_val", ",", "max_val", ")", "=", "_is_num_param", "(", "(", "'min'", ",", "'max'", ")", ",", "(", "min", ",", "max", ")", ",", "to_float", "=", ...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/configobj/validate.py#L811-L860
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/distutils/misc_util.py
python
get_path_from_frame
(frame, parent_path=None)
return d or '.'
Return path of the module given a frame object from the call stack. Returned path is relative to parent_path when given, otherwise it is absolute path.
Return path of the module given a frame object from the call stack.
[ "Return", "path", "of", "the", "module", "given", "a", "frame", "object", "from", "the", "call", "stack", "." ]
def get_path_from_frame(frame, parent_path=None): """Return path of the module given a frame object from the call stack. Returned path is relative to parent_path when given, otherwise it is absolute path. """ # First, try to find if the file name is in the frame. try: caller_file = eval('__file__', frame.f_globals, frame.f_locals) d = os.path.dirname(os.path.abspath(caller_file)) except NameError: # __file__ is not defined, so let's try __name__. We try this second # because setuptools spoofs __name__ to be '__main__' even though # sys.modules['__main__'] might be something else, like easy_install(1). caller_name = eval('__name__', frame.f_globals, frame.f_locals) __import__(caller_name) mod = sys.modules[caller_name] if hasattr(mod, '__file__'): d = os.path.dirname(os.path.abspath(mod.__file__)) else: # we're probably running setup.py as execfile("setup.py") # (likely we're building an egg) d = os.path.abspath('.') # hmm, should we use sys.argv[0] like in __builtin__ case? if parent_path is not None: d = rel_path(d, parent_path) return d or '.'
[ "def", "get_path_from_frame", "(", "frame", ",", "parent_path", "=", "None", ")", ":", "# First, try to find if the file name is in the frame.", "try", ":", "caller_file", "=", "eval", "(", "'__file__'", ",", "frame", ".", "f_globals", ",", "frame", ".", "f_locals",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/distutils/misc_util.py#L146-L175
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags.py
python
MarkFlagAsRequired
(flag_name, flag_values=FLAGS)
Ensure that flag is not None during program execution. Registers a flag validator, which will follow usual validator rules. Args: flag_name: string, name of the flag flag_values: FlagValues Raises: AttributeError: if flag_name is not registered as a valid flag name.
Ensure that flag is not None during program execution.
[ "Ensure", "that", "flag", "is", "not", "None", "during", "program", "execution", "." ]
def MarkFlagAsRequired(flag_name, flag_values=FLAGS): """Ensure that flag is not None during program execution. Registers a flag validator, which will follow usual validator rules. Args: flag_name: string, name of the flag flag_values: FlagValues Raises: AttributeError: if flag_name is not registered as a valid flag name. """ RegisterValidator(flag_name, lambda value: value is not None, message='Flag --%s must be specified.' % flag_name, flag_values=flag_values)
[ "def", "MarkFlagAsRequired", "(", "flag_name", ",", "flag_values", "=", "FLAGS", ")", ":", "RegisterValidator", "(", "flag_name", ",", "lambda", "value", ":", "value", "is", "not", "None", ",", "message", "=", "'Flag --%s must be specified.'", "%", "flag_name", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/python-gflags/gflags.py#L2112-L2126
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/compiler/xla/experimental/xla_sharding/xla_sharding.py
python
Sharding.assign_device
(cls, core)
return Sharding( proto=xla_data_pb2.OpSharding( type=xla_data_pb2.OpSharding.MAXIMAL, tile_assignment_dimensions=[1], tile_assignment_devices=[core]))
Returns an AssignDevice sharding attribute. This causes an op to be computed in its entirety only on one core in the XLA device. Args: core: The core to assign this Op to.
Returns an AssignDevice sharding attribute.
[ "Returns", "an", "AssignDevice", "sharding", "attribute", "." ]
def assign_device(cls, core): """Returns an AssignDevice sharding attribute. This causes an op to be computed in its entirety only on one core in the XLA device. Args: core: The core to assign this Op to. """ return Sharding( proto=xla_data_pb2.OpSharding( type=xla_data_pb2.OpSharding.MAXIMAL, tile_assignment_dimensions=[1], tile_assignment_devices=[core]))
[ "def", "assign_device", "(", "cls", ",", "core", ")", ":", "return", "Sharding", "(", "proto", "=", "xla_data_pb2", ".", "OpSharding", "(", "type", "=", "xla_data_pb2", ".", "OpSharding", ".", "MAXIMAL", ",", "tile_assignment_dimensions", "=", "[", "1", "]",...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/compiler/xla/experimental/xla_sharding/xla_sharding.py#L56-L68
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/protobuf/python/google/protobuf/internal/well_known_types.py
python
FieldMask.FromJsonString
(self, value)
Converts string to FieldMask according to proto3 JSON spec.
Converts string to FieldMask according to proto3 JSON spec.
[ "Converts", "string", "to", "FieldMask", "according", "to", "proto3", "JSON", "spec", "." ]
def FromJsonString(self, value): """Converts string to FieldMask according to proto3 JSON spec.""" self.Clear() for path in value.split(','): self.paths.append(path)
[ "def", "FromJsonString", "(", "self", ",", "value", ")", ":", "self", ".", "Clear", "(", ")", "for", "path", "in", "value", ".", "split", "(", "','", ")", ":", "self", ".", "paths", ".", "append", "(", "path", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/protobuf/python/google/protobuf/internal/well_known_types.py#L384-L388
mapequation/infomap
5f56b94fe0f956483f61a03ef07e94d8def2205e
interfaces/python/infomap.py
python
Infomap.module_codelength
(self)
return super().getModuleCodelength()
Get the total codelength of the modules. The module codelength is defined such that ``codelength = index_codelength + module_codelength`` For a hierarchical solution, the module codelength is the sum of codelengths for each top module. See Also -------- codelength index_codelength Returns ------- float The module codelength
Get the total codelength of the modules.
[ "Get", "the", "total", "codelength", "of", "the", "modules", "." ]
def module_codelength(self): """Get the total codelength of the modules. The module codelength is defined such that ``codelength = index_codelength + module_codelength`` For a hierarchical solution, the module codelength is the sum of codelengths for each top module. See Also -------- codelength index_codelength Returns ------- float The module codelength """ return super().getModuleCodelength()
[ "def", "module_codelength", "(", "self", ")", ":", "return", "super", "(", ")", ".", "getModuleCodelength", "(", ")" ]
https://github.com/mapequation/infomap/blob/5f56b94fe0f956483f61a03ef07e94d8def2205e/interfaces/python/infomap.py#L2212-L2231
JoseExposito/touchegg
1f3fda214358d071c05da4bf17c070c33d67b5eb
cmake/cpplint.py
python
_IncludeState.ResetSection
(self, directive)
Reset section checking for preprocessor directive. Args: directive: preprocessor directive (e.g. "if", "else").
Reset section checking for preprocessor directive.
[ "Reset", "section", "checking", "for", "preprocessor", "directive", "." ]
def ResetSection(self, directive): """Reset section checking for preprocessor directive. Args: directive: preprocessor directive (e.g. "if", "else"). """ # The name of the current section. self._section = self._INITIAL_SECTION # The path of last found header. self._last_header = '' # Update list of includes. Note that we never pop from the # include list. if directive in ('if', 'ifdef', 'ifndef'): self.include_list.append([]) elif directive in ('else', 'elif'): self.include_list[-1] = []
[ "def", "ResetSection", "(", "self", ",", "directive", ")", ":", "# The name of the current section.", "self", ".", "_section", "=", "self", ".", "_INITIAL_SECTION", "# The path of last found header.", "self", ".", "_last_header", "=", "''", "# Update list of includes. No...
https://github.com/JoseExposito/touchegg/blob/1f3fda214358d071c05da4bf17c070c33d67b5eb/cmake/cpplint.py#L751-L767
materialx/MaterialX
77ff72f352470b5c76dddde765951a8e3bcf79fc
python/MaterialX/main.py
python
_getActiveParameters
(self)
return list()
(Deprecated) Return a vector of all parameters belonging to this interface, taking inheritance into account.
(Deprecated) Return a vector of all parameters belonging to this interface, taking inheritance into account.
[ "(", "Deprecated", ")", "Return", "a", "vector", "of", "all", "parameters", "belonging", "to", "this", "interface", "taking", "inheritance", "into", "account", "." ]
def _getActiveParameters(self): """(Deprecated) Return a vector of all parameters belonging to this interface, taking inheritance into account.""" warnings.warn("This function is deprecated; parameters have been replaced with uniform inputs in 1.38.", DeprecationWarning, stacklevel = 2) return list()
[ "def", "_getActiveParameters", "(", "self", ")", ":", "warnings", ".", "warn", "(", "\"This function is deprecated; parameters have been replaced with uniform inputs in 1.38.\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "return", "list", "(", ")" ]
https://github.com/materialx/MaterialX/blob/77ff72f352470b5c76dddde765951a8e3bcf79fc/python/MaterialX/main.py#L114-L117
esa/pykep
b410363653623730b577de257c04b0e0289f2014
pykep/phasing/__init__.py
python
three_impulses_approx
(pl1, pl2, ep1=None, ep2=None)
return _three_impulses_approx(pl1, pl2, ep1, ep2)
DV = pykep.phasing.three_impulses_approx(pl1, pl2, ep1=None, ep2=None) - pl1: departure planet - pl2: arrival planet - ep1: departure epoch (optional and only useful for non keplerian planets) - ep1: arrival epoch (default value is ep1). - [out] DV: estimated DV cost for the orbital trab=nsfer Returns the DV in m/s necessary for an orbit transfer between pl1 and pl2 assuming a perfect phasing. The transfer will be made of three impulses. One to match apogees, one to match inclination and RAAN and one to match perigees. Two of the three impulses will be merged together at either departure or arrival. The argument of perigee is not matched, so that this approximation is only good for near-circular orbits. Examples:: DV = three_impulses_approx(pl1, pl2) DV = three_impulses_approx(pl1, pl2, ep1 = epoch(5500)) DV = three_impulses_approx(pl1, pl2, ep1 = epoch(5500), ep2 = epoch(5700))
DV = pykep.phasing.three_impulses_approx(pl1, pl2, ep1=None, ep2=None)
[ "DV", "=", "pykep", ".", "phasing", ".", "three_impulses_approx", "(", "pl1", "pl2", "ep1", "=", "None", "ep2", "=", "None", ")" ]
def three_impulses_approx(pl1, pl2, ep1=None, ep2=None): """ DV = pykep.phasing.three_impulses_approx(pl1, pl2, ep1=None, ep2=None) - pl1: departure planet - pl2: arrival planet - ep1: departure epoch (optional and only useful for non keplerian planets) - ep1: arrival epoch (default value is ep1). - [out] DV: estimated DV cost for the orbital trab=nsfer Returns the DV in m/s necessary for an orbit transfer between pl1 and pl2 assuming a perfect phasing. The transfer will be made of three impulses. One to match apogees, one to match inclination and RAAN and one to match perigees. Two of the three impulses will be merged together at either departure or arrival. The argument of perigee is not matched, so that this approximation is only good for near-circular orbits. Examples:: DV = three_impulses_approx(pl1, pl2) DV = three_impulses_approx(pl1, pl2, ep1 = epoch(5500)) DV = three_impulses_approx(pl1, pl2, ep1 = epoch(5500), ep2 = epoch(5700)) """ from pykep.core import _three_impulses_approx if ep2 is None: ep2 = ep1 if ep1 is None: return _three_impulses_approx(pl1, pl2) return _three_impulses_approx(pl1, pl2, ep1, ep2)
[ "def", "three_impulses_approx", "(", "pl1", ",", "pl2", ",", "ep1", "=", "None", ",", "ep2", "=", "None", ")", ":", "from", "pykep", ".", "core", "import", "_three_impulses_approx", "if", "ep2", "is", "None", ":", "ep2", "=", "ep1", "if", "ep1", "is", ...
https://github.com/esa/pykep/blob/b410363653623730b577de257c04b0e0289f2014/pykep/phasing/__init__.py#L17-L45
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/mock/mock.py
python
_patch.start
(self)
return result
Activate a patch, returning any created mock.
Activate a patch, returning any created mock.
[ "Activate", "a", "patch", "returning", "any", "created", "mock", "." ]
def start(self): """Activate a patch, returning any created mock.""" result = self.__enter__() self._active_patches.add(self) return result
[ "def", "start", "(", "self", ")", ":", "result", "=", "self", ".", "__enter__", "(", ")", "self", ".", "_active_patches", ".", "add", "(", "self", ")", "return", "result" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mock/mock.py#L1394-L1398
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py
python
Context.remainder_near
(self, a, b)
return a.remainder_near(b, context=self)
Returns to be "a - b * n", where n is the integer nearest the exact value of "x / b" (if two integers are equally near then the even one is chosen). If the result is equal to 0 then its sign will be the sign of a. This operation will fail under the same conditions as integer division (that is, if integer division on the same two operands would fail, the remainder cannot be calculated). >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) Decimal('-0.9') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) Decimal('-2') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) Decimal('1') >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) Decimal('-1') >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) Decimal('0.2') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) Decimal('0.1') >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) Decimal('-0.3') >>> ExtendedContext.remainder_near(3, 11) Decimal('3') >>> ExtendedContext.remainder_near(Decimal(3), 11) Decimal('3') >>> ExtendedContext.remainder_near(3, Decimal(11)) Decimal('3')
Returns to be "a - b * n", where n is the integer nearest the exact value of "x / b" (if two integers are equally near then the even one is chosen). If the result is equal to 0 then its sign will be the sign of a.
[ "Returns", "to", "be", "a", "-", "b", "*", "n", "where", "n", "is", "the", "integer", "nearest", "the", "exact", "value", "of", "x", "/", "b", "(", "if", "two", "integers", "are", "equally", "near", "then", "the", "even", "one", "is", "chosen", ")"...
def remainder_near(self, a, b): """Returns to be "a - b * n", where n is the integer nearest the exact value of "x / b" (if two integers are equally near then the even one is chosen). If the result is equal to 0 then its sign will be the sign of a. This operation will fail under the same conditions as integer division (that is, if integer division on the same two operands would fail, the remainder cannot be calculated). >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) Decimal('-0.9') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) Decimal('-2') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) Decimal('1') >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) Decimal('-1') >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) Decimal('0.2') >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) Decimal('0.1') >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) Decimal('-0.3') >>> ExtendedContext.remainder_near(3, 11) Decimal('3') >>> ExtendedContext.remainder_near(Decimal(3), 11) Decimal('3') >>> ExtendedContext.remainder_near(3, Decimal(11)) Decimal('3') """ a = _convert_other(a, raiseit=True) return a.remainder_near(b, context=self)
[ "def", "remainder_near", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "remainder_near", "(", "b", ",", "context", "=", "self", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py#L5149-L5181
freesurfer/freesurfer
6dbe527d43ffa611acb2cd112e9469f9bfec8e36
cnn_sphere_register/ext/neuron/neuron/utils.py
python
volshape_to_meshgrid
(volshape, **kwargs)
return tf.meshgrid(*linvec, **kwargs)
compute Tensor meshgrid from a volume size Parameters: volshape: the volume size **args: "name" (optional) Returns: A list of Tensors See Also: tf.meshgrid, ndgrid, volshape_to_ndgrid
compute Tensor meshgrid from a volume size
[ "compute", "Tensor", "meshgrid", "from", "a", "volume", "size" ]
def volshape_to_meshgrid(volshape, **kwargs): """ compute Tensor meshgrid from a volume size Parameters: volshape: the volume size **args: "name" (optional) Returns: A list of Tensors See Also: tf.meshgrid, ndgrid, volshape_to_ndgrid """ isint = [float(d).is_integer() for d in volshape] if not all(isint): raise ValueError("volshape needs to be a list of integers") linvec = [tf.range(0, d) for d in volshape] return tf.meshgrid(*linvec, **kwargs)
[ "def", "volshape_to_meshgrid", "(", "volshape", ",", "*", "*", "kwargs", ")", ":", "isint", "=", "[", "float", "(", "d", ")", ".", "is_integer", "(", ")", "for", "d", "in", "volshape", "]", "if", "not", "all", "(", "isint", ")", ":", "raise", "Valu...
https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/cnn_sphere_register/ext/neuron/neuron/utils.py#L368-L388
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/array_ops.py
python
_BitcastShape
(op)
Shape function for Bitcast op.
Shape function for Bitcast op.
[ "Shape", "function", "for", "Bitcast", "op", "." ]
def _BitcastShape(op): """Shape function for Bitcast op.""" input_shape = op.inputs[0].get_shape() if input_shape == tensor_shape.unknown_shape(): return [tensor_shape.unknown_shape()] input_type = op.inputs[0].dtype size_of_input = input_type.size output = dtypes.as_dtype(op.get_attr("type")) size_of_output = output.size if size_of_input == size_of_output: return [input_shape] else: if size_of_output > size_of_input: new_shape = input_shape.with_rank_at_least(1).as_list() last_val = new_shape[-1] if last_val is None or last_val == (size_of_output // size_of_input): new_shape = new_shape[:-1] else: raise ValueError( "Cannot bitcast due to shape. %d is not evenly divisible by %d." % (new_shape[-1], size_of_input // size_of_output)) else: new_shape = input_shape new_shape = new_shape.concatenate([size_of_input // size_of_output]) return [tensor_shape.TensorShape(new_shape)]
[ "def", "_BitcastShape", "(", "op", ")", ":", "input_shape", "=", "op", ".", "inputs", "[", "0", "]", ".", "get_shape", "(", ")", "if", "input_shape", "==", "tensor_shape", ".", "unknown_shape", "(", ")", ":", "return", "[", "tensor_shape", ".", "unknown_...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/array_ops.py#L1806-L1830
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
util/minorview/view.py
python
BlobView.set_da_size
(self)
Set the DrawingArea size after scaling
Set the DrawingArea size after scaling
[ "Set", "the", "DrawingArea", "size", "after", "scaling" ]
def set_da_size(self): """Set the DrawingArea size after scaling""" self.da.set_size_request(10 , int(self.initialHeight))
[ "def", "set_da_size", "(", "self", ")", ":", "self", ".", "da", ".", "set_size_request", "(", "10", ",", "int", "(", "self", ".", "initialHeight", ")", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/util/minorview/view.py#L179-L181
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
python
Grid.grid_remove
(self)
Unmap this widget but remember the grid options.
Unmap this widget but remember the grid options.
[ "Unmap", "this", "widget", "but", "remember", "the", "grid", "options", "." ]
def grid_remove(self): """Unmap this widget but remember the grid options.""" self.tk.call('grid', 'remove', self._w)
[ "def", "grid_remove", "(", "self", ")", ":", "self", ".", "tk", ".", "call", "(", "'grid'", ",", "'remove'", ",", "self", ".", "_w", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L2234-L2236
zhaoweicai/cascade-rcnn
2252f46158ea6555868ca6fa5c221ea71d9b5e6c
scripts/cpp_lint.py
python
_NamespaceInfo.CheckEnd
(self, filename, clean_lines, linenum, error)
Check end of namespace comments.
Check end of namespace comments.
[ "Check", "end", "of", "namespace", "comments", "." ]
def CheckEnd(self, filename, clean_lines, linenum, error): """Check end of namespace comments.""" line = clean_lines.raw_lines[linenum] # Check how many lines is enclosed in this namespace. Don't issue # warning for missing namespace comments if there aren't enough # lines. However, do apply checks if there is already an end of # namespace comment and it's incorrect. # # TODO(unknown): We always want to check end of namespace comments # if a namespace is large, but sometimes we also want to apply the # check if a short namespace contained nontrivial things (something # other than forward declarations). There is currently no logic on # deciding what these nontrivial things are, so this check is # triggered by namespace size only, which works most of the time. if (linenum - self.starting_linenum < 10 and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)): return # Look for matching comment at end of namespace. # # Note that we accept C style "/* */" comments for terminating # namespaces, so that code that terminate namespaces inside # preprocessor macros can be cpplint clean. # # We also accept stuff like "// end of namespace <name>." with the # period at the end. # # Besides these, we don't accept anything else, otherwise we might # get false negatives when existing comment is a substring of the # expected namespace. if self.name: # Named namespace if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + r'[\*/\.\\\s]*$'), line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace %s"' % self.name) else: # Anonymous namespace if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace"')
[ "def", "CheckEnd", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "raw_lines", "[", "linenum", "]", "# Check how many lines is enclosed in this namespace. Don't issue", "# warning for missing n...
https://github.com/zhaoweicai/cascade-rcnn/blob/2252f46158ea6555868ca6fa5c221ea71d9b5e6c/scripts/cpp_lint.py#L1860-L1903
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
tools/isolate/merge_isolate.py
python
invert_map
(variables)
return out, set(variables)
Converts a dict(OS, dict(deptype, list(dependencies)) to a flattened view. Returns a tuple of: 1. dict(deptype, dict(dependency, set(OSes)) for easier processing. 2. All the OSes found as a set.
Converts a dict(OS, dict(deptype, list(dependencies)) to a flattened view.
[ "Converts", "a", "dict", "(", "OS", "dict", "(", "deptype", "list", "(", "dependencies", "))", "to", "a", "flattened", "view", "." ]
def invert_map(variables): """Converts a dict(OS, dict(deptype, list(dependencies)) to a flattened view. Returns a tuple of: 1. dict(deptype, dict(dependency, set(OSes)) for easier processing. 2. All the OSes found as a set. """ KEYS = ( KEY_TRACKED, KEY_UNTRACKED, 'command', 'read_only', ) out = dict((key, {}) for key in KEYS) for os_name, values in variables.iteritems(): for key in (KEY_TRACKED, KEY_UNTRACKED): for item in values.get(key, []): out[key].setdefault(item, set()).add(os_name) # command needs special handling. command = tuple(values.get('command', [])) out['command'].setdefault(command, set()).add(os_name) # read_only needs special handling. out['read_only'].setdefault(values.get('read_only'), set()).add(os_name) return out, set(variables)
[ "def", "invert_map", "(", "variables", ")", ":", "KEYS", "=", "(", "KEY_TRACKED", ",", "KEY_UNTRACKED", ",", "'command'", ",", "'read_only'", ",", ")", "out", "=", "dict", "(", "(", "key", ",", "{", "}", ")", "for", "key", "in", "KEYS", ")", "for", ...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/isolate/merge_isolate.py#L174-L199
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py
python
_decimal_lshift_exact
(n, e)
Given integers n and e, return n * 10**e if it's an integer, else None. The computation is designed to avoid computing large powers of 10 unnecessarily. >>> _decimal_lshift_exact(3, 4) 30000 >>> _decimal_lshift_exact(300, -999999999) # returns None
Given integers n and e, return n * 10**e if it's an integer, else None.
[ "Given", "integers", "n", "and", "e", "return", "n", "*", "10", "**", "e", "if", "it", "s", "an", "integer", "else", "None", "." ]
def _decimal_lshift_exact(n, e): """ Given integers n and e, return n * 10**e if it's an integer, else None. The computation is designed to avoid computing large powers of 10 unnecessarily. >>> _decimal_lshift_exact(3, 4) 30000 >>> _decimal_lshift_exact(300, -999999999) # returns None """ if n == 0: return 0 elif e >= 0: return n * 10**e else: # val_n = largest power of 10 dividing n. str_n = str(abs(n)) val_n = len(str_n) - len(str_n.rstrip('0')) return None if val_n < -e else n // 10**-e
[ "def", "_decimal_lshift_exact", "(", "n", ",", "e", ")", ":", "if", "n", "==", "0", ":", "return", "0", "elif", "e", ">=", "0", ":", "return", "n", "*", "10", "**", "e", "else", ":", "# val_n = largest power of 10 dividing n.", "str_n", "=", "str", "("...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/_pydecimal.py#L5674-L5693
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_aarch64/python2.7/dist-packages/geographic_msgs/msg/_GeoPose.py
python
GeoPose._get_types
(self)
return self._slot_types
internal API method
internal API method
[ "internal", "API", "method" ]
def _get_types(self): """ internal API method """ return self._slot_types
[ "def", "_get_types", "(", "self", ")", ":", "return", "self", ".", "_slot_types" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/geographic_msgs/msg/_GeoPose.py#L77-L81
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/v8/third_party/jinja2/sandbox.py
python
unsafe
(f)
return f
Marks a function or method as unsafe. :: @unsafe def delete(self): pass
Marks a function or method as unsafe.
[ "Marks", "a", "function", "or", "method", "as", "unsafe", "." ]
def unsafe(f): """Marks a function or method as unsafe. :: @unsafe def delete(self): pass """ f.unsafe_callable = True return f
[ "def", "unsafe", "(", "f", ")", ":", "f", ".", "unsafe_callable", "=", "True", "return", "f" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/third_party/jinja2/sandbox.py#L158-L168
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/optimize.py
python
check_grad
(func, grad, x0, *args, **kwargs)
return sqrt(sum((grad(x0, *args) - approx_fprime(x0, func, step, *args))**2))
Check the correctness of a gradient function by comparing it against a (forward) finite-difference approximation of the gradient. Parameters ---------- func : callable ``func(x0, *args)`` Function whose derivative is to be checked. grad : callable ``grad(x0, *args)`` Gradient of `func`. x0 : ndarray Points to check `grad` against forward difference approximation of grad using `func`. args : \\*args, optional Extra arguments passed to `func` and `grad`. epsilon : float, optional Step size used for the finite difference approximation. It defaults to ``sqrt(numpy.finfo(float).eps)``, which is approximately 1.49e-08. Returns ------- err : float The square root of the sum of squares (i.e. the 2-norm) of the difference between ``grad(x0, *args)`` and the finite difference approximation of `grad` using func at the points `x0`. See Also -------- approx_fprime Examples -------- >>> def func(x): ... return x[0]**2 - 0.5 * x[1]**3 >>> def grad(x): ... return [2 * x[0], -1.5 * x[1]**2] >>> from scipy.optimize import check_grad >>> check_grad(func, grad, [1.5, -1.5]) 2.9802322387695312e-08
Check the correctness of a gradient function by comparing it against a (forward) finite-difference approximation of the gradient.
[ "Check", "the", "correctness", "of", "a", "gradient", "function", "by", "comparing", "it", "against", "a", "(", "forward", ")", "finite", "-", "difference", "approximation", "of", "the", "gradient", "." ]
def check_grad(func, grad, x0, *args, **kwargs): """Check the correctness of a gradient function by comparing it against a (forward) finite-difference approximation of the gradient. Parameters ---------- func : callable ``func(x0, *args)`` Function whose derivative is to be checked. grad : callable ``grad(x0, *args)`` Gradient of `func`. x0 : ndarray Points to check `grad` against forward difference approximation of grad using `func`. args : \\*args, optional Extra arguments passed to `func` and `grad`. epsilon : float, optional Step size used for the finite difference approximation. It defaults to ``sqrt(numpy.finfo(float).eps)``, which is approximately 1.49e-08. Returns ------- err : float The square root of the sum of squares (i.e. the 2-norm) of the difference between ``grad(x0, *args)`` and the finite difference approximation of `grad` using func at the points `x0`. See Also -------- approx_fprime Examples -------- >>> def func(x): ... return x[0]**2 - 0.5 * x[1]**3 >>> def grad(x): ... return [2 * x[0], -1.5 * x[1]**2] >>> from scipy.optimize import check_grad >>> check_grad(func, grad, [1.5, -1.5]) 2.9802322387695312e-08 """ step = kwargs.pop('epsilon', _epsilon) if kwargs: raise ValueError("Unknown keyword arguments: %r" % (list(kwargs.keys()),)) return sqrt(sum((grad(x0, *args) - approx_fprime(x0, func, step, *args))**2))
[ "def", "check_grad", "(", "func", ",", "grad", ",", "x0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "step", "=", "kwargs", ".", "pop", "(", "'epsilon'", ",", "_epsilon", ")", "if", "kwargs", ":", "raise", "ValueError", "(", "\"Unknown keyw...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/optimize.py#L733-L779
GoldenCheetah/GoldenCheetah
919a418895040144be5579884446ed6cd701bf0d
travis/macdeployqtfix.py
python
fix_main_binaries
()
return True
list the main binaries of the app bundle and fix them
list the main binaries of the app bundle and fix them
[ "list", "the", "main", "binaries", "of", "the", "app", "bundle", "and", "fix", "them" ]
def fix_main_binaries(): """ list the main binaries of the app bundle and fix them """ # deduce bundle path bundlepath = os.path.sep.join(GlobalConfig.exepath.split(os.path.sep)[0:-3]) # fix main binary GlobalConfig.logger.info('fixing executable \'{0}\''.format(GlobalConfig.exepath)) if fix_binary(GlobalConfig.exepath): GlobalConfig.logger.info('fixing plugins') for root, dummy, files in os.walk(bundlepath): for name in [f for f in files if os.path.splitext(f)[1] == '.dylib']: GlobalConfig.logger.info('fixing plugin {0}'.format(name)) if not fix_binary(os.path.join(root, name)): return False return True
[ "def", "fix_main_binaries", "(", ")", ":", "# deduce bundle path", "bundlepath", "=", "os", ".", "path", ".", "sep", ".", "join", "(", "GlobalConfig", ".", "exepath", ".", "split", "(", "os", ".", "path", ".", "sep", ")", "[", "0", ":", "-", "3", "]"...
https://github.com/GoldenCheetah/GoldenCheetah/blob/919a418895040144be5579884446ed6cd701bf0d/travis/macdeployqtfix.py#L249-L265
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/sim/batch.py
python
saveStateCSV
(state,f)
Given a state dictionary, saves it to CSV format to the given output stream f
Given a state dictionary, saves it to CSV format to the given output stream f
[ "Given", "a", "state", "dictionary", "saves", "it", "to", "CSV", "format", "to", "the", "given", "output", "stream", "f" ]
def saveStateCSV(state,f): """Given a state dictionary, saves it to CSV format to the given output stream f""" saveStateHeaderCSV(state,f) f.write(','.join(str(v) for v in access.flatten(state))) f.write('\n')
[ "def", "saveStateCSV", "(", "state", ",", "f", ")", ":", "saveStateHeaderCSV", "(", "state", ",", "f", ")", "f", ".", "write", "(", "','", ".", "join", "(", "str", "(", "v", ")", "for", "v", "in", "access", ".", "flatten", "(", "state", ")", ")",...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/sim/batch.py#L251-L256
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/framework/python/ops/sampling_ops.py
python
_calculate_acceptance_probabilities
(init_probs, target_probs)
return ratio_l / max_ratio
Calculate the per-class acceptance rates. Args: init_probs: The class probabilities of the data. target_probs: The desired class proportion in minibatches. Returns: A list of the per-class acceptance probabilities. This method is based on solving the following analysis: Let F be the probability of a rejection (on any example). Let p_i be the proportion of examples in the data in class i (init_probs) Let a_i is the rate the rejection sampler should *accept* class i Let t_i is the target proportion in the minibatches for class i (target_probs) ``` F = sum_i(p_i * (1-a_i)) = 1 - sum_i(p_i * a_i) using sum_i(p_i) = 1 ``` An example with class `i` will be accepted if `k` rejections occur, then an example with class `i` is seen by the rejector, and it is accepted. This can be written as follows: ``` t_i = sum_k=0^inf(F^k * p_i * a_i) = p_i * a_j / (1 - F) using geometric series identity, since 0 <= F < 1 = p_i * a_i / sum_j(p_j * a_j) using F from above ``` Note that the following constraints hold: ``` 0 <= p_i <= 1, sum_i(p_i) = 1 0 <= a_i <= 1 0 <= t_i <= 1, sum_i(t_i) = 1 ``` A solution for a_i in terms of the other variabes is the following: ```a_i = (t_i / p_i) / max_i[t_i / p_i]```
Calculate the per-class acceptance rates.
[ "Calculate", "the", "per", "-", "class", "acceptance", "rates", "." ]
def _calculate_acceptance_probabilities(init_probs, target_probs): """Calculate the per-class acceptance rates. Args: init_probs: The class probabilities of the data. target_probs: The desired class proportion in minibatches. Returns: A list of the per-class acceptance probabilities. This method is based on solving the following analysis: Let F be the probability of a rejection (on any example). Let p_i be the proportion of examples in the data in class i (init_probs) Let a_i is the rate the rejection sampler should *accept* class i Let t_i is the target proportion in the minibatches for class i (target_probs) ``` F = sum_i(p_i * (1-a_i)) = 1 - sum_i(p_i * a_i) using sum_i(p_i) = 1 ``` An example with class `i` will be accepted if `k` rejections occur, then an example with class `i` is seen by the rejector, and it is accepted. This can be written as follows: ``` t_i = sum_k=0^inf(F^k * p_i * a_i) = p_i * a_j / (1 - F) using geometric series identity, since 0 <= F < 1 = p_i * a_i / sum_j(p_j * a_j) using F from above ``` Note that the following constraints hold: ``` 0 <= p_i <= 1, sum_i(p_i) = 1 0 <= a_i <= 1 0 <= t_i <= 1, sum_i(t_i) = 1 ``` A solution for a_i in terms of the other variabes is the following: ```a_i = (t_i / p_i) / max_i[t_i / p_i]``` """ # Make list of t_i / p_i. ratio_l = target_probs / init_probs # Replace NaNs with 0s. ratio_l = math_ops.select(math_ops.is_nan(ratio_l), array_ops.zeros_like(ratio_l), ratio_l) # Calculate list of acceptance probabilities. max_ratio = math_ops.reduce_max(ratio_l) return ratio_l / max_ratio
[ "def", "_calculate_acceptance_probabilities", "(", "init_probs", ",", "target_probs", ")", ":", "# Make list of t_i / p_i.", "ratio_l", "=", "target_probs", "/", "init_probs", "# Replace NaNs with 0s.", "ratio_l", "=", "math_ops", ".", "select", "(", "math_ops", ".", "i...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/framework/python/ops/sampling_ops.py#L319-L371
su2code/SU2
72b2fa977b64b9683a388920f05298a40d39e5c5
SU2_PY/SU2/util/ordered_dict.py
python
OrderedDict.__setitem__
(self, key, value, dict_setitem=dict.__setitem__)
od.__setitem__(i, y) <==> od[i]=y
od.__setitem__(i, y) <==> od[i]=y
[ "od", ".", "__setitem__", "(", "i", "y", ")", "<", "==", ">", "od", "[", "i", "]", "=", "y" ]
def __setitem__(self, key, value, dict_setitem=dict.__setitem__): 'od.__setitem__(i, y) <==> od[i]=y' # Setting a new item creates a new link which goes at the end of the linked # list, and the inherited dictionary is updated with the new key/value pair. if key not in self: root = self.__root last = root[0] last[1] = root[0] = self.__map[key] = [last, root, key] dict_setitem(self, key, value)
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ",", "dict_setitem", "=", "dict", ".", "__setitem__", ")", ":", "# Setting a new item creates a new link which goes at the end of the linked", "# list, and the inherited dictionary is updated with the new key/value pair."...
https://github.com/su2code/SU2/blob/72b2fa977b64b9683a388920f05298a40d39e5c5/SU2_PY/SU2/util/ordered_dict.py#L50-L58
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/predictor/predictor_factories.py
python
from_estimator
(estimator, serving_input_receiver_fn, output_key=None, graph=None, config=None)
return core_estimator_predictor.CoreEstimatorPredictor( estimator, serving_input_receiver_fn, output_key=output_key, graph=graph, config=config)
Constructs a `Predictor` from a `tf.python.estimator.Estimator`. Args: estimator: an instance of `learn.python.estimator.Estimator`. serving_input_receiver_fn: a function that takes no arguments and returns an instance of `ServingInputReceiver` compatible with `estimator`. output_key: Optional string specifying the export output to use. If `None`, then `DEFAULT_SERVING_SIGNATURE_DEF_KEY` is used. graph: Optional. The Tensorflow `graph` in which prediction should be done. config: `ConfigProto` proto used to configure the session. Returns: An initialized `Predictor`. Raises: TypeError: if `estimator` is a contrib `Estimator` instead of a core `Estimator`.
Constructs a `Predictor` from a `tf.python.estimator.Estimator`.
[ "Constructs", "a", "Predictor", "from", "a", "tf", ".", "python", ".", "estimator", ".", "Estimator", "." ]
def from_estimator(estimator, serving_input_receiver_fn, output_key=None, graph=None, config=None): """Constructs a `Predictor` from a `tf.python.estimator.Estimator`. Args: estimator: an instance of `learn.python.estimator.Estimator`. serving_input_receiver_fn: a function that takes no arguments and returns an instance of `ServingInputReceiver` compatible with `estimator`. output_key: Optional string specifying the export output to use. If `None`, then `DEFAULT_SERVING_SIGNATURE_DEF_KEY` is used. graph: Optional. The Tensorflow `graph` in which prediction should be done. config: `ConfigProto` proto used to configure the session. Returns: An initialized `Predictor`. Raises: TypeError: if `estimator` is a contrib `Estimator` instead of a core `Estimator`. """ if isinstance(estimator, contrib_estimator.Estimator): raise TypeError('Expected estimator to be of type ' 'tf.python.estimator.Estimator, but got type ' 'tf.contrib.learn.Estimator. You likely want to call ' 'from_contrib_estimator.') return core_estimator_predictor.CoreEstimatorPredictor( estimator, serving_input_receiver_fn, output_key=output_key, graph=graph, config=config)
[ "def", "from_estimator", "(", "estimator", ",", "serving_input_receiver_fn", ",", "output_key", "=", "None", ",", "graph", "=", "None", ",", "config", "=", "None", ")", ":", "if", "isinstance", "(", "estimator", ",", "contrib_estimator", ".", "Estimator", ")",...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/predictor/predictor_factories.py#L71-L105
psnonis/FinBERT
c0c555d833a14e2316a3701e59c0b5156f804b4e
bert-gpu/run_pretraining.py
python
get_next_sentence_output
(bert_config, input_tensor, labels)
Get loss and log probs for the next sentence prediction.
Get loss and log probs for the next sentence prediction.
[ "Get", "loss", "and", "log", "probs", "for", "the", "next", "sentence", "prediction", "." ]
def get_next_sentence_output(bert_config, input_tensor, labels): """Get loss and log probs for the next sentence prediction.""" # Simple binary classification. Note that 0 is "next sentence" and 1 is # "random sentence". This weight matrix is not used after pre-training. with tf.variable_scope("cls/seq_relationship"): output_weights = tf.get_variable( "output_weights", shape=[2, bert_config.hidden_size], initializer=modeling.create_initializer(bert_config.initializer_range)) output_bias = tf.get_variable( "output_bias", shape=[2], initializer=tf.zeros_initializer()) logits = tf.matmul(tf.cast(input_tensor, tf.float32), output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias) log_probs = tf.nn.log_softmax(logits, axis=-1) labels = tf.reshape(labels, [-1]) one_hot_labels = tf.one_hot(labels, depth=2, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) loss = tf.reduce_mean(per_example_loss) return (loss, per_example_loss, log_probs)
[ "def", "get_next_sentence_output", "(", "bert_config", ",", "input_tensor", ",", "labels", ")", ":", "# Simple binary classification. Note that 0 is \"next sentence\" and 1 is", "# \"random sentence\". This weight matrix is not used after pre-training.", "with", "tf", ".", "variable_sc...
https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/run_pretraining.py#L315-L335
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/grid.py
python
Grid.GetCellHighlightColour
(*args, **kwargs)
return _grid.Grid_GetCellHighlightColour(*args, **kwargs)
GetCellHighlightColour(self) -> Colour
GetCellHighlightColour(self) -> Colour
[ "GetCellHighlightColour", "(", "self", ")", "-", ">", "Colour" ]
def GetCellHighlightColour(*args, **kwargs): """GetCellHighlightColour(self) -> Colour""" return _grid.Grid_GetCellHighlightColour(*args, **kwargs)
[ "def", "GetCellHighlightColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_GetCellHighlightColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L1518-L1520
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextBuffer.BeginURL
(*args, **kwargs)
return _richtext.RichTextBuffer_BeginURL(*args, **kwargs)
BeginURL(self, String url, String characterStyle=wxEmptyString) -> bool
BeginURL(self, String url, String characterStyle=wxEmptyString) -> bool
[ "BeginURL", "(", "self", "String", "url", "String", "characterStyle", "=", "wxEmptyString", ")", "-", ">", "bool" ]
def BeginURL(*args, **kwargs): """BeginURL(self, String url, String characterStyle=wxEmptyString) -> bool""" return _richtext.RichTextBuffer_BeginURL(*args, **kwargs)
[ "def", "BeginURL", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextBuffer_BeginURL", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2475-L2477
protocolbuffers/protobuf
b5ab0b7a18b7336c60130f4ddb2d97c51792f896
python/google/protobuf/message.py
python
Message.CopyFrom
(self, other_msg)
Copies the content of the specified message into the current message. The method clears the current message and then merges the specified message using MergeFrom. Args: other_msg (Message): A message to copy into the current one.
Copies the content of the specified message into the current message.
[ "Copies", "the", "content", "of", "the", "specified", "message", "into", "the", "current", "message", "." ]
def CopyFrom(self, other_msg): """Copies the content of the specified message into the current message. The method clears the current message and then merges the specified message using MergeFrom. Args: other_msg (Message): A message to copy into the current one. """ if self is other_msg: return self.Clear() self.MergeFrom(other_msg)
[ "def", "CopyFrom", "(", "self", ",", "other_msg", ")", ":", "if", "self", "is", "other_msg", ":", "return", "self", ".", "Clear", "(", ")", "self", ".", "MergeFrom", "(", "other_msg", ")" ]
https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/message.py#L117-L129
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/cross_device_utils.py
python
stitch_values
(values_and_indices_list)
return result
Stitch values together according to their indices. Args: values_and_indices_list: a list of tuples of values and indices indicating the values and postions in the returned list. Returns: a stitched list of values.
Stitch values together according to their indices.
[ "Stitch", "values", "together", "according", "to", "their", "indices", "." ]
def stitch_values(values_and_indices_list): """Stitch values together according to their indices. Args: values_and_indices_list: a list of tuples of values and indices indicating the values and postions in the returned list. Returns: a stitched list of values. """ length = 0 for values_and_indices in values_and_indices_list: length += len(values_and_indices[0]) result = [None] * length for values_and_indices in values_and_indices_list: if values_and_indices and values_and_indices[0]: for v, i in zip(*values_and_indices): assert result[i] is None result[i] = v return result
[ "def", "stitch_values", "(", "values_and_indices_list", ")", ":", "length", "=", "0", "for", "values_and_indices", "in", "values_and_indices_list", ":", "length", "+=", "len", "(", "values_and_indices", "[", "0", "]", ")", "result", "=", "[", "None", "]", "*",...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/distribute/cross_device_utils.py#L750-L770
ducha-aiki/LSUVinit
a42ecdc0d44c217a29b65e98748d80b90d5c6279
python/caffe/detector.py
python
Detector.configure_crop
(self, context_pad)
Configure crop dimensions and amount of context for cropping. If context is included, make the special input mean for context padding. Parameters ---------- context_pad : amount of context for cropping.
Configure crop dimensions and amount of context for cropping. If context is included, make the special input mean for context padding.
[ "Configure", "crop", "dimensions", "and", "amount", "of", "context", "for", "cropping", ".", "If", "context", "is", "included", "make", "the", "special", "input", "mean", "for", "context", "padding", "." ]
def configure_crop(self, context_pad): """ Configure crop dimensions and amount of context for cropping. If context is included, make the special input mean for context padding. Parameters ---------- context_pad : amount of context for cropping. """ # crop dimensions in_ = self.inputs[0] tpose = self.transformer.transpose[in_] inv_tpose = [tpose[t] for t in tpose] self.crop_dims = np.array(self.blobs[in_].data.shape[1:])[inv_tpose] #.transpose(inv_tpose) # context padding self.context_pad = context_pad if self.context_pad: in_ = self.inputs[0] transpose = self.transformer.transpose.get(in_) channel_order = self.transformer.channel_swap.get(in_) raw_scale = self.transformer.raw_scale.get(in_) # Padding context crops needs the mean in unprocessed input space. mean = self.transformer.mean.get(in_) if mean is not None: inv_transpose = [transpose[t] for t in transpose] crop_mean = mean.copy().transpose(inv_transpose) if channel_order is not None: channel_order_inverse = [channel_order.index(i) for i in range(crop_mean.shape[2])] crop_mean = crop_mean[:, :, channel_order_inverse] if raw_scale is not None: crop_mean /= raw_scale self.crop_mean = crop_mean else: self.crop_mean = np.zeros(self.crop_dims, dtype=np.float32)
[ "def", "configure_crop", "(", "self", ",", "context_pad", ")", ":", "# crop dimensions", "in_", "=", "self", ".", "inputs", "[", "0", "]", "tpose", "=", "self", ".", "transformer", ".", "transpose", "[", "in_", "]", "inv_tpose", "=", "[", "tpose", "[", ...
https://github.com/ducha-aiki/LSUVinit/blob/a42ecdc0d44c217a29b65e98748d80b90d5c6279/python/caffe/detector.py#L181-L216
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/pyserial/serial/serialjava.py
python
Serial.cd
(self)
Read terminal status line: Carrier Detect
Read terminal status line: Carrier Detect
[ "Read", "terminal", "status", "line", ":", "Carrier", "Detect" ]
def cd(self): """Read terminal status line: Carrier Detect""" if not self.sPort: raise portNotOpenError self.sPort.isCD()
[ "def", "cd", "(", "self", ")", ":", "if", "not", "self", ".", "sPort", ":", "raise", "portNotOpenError", "self", ".", "sPort", ".", "isCD", "(", ")" ]
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/pyserial/serial/serialjava.py#L245-L249
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/command/easy_install.py
python
ScriptWriter.get_args
(cls, dist, header=None)
Yield write_script() argument tuples for a distribution's console_scripts and gui_scripts entry points.
Yield write_script() argument tuples for a distribution's console_scripts and gui_scripts entry points.
[ "Yield", "write_script", "()", "argument", "tuples", "for", "a", "distribution", "s", "console_scripts", "and", "gui_scripts", "entry", "points", "." ]
def get_args(cls, dist, header=None): """ Yield write_script() argument tuples for a distribution's console_scripts and gui_scripts entry points. """ if header is None: header = cls.get_header() spec = str(dist.as_requirement()) for type_ in 'console', 'gui': group = type_ + '_scripts' for name, ep in dist.get_entry_map(group).items(): cls._ensure_safe_name(name) script_text = cls.template % locals() args = cls._get_script_args(type_, name, header, script_text) for res in args: yield res
[ "def", "get_args", "(", "cls", ",", "dist", ",", "header", "=", "None", ")", ":", "if", "header", "is", "None", ":", "header", "=", "cls", ".", "get_header", "(", ")", "spec", "=", "str", "(", "dist", ".", "as_requirement", "(", ")", ")", "for", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/command/easy_install.py#L2107-L2122
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/urllib/request.py
python
FancyURLopener.http_error_301
(self, url, fp, errcode, errmsg, headers, data=None)
return self.http_error_302(url, fp, errcode, errmsg, headers, data)
Error 301 -- also relocated (permanently).
Error 301 -- also relocated (permanently).
[ "Error", "301", "--", "also", "relocated", "(", "permanently", ")", "." ]
def http_error_301(self, url, fp, errcode, errmsg, headers, data=None): """Error 301 -- also relocated (permanently).""" return self.http_error_302(url, fp, errcode, errmsg, headers, data)
[ "def", "http_error_301", "(", "self", ",", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ",", "data", "=", "None", ")", ":", "return", "self", ".", "http_error_302", "(", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "heade...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/urllib/request.py#L2200-L2202
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/feature_selection/_mutual_info.py
python
_estimate_mi
(X, y, discrete_features='auto', discrete_target=False, n_neighbors=3, copy=True, random_state=None)
return np.array(mi)
Estimate mutual information between the features and the target. Parameters ---------- X : array_like or sparse matrix, shape (n_samples, n_features) Feature matrix. y : array_like, shape (n_samples,) Target vector. discrete_features : {'auto', bool, array_like}, default 'auto' If bool, then determines whether to consider all features discrete or continuous. If array, then it should be either a boolean mask with shape (n_features,) or array with indices of discrete features. If 'auto', it is assigned to False for dense `X` and to True for sparse `X`. discrete_target : bool, default False Whether to consider `y` as a discrete variable. n_neighbors : int, default 3 Number of neighbors to use for MI estimation for continuous variables, see [1]_ and [2]_. Higher values reduce variance of the estimation, but could introduce a bias. copy : bool, default True Whether to make a copy of the given data. If set to False, the initial data will be overwritten. random_state : int, RandomState instance or None, optional, default None The seed of the pseudo random number generator for adding small noise to continuous variables in order to remove repeated values. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Returns ------- mi : ndarray, shape (n_features,) Estimated mutual information between each feature and the target. A negative value will be replaced by 0. References ---------- .. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual information". Phys. Rev. E 69, 2004. .. [2] B. C. Ross "Mutual Information between Discrete and Continuous Data Sets". PLoS ONE 9(2), 2014.
Estimate mutual information between the features and the target.
[ "Estimate", "mutual", "information", "between", "the", "features", "and", "the", "target", "." ]
def _estimate_mi(X, y, discrete_features='auto', discrete_target=False, n_neighbors=3, copy=True, random_state=None): """Estimate mutual information between the features and the target. Parameters ---------- X : array_like or sparse matrix, shape (n_samples, n_features) Feature matrix. y : array_like, shape (n_samples,) Target vector. discrete_features : {'auto', bool, array_like}, default 'auto' If bool, then determines whether to consider all features discrete or continuous. If array, then it should be either a boolean mask with shape (n_features,) or array with indices of discrete features. If 'auto', it is assigned to False for dense `X` and to True for sparse `X`. discrete_target : bool, default False Whether to consider `y` as a discrete variable. n_neighbors : int, default 3 Number of neighbors to use for MI estimation for continuous variables, see [1]_ and [2]_. Higher values reduce variance of the estimation, but could introduce a bias. copy : bool, default True Whether to make a copy of the given data. If set to False, the initial data will be overwritten. random_state : int, RandomState instance or None, optional, default None The seed of the pseudo random number generator for adding small noise to continuous variables in order to remove repeated values. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Returns ------- mi : ndarray, shape (n_features,) Estimated mutual information between each feature and the target. A negative value will be replaced by 0. References ---------- .. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual information". Phys. Rev. E 69, 2004. .. [2] B. C. Ross "Mutual Information between Discrete and Continuous Data Sets". PLoS ONE 9(2), 2014. """ X, y = check_X_y(X, y, accept_sparse='csc', y_numeric=not discrete_target) n_samples, n_features = X.shape if isinstance(discrete_features, (str, bool)): if isinstance(discrete_features, str): if discrete_features == 'auto': discrete_features = issparse(X) else: raise ValueError("Invalid string value for discrete_features.") discrete_mask = np.empty(n_features, dtype=bool) discrete_mask.fill(discrete_features) else: discrete_features = check_array(discrete_features, ensure_2d=False) if discrete_features.dtype != 'bool': discrete_mask = np.zeros(n_features, dtype=bool) discrete_mask[discrete_features] = True else: discrete_mask = discrete_features continuous_mask = ~discrete_mask if np.any(continuous_mask) and issparse(X): raise ValueError("Sparse matrix `X` can't have continuous features.") rng = check_random_state(random_state) if np.any(continuous_mask): if copy: X = X.copy() if not discrete_target: X[:, continuous_mask] = scale(X[:, continuous_mask], with_mean=False, copy=False) # Add small noise to continuous features as advised in Kraskov et. al. X = X.astype(float, **_astype_copy_false(X)) means = np.maximum(1, np.mean(np.abs(X[:, continuous_mask]), axis=0)) X[:, continuous_mask] += 1e-10 * means * rng.randn( n_samples, np.sum(continuous_mask)) if not discrete_target: y = scale(y, with_mean=False) y += 1e-10 * np.maximum(1, np.mean(np.abs(y))) * rng.randn(n_samples) mi = [_compute_mi(x, y, discrete_feature, discrete_target, n_neighbors) for x, discrete_feature in zip(_iterate_columns(X), discrete_mask)] return np.array(mi)
[ "def", "_estimate_mi", "(", "X", ",", "y", ",", "discrete_features", "=", "'auto'", ",", "discrete_target", "=", "False", ",", "n_neighbors", "=", "3", ",", "copy", "=", "True", ",", "random_state", "=", "None", ")", ":", "X", ",", "y", "=", "check_X_y...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/feature_selection/_mutual_info.py#L195-L292
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/eclib/errdlg.py
python
ErrorDialog.OnButton
(self, evt)
Handles button events @param evt: event that called this handler @postcondition: Dialog is closed @postcondition: If Report Event then email program is opened
Handles button events @param evt: event that called this handler @postcondition: Dialog is closed @postcondition: If Report Event then email program is opened
[ "Handles", "button", "events", "@param", "evt", ":", "event", "that", "called", "this", "handler", "@postcondition", ":", "Dialog", "is", "closed", "@postcondition", ":", "If", "Report", "Event", "then", "email", "program", "is", "opened" ]
def OnButton(self, evt): """Handles button events @param evt: event that called this handler @postcondition: Dialog is closed @postcondition: If Report Event then email program is opened """ e_id = evt.GetId() if e_id == wx.ID_CLOSE: self.Close() elif e_id == ErrorDialog.ID_SEND: self.Send() self.Close() elif e_id == wx.ID_ABORT: ErrorDialog.ABORT = True self.Abort() self.Close() else: evt.Skip()
[ "def", "OnButton", "(", "self", ",", "evt", ")", ":", "e_id", "=", "evt", ".", "GetId", "(", ")", "if", "e_id", "==", "wx", ".", "ID_CLOSE", ":", "self", ".", "Close", "(", ")", "elif", "e_id", "==", "ErrorDialog", ".", "ID_SEND", ":", "self", "....
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/errdlg.py#L265-L283
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py
python
_expand_macro_value
(macros, rhs, properties)
return rhs
Expand the value of a macro based on ones seen so far.
Expand the value of a macro based on ones seen so far.
[ "Expand", "the", "value", "of", "a", "macro", "based", "on", "ones", "seen", "so", "far", "." ]
def _expand_macro_value(macros, rhs, properties): """Expand the value of a macro based on ones seen so far.""" estart = rhs.find("$$(") mstart = rhs.find("$$") while mstart >= 0 and mstart != estart: rstart = mstart + 2 if rstart < len(rhs) and rhs[rstart] == "{": rstart = rstart + 1 term = "}" elif rstart < len(rhs) and rhs[rstart] == "[": rstart = rstart + 1 term = "]" else: term = string.whitespace mend = rstart while mend < len(rhs) and rhs[mend] not in term: mend = mend + 1 lhs = rhs[rstart:mend] if term in "}]": mend = mend + 1 if term == "]": # Assume a missing property expands to an empty string. if properties is None: value = "" else: value = properties.get(lhs, "") else: # We used to treat a missing value as an error, but Qt v4.3.0 has # at least one case that refers to an undefined macro. If qmake # handles it then this must be the correct behaviour. value = macros.get(lhs, "") rhs = rhs[:mstart] + value + rhs[mend:] estart = rhs.find("$$(") mstart = rhs.find("$$") return rhs
[ "def", "_expand_macro_value", "(", "macros", ",", "rhs", ",", "properties", ")", ":", "estart", "=", "rhs", ".", "find", "(", "\"$$(\"", ")", "mstart", "=", "rhs", ".", "find", "(", "\"$$\"", ")", "while", "mstart", ">=", "0", "and", "mstart", "!=", ...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py#L2640-L2681
TGAC/KAT
e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216
deps/boost/tools/build/src/util/path.py
python
reverse
(path)
return os.sep.join('..' for t in path.split(os.sep))
Returns path2 such that `os.path.join(path, path2) == '.'`. `path` may not contain '..' or be rooted. Args: path (str): the path to reverse Returns: the string of the reversed path Example: >>> p1 = 'path/to/somewhere' >>> p2 = reverse('path/to/somewhere') >>> p2 '../../..' >>> os.path.normpath(os.path.join(p1, p2)) '.'
Returns path2 such that `os.path.join(path, path2) == '.'`. `path` may not contain '..' or be rooted.
[ "Returns", "path2", "such", "that", "os", ".", "path", ".", "join", "(", "path", "path2", ")", "==", ".", ".", "path", "may", "not", "contain", "..", "or", "be", "rooted", "." ]
def reverse(path): """Returns path2 such that `os.path.join(path, path2) == '.'`. `path` may not contain '..' or be rooted. Args: path (str): the path to reverse Returns: the string of the reversed path Example: >>> p1 = 'path/to/somewhere' >>> p2 = reverse('path/to/somewhere') >>> p2 '../../..' >>> os.path.normpath(os.path.join(p1, p2)) '.' """ if is_rooted(path) or '..' in path: from b2.manager import get_manager get_manager().errors()( 'reverse(path): path is either rooted or contains ".." in the path') if path == '.': return path path = os.path.normpath(path) # os.sep.join() is being used over os.path.join() due # to an extra '..' that is created by os.path.join() return os.sep.join('..' for t in path.split(os.sep))
[ "def", "reverse", "(", "path", ")", ":", "if", "is_rooted", "(", "path", ")", "or", "'..'", "in", "path", ":", "from", "b2", ".", "manager", "import", "get_manager", "get_manager", "(", ")", ".", "errors", "(", ")", "(", "'reverse(path): path is either roo...
https://github.com/TGAC/KAT/blob/e8870331de2b4bb0a1b3b91c6afb8fb9d59e9216/deps/boost/tools/build/src/util/path.py#L197-L225
NVIDIA/DALI
bf16cc86ba8f091b145f91962f21fe1b6aff243d
dali/python/nvidia/dali/backend.py
python
check_cuda_runtime
()
Checks the availability of CUDA runtime/GPU, and NPP, nvJEPG, and cuFFT libraries and prints an appropriate warning.
Checks the availability of CUDA runtime/GPU, and NPP, nvJEPG, and cuFFT libraries and prints an appropriate warning.
[ "Checks", "the", "availability", "of", "CUDA", "runtime", "/", "GPU", "and", "NPP", "nvJEPG", "and", "cuFFT", "libraries", "and", "prints", "an", "appropriate", "warning", "." ]
def check_cuda_runtime(): """ Checks the availability of CUDA runtime/GPU, and NPP, nvJEPG, and cuFFT libraries and prints an appropriate warning. """ global cuda_checked if not cuda_checked: cuda_checked = True if GetCudaVersion() == -1: deprecation_warning("GPU is not available. Only CPU operators are available.") if GetCufftVersion() == -1: deprecation_warning("Cannot access cuFFT library. Please check cuda installation and/or " "if an appropriate wheel is installed.") if GetNppVersion() == -1: deprecation_warning("Cannot access NPP library. Please check cuda installation and/or " "if an appropriate wheel is installed.") if GetNvjpegVersion() == -1: deprecation_warning("Cannot access nvJPEG library. Please check cuda installation and/or " "if an appropriate wheel is installed.")
[ "def", "check_cuda_runtime", "(", ")", ":", "global", "cuda_checked", "if", "not", "cuda_checked", ":", "cuda_checked", "=", "True", "if", "GetCudaVersion", "(", ")", "==", "-", "1", ":", "deprecation_warning", "(", "\"GPU is not available. Only CPU operators are avai...
https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/dali/python/nvidia/dali/backend.py#L52-L73
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/v8/third_party/jinja2/loaders.py
python
BaseLoader.list_templates
(self)
Iterates over all templates. If the loader does not support that it should raise a :exc:`TypeError` which is the default behavior.
Iterates over all templates. If the loader does not support that it should raise a :exc:`TypeError` which is the default behavior.
[ "Iterates", "over", "all", "templates", ".", "If", "the", "loader", "does", "not", "support", "that", "it", "should", "raise", "a", ":", "exc", ":", "TypeError", "which", "is", "the", "default", "behavior", "." ]
def list_templates(self): """Iterates over all templates. If the loader does not support that it should raise a :exc:`TypeError` which is the default behavior. """ raise TypeError('this loader cannot iterate over all templates')
[ "def", "list_templates", "(", "self", ")", ":", "raise", "TypeError", "(", "'this loader cannot iterate over all templates'", ")" ]
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/loaders.py#L93-L97
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/PngImagePlugin.py
python
iTXt.__new__
(cls, text, lang=None, tkey=None)
return self
:param cls: the class to use when creating the instance :param text: value for this key :param lang: language code :param tkey: UTF-8 version of the key name
:param cls: the class to use when creating the instance :param text: value for this key :param lang: language code :param tkey: UTF-8 version of the key name
[ ":", "param", "cls", ":", "the", "class", "to", "use", "when", "creating", "the", "instance", ":", "param", "text", ":", "value", "for", "this", "key", ":", "param", "lang", ":", "language", "code", ":", "param", "tkey", ":", "UTF", "-", "8", "versio...
def __new__(cls, text, lang=None, tkey=None): """ :param cls: the class to use when creating the instance :param text: value for this key :param lang: language code :param tkey: UTF-8 version of the key name """ self = str.__new__(cls, text) self.lang = lang self.tkey = tkey return self
[ "def", "__new__", "(", "cls", ",", "text", ",", "lang", "=", "None", ",", "tkey", "=", "None", ")", ":", "self", "=", "str", ".", "__new__", "(", "cls", ",", "text", ")", "self", ".", "lang", "=", "lang", "self", ".", "tkey", "=", "tkey", "retu...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/PngImagePlugin.py#L208-L219
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/webkit.py
python
WebKitCtrl.IncreaseTextSize
(*args, **kwargs)
return _webkit.WebKitCtrl_IncreaseTextSize(*args, **kwargs)
IncreaseTextSize(self)
IncreaseTextSize(self)
[ "IncreaseTextSize", "(", "self", ")" ]
def IncreaseTextSize(*args, **kwargs): """IncreaseTextSize(self)""" return _webkit.WebKitCtrl_IncreaseTextSize(*args, **kwargs)
[ "def", "IncreaseTextSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_webkit", ".", "WebKitCtrl_IncreaseTextSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/webkit.py#L140-L142
google/nucleus
68d3947fafba1337f294c0668a6e1c7f3f1273e3
nucleus/io/genomics_reader.py
python
DispatchingGenomicsReader._native_reader
(self, input_path, **kwargs)
Returns a GenomicsReader for reading the records `natively`. Args: input_path: The path to the native file to read. **kwargs: Zero or more keyword arguments. Returns: A GenomicsReader.
Returns a GenomicsReader for reading the records `natively`.
[ "Returns", "a", "GenomicsReader", "for", "reading", "the", "records", "natively", "." ]
def _native_reader(self, input_path, **kwargs): """Returns a GenomicsReader for reading the records `natively`. Args: input_path: The path to the native file to read. **kwargs: Zero or more keyword arguments. Returns: A GenomicsReader. """
[ "def", "_native_reader", "(", "self", ",", "input_path", ",", "*", "*", "kwargs", ")", ":" ]
https://github.com/google/nucleus/blob/68d3947fafba1337f294c0668a6e1c7f3f1273e3/nucleus/io/genomics_reader.py#L213-L222
moflow/moflow
2dfb27c799c90c6caf1477508eca3eec616ef7d2
bap/libtracewrap/libtrace/protobuf/python/mox.py
python
And.equals
(self, rhs)
return True
Checks whether all Comparators are equal to rhs. Args: # rhs: can be anything Returns: bool
Checks whether all Comparators are equal to rhs.
[ "Checks", "whether", "all", "Comparators", "are", "equal", "to", "rhs", "." ]
def equals(self, rhs): """Checks whether all Comparators are equal to rhs. Args: # rhs: can be anything Returns: bool """ for comparator in self._comparators: if not comparator.equals(rhs): return False return True
[ "def", "equals", "(", "self", ",", "rhs", ")", ":", "for", "comparator", "in", "self", ".", "_comparators", ":", "if", "not", "comparator", ".", "equals", "(", "rhs", ")", ":", "return", "False", "return", "True" ]
https://github.com/moflow/moflow/blob/2dfb27c799c90c6caf1477508eca3eec616ef7d2/bap/libtracewrap/libtrace/protobuf/python/mox.py#L1059-L1073
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/config.py
python
PyPIRCCommand._get_rc_file
(self)
return os.path.join(os.path.expanduser('~'), '.pypirc')
Returns rc file path.
Returns rc file path.
[ "Returns", "rc", "file", "path", "." ]
def _get_rc_file(self): """Returns rc file path.""" return os.path.join(os.path.expanduser('~'), '.pypirc')
[ "def", "_get_rc_file", "(", "self", ")", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ",", "'.pypirc'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/config.py#L38-L40
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gdal.py
python
Band.GetDataCoverageStatus
(self, *args)
return _gdal.Band_GetDataCoverageStatus(self, *args)
r"""GetDataCoverageStatus(Band self, int nXOff, int nYOff, int nXSize, int nYSize, int nMaskFlagStop=0) -> int
r"""GetDataCoverageStatus(Band self, int nXOff, int nYOff, int nXSize, int nYSize, int nMaskFlagStop=0) -> int
[ "r", "GetDataCoverageStatus", "(", "Band", "self", "int", "nXOff", "int", "nYOff", "int", "nXSize", "int", "nYSize", "int", "nMaskFlagStop", "=", "0", ")", "-", ">", "int" ]
def GetDataCoverageStatus(self, *args): r"""GetDataCoverageStatus(Band self, int nXOff, int nYOff, int nXSize, int nYSize, int nMaskFlagStop=0) -> int""" return _gdal.Band_GetDataCoverageStatus(self, *args)
[ "def", "GetDataCoverageStatus", "(", "self", ",", "*", "args", ")", ":", "return", "_gdal", ".", "Band_GetDataCoverageStatus", "(", "self", ",", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L3580-L3582
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/nn/masked_linear.py
python
wrap_kernel_init
(kernel_init, mask)
return wrapped_kernel_init
Correction to LeCun normal init.
Correction to LeCun normal init.
[ "Correction", "to", "LeCun", "normal", "init", "." ]
def wrap_kernel_init(kernel_init, mask): """Correction to LeCun normal init.""" corr = jnp.sqrt(mask.size / mask.sum()) def wrapped_kernel_init(*args): return corr * mask * kernel_init(*args) return wrapped_kernel_init
[ "def", "wrap_kernel_init", "(", "kernel_init", ",", "mask", ")", ":", "corr", "=", "jnp", ".", "sqrt", "(", "mask", ".", "size", "/", "mask", ".", "sum", "(", ")", ")", "def", "wrapped_kernel_init", "(", "*", "args", ")", ":", "return", "corr", "*", ...
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/nn/masked_linear.py#L28-L36
scummvm/scummvm
9c039d027e7ffb9d83ae2e274147e2daf8d57ce2
devtools/dumper-companion.py
python
has_resource_fork
(dirpath: bytes, filename: bytes)
return os.path.exists(os.path.join(filepath, bytes("..namedfork/rsrc", "utf8")))
Check if file has a resource fork Ease of compatibility between macOS and linux
Check if file has a resource fork
[ "Check", "if", "file", "has", "a", "resource", "fork" ]
def has_resource_fork(dirpath: bytes, filename: bytes) -> bool: """ Check if file has a resource fork Ease of compatibility between macOS and linux """ filepath = os.path.join(dirpath, filename) return os.path.exists(os.path.join(filepath, bytes("..namedfork/rsrc", "utf8")))
[ "def", "has_resource_fork", "(", "dirpath", ":", "bytes", ",", "filename", ":", "bytes", ")", "->", "bool", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "dirpath", ",", "filename", ")", "return", "os", ".", "path", ".", "exists", "(", "...
https://github.com/scummvm/scummvm/blob/9c039d027e7ffb9d83ae2e274147e2daf8d57ce2/devtools/dumper-companion.py#L396-L403
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/jinja2/environment.py
python
_environment_sanity_check
(environment)
return environment
Perform a sanity check on the environment.
Perform a sanity check on the environment.
[ "Perform", "a", "sanity", "check", "on", "the", "environment", "." ]
def _environment_sanity_check(environment): """Perform a sanity check on the environment.""" assert issubclass(environment.undefined, Undefined), 'undefined must ' \ 'be a subclass of undefined because filters depend on it.' assert environment.block_start_string != \ environment.variable_start_string != \ environment.comment_start_string, 'block, variable and comment ' \ 'start strings must be different' assert environment.newline_sequence in ('\r', '\r\n', '\n'), \ 'newline_sequence set to unknown line ending string.' return environment
[ "def", "_environment_sanity_check", "(", "environment", ")", ":", "assert", "issubclass", "(", "environment", ".", "undefined", ",", "Undefined", ")", ",", "'undefined must '", "'be a subclass of undefined because filters depend on it.'", "assert", "environment", ".", "bloc...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/environment.py#L90-L100
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/wix.py
python
generate
(env)
Add Builders and construction variables for WiX to an Environment.
Add Builders and construction variables for WiX to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "WiX", "to", "an", "Environment", "." ]
def generate(env): """Add Builders and construction variables for WiX to an Environment.""" if not exists(env): return env['WIXCANDLEFLAGS'] = ['-nologo'] env['WIXCANDLEINCLUDE'] = [] env['WIXCANDLECOM'] = '$WIXCANDLE $WIXCANDLEFLAGS -I $WIXCANDLEINCLUDE -o ${TARGET} ${SOURCE}' env['WIXLIGHTFLAGS'].append( '-nologo' ) env['WIXLIGHTCOM'] = "$WIXLIGHT $WIXLIGHTFLAGS -out ${TARGET} ${SOURCES}" env['WIXSRCSUF'] = '.wxs' env['WIXOBJSUF'] = '.wixobj' object_builder = SCons.Builder.Builder( action = '$WIXCANDLECOM', suffix = '$WIXOBJSUF', src_suffix = '$WIXSRCSUF') linker_builder = SCons.Builder.Builder( action = '$WIXLIGHTCOM', src_suffix = '$WIXOBJSUF', src_builder = object_builder) env['BUILDERS']['WiX'] = linker_builder
[ "def", "generate", "(", "env", ")", ":", "if", "not", "exists", "(", "env", ")", ":", "return", "env", "[", "'WIXCANDLEFLAGS'", "]", "=", "[", "'-nologo'", "]", "env", "[", "'WIXCANDLEINCLUDE'", "]", "=", "[", "]", "env", "[", "'WIXCANDLECOM'", "]", ...
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/wix.py#L39-L63
GoSSIP-SJTU/TripleDoggy
03648d6b19c812504b14e8b98c8c7b3f443f4e54
bindings/python/llvm/object.py
python
Relocation.offset
(self)
return lib.LLVMGetRelocationOffset(self)
The offset of this relocation, in long bytes.
The offset of this relocation, in long bytes.
[ "The", "offset", "of", "this", "relocation", "in", "long", "bytes", "." ]
def offset(self): """The offset of this relocation, in long bytes.""" if self.expired: raise Exception('Relocation instance has expired.') return lib.LLVMGetRelocationOffset(self)
[ "def", "offset", "(", "self", ")", ":", "if", "self", ".", "expired", ":", "raise", "Exception", "(", "'Relocation instance has expired.'", ")", "return", "lib", ".", "LLVMGetRelocationOffset", "(", "self", ")" ]
https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/bindings/python/llvm/object.py#L375-L380
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/nntplib.py
python
NNTP.body
(self, id, file=None)
return self.artcmd('BODY ' + id, file)
Process a BODY command. Argument: - id: article number or message id - file: Filename string or file object to store the article in Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article's body or an empty list if file was used
Process a BODY command. Argument: - id: article number or message id - file: Filename string or file object to store the article in Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article's body or an empty list if file was used
[ "Process", "a", "BODY", "command", ".", "Argument", ":", "-", "id", ":", "article", "number", "or", "message", "id", "-", "file", ":", "Filename", "string", "or", "file", "object", "to", "store", "the", "article", "in", "Returns", ":", "-", "resp", ":"...
def body(self, id, file=None): """Process a BODY command. Argument: - id: article number or message id - file: Filename string or file object to store the article in Returns: - resp: server response if successful - nr: article number - id: message id - list: the lines of the article's body or an empty list if file was used""" return self.artcmd('BODY ' + id, file)
[ "def", "body", "(", "self", ",", "id", ",", "file", "=", "None", ")", ":", "return", "self", ".", "artcmd", "(", "'BODY '", "+", "id", ",", "file", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/nntplib.py#L422-L433
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/arrays/base.py
python
ExtensionArray.__iter__
(self)
Iterate over elements of the array.
Iterate over elements of the array.
[ "Iterate", "over", "elements", "of", "the", "array", "." ]
def __iter__(self): """ Iterate over elements of the array. """ # This needs to be implemented so that pandas recognizes extension # arrays as list-like. The default implementation makes successive # calls to ``__getitem__``, which may be slower than necessary. for i in range(len(self)): yield self[i]
[ "def", "__iter__", "(", "self", ")", ":", "# This needs to be implemented so that pandas recognizes extension", "# arrays as list-like. The default implementation makes successive", "# calls to ``__getitem__``, which may be slower than necessary.", "for", "i", "in", "range", "(", "len", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/arrays/base.py#L344-L352
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/command/install.py
python
install.get_inputs
(self)
return inputs
Returns the inputs of all the sub-commands
Returns the inputs of all the sub-commands
[ "Returns", "the", "inputs", "of", "all", "the", "sub", "-", "commands" ]
def get_inputs(self): """Returns the inputs of all the sub-commands""" # XXX gee, this looks familiar ;-( inputs = [] for cmd_name in self.get_sub_commands(): cmd = self.get_finalized_command(cmd_name) inputs.extend(cmd.get_inputs()) return inputs
[ "def", "get_inputs", "(", "self", ")", ":", "# XXX gee, this looks familiar ;-(", "inputs", "=", "[", "]", "for", "cmd_name", "in", "self", ".", "get_sub_commands", "(", ")", ":", "cmd", "=", "self", ".", "get_finalized_command", "(", "cmd_name", ")", "inputs"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/command/install.py#L616-L624
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py
python
ConstBitStream.bytealign
(self)
return skipped
Align to next byte and return number of skipped bits. Raises ValueError if the end of the bitstring is reached before aligning to the next byte.
Align to next byte and return number of skipped bits.
[ "Align", "to", "next", "byte", "and", "return", "number", "of", "skipped", "bits", "." ]
def bytealign(self): """Align to next byte and return number of skipped bits. Raises ValueError if the end of the bitstring is reached before aligning to the next byte. """ skipped = (8 - (self._pos % 8)) % 8 self.pos += self._offset + skipped assert self._assertsanity() return skipped
[ "def", "bytealign", "(", "self", ")", ":", "skipped", "=", "(", "8", "-", "(", "self", ".", "_pos", "%", "8", ")", ")", "%", "8", "self", ".", "pos", "+=", "self", ".", "_offset", "+", "skipped", "assert", "self", ".", "_assertsanity", "(", ")", ...
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L3977-L3987
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/hotshot/__init__.py
python
Profile.runctx
(self, cmd, globals, locals)
return self
Evaluate an exec-compatible string in a specific environment. The string is compiled before profiling begins.
Evaluate an exec-compatible string in a specific environment.
[ "Evaluate", "an", "exec", "-", "compatible", "string", "in", "a", "specific", "environment", "." ]
def runctx(self, cmd, globals, locals): """Evaluate an exec-compatible string in a specific environment. The string is compiled before profiling begins. """ code = compile(cmd, "<string>", "exec") self._prof.runcode(code, globals, locals) return self
[ "def", "runctx", "(", "self", ",", "cmd", ",", "globals", ",", "locals", ")", ":", "code", "=", "compile", "(", "cmd", ",", "\"<string>\"", ",", "\"exec\"", ")", "self", ".", "_prof", ".", "runcode", "(", "code", ",", "globals", ",", "locals", ")", ...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/hotshot/__init__.py#L60-L68
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
xmlDtd.dtdAttrDesc
(self, elem, name)
return __tmp
Search the DTD for the description of this attribute on this element.
Search the DTD for the description of this attribute on this element.
[ "Search", "the", "DTD", "for", "the", "description", "of", "this", "attribute", "on", "this", "element", "." ]
def dtdAttrDesc(self, elem, name): """Search the DTD for the description of this attribute on this element. """ ret = libxml2mod.xmlGetDtdAttrDesc(self._o, elem, name) if ret is None:raise treeError('xmlGetDtdAttrDesc() failed') __tmp = xmlAttribute(_obj=ret) return __tmp
[ "def", "dtdAttrDesc", "(", "self", ",", "elem", ",", "name", ")", ":", "ret", "=", "libxml2mod", ".", "xmlGetDtdAttrDesc", "(", "self", ".", "_o", ",", "elem", ",", "name", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlGetDtdAttr...
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L4957-L4963
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/extern/__init__.py
python
VendorImporter.search_path
(self)
Search first the vendor package then as a natural package.
Search first the vendor package then as a natural package.
[ "Search", "first", "the", "vendor", "package", "then", "as", "a", "natural", "package", "." ]
def search_path(self): """ Search first the vendor package then as a natural package. """ yield self.vendor_pkg + '.' yield ''
[ "def", "search_path", "(", "self", ")", ":", "yield", "self", ".", "vendor_pkg", "+", "'.'", "yield", "''" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/extern/__init__.py#L16-L21
CGRU/cgru
1881a4128530e3d31ac6c25314c18314fc50c2c7
afanasy/python/af.py
python
Block.setTaskProgressChangeTimeout
(self, value)
If running task will not change its progress (percentage) for this time, it will be stopped with an error. :param value: timeout in seconds
If running task will not change its progress (percentage) for this time, it will be stopped with an error. :param value: timeout in seconds
[ "If", "running", "task", "will", "not", "change", "its", "progress", "(", "percentage", ")", "for", "this", "time", "it", "will", "be", "stopped", "with", "an", "error", ".", ":", "param", "value", ":", "timeout", "in", "seconds" ]
def setTaskProgressChangeTimeout(self, value): """If running task will not change its progress (percentage) for this time, it will be stopped with an error. :param value: timeout in seconds """ if value > 0: self.data["task_progress_change_timeout"] = int(value)
[ "def", "setTaskProgressChangeTimeout", "(", "self", ",", "value", ")", ":", "if", "value", ">", "0", ":", "self", ".", "data", "[", "\"task_progress_change_timeout\"", "]", "=", "int", "(", "value", ")" ]
https://github.com/CGRU/cgru/blob/1881a4128530e3d31ac6c25314c18314fc50c2c7/afanasy/python/af.py#L425-L431